дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 01:01:17 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
05eed6d7de | ||
|
|
ace118d6fb | ||
|
|
8d4baa4cf4 | ||
|
|
448b33446a |
No files matched your search
@@ -1,2 +0,0 @@
|
||||
custom:
|
||||
- https://github.com/l0ng-ai/openidea#sponsor
|
||||
Бінарний файл не відображається.
|
До Ширина: | Висота: | Розмір: 70 KiB |
Бінарний файл не відображається.
|
До Ширина: | Висота: | Розмір: 97 KiB |
@@ -19,8 +19,6 @@
|
||||
<a href="#plugins">Plugins</a>
|
||||
·
|
||||
<a href="#community">Community</a>
|
||||
·
|
||||
<a href="#sponsor">Sponsor</a>
|
||||
</p>
|
||||
|
||||
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
|
||||
@@ -70,17 +68,6 @@ the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
|
||||
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
## Sponsor
|
||||
|
||||
If OpenIDEA saves you time, you can support its development with Alipay or WeChat Pay.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center"><img src=".github/assets/sponsor-alipay.png" alt="Alipay QR code" width="200"><br>Alipay</td>
|
||||
<td align="center"><img src=".github/assets/sponsor-wechat.png" alt="WeChat Pay QR code" width="200"><br>WeChat Pay</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## License
|
||||
|
||||
[Apache 2.0](LICENSE). Bundled third-party assets are listed in [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md).
|
||||
|
||||
@@ -1234,17 +1234,6 @@ impl AgentManager {
|
||||
};
|
||||
// A copy of the task (a fork) may work in the same worktree.
|
||||
let shared = self.tasks.read().values().any(|t| t.id != id && t.state.lock().task.cwd.0 == cwd);
|
||||
self.tasks.write().remove(id);
|
||||
*task.deleted.lock() = true;
|
||||
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
|
||||
let saved = task.state.lock().saved.clone();
|
||||
if let Some(saved) = saved
|
||||
&& !self.tasks.read().values().any(|t| t.state.lock().saved.as_ref() == Some(&saved))
|
||||
{
|
||||
let _ = std::fs::remove_dir_all(self.shared.paths.store_dir.join(saved));
|
||||
}
|
||||
// The list drops the task now; removing a large worktree's folder can take a while.
|
||||
self.shared.emit(AgentEvent::Removed { id: id.to_owned() });
|
||||
if remove_worktree && !shared && isolation == Isolation::Worktree && cwd.exists() {
|
||||
// On Windows the agent's processes lock the folder (their working directory,
|
||||
// open files) until they have exited.
|
||||
@@ -1254,6 +1243,16 @@ impl AgentManager {
|
||||
let worktrees = self.shared.paths.worktrees_dir.clone();
|
||||
blocking(move || worktree::remove(&root, &worktrees, &cwd)).await?;
|
||||
}
|
||||
self.tasks.write().remove(id);
|
||||
*task.deleted.lock() = true;
|
||||
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
|
||||
let saved = task.state.lock().saved.clone();
|
||||
if let Some(saved) = saved
|
||||
&& !self.tasks.read().values().any(|t| t.state.lock().saved.as_ref() == Some(&saved))
|
||||
{
|
||||
let _ = std::fs::remove_dir_all(self.shared.paths.store_dir.join(saved));
|
||||
}
|
||||
self.shared.emit(AgentEvent::Removed { id: id.to_owned() });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -93,9 +93,8 @@ fn retrying(attempts: u32, pause: Duration, mut op: impl FnMut() -> std::io::Res
|
||||
pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
let Some(repo) = Repo::discover(cwd)? else { return Ok(Vec::new()) };
|
||||
let root = repo.root().to_path_buf();
|
||||
let stats: std::collections::HashMap<String, (u32, u32)> =
|
||||
repo.numstat_with_worktree(base)?.into_iter().map(|(p, a, r)| (p, (a, r))).collect();
|
||||
let stat = |rel: &str| stats.get(rel).copied().unwrap_or((0, 0));
|
||||
let stats = repo.numstat_with_worktree(base)?;
|
||||
let stat = |rel: &str| stats.iter().find(|(p, ..)| p == rel).map_or((0, 0), |&(_, a, r)| (a, r));
|
||||
let mut out: Vec<AgentChange> = repo
|
||||
.diff_with_worktree(base)?
|
||||
.into_iter()
|
||||
@@ -104,9 +103,8 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
AgentChange { path: IpcPath(root.join(&f.path)), rel_path: f.path, kind: f.kind, added, removed }
|
||||
})
|
||||
.collect();
|
||||
let tracked: std::collections::HashSet<String> = out.iter().map(|c| c.rel_path.clone()).collect();
|
||||
for s in repo.status()? {
|
||||
if s.unstaged == Some(ChangeKind::Untracked) && !tracked.contains(&s.rel_path) {
|
||||
if s.unstaged == Some(ChangeKind::Untracked) && !out.iter().any(|c| c.rel_path == s.rel_path) {
|
||||
let added = std::fs::read_to_string(&*s.path).map_or(0, |t| t.lines().count() as u32);
|
||||
out.push(AgentChange { path: s.path, rel_path: s.rel_path, kind: ChangeKind::Added, added, removed: 0 });
|
||||
}
|
||||
@@ -126,10 +124,7 @@ pub(crate) fn stamp(path: &Path) -> Stamp {
|
||||
|
||||
/// The files already changed in `cwd` against `HEAD`, stamped so later edits to them show.
|
||||
pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
|
||||
// Paths and stamps only: no diff and no line counts, which read every untracked file
|
||||
// and held up starting a task in a checkout with many of them.
|
||||
let Some(repo) = Repo::discover(cwd)? else { return Ok(BTreeMap::new()) };
|
||||
Ok(repo.status()?.into_iter().map(|s| (s.rel_path, stamp(&s.path))).collect())
|
||||
Ok(changes(cwd, "HEAD")?.into_iter().map(|c| (c.rel_path, stamp(&c.path))).collect())
|
||||
}
|
||||
|
||||
/// Drops the changes that were there before the task and haven't been touched since.
|
||||
|
||||
@@ -333,23 +333,6 @@ pub struct InlayHintsSettings {
|
||||
pub code_vision_usages: bool,
|
||||
/// Code vision: last author of a declaration (VCS blame) beside its usages.
|
||||
pub code_vision_author: bool,
|
||||
/// Code vision: "no usages" on declarations nothing uses (IDEA shows it; clicking searches everywhere).
|
||||
pub code_vision_no_usages: bool,
|
||||
/// Code vision: where the usages go, above the declaration or at the end of its line.
|
||||
pub code_vision_usages_position: CodeVisionPosition,
|
||||
/// Code vision: where the author goes, above the declaration or at the end of its line.
|
||||
pub code_vision_author_position: CodeVisionPosition,
|
||||
}
|
||||
|
||||
/// Editor › Inlay Hints › Code Vision position (IDEA's "Default position for metrics").
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum CodeVisionPosition {
|
||||
/// A row of its own above the declaration.
|
||||
#[default]
|
||||
Top,
|
||||
/// After the end of the declaration's first line.
|
||||
Right,
|
||||
}
|
||||
|
||||
impl Default for InlayHintsSettings {
|
||||
@@ -361,9 +344,6 @@ impl Default for InlayHintsSettings {
|
||||
disabled_languages: Vec::new(),
|
||||
code_vision_usages: true,
|
||||
code_vision_author: true,
|
||||
code_vision_no_usages: true,
|
||||
code_vision_usages_position: CodeVisionPosition::Top,
|
||||
code_vision_author_position: CodeVisionPosition::Top,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,9 +261,6 @@ pub enum WhileRunning {
|
||||
pub struct McpServerSettings {
|
||||
/// Serve the tools on 127.0.0.1 while the IDE runs.
|
||||
pub enabled: bool,
|
||||
/// Run the tools that change the project or start processes without asking first
|
||||
/// (IDEA's brave mode). Read from the IDE's own settings only, never a project's.
|
||||
pub run_without_confirmation: bool,
|
||||
}
|
||||
|
||||
/// Absent profiles retain automatic discovery for existing projects.
|
||||
|
||||
@@ -342,16 +342,4 @@ mod tests {
|
||||
assert_eq!(error_message(&msg), "cannot find a.py");
|
||||
assert_eq!(error_message(&json!({"message": "nope"})), "nope");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_launch_response_keeps_delves_too_old_error_verbatim() {
|
||||
// The UI's repair offer keys off this exact wording (`missingAdapter`), so the
|
||||
// conversion to the IPC error must not fold it into a generic message.
|
||||
let message = "Failed to launch /p/api: Version of Delve is too old for Go version go1.27.0 \
|
||||
(maximum supported version 1.26, suppress this error with --check-go-version=false)";
|
||||
let e = ide_core::IdeError::from(DapError::Failed { command: "launch".into(), message: message.into() });
|
||||
assert_eq!(e.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
assert_eq!(e.message, format!("launch failed: {message}"));
|
||||
assert!(e.message.contains("Version of Delve is too old for Go version go1.27.0"));
|
||||
}
|
||||
}
|
||||
@@ -136,19 +136,24 @@ pub struct DockerRegistry {
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DockerSettings {
|
||||
#[serde(default)]
|
||||
#[serde(default = "default_connections")]
|
||||
pub connections: Vec<DockerConnection>,
|
||||
#[serde(default)]
|
||||
pub registries: Vec<DockerRegistry>,
|
||||
}
|
||||
|
||||
/// Whether `c` is the connection older versions injected when nothing was configured:
|
||||
/// Services lists only connections the user added, so this one is dropped on load.
|
||||
fn is_injected_default(c: &DockerConnection) -> bool {
|
||||
c.id == "default" && c.name == "Docker" && c.endpoint == DockerEndpoint::Default
|
||||
impl Default for DockerSettings {
|
||||
fn default() -> Self {
|
||||
Self { connections: default_connections(), registries: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Before anything is configured the CLI's own daemon is shown, as before connections existed.
|
||||
fn default_connections() -> Vec<DockerConnection> {
|
||||
vec![DockerConnection { id: "default".into(), name: "Docker".into(), endpoint: DockerEndpoint::Default }]
|
||||
}
|
||||
|
||||
const SETTINGS_FILE: &str = "docker.json";
|
||||
@@ -156,17 +161,10 @@ const PASSWORDS_FILE: &str = "docker-passwords.json";
|
||||
|
||||
pub fn load_settings(data_dir: &Path) -> DockerSettings {
|
||||
match std::fs::read(data_dir.join(SETTINGS_FILE)) {
|
||||
// A file written before the opt-in Services rework carries the injected default
|
||||
// (saved along with a registry or another connection); drop it unless edited.
|
||||
Ok(bytes) => serde_json::from_slice(&bytes)
|
||||
.map(|mut s: DockerSettings| {
|
||||
s.connections.retain(|c| !is_injected_default(c));
|
||||
s
|
||||
})
|
||||
.unwrap_or_else(|e| {
|
||||
tracing::warn!("{SETTINGS_FILE}: {e}");
|
||||
DockerSettings::default()
|
||||
}),
|
||||
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
|
||||
tracing::warn!("{SETTINGS_FILE}: {e}");
|
||||
DockerSettings::default()
|
||||
}),
|
||||
Err(_) => DockerSettings::default(),
|
||||
}
|
||||
}
|
||||
@@ -375,8 +373,7 @@ mod tests {
|
||||
fn settings_round_trip_and_passwords() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
// Nothing configured: no connection is invented.
|
||||
assert!(load_settings(dir).connections.is_empty());
|
||||
assert_eq!(load_settings(dir).connections[0].endpoint, DockerEndpoint::Default);
|
||||
let settings = DockerSettings {
|
||||
connections: vec![DockerConnection {
|
||||
id: "c1".into(),
|
||||
@@ -398,32 +395,8 @@ mod tests {
|
||||
assert!(auth_for(dir, "postgres").is_none());
|
||||
save_settings(dir, &DockerSettings { registries: Vec::new(), ..settings }).unwrap();
|
||||
assert_eq!(registry_password(dir, "r1"), None);
|
||||
// An empty list stays empty.
|
||||
// An empty list stays empty (the default connection is only for a missing file).
|
||||
save_settings(dir, &DockerSettings { connections: Vec::new(), registries: Vec::new() }).unwrap();
|
||||
assert!(load_settings(dir).connections.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_drops_the_injected_default_connection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let injected =
|
||||
|| DockerConnection { id: "default".into(), name: "Docker".into(), endpoint: DockerEndpoint::Default };
|
||||
let registry =
|
||||
DockerRegistry { id: "r1".into(), name: "GHCR".into(), address: "ghcr.io".into(), username: "me".into() };
|
||||
// Saved untouched by an older version (e.g. along with a registry): dropped on load.
|
||||
save_settings(dir, &DockerSettings { connections: vec![injected()], registries: vec![registry.clone()] })
|
||||
.unwrap();
|
||||
let loaded = load_settings(dir);
|
||||
assert!(loaded.connections.is_empty());
|
||||
assert_eq!(loaded.registries, vec![registry]);
|
||||
// A connection the user renamed or re-pointed stays theirs.
|
||||
let renamed = DockerConnection { name: "Local engine".into(), ..injected() };
|
||||
save_settings(dir, &DockerSettings { connections: vec![renamed.clone()], registries: Vec::new() }).unwrap();
|
||||
assert_eq!(load_settings(dir).connections, vec![renamed]);
|
||||
let repointed =
|
||||
DockerConnection { endpoint: DockerEndpoint::Socket { path: "/var/run/docker.sock".into() }, ..injected() };
|
||||
save_settings(dir, &DockerSettings { connections: vec![repointed.clone()], registries: Vec::new() }).unwrap();
|
||||
assert_eq!(load_settings(dir).connections, vec![repointed]);
|
||||
}
|
||||
}
|
||||
@@ -352,22 +352,6 @@ pub struct IndexEntry {
|
||||
/// the IDE before showing it.
|
||||
#[serde(default)]
|
||||
pub icon: Option<PluginIcon>,
|
||||
/// Where to read more: the manifest's homepage, else the registry's source repository.
|
||||
#[serde(default)]
|
||||
pub homepage: Option<String>,
|
||||
/// This version's release notes (the manifest's `change-notes`).
|
||||
#[serde(default)]
|
||||
pub notes: Option<String>,
|
||||
/// Downloads of the plugin's packages, as counted by whoever serves them.
|
||||
#[serde(default)]
|
||||
pub downloads: Option<u64>,
|
||||
/// Picked by the marketplace's maintainers.
|
||||
#[serde(default)]
|
||||
pub featured: bool,
|
||||
/// Project-relative paths whose presence makes the plugin worth suggesting
|
||||
/// (`pom.xml`, `config/routes.rb`).
|
||||
#[serde(default)]
|
||||
pub suggest: Vec<String>,
|
||||
}
|
||||
|
||||
impl IndexEntry {
|
||||
@@ -701,33 +685,9 @@ mod tests {
|
||||
engine: "^1.0".into(),
|
||||
categories: Vec::new(),
|
||||
icon: None,
|
||||
homepage: None,
|
||||
notes: None,
|
||||
downloads: None,
|
||||
featured: false,
|
||||
suggest: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listing_details_are_optional() {
|
||||
let mut json = serde_json::to_value(entry("acme.a", "acme")).unwrap();
|
||||
for key in ["homepage", "notes", "downloads", "featured", "suggest"] {
|
||||
json.as_object_mut().unwrap().remove(key);
|
||||
}
|
||||
assert_eq!(serde_json::from_value::<IndexEntry>(json).unwrap(), entry("acme.a", "acme"));
|
||||
let full = IndexEntry {
|
||||
homepage: Some("https://example.com".into()),
|
||||
notes: Some("Fixes".into()),
|
||||
downloads: Some(42),
|
||||
featured: true,
|
||||
suggest: vec!["pom.xml".into()],
|
||||
..entry("acme.a", "acme")
|
||||
};
|
||||
let back: IndexEntry = serde_json::from_str(&serde_json::to_string(&full).unwrap()).unwrap();
|
||||
assert_eq!(back, full);
|
||||
}
|
||||
|
||||
fn version(id: &str, version: &str, engine: &str) -> IndexEntry {
|
||||
IndexEntry { version: version.into(), engine: engine.into(), ..entry(id, "acme") }
|
||||
}
|
||||
|
||||
@@ -653,11 +653,6 @@ fn cmd_index(args: &[String]) -> Result<(), String> {
|
||||
engine: package::engine_requirement(&m.engine, built_for.as_ref()),
|
||||
categories: m.categories(),
|
||||
icon: plugin_icon(&ide_extension::Package::new(m.clone(), scratch.clone()))?,
|
||||
homepage: m.homepage.clone().filter(|h| !h.trim().is_empty()),
|
||||
notes: m.change_notes.clone().filter(|n| !n.trim().is_empty()),
|
||||
downloads: None,
|
||||
featured: false,
|
||||
suggest: Vec::new(),
|
||||
})
|
||||
})();
|
||||
let entry = entry.map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
|
||||
@@ -51,12 +51,7 @@ impl Call {
|
||||
pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> {
|
||||
self.host.mcp_requests.ask(self, request).await
|
||||
}
|
||||
/// Asks the user before a tool changes the project or starts a process, unless brave mode
|
||||
/// is on — read from the IDE's own settings only, which a project's settings can't set.
|
||||
pub async fn confirm(&self, subject: &str, detail: Option<String>) -> IdeResult<()> {
|
||||
if self.host.global_settings.effective().mcp_server.run_without_confirmation {
|
||||
return self.project.require_trust();
|
||||
}
|
||||
self.ask(ide_core::event::McpUiRequest::Confirm {
|
||||
client: self.client.clone(),
|
||||
tool: self.tool.clone(),
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::rpc::Dispatcher;
|
||||
use ide_core::{DocId, IdeError, IdeResult, OutlineItem, Range};
|
||||
use ide_language::{FoldRange, SyntaxHighlights};
|
||||
use ide_text::LineEnding;
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, HistoryEntry};
|
||||
use ide_workspace::{DocumentInfo, HistoryEntry};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Runs blocking work (disk I/O, parsing, large copies) on the blocking pool,
|
||||
@@ -29,24 +29,18 @@ pub async fn doc_ui_mode(host: &Host, window: &str, path: PathBuf) -> IdeResult<
|
||||
blocking(move || Ok(project.documents.ui_mode_of(&path))).await
|
||||
}
|
||||
|
||||
/// "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding and BOM state.
|
||||
/// "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding label.
|
||||
pub async fn doc_set_encoding(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
encoding: String,
|
||||
reload: bool,
|
||||
) -> IdeResult<DocumentEncoding> {
|
||||
) -> IdeResult<String> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.set_encoding(doc, &encoding, reload)).await
|
||||
}
|
||||
|
||||
/// Adds or removes the BOM on a UTF-8 document; the change is written on save.
|
||||
pub async fn doc_set_bom(host: &Host, window: &str, doc: DocId, has_bom: bool) -> IdeResult<DocumentEncoding> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.set_bom(doc, has_bom)).await
|
||||
}
|
||||
|
||||
pub fn doc_set_line_ending(host: &Host, window: &str, doc: DocId, line_ending: LineEnding) -> IdeResult<()> {
|
||||
host.project(window)?.documents.set_line_ending(doc, line_ending)
|
||||
}
|
||||
@@ -181,7 +175,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("doc_set_encoding", |c| async move {
|
||||
doc_set_encoding(&c.host, &c.window, c.arg("doc")?, c.arg("encoding")?, c.arg("reload")?).await
|
||||
});
|
||||
d.add("doc_set_bom", |c| async move { doc_set_bom(&c.host, &c.window, c.arg("doc")?, c.arg("hasBom")?).await });
|
||||
d.add("doc_set_line_ending", |c| async move {
|
||||
blocking(move || doc_set_line_ending(&c.host, &c.window, c.arg("doc")?, c.arg("lineEnding")?)).await
|
||||
});
|
||||
|
||||
@@ -71,12 +71,6 @@ pub trait PluginWorkspace: Send + Sync {
|
||||
|
||||
/// Roots of the open projects.
|
||||
fn projects(&self) -> Vec<PathBuf>;
|
||||
/// Roots of the workspace members attached to the project at `root` (a
|
||||
/// project window group's folders, as the editor and LSP resolve them).
|
||||
/// Empty for a plain project.
|
||||
fn member_roots(&self, _root: &Path) -> Vec<PathBuf> {
|
||||
Vec::new()
|
||||
}
|
||||
/// Unsaved text of the open document at `path`.
|
||||
fn buffer_text(&self, path: &Path) -> Option<String>;
|
||||
/// A window's unsaved text, with the normal project overlay as fallback.
|
||||
@@ -2025,10 +2019,6 @@ impl HostApi for PluginApi {
|
||||
self.shared.workspace().map(|w| w.projects()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn member_roots(&self, root: &Path) -> Vec<PathBuf> {
|
||||
self.shared.workspace().map(|w| w.member_roots(root)).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn buffer_text(&self, path: &Path) -> Option<String> {
|
||||
self.shared.workspace()?.buffer_text(path)
|
||||
}
|
||||
@@ -2169,29 +2159,23 @@ impl HostApi for PluginApi {
|
||||
out.sort();
|
||||
return Ok(out);
|
||||
}
|
||||
// A project window group's members are project scope too (their files
|
||||
// are in the group's index, and a group root holds none of them).
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(self.member_roots(root));
|
||||
let mut out = Vec::new();
|
||||
'walk: for root in &roots {
|
||||
for (n, entry) in ignore::WalkBuilder::new(root)
|
||||
.hidden(false)
|
||||
.filter_entry(|e| e.file_name() != ".git")
|
||||
.build()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
{
|
||||
if n >= MAX_WALK || out.len() >= limit {
|
||||
break 'walk;
|
||||
}
|
||||
if !entry.file_type().is_some_and(|t| t.is_file()) {
|
||||
continue;
|
||||
}
|
||||
let Ok(rel) = entry.path().strip_prefix(root) else { continue };
|
||||
if matcher.is_match(rel) {
|
||||
out.push(to_ipc(entry.path()));
|
||||
}
|
||||
for (n, entry) in ignore::WalkBuilder::new(root)
|
||||
.hidden(false)
|
||||
.filter_entry(|e| e.file_name() != ".git")
|
||||
.build()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
{
|
||||
if n >= MAX_WALK || out.len() >= limit {
|
||||
break;
|
||||
}
|
||||
if !entry.file_type().is_some_and(|t| t.is_file()) {
|
||||
continue;
|
||||
}
|
||||
let Ok(rel) = entry.path().strip_prefix(root) else { continue };
|
||||
if matcher.is_match(rel) {
|
||||
out.push(to_ipc(entry.path()));
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
@@ -2908,26 +2892,11 @@ impl HostWorkspace {
|
||||
.and_then(|w| host.project(w).ok())
|
||||
.filter(|p| p.root == root)
|
||||
.or_else(|| host.windows_for_root(root).first().and_then(|w| host.project(w).ok()))
|
||||
// A project window group's member root: its files belong to the
|
||||
// group's project, like everywhere else in the editor.
|
||||
.or_else(|| {
|
||||
host.projects()
|
||||
.into_iter()
|
||||
.find(|p| crate::project::workspace_member_roots(&p.root).iter().any(|m| m.as_path() == root))
|
||||
})
|
||||
}
|
||||
fn projects(&self) -> Vec<Arc<crate::project::Project>> {
|
||||
self.0.upgrade().map(|h| h.projects()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The open project whose workspace group contains `root` (the group root
|
||||
/// itself matches `p.root == root` and needs no member lookup).
|
||||
fn project_covering(&self, root: &Path) -> Option<Arc<crate::project::Project>> {
|
||||
self.projects().into_iter().find(|p| {
|
||||
p.root == root || crate::project::workspace_member_roots(&p.root).iter().any(|m| m.as_path() == root)
|
||||
})
|
||||
}
|
||||
|
||||
/// The project holding an open document at `path`, and its id.
|
||||
fn open_document(&self, path: &Path) -> Option<(Arc<crate::project::Project>, ide_core::DocId)> {
|
||||
self.projects().into_iter().find_map(|p| p.documents.by_path(path).map(|doc| (p, doc)))
|
||||
@@ -3017,10 +2986,6 @@ impl PluginWorkspace for HostWorkspace {
|
||||
) -> Result<ide_plugin::TextSearch, HostError> {
|
||||
let host = self.0.upgrade().ok_or(HostError::Cancelled)?;
|
||||
let project = self.project_for(client, root).ok_or_else(|| HostError::NotFound("project closed".into()))?;
|
||||
// Matches must land in the project root or, for a project window group,
|
||||
// in any of its members.
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(crate::project::workspace_member_roots(root));
|
||||
if limit == 0 {
|
||||
return Ok(ide_plugin::TextSearch::default());
|
||||
}
|
||||
@@ -3050,9 +3015,8 @@ impl PluginWorkspace for HostWorkspace {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(HostError::Cancelled);
|
||||
}
|
||||
// Restrict project.read to the project root and its workspace
|
||||
// members, including symlink targets.
|
||||
let Ok(path) = ide_plugin::resolve_in_roots(&roots, &to_ipc(&file.path.0)) else {
|
||||
// Restrict project.read to the project root, including symlink targets.
|
||||
let Ok(path) = ide_plugin::resolve_in_root(root, &to_ipc(&file.path.0)) else {
|
||||
continue;
|
||||
};
|
||||
let text = project.documents.text_of(&path).or_else(|| {
|
||||
@@ -3118,19 +3082,12 @@ impl PluginWorkspace for HostWorkspace {
|
||||
}
|
||||
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
let mut roots: Vec<PathBuf> = HostWorkspace::projects(self)
|
||||
.iter()
|
||||
.flat_map(|p| std::iter::once(p.root.clone()).chain(crate::project::workspace_member_roots(&p.root)))
|
||||
.collect();
|
||||
let mut roots: Vec<PathBuf> = HostWorkspace::projects(self).iter().map(|p| p.root.clone()).collect();
|
||||
roots.sort();
|
||||
roots.dedup();
|
||||
roots
|
||||
}
|
||||
|
||||
fn member_roots(&self, root: &Path) -> Vec<PathBuf> {
|
||||
crate::project::workspace_member_roots(root)
|
||||
}
|
||||
|
||||
fn buffer_text(&self, path: &Path) -> Option<String> {
|
||||
HostWorkspace::projects(self).iter().find_map(|p| p.documents.text_of(path))
|
||||
}
|
||||
@@ -3141,9 +3098,9 @@ impl PluginWorkspace for HostWorkspace {
|
||||
}
|
||||
|
||||
fn indexed_files(&self, root: &Path, matches: &dyn Fn(&Path) -> bool, limit: usize) -> Option<Vec<PathBuf>> {
|
||||
// The index covering `root`: the project rooted there, or the workspace
|
||||
// group project whose member it is (a member's files are in the group's).
|
||||
HostWorkspace::project_covering(self, root)?.index.files_matching(root, matches, limit)
|
||||
// The index of the project rooted at `root` (a workspace member's files are in its own).
|
||||
let project = HostWorkspace::projects(self).into_iter().find(|p| p.root == root)?;
|
||||
project.index.files_matching(root, matches, limit)
|
||||
}
|
||||
|
||||
fn symbols(
|
||||
@@ -3154,7 +3111,9 @@ impl PluginWorkspace for HostWorkspace {
|
||||
cancel: &CancellationToken,
|
||||
deadline: Instant,
|
||||
) -> Result<Vec<ide_plugin::SymbolInfo>, HostError> {
|
||||
let project = HostWorkspace::project_covering(self, root)
|
||||
let project = HostWorkspace::projects(self)
|
||||
.into_iter()
|
||||
.find(|p| p.root == root)
|
||||
.ok_or_else(|| HostError::NotFound("the project is no longer open".into()))?;
|
||||
let stopped = || cancel.is_cancelled() || Instant::now() >= deadline;
|
||||
let interrupted = || {
|
||||
@@ -3164,13 +3123,15 @@ impl PluginWorkspace for HostWorkspace {
|
||||
HostError::Failed("symbol search timed out".into())
|
||||
}
|
||||
};
|
||||
// The symbols of the requested root and, for a project window group, of
|
||||
// its members (a member's symbols are in the group's index).
|
||||
let members = crate::project::workspace_member_roots(root);
|
||||
let in_scope = |path: &Path| path.starts_with(root) || members.iter().any(|m| path.starts_with(m));
|
||||
let symbols = project
|
||||
.index
|
||||
.find_symbols_until(query, ide_index::SymbolFilter::All, limit.min(1000), &in_scope, &stopped)
|
||||
.find_symbols_until(
|
||||
query,
|
||||
ide_index::SymbolFilter::All,
|
||||
limit.min(1000),
|
||||
&|path| path.starts_with(root),
|
||||
&stopped,
|
||||
)
|
||||
.ok_or_else(interrupted)?;
|
||||
let mut out = Vec::new();
|
||||
for s in symbols {
|
||||
@@ -3212,8 +3173,7 @@ impl PluginWorkspace for HostWorkspace {
|
||||
}
|
||||
|
||||
fn trusted(&self, root: &Path) -> bool {
|
||||
// A workspace member is as trusted as the group's project it was opened with.
|
||||
HostWorkspace::project_covering(self, root).is_some_and(|p| p.is_trusted())
|
||||
HostWorkspace::projects(self).iter().any(|p| p.root == root && p.is_trusted())
|
||||
}
|
||||
|
||||
fn project_of(&self, window: &str) -> Option<PathBuf> {
|
||||
@@ -3238,12 +3198,6 @@ impl PluginWorkspace for HostWorkspace {
|
||||
.iter()
|
||||
.filter(|p| path.starts_with(&p.root))
|
||||
.max_by_key(|p| p.root.as_os_str().len())
|
||||
// A project window group's member files report through the group's project.
|
||||
.or_else(|| {
|
||||
projects
|
||||
.iter()
|
||||
.find(|p| crate::project::workspace_member_roots(&p.root).iter().any(|m| path.starts_with(m)))
|
||||
})
|
||||
.ok_or_else(|| HostError::Invalid(format!("{} is not in an open project", path.display())))?;
|
||||
project.sink.emit(ide_core::IdeEvent::Diagnostics {
|
||||
path: path.to_path_buf().into(),
|
||||
@@ -3258,25 +3212,15 @@ impl PluginWorkspace for HostWorkspace {
|
||||
.into_iter()
|
||||
.filter(|p| path.starts_with(&p.root))
|
||||
.max_by_key(|p| p.root.as_os_str().len())
|
||||
.or_else(|| {
|
||||
HostWorkspace::projects(self)
|
||||
.into_iter()
|
||||
.find(|p| crate::project::workspace_member_roots(&p.root).iter().any(|m| path.starts_with(m)))
|
||||
})
|
||||
.and_then(|p| p.vcs_encoding(path, None).ok())
|
||||
.unwrap_or_else(|| encoding_rs::UTF_8.into())
|
||||
}
|
||||
|
||||
fn plugin_settings(&self, plugin: &str, root: Option<&Path>) -> serde_json::Map<String, serde_json::Value> {
|
||||
let Some(host) = self.0.upgrade() else { return serde_json::Map::new() };
|
||||
// A member root reads the settings of the group's project, like the
|
||||
// group's own root does.
|
||||
let settings = match root.and_then(|r| host.projects().into_iter().find(|p| p.root == r)) {
|
||||
Some(p) => p.settings.effective(),
|
||||
None => match root.map(|r| HostWorkspace::project_covering(self, r)) {
|
||||
Some(Some(p)) => p.settings.effective(),
|
||||
_ => host.global_settings.effective(),
|
||||
},
|
||||
None => host.global_settings.effective(),
|
||||
};
|
||||
settings.plugins.get(plugin).cloned().unwrap_or_default()
|
||||
}
|
||||
@@ -3582,55 +3526,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A workspace whose container root has no files: the member holds them.
|
||||
struct Members(PathBuf, Vec<PathBuf>);
|
||||
impl PluginWorkspace for Members {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
vec![self.0.clone()]
|
||||
}
|
||||
fn member_roots(&self, root: &Path) -> Vec<PathBuf> {
|
||||
if root == self.0 { self.1.clone() } else { Vec::new() }
|
||||
}
|
||||
fn buffer_text(&self, _: &Path) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn document(&self, _: &Path) -> Option<(u64, String)> {
|
||||
None
|
||||
}
|
||||
fn apply_edits(&self, _: &Path, _: u64, _: &[TextEdit]) -> Result<u64, HostError> {
|
||||
Err(HostError::Stale)
|
||||
}
|
||||
fn trusted(&self, _: &Path) -> bool {
|
||||
true
|
||||
}
|
||||
fn project_of(&self, _: &str) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
fn publish_diagnostics(&self, _: &str, _: &Path, _: Vec<ide_core::Diagnostic>) -> Result<(), HostError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_files_cover_workspace_members() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (root, member) = (base.join("workspace"), base.join("member"));
|
||||
std::fs::create_dir_all(root.join(".openidea")).unwrap();
|
||||
std::fs::create_dir_all(member.join("src")).unwrap();
|
||||
std::fs::write(root.join(".openidea/workspace.json"), "{}").unwrap();
|
||||
std::fs::write(member.join("src/UserMapper.xml"), "<mapper/>").unwrap();
|
||||
let api = api(&root, Arc::default());
|
||||
*api.shared.workspace.write() = Some(Arc::new(Members(root.clone(), vec![member.clone()])));
|
||||
// The container holds no sources: the member's files are project scope.
|
||||
assert_eq!(api.find_files(&root, "**/*Mapper.xml", 10).unwrap(), [to_ipc(&member.join("src/UserMapper.xml"))]);
|
||||
// A member root lists its own files, like any project root.
|
||||
assert_eq!(api.find_files(&member, "src/*.xml", 10).unwrap(), [to_ipc(&member.join("src/UserMapper.xml"))]);
|
||||
// And a path outside the group is never listed.
|
||||
std::fs::write(base.join("OutsideMapper.xml"), "<mapper/>").unwrap();
|
||||
assert!(api.find_files(&root, "**/*Mapper.xml", 10).unwrap().len() == 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_environment_only_adds_variables() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -27,12 +27,8 @@ pub async fn plugin_navigation_files(
|
||||
if files.len() > 20_000 {
|
||||
return Err(IdeError::unavailable("plugin navigation supports up to 20,000 matching files"));
|
||||
}
|
||||
// A project window group's members are project scope: their files are
|
||||
// in the group's index (the group root holds none of them).
|
||||
let members = crate::project::workspace_member_roots(&project.root);
|
||||
let in_scope = |p: &PathBuf| p.starts_with(&project.root) || members.iter().any(|m| p.starts_with(m));
|
||||
Ok(NavigationFiles {
|
||||
paths: files.into_iter().filter(in_scope).map(Into::into).collect(),
|
||||
paths: files.into_iter().filter(|p| p.starts_with(&project.root)).map(Into::into).collect(),
|
||||
indexing,
|
||||
extensions,
|
||||
})
|
||||
@@ -68,14 +64,11 @@ pub async fn plugin_navigation_index(
|
||||
if !project.is_trusted() {
|
||||
return Err(IdeError::unavailable("project is not trusted"));
|
||||
}
|
||||
// A project window group's members are project scope.
|
||||
let mut roots = vec![project.root.clone()];
|
||||
roots.extend(crate::project::workspace_member_roots(&project.root));
|
||||
for path in paths {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let Ok(path) = ide_plugin::resolve_in_roots(&roots, &path.to_string_lossy()) else {
|
||||
let Ok(path) = ide_plugin::resolve_in_root(&project.root, &path.to_string_lossy()) else {
|
||||
continue;
|
||||
};
|
||||
let extensions = plugins.navigation_extensions(&project.root);
|
||||
|
||||
@@ -31,7 +31,6 @@ const MAX_STAGED_FILES: usize = 256;
|
||||
const MAX_STAGED_BYTES: usize = 16 << 20;
|
||||
/// `moved` links followed before giving up (a loop, or a misconfiguration).
|
||||
const MAX_MOVES: usize = 3;
|
||||
const MAX_SUGGESTIONS: usize = 8;
|
||||
|
||||
/// A marketplace entry with what is installed.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, specta::Type)]
|
||||
@@ -43,9 +42,6 @@ pub struct MarketPlugin {
|
||||
pub installed: Option<String>,
|
||||
/// Whether this IDE can load `entry` (the newest version it can, else the newest).
|
||||
pub compatible: bool,
|
||||
/// The publisher's display name, as the index lists it.
|
||||
#[serde(default)]
|
||||
pub publisher_name: Option<String>,
|
||||
}
|
||||
|
||||
impl MarketPlugin {
|
||||
@@ -80,19 +76,6 @@ fn safe_icon(icon: PluginIcon) -> Option<PluginIcon> {
|
||||
Some(PluginIcon { light: clean(icon.light)?, dark: icon.dark.and_then(clean) })
|
||||
}
|
||||
|
||||
/// Paths an index suggests a plugin for, as the UI may look them up: relative,
|
||||
/// inside the project, and few.
|
||||
fn safe_suggestions(paths: Vec<String>) -> Vec<String> {
|
||||
let ok = |p: &String| {
|
||||
!p.is_empty()
|
||||
&& p.len() <= 128
|
||||
&& !p.starts_with('/')
|
||||
&& !p.contains(['\\', ':', '\0', '*', '?'])
|
||||
&& p.split('/').all(|part| !matches!(part, "" | "." | ".."))
|
||||
};
|
||||
paths.into_iter().filter(ok).take(MAX_SUGGESTIONS).collect()
|
||||
}
|
||||
|
||||
/// Reads `url`: `http(s)://…`, `file://…` or a local path.
|
||||
pub fn read_url(url: &str, max: usize) -> Result<Vec<u8>, String> {
|
||||
if url.starts_with("https://") || url.starts_with("http://") {
|
||||
@@ -270,9 +253,7 @@ impl PluginHost {
|
||||
.map(|p| p.manifest().version.clone());
|
||||
let mut entry = entry.clone();
|
||||
entry.icon = entry.icon.and_then(safe_icon);
|
||||
entry.suggest = safe_suggestions(std::mem::take(&mut entry.suggest));
|
||||
let publisher_name = index.publishers.iter().find(|p| p.id == entry.publisher).map(|p| p.name.clone());
|
||||
MarketPlugin { entry, installed, compatible, publisher_name }
|
||||
MarketPlugin { entry, installed, compatible }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -501,11 +482,4 @@ mod tests {
|
||||
assert_eq!(resolve(r"C:\market\index.json", "a.oiplugin"), r"C:\market\a.oiplugin");
|
||||
assert_eq!(resolve("https://x.dev/index.json", "https://cdn.dev/a"), "https://cdn.dev/a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggestions_stay_inside_the_project() {
|
||||
let paths = ["pom.xml", "config/routes.rb", "/etc/passwd", "../x", "a//b", "C:x", "*.php", ""];
|
||||
assert_eq!(safe_suggestions(paths.iter().map(|p| p.to_string()).collect()), ["pom.xml", "config/routes.rb"]);
|
||||
assert_eq!(safe_suggestions(vec!["a".into(); 20]).len(), MAX_SUGGESTIONS);
|
||||
}
|
||||
}
|
||||
@@ -204,11 +204,7 @@ impl PluginHost {
|
||||
if text.len() > MAX_DOCUMENT_BYTES {
|
||||
return Err(IdeError::invalid("navigation document is too large"));
|
||||
}
|
||||
// A project window group's members are project scope: a member's file
|
||||
// is indexed into the group's graph like any file of the group root.
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(crate::project::workspace_member_roots(root));
|
||||
let real = ide_plugin::resolve_in_roots(&roots, &path.to_string_lossy()).map_err(IdeError::invalid)?;
|
||||
let real = ide_plugin::resolve_in_root(root, &path.to_string_lossy()).map_err(IdeError::invalid)?;
|
||||
if real != path {
|
||||
return Err(IdeError::invalid("navigation requires a canonical project path"));
|
||||
}
|
||||
|
||||
@@ -246,7 +246,6 @@ impl Host {
|
||||
&bundles,
|
||||
lombok.jar(),
|
||||
);
|
||||
ide_sdk::apply::configure_gradle_runtime(cfg, root, server_root, &effective);
|
||||
ide_sdk::jdtls::launch_directly(cfg);
|
||||
}
|
||||
ide_sdk::apply::server_protocol_overrides(cfg, &effective);
|
||||
@@ -1188,19 +1187,6 @@ fn index_roots(root: &Path, folders: Vec<PathBuf>) -> ide_index::IndexRoots {
|
||||
ide_index::IndexRoots { include_root: !container, folders: folders.into_iter().filter(|p| p != root).collect() }
|
||||
}
|
||||
|
||||
/// The member roots of an explicit workspace container (empty for a plain
|
||||
/// project): how the editor and the language servers resolve a file's own
|
||||
/// project in a project window group. Also the roots the plugin surface may
|
||||
/// reach into — see `plugins::api`.
|
||||
pub(crate) fn workspace_member_roots(root: &Path) -> Vec<PathBuf> {
|
||||
ide_workspace::workspace::Workspace::load(root)
|
||||
.ok()
|
||||
.flatten()
|
||||
.filter(|w| w.is_container(root))
|
||||
.map(|w| w.projects)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Workspace members in manifest order, or extra Project Structure directories and the
|
||||
/// Gradle project folders outside the project as of the last sync (`build_cache`).
|
||||
fn content_roots(settings: &ide_core::settings::Settings, root: &Path, build_cache: &Path) -> Vec<PathBuf> {
|
||||
|
||||
@@ -177,11 +177,6 @@ fn signed(
|
||||
engine: "^1.0".into(),
|
||||
categories: vec!["tools".into()],
|
||||
icon: None,
|
||||
homepage: None,
|
||||
notes: None,
|
||||
downloads: None,
|
||||
featured: false,
|
||||
suggest: vec![],
|
||||
};
|
||||
(out, entry)
|
||||
}
|
||||
|
||||
@@ -416,40 +416,3 @@ async fn rust_references_and_rename_through_mcp() {
|
||||
assert!(project.documents.text_snapshot(doc.id).unwrap().text.contains("format_amount"));
|
||||
assert!(std::fs::read_to_string(h.root.join("src/main.rs")).unwrap().contains("format_amount"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn brave_mode_runs_tools_without_asking_only_from_the_global_settings() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let p = h.host.project("main").unwrap();
|
||||
// A project's own settings can't turn the confirmations off.
|
||||
let project_layer =
|
||||
p.settings.set(ide_workspace::SettingsScope::Project, "mcpServer.runWithoutConfirmation", json!(true));
|
||||
assert!(project_layer.is_err());
|
||||
let denied = h.error("build_project", json!({}));
|
||||
let answer = async {
|
||||
let id = h.request().await;
|
||||
h.host.mcp_requests.answer("main", id, false, None).unwrap();
|
||||
};
|
||||
let (error, ()) = tokio::join!(denied, answer);
|
||||
assert!(error.contains("denied by the user"), "{error}");
|
||||
|
||||
h.events.lock().unwrap().clear();
|
||||
h.host
|
||||
.global_settings
|
||||
.set(ide_workspace::SettingsScope::Global, "mcpServer.runWithoutConfirmation", json!(true))
|
||||
.unwrap();
|
||||
let (host, root) = (h.host.clone(), h.root.clone());
|
||||
let result = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(60),
|
||||
tokio::task::spawn_blocking(move || {
|
||||
Registry::new(host).call(&root, "build_project", "{}", CancellationToken::new())
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.expect("ran without waiting for an answer")
|
||||
.unwrap();
|
||||
assert!(!format!("{result:?}").contains("denied"), "{result:?}");
|
||||
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
|
||||
}
|
||||
@@ -8,7 +8,6 @@
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::ipc_path::to_ipc;
|
||||
use ide_host::plugins::*;
|
||||
use ide_host::{Host, HostConfig};
|
||||
use ide_plugin::{EditorContext, HostError, Invocation, Limits};
|
||||
use parking_lot::Mutex;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -6336,241 +6335,3 @@ fn api14_stage3_terminal_calls_are_denied_without_process_grants() {
|
||||
f.host.set_capability("execution", "process:execution-tool", false).unwrap();
|
||||
assert!(f.run("execution", "terminal", None).unwrap_err().contains("not granted"));
|
||||
}
|
||||
|
||||
// ─── Project window groups ────────────────────────────────────────────────────
|
||||
// A group's container root holds only `.openidea` metadata; the files live in
|
||||
// the member projects. The plugin surface reaches them like the editor and the
|
||||
// language servers do.
|
||||
|
||||
/// A real host over a project window group with the members `alpha` (holding a
|
||||
/// nested `inner` member, for deepest resolution) and `beta`.
|
||||
struct GroupFixture {
|
||||
base: PathBuf,
|
||||
host: Arc<Host>,
|
||||
plugins: Arc<PluginHost>,
|
||||
root: PathBuf,
|
||||
alpha: PathBuf,
|
||||
inner: PathBuf,
|
||||
beta: PathBuf,
|
||||
_runtime: tokio::runtime::Runtime,
|
||||
_tmp: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl GroupFixture {
|
||||
fn new() -> Self {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (root, alpha, beta) = (base.join("workspace"), base.join("alpha"), base.join("beta"));
|
||||
let inner = alpha.join("inner");
|
||||
for dir in [alpha.join("src"), inner.join("mappers"), beta.join("src")] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
ide_workspace::workspace::Workspace::save(
|
||||
&root,
|
||||
"Group",
|
||||
vec![alpha.clone(), inner.clone(), beta.clone()],
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(alpha.join("src/needle.php"), "alpha needle\n").unwrap();
|
||||
std::fs::write(inner.join("mappers/route.idx"), "def route:item\nref route:item\n").unwrap();
|
||||
std::fs::write(beta.join("src/Notes.txt"), "beta needle\n").unwrap();
|
||||
std::fs::write(base.join("secret.txt"), "top secret").unwrap();
|
||||
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: runtime.handle().clone(),
|
||||
project_environment: false,
|
||||
}));
|
||||
for dir in [&root, &alpha, &beta] {
|
||||
host.trust.decide(dir, true, false).unwrap();
|
||||
}
|
||||
{
|
||||
let _guard = runtime.enter();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
assert!(project.index.wait_idle(Duration::from_secs(30)));
|
||||
}
|
||||
let plugins = Arc::new(
|
||||
PluginHost::new(base.join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(),
|
||||
);
|
||||
plugins.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host)))));
|
||||
plugins.set_project_policy(Arc::new(|_| true));
|
||||
Self { base, host, plugins, root, alpha, inner, beta, _runtime: runtime, _tmp: tmp }
|
||||
}
|
||||
|
||||
/// Runs an installed plugin's `command` with `root` (default: the group
|
||||
/// container) as the invoking project.
|
||||
fn run(&self, id: &str, command: &str, arg: Option<&str>, root: Option<&Path>) -> Result<Option<String>, String> {
|
||||
let inv = Invocation {
|
||||
client: Some("main".into()),
|
||||
workspace_root: Some(dunce::canonicalize(root.unwrap_or(&self.root)).unwrap()),
|
||||
..Default::default()
|
||||
};
|
||||
self.plugins.run_command(id, command, arg, inv).map_err(|e| e.message)
|
||||
}
|
||||
|
||||
/// Installs `dir` with everything granted.
|
||||
fn install(&self, dir: &Path) {
|
||||
self.plugins.install_from_dir(dir, &Consent::all()).unwrap();
|
||||
}
|
||||
|
||||
/// The roots the plugin surface lists, sorted and deduplicated.
|
||||
fn listed_roots(&self) -> Vec<PathBuf> {
|
||||
HostWorkspace(Arc::downgrade(&self.host)).projects()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for GroupFixture {
|
||||
fn drop(&mut self) {
|
||||
self.host.close_project("main");
|
||||
}
|
||||
}
|
||||
|
||||
/// `projects()` lists the members with their own roots, and the member roots of
|
||||
/// the container are exactly the workspace manifest's.
|
||||
#[test]
|
||||
fn projects_list_the_workspace_members() {
|
||||
let f = GroupFixture::new();
|
||||
assert_eq!(
|
||||
f.listed_roots(),
|
||||
[f.alpha.clone(), f.inner.clone(), f.beta.clone(), f.root.clone()]
|
||||
.iter()
|
||||
.map(|p| dunce::canonicalize(p).unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(
|
||||
HostWorkspace(Arc::downgrade(&f.host)).member_roots(&f.root),
|
||||
[f.alpha.clone(), f.inner.clone(), f.beta.clone()]
|
||||
.iter()
|
||||
.map(|p| dunce::canonicalize(p).unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
// A member has no members of its own.
|
||||
assert!(HostWorkspace(Arc::downgrade(&f.host)).member_roots(&f.alpha).is_empty());
|
||||
}
|
||||
|
||||
/// `project-of(path)` resolves to the deepest member project containing the
|
||||
/// path, where the container and every member appear.
|
||||
#[test]
|
||||
fn project_of_resolves_to_the_deepest_workspace_member() {
|
||||
let f = GroupFixture::new();
|
||||
f.install(&sample("path-events"));
|
||||
let project =
|
||||
|path: &Path| f.run("test.path-events", "project", Some(path.to_str().unwrap()), None).unwrap().unwrap();
|
||||
assert_eq!(project(&f.alpha.join("src/needle.php")), to_ipc(&f.alpha));
|
||||
// The nested member, not its containing member.
|
||||
assert_eq!(project(&f.inner.join("mappers/route.idx")), to_ipc(&f.inner));
|
||||
assert_eq!(project(&f.beta.join("src/Notes.txt")), to_ipc(&f.beta));
|
||||
// The container itself is still a project.
|
||||
assert_eq!(project(&f.root), to_ipc(&f.root));
|
||||
// And a path in no project resolves to none.
|
||||
assert!(
|
||||
f.run("test.path-events", "project", Some(f.base.join("secret.txt").to_str().unwrap()), None)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
/// `project.read` and `project.write` reach the member files through the
|
||||
/// group's project, and never leave the group's roots.
|
||||
#[test]
|
||||
fn project_reads_and_writes_reach_workspace_members() {
|
||||
let f = GroupFixture::new();
|
||||
f.install(&misbehave_with(f._tmp.path(), "misbehave-group-writer", "project.write"));
|
||||
let notes = f.beta.join("src/Notes.txt");
|
||||
assert_eq!(f.run("misbehave", "read", Some(notes.to_str().unwrap()), None).unwrap().unwrap(), "beta needle\n");
|
||||
// Writing into a member creates its missing parent directories.
|
||||
let fresh = f.beta.join("src/generated/mapper.xml");
|
||||
f.run("misbehave", "projwrite", Some(fresh.to_str().unwrap()), None).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&fresh).unwrap(), "written inside the project\n");
|
||||
// `ctx.project()` is still the group's project.
|
||||
assert_eq!(f.run("misbehave", "root", None, None).unwrap().unwrap(), to_ipc(&f.root));
|
||||
// What is outside every root of the group stays refused, unwritten.
|
||||
let outside = f.base.join("secret.txt");
|
||||
let err = f.run("misbehave", "read", Some(outside.to_str().unwrap()), None).unwrap_err();
|
||||
assert!(err.contains("outside the project root"), "{err}");
|
||||
let err = f.run("misbehave", "projwrite", Some(outside.to_str().unwrap()), None).unwrap_err();
|
||||
assert!(err.contains("outside the project root"), "{err}");
|
||||
assert_eq!(std::fs::read_to_string(outside).unwrap(), "top secret");
|
||||
// A member-scoped project reads its own files only: its root is the member.
|
||||
assert_eq!(f.run("misbehave", "read", Some("src/Notes.txt"), Some(&f.beta)).unwrap().unwrap(), "beta needle\n");
|
||||
}
|
||||
|
||||
/// Find in Files covers the members: search from the container finds member
|
||||
/// matches, a member-scoped project sees only its own.
|
||||
#[test]
|
||||
fn project_search_reaches_workspace_members() {
|
||||
let f = GroupFixture::new();
|
||||
f.install(&sample("api14"));
|
||||
let search = |root: &Path, needle: &str| f.run("api14", "search-text", Some(needle), Some(root)).unwrap().unwrap();
|
||||
// From the container: matches in the members come through.
|
||||
let all = search(&f.root, "needle");
|
||||
assert!(all.contains("needle.php"), "{all}");
|
||||
assert!(all.contains("Notes.txt"), "{all}");
|
||||
// The container holds no sources: `.openidea` metadata never matches.
|
||||
assert!(!all.contains("workspace.json"), "{all}");
|
||||
// From a member: only that member's matches.
|
||||
let own = search(&f.beta, "needle");
|
||||
assert!(own.contains("Notes.txt"), "{own}");
|
||||
assert!(!own.contains("needle.php"), "{own}");
|
||||
// What is outside every root is never found.
|
||||
assert!(!search(&f.root, "top secret").contains("secret.txt"));
|
||||
}
|
||||
|
||||
/// The document-indexer covers member files: discovery offers them, indexing
|
||||
/// one publishes its navigation, and files outside the group stay out.
|
||||
#[test]
|
||||
fn document_indexer_covers_workspace_members() {
|
||||
let f = GroupFixture::new();
|
||||
f.install(&sample("indexer"));
|
||||
let mapping = f.inner.join("mappers/route.idx");
|
||||
// Discovery: the member file is in the window's project scope.
|
||||
let files = f
|
||||
._runtime
|
||||
.block_on(ide_host::plugins::index_ops::plugin_navigation_files(&f.host, f.plugins.clone(), "main"))
|
||||
.unwrap();
|
||||
assert!(files.paths.iter().any(|p| p.0 == mapping), "{:?}", files.paths);
|
||||
// Indexing the member file through the window's project publishes it: the
|
||||
// open document is indexed at its version, like an editor click resolves.
|
||||
let project = f.host.project("main").unwrap();
|
||||
let doc = project.documents.open(&mapping).unwrap();
|
||||
f._runtime
|
||||
.block_on(ide_host::plugins::index_ops::plugin_navigation_index(
|
||||
&f.host,
|
||||
f.plugins.clone(),
|
||||
"main",
|
||||
vec![mapping.clone()],
|
||||
ide_core::RequestId::next(),
|
||||
))
|
||||
.unwrap();
|
||||
let result = f
|
||||
.plugins
|
||||
.navigation_at(&f.root, &mapping, doc.version, ide_core::Pos::new(1, 5), Some("main"), |_| None)
|
||||
.unwrap();
|
||||
assert_eq!(result.targets[0].path.0, mapping);
|
||||
// A file outside the group is never offered, and indexing skips it.
|
||||
let outside = f.base.join("escape.idx");
|
||||
std::fs::write(&outside, "def outside:item\n").unwrap();
|
||||
let files = f
|
||||
._runtime
|
||||
.block_on(ide_host::plugins::index_ops::plugin_navigation_files(&f.host, f.plugins.clone(), "main"))
|
||||
.unwrap();
|
||||
assert!(!files.paths.iter().any(|p| p.0 == outside), "{:?}", files.paths);
|
||||
f._runtime
|
||||
.block_on(ide_host::plugins::index_ops::plugin_navigation_index(
|
||||
&f.host,
|
||||
f.plugins.clone(),
|
||||
"main",
|
||||
vec![outside.clone()],
|
||||
ide_core::RequestId::next(),
|
||||
))
|
||||
.unwrap();
|
||||
assert!(f.plugins.navigation_at(&f.root, &outside, 1, ide_core::Pos::new(0, 4), Some("main"), |_| None).is_none());
|
||||
}
|
||||
@@ -33,7 +33,6 @@ mod tsserver_bridge;
|
||||
pub mod types;
|
||||
mod uri;
|
||||
mod virtual_doc;
|
||||
mod vue_navigation;
|
||||
|
||||
pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES};
|
||||
pub use inspect::{FileInspection, InspectHost, InspectOptions};
|
||||
@@ -844,7 +843,6 @@ impl LspManager {
|
||||
self.schedule_pull(doc, Some(&server), Duration::ZERO);
|
||||
}
|
||||
self.check_clang_tidy(&server).await;
|
||||
self.check_vue_navigation(&server).await;
|
||||
server.refresh_busy_status(&self.sink);
|
||||
server.announce_ready(generation);
|
||||
self.spawn_supervisor(server, generation, peer);
|
||||
@@ -1062,11 +1060,8 @@ impl LspManager {
|
||||
if s.name == compose::SERVER && compose_added {
|
||||
me.reconfigure_soon();
|
||||
}
|
||||
let hint = me.clone();
|
||||
let server = s.clone();
|
||||
self.runtime.spawn(async move { me.check_clang_tidy(&server).await });
|
||||
let server = s.clone();
|
||||
self.runtime.spawn(async move { hint.check_vue_navigation(&server).await });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,182 +0,0 @@
|
||||
//! Vue 2 (Options API) template navigation: without `strictFunctionTypes`, the Vue 2.7
|
||||
//! types infer `methods` / `computed` on `this` as `any`, so `textDocument/definition`
|
||||
//! and hover in templates resolve to nothing (vuejs/language-tools#5257). The bundled
|
||||
//! server can serve Vue 2.7 fine once the option is on (see #1164).
|
||||
|
||||
use crate::{LspManager, Server};
|
||||
use ide_core::IdeEvent;
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) const SERVER: &str = "vue-language-server";
|
||||
|
||||
pub(crate) const MESSAGE: &str = "Vue 2 (Options API) template navigation needs 'strictFunctionTypes': true (or 'strict': true) in the compilerOptions of jsconfig.json / tsconfig.json — without it the Vue 2.7 types infer methods and computed on this as any, so jump-to-definition and hover in templates resolve to nothing. Add the option (create jsconfig.json if the project has none), then reopen the file or restart the language server.";
|
||||
|
||||
impl LspManager {
|
||||
pub(crate) async fn check_vue_navigation(&self, server: &Server) {
|
||||
if server.name != SERVER || self.shown_messages.lock().contains(&(SERVER.into(), MESSAGE.into())) {
|
||||
return;
|
||||
}
|
||||
let Some(file) = self
|
||||
.docs
|
||||
.lock()
|
||||
.values()
|
||||
.find(|doc| {
|
||||
doc.language.as_str() == "vue" && doc.servers.iter().any(|attached| attached.server.id == server.id)
|
||||
})
|
||||
.map(|doc| doc.path.clone())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let root = self.project_root_for(&file);
|
||||
let Some(me) = self.me.upgrade() else { return };
|
||||
let _ = tokio::task::spawn_blocking(move || {
|
||||
if vue2_project(&root)
|
||||
&& missing_strict_function_types(&root)
|
||||
&& !me.shutting_down.load(std::sync::atomic::Ordering::Acquire)
|
||||
&& me.first_message(SERVER, MESSAGE)
|
||||
{
|
||||
me.sink.emit(IdeEvent::LanguageServerWarning {
|
||||
name: SERVER.into(),
|
||||
message: MESSAGE.into(),
|
||||
// No managed tool fixes this (the server itself is fine), so none is
|
||||
// offered: the UI falls back to the settings shortcut only.
|
||||
install_tool: String::new(),
|
||||
});
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The project's `package.json` depends on Vue 2 (2.7 is the version the Vue Language
|
||||
/// Tools serve; older 2.x ranges resolve to it).
|
||||
fn vue2_project(root: &Path) -> bool {
|
||||
let Ok(manifest) = std::fs::read_to_string(root.join("package.json")) else { return false };
|
||||
let Ok(json) = serde_json::from_str::<serde_json::Value>(&manifest) else { return false };
|
||||
["dependencies", "devDependencies"]
|
||||
.iter()
|
||||
.any(|section| json.get(section).and_then(|s| s.get("vue")).and_then(|v| v.as_str()).is_some_and(is_vue_2))
|
||||
}
|
||||
|
||||
/// A `vue` version range whose major version is 2: `^2.7.16`, `~2.7`, `2.x`, `2`, `v2`.
|
||||
fn is_vue_2(spec: &str) -> bool {
|
||||
let rest = spec.trim().trim_start_matches(|c: char| !(c.is_ascii_digit() || c == 'v'));
|
||||
let rest = rest.trim_start_matches('v');
|
||||
let mut parts = rest.split('.');
|
||||
parts.next().and_then(|major| major.parse::<u32>().ok()) == Some(2)
|
||||
}
|
||||
|
||||
/// `jsconfig.json` / `tsconfig.json` at the root all lack the option: `strict` or
|
||||
/// `strictFunctionTypes` is not `true` in their own `compilerOptions`. A config that
|
||||
/// `extends` a base (which could set it) or can't be parsed stays quiet: a wrong hint
|
||||
/// is worse than a missed one.
|
||||
fn missing_strict_function_types(root: &Path) -> bool {
|
||||
["jsconfig.json", "tsconfig.json"].iter().all(|name| match std::fs::read_to_string(root.join(name)) {
|
||||
// No config there: nothing contradicts the hint (the option defaults to off).
|
||||
Err(_) => true,
|
||||
Ok(src) => strict_function_types(&src) == Some(false),
|
||||
})
|
||||
}
|
||||
|
||||
/// `strictFunctionTypes: true` or `strict: true` in `compilerOptions` of a JSONC config;
|
||||
/// `None` when the config `extends` another or can't be parsed (the effective options
|
||||
/// are unknown).
|
||||
fn strict_function_types(src: &str) -> Option<bool> {
|
||||
let json = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(src)).ok()?;
|
||||
if json.get("extends").and_then(|e| e.as_str()).is_some_and(|e| !e.trim().is_empty()) {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
["strictFunctionTypes", "strict"]
|
||||
.iter()
|
||||
.any(|key| json.get("compilerOptions").and_then(|o| o.get(key)).and_then(|v| v.as_bool()) == Some(true)),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn vue_2_version_ranges() {
|
||||
for spec in ["^2.7.16", "~2.7.0", "2.7", "2.x", "2.*", "2", "v2.7.16", ">=2.6.0 <3"] {
|
||||
assert!(is_vue_2(spec), "{spec}");
|
||||
}
|
||||
for spec in ["^3.5.13", "3", "~3.0.0", "latest", "workspace:*", "*"] {
|
||||
assert!(!is_vue_2(spec), "{spec}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vue_2_dependency_in_either_section() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::write(
|
||||
root.join("package.json"),
|
||||
r#"{"dependencies": {"vue": "^2.7.16", "vue-template-compiler": "^2.7.16"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(vue2_project(root));
|
||||
std::fs::write(root.join("package.json"), r#"{"devDependencies": {"vue": "~2.7"}}"#).unwrap();
|
||||
assert!(vue2_project(root));
|
||||
std::fs::write(root.join("package.json"), r#"{"dependencies": {"vue": "^3.5.13"}}"#).unwrap();
|
||||
assert!(!vue2_project(root));
|
||||
std::fs::write(root.join("package.json"), r#"{"dependencies": {}}"#).unwrap();
|
||||
assert!(!vue2_project(root));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_function_types_in_jsonc() {
|
||||
// Comments and trailing commas survive a real jsconfig.json.
|
||||
let src = r#"{
|
||||
// Generated by @vue/cli.
|
||||
"compilerOptions": {
|
||||
"target": "ES6",
|
||||
"module": "commonjs", /* kept */
|
||||
"allowJs": true,
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
}"#;
|
||||
assert_eq!(strict_function_types(src), Some(false));
|
||||
assert_eq!(
|
||||
strict_function_types(&src.replace("\"allowJs\": true", "\"strictFunctionTypes\": true")),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(strict_function_types(&src.replace("\"allowJs\": true", "\"strict\": true")), Some(true));
|
||||
assert_eq!(strict_function_types(&src.replace("\"allowJs\": true", "\"strict\": false")), Some(false));
|
||||
assert_eq!(
|
||||
strict_function_types(&src.replace(
|
||||
"\"include\": [\"src/**/*\"],",
|
||||
"\"extends\": \"@vue/tsconfig\", \"include\": [\"src/**/*\"],"
|
||||
)),
|
||||
None
|
||||
);
|
||||
assert_eq!(strict_function_types("no json here"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_option_needs_a_quiet_config() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
// No config at all: the option defaults to off.
|
||||
assert!(missing_strict_function_types(root));
|
||||
let jsconfig = root.join("jsconfig.json");
|
||||
std::fs::write(&jsconfig, r#"{"compilerOptions": {"module": "commonjs"}}"#).unwrap();
|
||||
assert!(missing_strict_function_types(root));
|
||||
// The option on in either config: navigation works there.
|
||||
std::fs::write(&jsconfig, r#"{"compilerOptions": {"strictFunctionTypes": true}}"#).unwrap();
|
||||
assert!(!missing_strict_function_types(root));
|
||||
std::fs::write(&jsconfig, r#"{"compilerOptions": {"strict": true}}"#).unwrap();
|
||||
assert!(!missing_strict_function_types(root));
|
||||
// A base config could set it: stay quiet.
|
||||
std::fs::write(&jsconfig, r#"{"extends": "./tsconfig.base.json", "compilerOptions": {}}"#).unwrap();
|
||||
assert!(!missing_strict_function_types(root));
|
||||
// An unparsable config: stay quiet.
|
||||
std::fs::write(&jsconfig, "not json").unwrap();
|
||||
assert!(!missing_strict_function_types(root));
|
||||
// tsconfig.json carries the option for a jsconfig-less project.
|
||||
std::fs::remove_file(&jsconfig).unwrap();
|
||||
std::fs::write(root.join("tsconfig.json"), r#"{"compilerOptions": {"strict": true}}"#).unwrap();
|
||||
assert!(!missing_strict_function_types(root));
|
||||
}
|
||||
}
|
||||
@@ -21,8 +21,8 @@ pub use runtime::{
|
||||
component_api, host_api,
|
||||
};
|
||||
pub use sandbox::{
|
||||
MAX_READ_BYTES, inside_root, inside_roots, read_text, resolve_in_root, resolve_in_roots, resolve_new_in_root,
|
||||
resolve_real, resolve_writable_in_root, resolve_writable_in_roots,
|
||||
MAX_READ_BYTES, inside_root, read_text, resolve_in_root, resolve_new_in_root, resolve_real,
|
||||
resolve_writable_in_root,
|
||||
};
|
||||
pub use types::*;
|
||||
pub use wasmtime::component::Component;
|
||||
|
||||
@@ -356,13 +356,6 @@ pub trait HostApi: Send + Sync {
|
||||
}
|
||||
/// Roots of the open projects.
|
||||
fn projects(&self) -> Vec<std::path::PathBuf>;
|
||||
/// Roots of the workspace members attached to the project at `root` (a
|
||||
/// project window group's folders, as the editor and LSP resolve them).
|
||||
/// Empty for a plain project.
|
||||
fn member_roots(&self, root: &Path) -> Vec<std::path::PathBuf> {
|
||||
let _ = root;
|
||||
Vec::new()
|
||||
}
|
||||
/// The most specific open project containing a document (including a new file).
|
||||
fn project_of(&self, path: &Path) -> Option<std::path::PathBuf> {
|
||||
if !path.is_absolute() {
|
||||
|
||||
@@ -65,29 +65,6 @@ pub fn resolve_in_root(root: &Path, path: &str) -> Result<PathBuf, String> {
|
||||
Ok(real)
|
||||
}
|
||||
|
||||
/// [`resolve_in_root`] over several roots: the project root and, for a project
|
||||
/// window group, its member roots. `roots` is tried in order (the project root
|
||||
/// first), and the first root that contains `path` wins; a relative path may
|
||||
/// name a file of any member. When no root contains it, the project root's
|
||||
/// refusal is the error, as if there had been no members at all.
|
||||
pub fn resolve_in_roots(roots: &[PathBuf], path: &str) -> Result<PathBuf, String> {
|
||||
let (project_root, members) = match roots.split_first() {
|
||||
Some((project_root, members)) => (project_root, members),
|
||||
None => return Err(format!("{path}: no such file")),
|
||||
};
|
||||
match resolve_in_root(project_root, path) {
|
||||
Ok(real) => Ok(real),
|
||||
Err(project_root_error) => {
|
||||
for root in members {
|
||||
if let Ok(real) = resolve_in_root(root, path) {
|
||||
return Ok(real);
|
||||
}
|
||||
}
|
||||
Err(project_root_error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` (absolute, or relative to `root`) lands inside `root`,
|
||||
/// without requiring it to exist: `Ok(true)` also for a missing path, so
|
||||
/// callers distinguish "outside" from "absent". Existing symlinks are
|
||||
@@ -97,23 +74,6 @@ pub fn inside_root(root: &Path, path: &str) -> Result<bool, String> {
|
||||
Ok(resolve_real(&joined).starts_with(&root))
|
||||
}
|
||||
|
||||
/// [`inside_root`] over several roots, as [`resolve_in_roots`] does: a path is
|
||||
/// inside when any of them contains it.
|
||||
pub fn inside_roots(roots: &[PathBuf], path: &str) -> Result<bool, String> {
|
||||
let Some((project_root, members)) = roots.split_first() else {
|
||||
return Ok(false);
|
||||
};
|
||||
if inside_root(project_root, path)? {
|
||||
return Ok(true);
|
||||
}
|
||||
for root in members {
|
||||
if inside_root(root, path)? {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Like [`resolve_in_root`] for a path that may not exist yet (a file about to
|
||||
/// be created) or that names a symlink itself (to delete or rename it): the
|
||||
/// directory part is resolved through symlinks, the final name is kept as is,
|
||||
@@ -168,25 +128,6 @@ pub fn resolve_writable_in_root(root: &Path, path: &str) -> Result<PathBuf, Stri
|
||||
Ok(real)
|
||||
}
|
||||
|
||||
/// [`resolve_writable_in_root`] over several roots, as [`resolve_in_roots`] does.
|
||||
pub fn resolve_writable_in_roots(roots: &[PathBuf], path: &str) -> Result<PathBuf, String> {
|
||||
let (project_root, members) = match roots.split_first() {
|
||||
Some((project_root, members)) => (project_root, members),
|
||||
None => return Err(format!("{path}: access outside the project root is not allowed")),
|
||||
};
|
||||
match resolve_writable_in_root(project_root, path) {
|
||||
Ok(real) => Ok(real),
|
||||
Err(project_root_error) => {
|
||||
for root in members {
|
||||
if let Ok(real) = resolve_writable_in_root(root, path) {
|
||||
return Ok(real);
|
||||
}
|
||||
}
|
||||
Err(project_root_error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_write_target(path: &Path, links_left: usize) -> Result<PathBuf, std::io::Error> {
|
||||
match dunce::canonicalize(path) {
|
||||
Ok(real) => return Ok(real),
|
||||
@@ -470,80 +411,6 @@ mod tests {
|
||||
assert!(inside_root(&root, "").is_err());
|
||||
}
|
||||
|
||||
/// A project window group: the container root and its member roots.
|
||||
fn group(tmp: &tempfile::TempDir) -> (PathBuf, PathBuf, Vec<PathBuf>) {
|
||||
let container = tmp.path().join("workspace");
|
||||
let alpha = tmp.path().join("alpha");
|
||||
let beta = tmp.path().join("beta");
|
||||
for dir in [&container, &alpha, &beta] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
let container = dunce::canonicalize(container).unwrap();
|
||||
let alpha = dunce::canonicalize(alpha).unwrap();
|
||||
let beta = dunce::canonicalize(beta).unwrap();
|
||||
(container, alpha.clone(), vec![alpha, beta])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn member_roots_accept_their_files_and_the_container_still_confines() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (container, alpha, members) = group(&tmp);
|
||||
std::fs::create_dir_all(container.join("src")).unwrap();
|
||||
std::fs::write(container.join("src/notes.txt"), "hi").unwrap();
|
||||
std::fs::create_dir_all(alpha.join("src")).unwrap();
|
||||
let member_file = alpha.join("src/mapper.xml");
|
||||
std::fs::write(&member_file, "hi").unwrap();
|
||||
std::fs::write(tmp.path().join("secret.txt"), "s").unwrap();
|
||||
let roots = [container.clone()].iter().cloned().chain(members.clone()).collect::<Vec<_>>();
|
||||
|
||||
// A member's absolute file resolves through its member root.
|
||||
assert_eq!(resolve_in_roots(&roots, member_file.to_str().unwrap()).unwrap(), member_file);
|
||||
// The container's own files still resolve as before.
|
||||
let container_file = container.join("src/notes.txt");
|
||||
assert_eq!(resolve_in_roots(&roots, "src/notes.txt").unwrap(), container_file);
|
||||
// A missing path is `no such file`, wherever it would land.
|
||||
let gone = container_file.with_file_name("gone.txt");
|
||||
assert_eq!(
|
||||
resolve_in_roots(&roots, gone.to_str().unwrap()).unwrap_err(),
|
||||
format!("{}: no such file", gone.display())
|
||||
);
|
||||
// Outside every root is refused with the container's refusal.
|
||||
let outside = tmp.path().join("secret.txt");
|
||||
let err = resolve_in_roots(&roots, outside.to_str().unwrap()).unwrap_err();
|
||||
assert!(err.contains("outside the project root"), "{err}");
|
||||
let err = resolve_in_roots(&roots, "../secret.txt").unwrap_err();
|
||||
assert!(err.contains("outside the project root"), "{err}");
|
||||
// `inside_roots` accepts member paths, including missing ones, and
|
||||
// refuses what no root contains.
|
||||
assert!(inside_roots(&roots, member_file.to_str().unwrap()).unwrap());
|
||||
assert!(inside_roots(&roots, "missing/one.txt").unwrap());
|
||||
assert!(inside_roots(&roots, alpha.join("src/new.xml").to_str().unwrap()).unwrap());
|
||||
assert!(!inside_roots(&roots, outside.to_str().unwrap()).unwrap());
|
||||
// No members: exactly the single-root behaviour.
|
||||
let single = [container.clone()];
|
||||
assert_eq!(resolve_in_roots(&single, "src/notes.txt").unwrap(), container_file);
|
||||
assert!(!inside_roots(&single, member_file.to_str().unwrap()).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_and_writable_paths_accept_members() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (container, alpha, members) = group(&tmp);
|
||||
std::fs::create_dir_all(container.join("src")).unwrap();
|
||||
std::fs::create_dir_all(alpha.join("src")).unwrap();
|
||||
let roots = [container.clone()].iter().cloned().chain(members.iter().cloned()).collect::<Vec<_>>();
|
||||
|
||||
let member_new = alpha.join("src/new.xml");
|
||||
assert_eq!(resolve_writable_in_roots(&roots, member_new.to_str().unwrap()).unwrap(), member_new);
|
||||
let container_new = container.join("src/new.txt");
|
||||
assert_eq!(resolve_writable_in_roots(&roots, "src/new.txt").unwrap(), container_new);
|
||||
let outside = tmp.path().join("escape.txt");
|
||||
let err = resolve_writable_in_roots(&roots, outside.to_str().unwrap()).unwrap_err();
|
||||
assert!(err.contains("outside the project root"), "{err}");
|
||||
let err = resolve_writable_in_roots(&roots, "../../escape.txt").unwrap_err();
|
||||
assert!(err.contains("outside the project root"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_paths_are_confined_to_root() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -686,7 +686,7 @@ impl workspace::HostProject for StoreData {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&this)?.root.clone();
|
||||
let real = match self.resolve_in_project(&root, &path) {
|
||||
let real = match sandbox::resolve_in_root(&root, &path) {
|
||||
Ok(real) => real,
|
||||
Err(e) => {
|
||||
let e = if e.ends_with("no such file") { wit::Error::NotFound(e) } else { wit::Error::Invalid(e) };
|
||||
@@ -704,7 +704,7 @@ impl workspace::HostProject for StoreData {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&this)?.root.clone();
|
||||
let real = match self.resolve_in_project(&root, &path) {
|
||||
let real = match sandbox::resolve_in_root(&root, &path) {
|
||||
Ok(real) => real,
|
||||
Err(e) => {
|
||||
let e = if e.ends_with("no such file") { wit::Error::NotFound(e) } else { wit::Error::Invalid(e) };
|
||||
@@ -720,20 +720,15 @@ impl workspace::HostProject for StoreData {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&this)?.root.clone();
|
||||
match self.inside_project(&root, &path) {
|
||||
match sandbox::inside_root(&root, &path) {
|
||||
Err(e) => Ok(Err(wit::Error::Invalid(e))),
|
||||
Ok(false) => {
|
||||
Ok(Err(wit::Error::Invalid(format!("{path}: access outside the project root is not allowed"))))
|
||||
}
|
||||
Ok(true) => {
|
||||
let requested = Path::new(&path);
|
||||
let joined =
|
||||
|root: &Path| if requested.is_absolute() { requested.to_path_buf() } else { root.join(requested) };
|
||||
let mut exists = joined(&root).exists();
|
||||
if !exists && !requested.is_absolute() {
|
||||
exists = self.host.member_roots(&root).iter().any(|root| joined(root).exists());
|
||||
}
|
||||
Ok(Ok(exists))
|
||||
let joined = if requested.is_absolute() { requested.to_path_buf() } else { root.join(requested) };
|
||||
Ok(Ok(joined.exists()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -743,7 +738,7 @@ impl workspace::HostProject for StoreData {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&this)?.root.clone();
|
||||
let real = match self.resolve_in_project(&root, &path) {
|
||||
let real = match sandbox::resolve_in_root(&root, &path) {
|
||||
Ok(real) => real,
|
||||
Err(e) => {
|
||||
let e = if e.ends_with("no such file") { wit::Error::NotFound(e) } else { wit::Error::Invalid(e) };
|
||||
@@ -802,7 +797,7 @@ impl workspace::HostProject for StoreData {
|
||||
return Ok(Err(too_much_to_write(&path)));
|
||||
}
|
||||
let root = self.table.get(&this)?.root.clone();
|
||||
let real = match self.resolve_writable_in_project(&root, &path) {
|
||||
let real = match sandbox::resolve_writable_in_root(&root, &path) {
|
||||
Ok(real) => real,
|
||||
Err(e) => return Ok(Err(wit::Error::Invalid(e))),
|
||||
};
|
||||
@@ -858,27 +853,6 @@ fn core_range(r: wit::Range) -> ide_core::Range {
|
||||
ide_core::Range::new(pos(r.start), pos(r.end))
|
||||
}
|
||||
impl StoreData {
|
||||
/// A `project` resource's path: inside the resource's root, or — for a
|
||||
/// project window group — inside any of its member roots (as the editor and
|
||||
/// LSP resolve them). When no root accepts the path, the resource root's own
|
||||
/// refusal is the error, as if there were no members.
|
||||
fn resolve_in_project(&self, root: &Path, path: &str) -> Result<PathBuf, String> {
|
||||
sandbox::resolve_in_root(root, path).or_else(|root_error| {
|
||||
sandbox::resolve_in_roots(&self.host.member_roots(root), path).map_err(|_| root_error)
|
||||
})
|
||||
}
|
||||
/// [`Self::resolve_in_project`] for a content write's destination.
|
||||
fn resolve_writable_in_project(&self, root: &Path, path: &str) -> Result<PathBuf, String> {
|
||||
sandbox::resolve_writable_in_root(root, path).or_else(|root_error| {
|
||||
sandbox::resolve_writable_in_roots(&self.host.member_roots(root), path).map_err(|_| root_error)
|
||||
})
|
||||
}
|
||||
/// Whether a `project` resource's path lands inside the resource's root or
|
||||
/// any member of its workspace group, without requiring it to exist.
|
||||
fn inside_project(&self, root: &Path, path: &str) -> Result<bool, String> {
|
||||
sandbox::inside_root(root, path)
|
||||
.or_else(|root_error| sandbox::inside_roots(&self.host.member_roots(root), path).map_err(|_| root_error))
|
||||
}
|
||||
fn decoration_path(&self, path: &str) -> Result<PathBuf, wit::Error> {
|
||||
if Path::new(path).is_absolute() {
|
||||
return Ok(PathBuf::from(path));
|
||||
|
||||
@@ -439,46 +439,6 @@ pub fn gradle_env(
|
||||
env
|
||||
}
|
||||
|
||||
/// Settings › Build Tools › Gradle → jdtls `java.import.gradle.*`: the Java import of the Gradle
|
||||
/// build in `build_dir` runs the same Gradle installation, user home and JVM as the IDE's own
|
||||
/// Gradle runs ([`gradle_build_env`]: Gradle JVM, else the Project JDK, else an installed JDK
|
||||
/// this Gradle version runs on). Without it a project that ships no wrapper is never imported,
|
||||
/// one whose caches live in a configured user home resolves no dependencies, and an older Gradle
|
||||
/// fails on the JDK jdtls itself runs on. The wrapper stays jdtls's default unless a local
|
||||
/// distribution is chosen.
|
||||
pub fn configure_gradle_runtime(cfg: &mut LanguageServerConfig, root: &Path, build_dir: &Path, s: &Settings) {
|
||||
if cfg.name != "jdtls" {
|
||||
return;
|
||||
}
|
||||
let g = &s.languages.java.gradle;
|
||||
let mut gradle = serde_json::Map::new();
|
||||
if g.distribution == ide_core::settings::GradleDistribution::Local
|
||||
&& let Some(home) = setting_path(root, &g.home)
|
||||
{
|
||||
gradle.insert("home".into(), json!(home.to_string_lossy()));
|
||||
gradle.insert("wrapper".into(), json!({"enabled": false}));
|
||||
}
|
||||
let gradle_build = ["settings.gradle", "settings.gradle.kts", "build.gradle", "build.gradle.kts"]
|
||||
.iter()
|
||||
.any(|f| build_dir.join(f).is_file());
|
||||
let env = if gradle_build {
|
||||
let command = gradle_command(root, build_dir, s);
|
||||
gradle_build_env(root, build_dir, &command.to_string_lossy(), s, None)
|
||||
} else {
|
||||
gradle_env(root, s, Default::default())
|
||||
};
|
||||
if let Some(home) = env.get("GRADLE_USER_HOME") {
|
||||
gradle.insert("user".into(), json!({"home": home}));
|
||||
}
|
||||
if let Some(home) = env.get("JAVA_HOME") {
|
||||
gradle.insert("java".into(), json!({"home": home}));
|
||||
}
|
||||
if gradle.is_empty() {
|
||||
return;
|
||||
}
|
||||
merge(cfg.settings.get_or_insert_with(|| json!({})), json!({"java": {"import": {"gradle": gradle}}}));
|
||||
}
|
||||
|
||||
/// Maven options from settings, placed before the goals: `-s <settings.xml>`,
|
||||
/// `-t <toolchains.xml>`, `-Dmaven.repo.local=<dir>`, `-T <count>` and `-P <profiles>`.
|
||||
pub fn maven_options(root: &Path, s: &Settings) -> Vec<String> {
|
||||
@@ -1725,15 +1685,12 @@ pub fn terminal_activation(root: &Path, s: &Settings, shell: &str) -> Option<Str
|
||||
if !s.languages.python.activate_virtualenv {
|
||||
return None;
|
||||
}
|
||||
let python = python_interpreter(root, s)?;
|
||||
let name = shell.rsplit(['/', '\\']).next().unwrap_or(shell);
|
||||
let name = Path::new(name).file_stem().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
|
||||
let Some(venv) = venv_of(&python) else {
|
||||
return conda_activation(&python, &name, std::env::var_os("CONDA_EXE").map(PathBuf::from), which("conda"));
|
||||
};
|
||||
let venv = python_interpreter(root, s).as_deref().and_then(venv_of)?;
|
||||
if std::env::var_os("VIRTUAL_ENV").is_some_and(|v| Path::new(&v) == venv) {
|
||||
return None;
|
||||
}
|
||||
let name = shell.rsplit(['/', '\\']).next().unwrap_or(shell);
|
||||
let name = Path::new(name).file_stem().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
|
||||
let script = |file: &str| venv.join(bin_dir()).join(file);
|
||||
let line = match name.as_str() {
|
||||
"fish" => format!("source {}", sh_quote(&script("activate.fish").to_string_lossy())),
|
||||
@@ -1758,64 +1715,6 @@ pub fn terminal_activation(root: &Path, s: &Settings, shell: &str) -> Option<Str
|
||||
script(target).is_file().then_some(line)
|
||||
}
|
||||
|
||||
/// `conda activate <prefix>` for a conda interpreter, as PyCharm does for a Conda project
|
||||
/// interpreter: conda envs have no activate script of their own, and the shells' conda hook
|
||||
/// comes from the installation (the env itself for `base`, the parent of `envs/`, else
|
||||
/// `CONDA_EXE` or the `conda` on PATH). `name` is the shell's lowercased file stem.
|
||||
fn conda_activation(python: &Path, name: &str, conda_exe: Option<PathBuf>, on_path: Option<PathBuf>) -> Option<String> {
|
||||
let env = crate::discover::conda_env_home(python).filter(|env| env.join("conda-meta").is_dir())?;
|
||||
if std::env::var_os("CONDA_PREFIX").is_some_and(|p| Path::new(&p) == env) {
|
||||
return None;
|
||||
}
|
||||
let is_base = |dir: &Path| dir.join("condabin").is_dir();
|
||||
// `<base>/bin/conda`, `<base>/condabin/conda[.bat]`, `<base>\Scripts\conda.exe`.
|
||||
let base_of = |exe: PathBuf| exe.parent()?.parent().map(Path::to_path_buf).filter(|b| is_base(b));
|
||||
let base = Some(env.clone())
|
||||
.filter(|e| is_base(e))
|
||||
.or_else(|| {
|
||||
env.parent()
|
||||
.filter(|p| p.file_name().is_some_and(|n| n == "envs"))?
|
||||
.parent()
|
||||
.map(Path::to_path_buf)
|
||||
.filter(|b| is_base(b))
|
||||
})
|
||||
.or_else(|| conda_exe.and_then(base_of))
|
||||
.or_else(|| on_path.and_then(base_of))?;
|
||||
let prefix = env.to_string_lossy();
|
||||
let conda = if cfg!(windows) { base.join("Scripts").join("conda.exe") } else { base.join("bin").join("conda") };
|
||||
let posix = |hook: &str| {
|
||||
conda.is_file().then(|| {
|
||||
format!(
|
||||
"eval \"$({} shell.{hook} hook)\" && conda activate {}",
|
||||
sh_quote(&conda.to_string_lossy()),
|
||||
sh_quote(&prefix)
|
||||
)
|
||||
})
|
||||
};
|
||||
match name {
|
||||
"cmd" => {
|
||||
let bat = base.join("condabin").join("conda.bat");
|
||||
bat.is_file().then(|| format!("call \"{}\" activate \"{prefix}\"", bat.display()))
|
||||
}
|
||||
"pwsh" | "powershell" => {
|
||||
let hook = base.join("shell").join("condabin").join("conda-hook.ps1");
|
||||
let quote = |s: &str| format!("'{}'", s.replace('\'', "''"));
|
||||
hook.is_file().then(|| format!("& {}; conda activate {}", quote(&hook.to_string_lossy()), quote(&prefix)))
|
||||
}
|
||||
"bash" => posix("bash"),
|
||||
"zsh" => posix("zsh"),
|
||||
"sh" | "dash" | "ksh" | "mksh" | "ash" => posix("posix"),
|
||||
"fish" => conda.is_file().then(|| {
|
||||
format!(
|
||||
"{} shell.fish hook | source; and conda activate {}",
|
||||
sh_quote(&conda.to_string_lossy()),
|
||||
sh_quote(&prefix)
|
||||
)
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod java_compiler_tests {
|
||||
use super::*;
|
||||
@@ -2004,67 +1903,6 @@ mod maven_linkage_tests {
|
||||
assert_eq!(default_maven_repository_in(home), Some(home.join(".m2/repository")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradle_import_runs_the_gradle_the_ide_builds_with() {
|
||||
let root = Path::new("/p");
|
||||
let mut cfg = custom_server("jdtls", &LanguageServerSettings::default());
|
||||
cfg.settings = Some(json!({"java": {"import": {"gradle": {"enabled": true}}}}));
|
||||
let initial = cfg.clone();
|
||||
let mut settings = Settings::default();
|
||||
configure_gradle_runtime(&mut cfg, root, root, &settings);
|
||||
assert_eq!(cfg, initial, "no Gradle settings: jdtls keeps its own defaults and the wrapper");
|
||||
|
||||
let g = &mut settings.languages.java.gradle;
|
||||
g.distribution = ide_core::settings::GradleDistribution::Local;
|
||||
g.home = "tools/gradle-5.2.1".into();
|
||||
g.user_home = "/caches/gradle".into();
|
||||
g.jvm = "/jdk/8".into();
|
||||
configure_gradle_runtime(&mut cfg, root, root, &settings);
|
||||
let gradle = &cfg.settings.as_ref().unwrap()["java"]["import"]["gradle"];
|
||||
assert_eq!(gradle["enabled"], json!(true), "merged, not replaced");
|
||||
let resolved = |s: &str| json!(setting_path(root, s).unwrap().to_string_lossy());
|
||||
assert_eq!(gradle["home"], json!(root.join("tools/gradle-5.2.1").to_string_lossy()));
|
||||
assert_eq!(gradle["wrapper"]["enabled"], json!(false));
|
||||
assert_eq!(gradle["user"]["home"], resolved("/caches/gradle"));
|
||||
assert_eq!(gradle["java"]["home"], resolved("/jdk/8"));
|
||||
|
||||
// The wrapper distribution keeps the wrapper even with a home left over.
|
||||
let mut cfg = initial.clone();
|
||||
settings.languages.java.gradle.distribution = ide_core::settings::GradleDistribution::Wrapper;
|
||||
configure_gradle_runtime(&mut cfg, root, root, &settings);
|
||||
let gradle = &cfg.settings.as_ref().unwrap()["java"]["import"]["gradle"];
|
||||
assert!(gradle.get("home").is_none() && gradle.get("wrapper").is_none());
|
||||
assert_eq!(gradle["user"]["home"], resolved("/caches/gradle"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradle_import_of_a_gradle_build_runs_on_the_project_jdk_like_the_ides_builds() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
std::fs::write(root.join("build.gradle"), "plugins { id 'java' }").unwrap();
|
||||
let jdk = root.join("jdk11");
|
||||
std::fs::create_dir_all(jdk.join("bin")).unwrap();
|
||||
std::fs::write(jdk.join("bin").join(crate::exe("java")), "").unwrap();
|
||||
std::fs::write(jdk.join("release"), "JAVA_VERSION=\"11.0.2\"\n").unwrap();
|
||||
let mut settings = Settings::default();
|
||||
settings.languages.java.jdk = jdk.to_string_lossy().into_owned();
|
||||
let mut cfg = custom_server("jdtls", &LanguageServerSettings::default());
|
||||
configure_gradle_runtime(&mut cfg, root, root, &settings);
|
||||
let gradle = &cfg.settings.as_ref().unwrap()["java"]["import"]["gradle"];
|
||||
let expected =
|
||||
gradle_build_env(root, root, &gradle_command(root, root, &settings).to_string_lossy(), &settings, None);
|
||||
assert_eq!(gradle["java"]["home"], json!(expected["JAVA_HOME"]));
|
||||
assert!(expected["JAVA_HOME"].ends_with("jdk11"));
|
||||
assert!(gradle.get("wrapper").is_none(), "the wrapper stays on");
|
||||
|
||||
// An explicit Gradle JVM wins over the Project JDK.
|
||||
settings.languages.java.gradle.jvm = "/gradle-jdk".into();
|
||||
let mut cfg = custom_server("jdtls", &LanguageServerSettings::default());
|
||||
configure_gradle_runtime(&mut cfg, root, root, &settings);
|
||||
let gradle = &cfg.settings.as_ref().unwrap()["java"]["import"]["gradle"];
|
||||
assert_eq!(gradle["java"]["home"], json!(setting_path(root, "/gradle-jdk").unwrap().to_string_lossy()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_gradle_links_scope_jdt_import_and_unlink_all_disables_gradle() {
|
||||
let mut cfg = custom_server("jdtls", &LanguageServerSettings::default());
|
||||
@@ -2192,70 +2030,3 @@ mod java_compliance_tests {
|
||||
assert_eq!(c("latest"), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod conda_activation_tests {
|
||||
use super::*;
|
||||
|
||||
fn touch(path: &Path) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "").unwrap();
|
||||
}
|
||||
|
||||
/// A conda prefix with its interpreter where conda puts it on this OS.
|
||||
fn prefix(dir: &Path) -> PathBuf {
|
||||
std::fs::create_dir_all(dir.join("conda-meta")).unwrap();
|
||||
let python = if cfg!(windows) { dir.join("python.exe") } else { dir.join("bin").join("python") };
|
||||
touch(&python);
|
||||
python
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conda_envs_activate_through_the_installations_shell_hooks() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = tmp.path().join("miniconda3");
|
||||
let base_python = prefix(&base);
|
||||
std::fs::create_dir_all(base.join("condabin")).unwrap();
|
||||
let conda = if cfg!(windows) { base.join("Scripts").join("conda.exe") } else { base.join("bin").join("conda") };
|
||||
touch(&conda);
|
||||
let bat = base.join("condabin").join("conda.bat");
|
||||
touch(&bat);
|
||||
let hook = base.join("shell").join("condabin").join("conda-hook.ps1");
|
||||
touch(&hook);
|
||||
let env = base.join("envs").join("agent-gateway");
|
||||
let python = prefix(&env);
|
||||
let q = |p: &Path| sh_quote(&p.to_string_lossy());
|
||||
|
||||
assert_eq!(
|
||||
conda_activation(&python, "zsh", None, None).unwrap(),
|
||||
format!("eval \"$({} shell.zsh hook)\" && conda activate {}", q(&conda), q(&env))
|
||||
);
|
||||
assert_eq!(
|
||||
conda_activation(&python, "cmd", None, None).unwrap(),
|
||||
format!("call \"{}\" activate \"{}\"", bat.display(), env.display())
|
||||
);
|
||||
assert_eq!(
|
||||
conda_activation(&python, "powershell", None, None).unwrap(),
|
||||
format!("& '{}'; conda activate '{}'", hook.display(), env.display())
|
||||
);
|
||||
assert_eq!(
|
||||
conda_activation(&python, "fish", None, None).unwrap(),
|
||||
format!("{} shell.fish hook | source; and conda activate {}", q(&conda), q(&env))
|
||||
);
|
||||
assert_eq!(conda_activation(&python, "nu", None, None), None, "no conda hook for this shell");
|
||||
assert!(conda_activation(&base_python, "bash", None, None).unwrap().ends_with(&q(&base)), "base itself");
|
||||
|
||||
// A `--prefix` env elsewhere finds the installation through CONDA_EXE or PATH.
|
||||
let elsewhere = tmp.path().join("project").join(".conda");
|
||||
let python = prefix(&elsewhere);
|
||||
assert_eq!(conda_activation(&python, "bash", None, None), None);
|
||||
let line = conda_activation(&python, "bash", Some(conda.clone()), None).unwrap();
|
||||
assert!(line.ends_with(&format!("conda activate {}", q(&elsewhere))), "{line}");
|
||||
assert!(conda_activation(&python, "cmd", None, Some(bat.clone())).is_some());
|
||||
|
||||
// Not a conda prefix.
|
||||
let plain = tmp.path().join("python");
|
||||
touch(&plain.join("bin").join("python"));
|
||||
assert_eq!(conda_activation(&plain.join("bin").join("python"), "bash", Some(conda), None), None);
|
||||
}
|
||||
}
|
||||
@@ -321,7 +321,7 @@ fn python_sdk_with_version(path: &Path, source: &str, root: Option<&Path>, versi
|
||||
}
|
||||
|
||||
/// The prefix of a conda interpreter: `<env>/bin/python` on Unix, `<env>/python.exe` on Windows.
|
||||
pub(crate) fn conda_env_home(python: &Path) -> Option<PathBuf> {
|
||||
fn conda_env_home(python: &Path) -> Option<PathBuf> {
|
||||
let dir = python.parent()?;
|
||||
let bin = dir.file_name().is_some_and(|n| n == "bin" || n.eq_ignore_ascii_case("Scripts"));
|
||||
Some(if bin { dir.parent()? } else { dir }.to_path_buf())
|
||||
|
||||
@@ -21,7 +21,6 @@ pub struct DocumentInfo {
|
||||
pub version: u32,
|
||||
pub language: LanguageId,
|
||||
pub encoding: String,
|
||||
pub has_bom: bool,
|
||||
pub line_ending: LineEnding,
|
||||
pub read_only: bool,
|
||||
pub dirty: bool,
|
||||
@@ -42,14 +41,6 @@ pub struct DocumentInfo {
|
||||
pub ui_mode: Option<String>,
|
||||
}
|
||||
|
||||
/// Encoding and BOM currently applied to an open document.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DocumentEncoding {
|
||||
pub encoding: String,
|
||||
pub has_bom: bool,
|
||||
}
|
||||
|
||||
/// Current text and identity of a document, for analyses (outline, folding).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TextSnapshot {
|
||||
@@ -335,7 +326,6 @@ impl Documents {
|
||||
version: st.doc.version(),
|
||||
language: st.language.clone(),
|
||||
encoding: st.encoding.clone(),
|
||||
has_bom: st.has_bom,
|
||||
line_ending: st.doc.line_ending(),
|
||||
read_only: st.read_only,
|
||||
dirty: st.dirty,
|
||||
@@ -832,7 +822,7 @@ impl Documents {
|
||||
/// Changes the document's encoding. `reload`: re-decode the file on disk with
|
||||
/// it (refused while there are unsaved changes); otherwise convert: the text
|
||||
/// is kept and the next save writes it in the new encoding.
|
||||
pub fn set_encoding(&self, doc: DocId, encoding: &str, reload: bool) -> IdeResult<DocumentEncoding> {
|
||||
pub fn set_encoding(&self, doc: DocId, encoding: &str, reload: bool) -> IdeResult<String> {
|
||||
self.with_doc(doc, |st| {
|
||||
if st.uri.is_some() {
|
||||
return Err(read_only_error(&st.path));
|
||||
@@ -852,7 +842,7 @@ impl Documents {
|
||||
self.replace_locked(doc, st, &loaded.text)?;
|
||||
// Reloading is not an edit: the buffer matches the file again.
|
||||
self.set_dirty(doc, st, false);
|
||||
return Ok(DocumentEncoding { encoding: st.encoding.clone(), has_bom: st.has_bom });
|
||||
return Ok(loaded.encoding);
|
||||
}
|
||||
if st.read_only {
|
||||
return Err(read_only_error(&st.path));
|
||||
@@ -866,24 +856,7 @@ impl Documents {
|
||||
st.encoding = encoding.to_owned();
|
||||
st.has_bom = has_bom;
|
||||
self.set_dirty(doc, st, true);
|
||||
Ok(DocumentEncoding { encoding: st.encoding.clone(), has_bom: st.has_bom })
|
||||
})
|
||||
}
|
||||
|
||||
/// Adds or removes the BOM on a UTF-8 document; the change is written on save.
|
||||
pub fn set_bom(&self, doc: DocId, has_bom: bool) -> IdeResult<DocumentEncoding> {
|
||||
self.with_doc(doc, |st| {
|
||||
if st.uri.is_some() || st.read_only {
|
||||
return Err(read_only_error(&st.path));
|
||||
}
|
||||
if st.encoding != "utf-8" || st.native_to_ascii {
|
||||
return Err(IdeError::invalid("the BOM can only be changed for UTF-8 documents"));
|
||||
}
|
||||
if st.has_bom != has_bom {
|
||||
st.has_bom = has_bom;
|
||||
self.set_dirty(doc, st, true);
|
||||
}
|
||||
Ok(DocumentEncoding { encoding: st.encoding.clone(), has_bom: st.has_bom })
|
||||
Ok(st.encoding.clone())
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ pub mod unity;
|
||||
pub mod window_groups;
|
||||
pub mod workspace;
|
||||
|
||||
pub use documents::{DetectLanguage, DocumentEncoding, DocumentInfo, Documents, TextSnapshot};
|
||||
pub use documents::{DetectLanguage, DocumentInfo, Documents, TextSnapshot};
|
||||
pub use editorconfig::{EditorConfig, EditorConfigProps};
|
||||
pub use file_defaults::FileDefaults;
|
||||
pub use file_moves::{FileMove, FileMoves, UndoOutcome};
|
||||
|
||||
@@ -486,15 +486,11 @@ fn reload_and_convert_encoding() {
|
||||
let (bytes, _, _) = encoding_rs::GBK.encode("中文内容");
|
||||
fs::write(&path, &bytes).unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
let encoding = f.docs.set_encoding(info.id, "gbk", true).unwrap();
|
||||
assert_eq!(encoding.encoding, "gbk");
|
||||
assert!(!encoding.has_bom);
|
||||
assert_eq!(f.docs.set_encoding(info.id, "gbk", true).unwrap(), "gbk");
|
||||
assert_eq!(f.docs.snapshot(info.id).unwrap().text, "中文内容");
|
||||
|
||||
// Convert: same text, written in the new encoding on save.
|
||||
let encoding = f.docs.set_encoding(info.id, "utf-8", false).unwrap();
|
||||
assert_eq!(encoding.encoding, "utf-8");
|
||||
assert!(!encoding.has_bom);
|
||||
assert_eq!(f.docs.set_encoding(info.id, "utf-8", false).unwrap(), "utf-8");
|
||||
f.docs.save(info.id).unwrap();
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "中文内容");
|
||||
|
||||
@@ -505,29 +501,6 @@ fn reload_and_convert_encoding() {
|
||||
assert!(f.docs.set_encoding(info.id, "gbk", true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf8_bom_is_added_and_removed_on_save() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("bom.txt");
|
||||
fs::write(&path, "text").unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
assert!(!info.has_bom);
|
||||
|
||||
assert!(f.docs.set_bom(info.id, true).unwrap().has_bom);
|
||||
assert_eq!(fs::read(&path).unwrap(), b"text", "written on save only");
|
||||
f.docs.save(info.id).unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), b"\xEF\xBB\xBFtext");
|
||||
assert_eq!(f.docs.snapshot(info.id).unwrap().text, "text");
|
||||
|
||||
assert!(!f.docs.set_bom(info.id, false).unwrap().has_bom);
|
||||
f.docs.save(info.id).unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), b"text");
|
||||
|
||||
// Other encodings have no BOM to toggle.
|
||||
f.docs.set_encoding(info.id, "gbk", false).unwrap();
|
||||
assert!(f.docs.set_bom(info.id, true).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlinked_path_maps_to_same_document() {
|
||||
|
||||
@@ -17,7 +17,7 @@ The left side is a tree; the right side shows details of the selected item (a co
|
||||
|
||||
### Run configurations
|
||||
|
||||
Only types you add appear here: choose **Add Service › Run Configuration Type**; each type is a group, kept until you remove it with **Remove from Services**. Removing a type or a single configuration takes effect at once, even while it runs: the run moves to the Run tool window, so its console stays reachable. Running a configuration of a type you have not added keeps its output in the Run or Debug tool window too.
|
||||
Spring Boot configurations appear by default. Other types appear when you add them with **Add Service › Run Configuration Type**, or once a configuration of that type has run. Each type is a group.
|
||||
|
||||
- Group actions: **Run All**, **Restart All**, **Stop All**, **Open in Browser**.
|
||||
- Configuration actions: **Run** (or **Rerun**), **Debug**, **Stop**, **Open in Browser**, **Update Application** (for configurations that support it).
|
||||
@@ -31,7 +31,7 @@ OpenIDEA drives Docker through the `docker` CLI, so anything that provides a wor
|
||||
|
||||
### Connections
|
||||
|
||||
With nothing configured, Services lists no Docker connection. To add one (the first one usually connects to the Docker CLI default: `DOCKER_HOST` or the current context), choose **Add Service › Docker Connection…**:
|
||||
With nothing configured, Services shows one connection named **Docker** that uses the Docker CLI default (`DOCKER_HOST` or the current context). To add another, choose **Add Service › Docker Connection…**:
|
||||
|
||||
| Field | Options |
|
||||
| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
|
||||
@@ -17,7 +17,7 @@ description: "在服务工具窗口中管理运行配置、Docker 容器、镜
|
||||
|
||||
### 运行配置
|
||||
|
||||
只有你添加的类型才会出现:选择 **添加服务 › 运行配置类型**(类型会一直保留,直到用 **从服务中移除** 删掉;每种类型一个分组)。移除类型或单个配置立即生效——即使它正在运行,运行也会转到运行工具窗口,控制台始终可达。运行未添加类型的配置时,输出同样留在运行或调试工具窗口。
|
||||
Spring Boot 配置默认就会显示。其他类型在通过 **添加服务 › 运行配置类型** 添加后,或者该类型的配置运行过一次后出现。每种类型一个分组。
|
||||
|
||||
- 分组操作:**全部运行**、**全部重启**、**全部停止**、**在浏览器中打开**。
|
||||
- 配置操作:**运行**(或 **重新运行**)、**调试**、**停止**、**在浏览器中打开**、**更新应用**(仅支持的配置)。
|
||||
@@ -31,7 +31,7 @@ OpenIDEA 通过 `docker` 命令行操作 Docker,所以只要能提供可用的
|
||||
|
||||
### 连接
|
||||
|
||||
什么都不配置时,服务中不列出任何 Docker 连接。要添加一个连接(第一个通常连接 Docker CLI 默认设置:`DOCKER_HOST` 或当前上下文),选择 **添加服务 › Docker 连接…**:
|
||||
什么都不配置时,服务中会有一个名为 **Docker** 的连接,使用 Docker CLI 默认设置(`DOCKER_HOST` 或当前上下文)。要添加其他连接,选择 **添加服务 › Docker 连接…**:
|
||||
|
||||
| 字段 | 说明 |
|
||||
| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
|
||||
@@ -147,13 +147,3 @@ test("modal Commit dialog: double-click opens the diff in a front window, not an
|
||||
await expect(sourceTab(page)).toHaveCount(0);
|
||||
await expect(diffTab(page)).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("F4 in the changes tree opens the source file even where activation opens the diff", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const panel = await openCommitWindow(page);
|
||||
await panel.getByRole("tree", { name: "Changes" }).getByText(FILE, { exact: true }).click();
|
||||
await page.keyboard.press("F4");
|
||||
await expect(sourceTab(page)).toHaveAttribute("aria-selected", "true");
|
||||
await expect(diffTab(page)).toHaveCount(0);
|
||||
});
|
||||
@@ -153,46 +153,3 @@ test("Docker Compose editor completes service references and navigates to declar
|
||||
await page.keyboard.press("Meta+b");
|
||||
await expect(editor.locator(".cm-activeLine")).toHaveText(" backend:");
|
||||
});
|
||||
|
||||
test("the Services detail pane adds no second scrollbar over a console", async ({ workbench: page }) => {
|
||||
// A short window: the run toolbar is taller than the detail pane, which used to make
|
||||
// the split panel scroll too (the console had its own scrollbar right beside it).
|
||||
await page.setViewportSize({ width: 1200, height: 640 });
|
||||
await page.evaluate(async () => {
|
||||
const store = await import(/* @vite-ignore */ "/src/features/run/store.ts" as string);
|
||||
await store.startSampleOutput(200, 50);
|
||||
const id = store.useRun.getState().activeSession as string;
|
||||
store.useRun.setState((s: { sessions: { id: string }[]; versions: Record<string, number> }) => ({
|
||||
sessions: s.sessions.map((x) => (x.id === id ? { ...x, status: "running" } : x)),
|
||||
versions: { ...s.versions, [id]: (s.versions[id] ?? 0) + 1 },
|
||||
}));
|
||||
const svc = await import(/* @vite-ignore */ "/src/features/run/services.tsx" as string);
|
||||
const tree = await import(/* @vite-ignore */ "/src/features/services/tree.ts" as string);
|
||||
const session = store.useRun.getState().sessions.find((s: { id: string }) => s.id === id);
|
||||
svc.addType(session.config.kind);
|
||||
tree.useServicesTree.setState({
|
||||
selectedKey: `run:config:${session.config.id}`,
|
||||
selectedKeys: new Set([`run:config:${session.config.id}`]),
|
||||
});
|
||||
});
|
||||
await page.keyboard.press("Meta+8");
|
||||
await expect(page.getByRole("log").first()).toBeVisible();
|
||||
const result = await page.evaluate(() => {
|
||||
const log = document.querySelector('[data-toolwindow="services"] [role="log"]');
|
||||
let panel: Element | null = log;
|
||||
while (panel && !panel.hasAttribute("data-panel")) panel = panel.parentElement;
|
||||
const inner = panel?.firstElementChild as HTMLElement | null;
|
||||
const scrollers: string[] = [];
|
||||
for (const el of document.querySelectorAll<HTMLElement>('[data-toolwindow="services"] *')) {
|
||||
const cs = getComputedStyle(el);
|
||||
if ((cs.overflowY === "auto" || cs.overflowY === "scroll") && el.scrollHeight - el.clientHeight > 2)
|
||||
scrollers.push(String(el.className));
|
||||
}
|
||||
return { overflowY: inner ? getComputedStyle(inner).overflowY : "missing", scrollers };
|
||||
});
|
||||
// The panel's inner div carries the library's inline `overflow: auto`; the detail pane
|
||||
// overrides it, so the console is the only scroller.
|
||||
expect(result.overflowY).toBe("hidden");
|
||||
expect(result.scrollers.filter((c) => c.includes("detailPane") || c.includes("_panel_"))).toEqual([]);
|
||||
expect(result.scrollers.length).toBeGreaterThan(0);
|
||||
});
|
||||
@@ -134,68 +134,3 @@ test("sorts collapsed workspace roots by project type, shows their icons and ref
|
||||
]);
|
||||
await expect(tree.getByRole("treeitem", { selected: true })).toContainText("z-web");
|
||||
});
|
||||
|
||||
test("keeps surviving workspace icons and type order during removal", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const module = "/src/platform/project.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ module);
|
||||
const current = useProject.getState().project;
|
||||
const projects = ["/work/a-go", "/work/b-web", "/work/z-rust"];
|
||||
const project = {
|
||||
...current,
|
||||
root: "/workspace",
|
||||
name: "Workspace",
|
||||
workspace: { version: 1, name: "Workspace", projects },
|
||||
};
|
||||
const markers: Record<string, string> = {
|
||||
"/work/a-go": "go.mod",
|
||||
"/work/b-web": "package.json",
|
||||
"/work/z-rust": "Cargo.toml",
|
||||
};
|
||||
const rescan = new Promise<void>((resolve) => {
|
||||
window.__ipc.handlers.finish_workspace_rescan = () => resolve();
|
||||
});
|
||||
let removed = false;
|
||||
window.__ipc.handlers.fs_read_dir = async ({ path }) => {
|
||||
if (removed) await rescan;
|
||||
const name = markers[String(path)];
|
||||
return name
|
||||
? [{ path: `${path}/${name}`, name, kind: "file", size: 0, mtimeMs: 0, ignored: false, excluded: false }]
|
||||
: [];
|
||||
};
|
||||
window.__ipc.handlers.project_roots = () => ({ folders: [] });
|
||||
window.__ipc.handlers.workspace_update = ({ projects }) => {
|
||||
removed = true;
|
||||
return { ...project, workspace: { ...project.workspace, projects } };
|
||||
};
|
||||
useProject.setState({ project });
|
||||
});
|
||||
|
||||
const tree = page.getByRole("tree", { name: "Project" });
|
||||
const rust = tree.locator('[data-project-path="/work/z-rust"]');
|
||||
const go = tree.locator('[data-project-path="/work/a-go"]');
|
||||
const web = tree.locator('[data-project-path="/work/b-web"]');
|
||||
const icons = () =>
|
||||
Promise.all(
|
||||
[rust, go].map((row) =>
|
||||
row.locator("svg path").evaluateAll((paths) => paths.map((path) => path.getAttribute("d"))),
|
||||
),
|
||||
);
|
||||
const panel = page.getByRole("region", { name: "Project", exact: true });
|
||||
await panel.getByRole("button", { name: "Collapse All", exact: true }).click();
|
||||
await panel.getByRole("button", { name: "Options", exact: true }).click();
|
||||
await page.getByRole("menuitemcheckbox", { name: "Sort by Type", exact: true }).click();
|
||||
const rows = tree.locator('[data-project-path^="/work/"]');
|
||||
await expect(rows).toHaveText(["z-rust/work/z-rust", "a-go/work/a-go", "b-web/work/b-web"]);
|
||||
const before = await icons();
|
||||
|
||||
await web.click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Remove from Workspace", exact: true }).click();
|
||||
await expect(web).toHaveCount(0);
|
||||
await page.screenshot({ path: test.info().outputPath("workspace-removal.png"), animations: "disabled" });
|
||||
expect(await icons()).toEqual(before);
|
||||
await expect(rows).toHaveText(["z-rust/work/z-rust", "a-go/work/a-go"]);
|
||||
|
||||
await page.evaluate(() => window.__ipc.handlers.finish_workspace_rescan!({}));
|
||||
});
|
||||
@@ -108,6 +108,7 @@ windows = { version = "0.62", features = [
|
||||
windows-sys = { version = "0.61", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_UI_Input_KeyboardAndMouse",
|
||||
"Win32_UI_Shell",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
] }
|
||||
@@ -6,7 +6,7 @@ use ide_core::{ChangeSet, DocId, IdeResult, OutlineItem, Range};
|
||||
pub use ide_host::ops::doc::*;
|
||||
use ide_language::{FoldRange, SyntaxHighlights};
|
||||
use ide_text::LineEnding;
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, HistoryEntry};
|
||||
use ide_workspace::{DocumentInfo, HistoryEntry};
|
||||
use std::path::PathBuf;
|
||||
use tauri::{Manager, State, Window};
|
||||
|
||||
@@ -87,7 +87,7 @@ pub async fn doc_ui_mode(window: Window, state: State<'_, AppState>, path: PathB
|
||||
ide_host::ops::doc::doc_ui_mode(&state.host, window.label(), path).await
|
||||
}
|
||||
|
||||
/// "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding and BOM state.
|
||||
/// "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding label.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn doc_set_encoding(
|
||||
@@ -96,21 +96,10 @@ pub async fn doc_set_encoding(
|
||||
doc: DocId,
|
||||
encoding: String,
|
||||
reload: bool,
|
||||
) -> IdeResult<DocumentEncoding> {
|
||||
) -> IdeResult<String> {
|
||||
ide_host::ops::doc::doc_set_encoding(&state.host, window.label(), doc, encoding, reload).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn doc_set_bom(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
doc: DocId,
|
||||
has_bom: bool,
|
||||
) -> IdeResult<DocumentEncoding> {
|
||||
ide_host::ops::doc::doc_set_bom(&state.host, window.label(), doc, has_bom).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn doc_set_line_ending(
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
//! Detects shortcuts the OS already gave to another app (Windows only).
|
||||
//!
|
||||
//! Some vendors register system-wide hotkeys (e.g. NVIDIA's overlay grabs
|
||||
//! `Alt+R` / `Alt+Shift+R`), so those keystrokes never reach the IDE. Probing
|
||||
//! asks Windows to register each combo for an instant: success means it is
|
||||
//! free (released right away), `ERROR_HOTKEY_ALREADY_REGISTERED` means another
|
||||
//! app grabbed it. Nothing is left registered.
|
||||
|
||||
use ide_core::IdeResult;
|
||||
|
||||
/// Reports which of `combos` (single-stroke `Alt+Shift+R`-style bindings) are
|
||||
/// already registered to another app. Empty everywhere but Windows.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn system_probe_hotkeys(combos: Vec<String>) -> IdeResult<Vec<String>> {
|
||||
Ok(combos.into_iter().filter(|combo| imp::grabbed(combo)).collect())
|
||||
}
|
||||
|
||||
/// A parsed binding: `RegisterHotKey` modifiers plus a virtual-key code.
|
||||
#[cfg(windows)]
|
||||
struct Hotkey {
|
||||
modifiers: u32,
|
||||
vk: u32,
|
||||
}
|
||||
|
||||
/// Splits a canonical single-stroke binding into modifiers and key; `None`
|
||||
/// for chords, double-modifier gestures, mouse buttons and unknown keys.
|
||||
#[cfg(windows)]
|
||||
fn parse_combo(combo: &str) -> Option<Hotkey> {
|
||||
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{MOD_ALT, MOD_CONTROL, MOD_SHIFT, MOD_WIN};
|
||||
|
||||
if combo.contains(' ') {
|
||||
return None;
|
||||
}
|
||||
let mut parts = combo.split('+');
|
||||
let key = parts.next_back()?;
|
||||
let mut modifiers = 0;
|
||||
for part in parts {
|
||||
modifiers |= match part.to_ascii_uppercase().as_str() {
|
||||
"CTRL" => MOD_CONTROL,
|
||||
"ALT" => MOD_ALT,
|
||||
"SHIFT" => MOD_SHIFT,
|
||||
"META" => MOD_WIN,
|
||||
_ => return None,
|
||||
};
|
||||
}
|
||||
if modifiers == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(Hotkey { modifiers, vk: vk_of(key)? })
|
||||
}
|
||||
|
||||
/// The virtual-key code of a binding key, or `None` when it has no single
|
||||
/// `RegisterHotKey` code (mouse buttons, gestures, layout-dependent keys).
|
||||
#[cfg(windows)]
|
||||
fn vk_of(key: &str) -> Option<u32> {
|
||||
if key.len() == 1 {
|
||||
let c = key.as_bytes()[0].to_ascii_uppercase();
|
||||
if c.is_ascii_alphanumeric() {
|
||||
return Some(u32::from(c));
|
||||
}
|
||||
return match c {
|
||||
b'-' => Some(0xBD),
|
||||
b'=' => Some(0xBB),
|
||||
b'[' => Some(0xDB),
|
||||
b']' => Some(0xDD),
|
||||
b'\\' => Some(0xDC),
|
||||
b';' => Some(0xBA),
|
||||
b'\'' => Some(0xDE),
|
||||
b',' => Some(0xBC),
|
||||
b'.' => Some(0xBE),
|
||||
b'/' => Some(0xBF),
|
||||
b'`' => Some(0xC0),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
// "F13" → 0x7C … "F24" → 0x87; anything else falls through to the names below.
|
||||
let fkey =
|
||||
key.strip_prefix('F').and_then(|n| n.parse::<u32>().ok()).filter(|n| (1..=24).contains(n)).map(|n| 0x6F + n);
|
||||
if fkey.is_some() {
|
||||
return fkey;
|
||||
}
|
||||
match key.to_ascii_uppercase().as_str() {
|
||||
"SPACE" => Some(0x20),
|
||||
"ENTER" | "RETURN" => Some(0x0D),
|
||||
"ESCAPE" | "ESC" => Some(0x1B),
|
||||
"TAB" => Some(0x09),
|
||||
"BACKSPACE" | "BACK" => Some(0x08),
|
||||
"DELETE" | "DEL" => Some(0x2E),
|
||||
"INSERT" | "INS" => Some(0x2D),
|
||||
"HOME" => Some(0x24),
|
||||
"END" => Some(0x23),
|
||||
"PAGEUP" | "PRIOR" => Some(0x21),
|
||||
"PAGEDOWN" | "NEXT" => Some(0x22),
|
||||
"UP" => Some(0x26),
|
||||
"DOWN" => Some(0x28),
|
||||
"LEFT" => Some(0x25),
|
||||
"RIGHT" => Some(0x27),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use super::{Hotkey, parse_combo};
|
||||
use std::sync::atomic::{AtomicI32, Ordering};
|
||||
use windows_sys::Win32::Foundation::{ERROR_HOTKEY_ALREADY_REGISTERED, GetLastError};
|
||||
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{RegisterHotKey, UnregisterHotKey};
|
||||
|
||||
/// Probe ids (never shown, never left registered).
|
||||
static NEXT_ID: AtomicI32 = AtomicI32::new(0x1DEA00);
|
||||
|
||||
/// Registers `combo` for an instant: grabbed iff Windows refuses with
|
||||
/// `ERROR_HOTKEY_ALREADY_REGISTERED`. A granted registration is released
|
||||
/// before returning, so probing never steals a shortcut.
|
||||
pub(super) fn grabbed(combo: &str) -> bool {
|
||||
let Some(Hotkey { modifiers, vk }) = parse_combo(combo) else {
|
||||
return false;
|
||||
};
|
||||
// SAFETY: registering a hotkey to a null window only tests availability;
|
||||
// the id is unique per probe and unregistered on success.
|
||||
unsafe {
|
||||
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
|
||||
if RegisterHotKey(std::ptr::null_mut(), id, modifiers, vk) != 0 {
|
||||
UnregisterHotKey(std::ptr::null_mut(), id);
|
||||
false
|
||||
} else {
|
||||
GetLastError() == ERROR_HOTKEY_ALREADY_REGISTERED
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
mod imp {
|
||||
/// No other platform lets background apps swallow our keystrokes this way.
|
||||
pub(super) fn grabbed(_combo: &str) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, windows))]
|
||||
mod tests {
|
||||
use super::imp::grabbed;
|
||||
use super::parse_combo;
|
||||
use windows_sys::Win32::Foundation::{ERROR_HOTKEY_ALREADY_REGISTERED, GetLastError};
|
||||
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{MOD_ALT, MOD_SHIFT, RegisterHotKey, UnregisterHotKey};
|
||||
|
||||
#[test]
|
||||
fn parses_modifier_order_and_key() {
|
||||
let hotkey = parse_combo("Alt+Shift+R").expect("Alt+Shift+R parses");
|
||||
assert_eq!(hotkey.modifiers, MOD_ALT | MOD_SHIFT);
|
||||
assert_eq!(hotkey.vk, u32::from(b'R'));
|
||||
let f7 = parse_combo("Alt+F7").expect("Alt+F7 parses");
|
||||
assert_eq!(f7.modifiers, MOD_ALT);
|
||||
assert_eq!(f7.vk, 0x76);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_what_cannot_be_probed() {
|
||||
for combo in ["R", "Alt+R Alt+S", "Shift Shift", "Alt+Button4", "Ctrl+Foo", ""] {
|
||||
assert!(!grabbed(combo), "{combo} must not probe");
|
||||
}
|
||||
}
|
||||
|
||||
/// Holds a real hotkey, then the probe must report it as grabbed — whether
|
||||
/// our hold succeeded or another app already held it (both read 1409).
|
||||
#[test]
|
||||
fn sees_a_hotkey_held_by_another_registration() {
|
||||
const COMBO: &str = "Alt+Shift+F24";
|
||||
const VK_F24: u32 = 0x87;
|
||||
// SAFETY: a test-only registration, released below.
|
||||
let held = unsafe { RegisterHotKey(std::ptr::null_mut(), 0x1DEAFE, MOD_ALT | MOD_SHIFT, VK_F24) != 0 };
|
||||
if !held {
|
||||
assert_eq!(
|
||||
unsafe { GetLastError() },
|
||||
ERROR_HOTKEY_ALREADY_REGISTERED,
|
||||
"the test hotkey must be holdable or already held"
|
||||
);
|
||||
}
|
||||
assert!(grabbed(COMBO), "a held hotkey reads as grabbed");
|
||||
if held {
|
||||
// SAFETY: releases the registration above.
|
||||
unsafe {
|
||||
UnregisterHotKey(std::ptr::null_mut(), 0x1DEAFE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ pub mod fs;
|
||||
pub mod github;
|
||||
pub mod heap;
|
||||
pub mod history;
|
||||
pub mod hotkeys;
|
||||
pub mod http;
|
||||
pub mod java;
|
||||
pub mod lsp;
|
||||
@@ -194,7 +195,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
doc::doc_snapshot,
|
||||
doc::doc_ui_mode,
|
||||
doc::doc_set_encoding,
|
||||
doc::doc_set_bom,
|
||||
doc::doc_set_line_ending,
|
||||
doc::doc_outline,
|
||||
doc::doc_folding,
|
||||
@@ -214,6 +214,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
history::history_list_dir,
|
||||
history::history_put_label,
|
||||
history::history_restore,
|
||||
hotkeys::system_probe_hotkeys,
|
||||
refactor::refactor_file_move_edits,
|
||||
refactor::refactor_file_move_text_edits,
|
||||
refactor::refactor_move_files,
|
||||
|
||||
@@ -83,6 +83,7 @@ pub async fn app_metrics(app: AppHandle, state: State<'_, AppState>) -> IdeResul
|
||||
m.index_files += status.files;
|
||||
m.index_symbols += status.symbols;
|
||||
m.indexing |= status.indexing;
|
||||
let project = project_name(&p.root);
|
||||
for s in p.lsp.servers() {
|
||||
if matches!(s.status, ServerStatus::Starting | ServerStatus::Ready | ServerStatus::Busy) {
|
||||
m.language_servers += 1;
|
||||
@@ -92,10 +93,7 @@ pub async fn app_metrics(app: AppHandle, state: State<'_, AppState>) -> IdeResul
|
||||
pid,
|
||||
category: MemoryCategory::LanguageServer,
|
||||
label: s.name,
|
||||
// A project can attach several roots (additional content
|
||||
// roots); name the server's own workspace root, not the
|
||||
// project folder, so rows of one name don't collide.
|
||||
detail: Some(project_name(s.root.as_ref())),
|
||||
detail: Some(project.clone()),
|
||||
with_children: true,
|
||||
});
|
||||
}
|
||||
@@ -235,24 +233,3 @@ pub async fn clear_caches(window: Window, state: State<'_, AppState>) -> IdeResu
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Language server rows are named by the server's own workspace root, not
|
||||
/// the project folder: one project window can attach additional content
|
||||
/// roots, and a server per root would otherwise show up as rows with the
|
||||
/// same label and detail (e.g. "pyrefly MindSpeed" twice for MindSpeed +
|
||||
/// Megatron-LM).
|
||||
#[test]
|
||||
fn server_row_detail_is_the_server_root_folder() {
|
||||
let project = std::path::Path::new("B:/Program/Project/Ascend/MindSpeed");
|
||||
let megatron = std::path::PathBuf::from("B:/Program/Project/Source/Megatron-LM");
|
||||
assert_eq!(project_name(project), "MindSpeed");
|
||||
assert_ne!(project_name(&megatron), project_name(project));
|
||||
// IPC paths are `/`-separated on every OS, so `file_name` sees the
|
||||
// folder without a Windows special case.
|
||||
assert_eq!(project_name(&megatron), "Megatron-LM");
|
||||
}
|
||||
}
|
||||
+7
-43
@@ -298,9 +298,8 @@ export const commands = {
|
||||
* without opening it: previews of closed files.
|
||||
*/
|
||||
docUiMode: (path: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("doc_ui_mode", { path })),
|
||||
/** "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding and BOM state. */
|
||||
docSetEncoding: (doc: DocId, encoding: string, reload: boolean) => typedError<DocumentEncoding, IdeError>(__TAURI_INVOKE("doc_set_encoding", { doc, encoding, reload })),
|
||||
docSetBom: (doc: DocId, hasBom: boolean) => typedError<DocumentEncoding, IdeError>(__TAURI_INVOKE("doc_set_bom", { doc, hasBom })),
|
||||
/** "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding label. */
|
||||
docSetEncoding: (doc: DocId, encoding: string, reload: boolean) => typedError<string, IdeError>(__TAURI_INVOKE("doc_set_encoding", { doc, encoding, reload })),
|
||||
docSetLineEnding: (doc: DocId, lineEnding: LineEnding) => typedError<null, IdeError>(__TAURI_INVOKE("doc_set_line_ending", { doc, lineEnding })),
|
||||
/**
|
||||
* Structure view: LSP document symbols when available (with tree-sitter
|
||||
@@ -367,6 +366,11 @@ export const commands = {
|
||||
* file and its folders); an open editor updates in place.
|
||||
*/
|
||||
historyRestore: (path: string, id: string) => typedError<null, IdeError>(__TAURI_INVOKE("history_restore", { path, id })),
|
||||
/**
|
||||
* Reports which of `combos` (single-stroke `Alt+Shift+R`-style bindings) are
|
||||
* already registered to another app. Empty everywhere but Windows.
|
||||
*/
|
||||
systemProbeHotkeys: (combos: string[]) => typedError<string[], IdeError>(__TAURI_INVOKE("system_probe_hotkeys", { combos })),
|
||||
/** `workspace/willRenameFiles` on every interested server (before the move). Cancellable. */
|
||||
refactorFileMoveEdits: (request: RequestId, moves: FileMove[]) => typedError<FileRenameEdits, IdeError>(__TAURI_INVOKE("refactor_file_move_edits", { request, moves })),
|
||||
/**
|
||||
@@ -2715,13 +2719,6 @@ export type CodeStyleSettings_Serialize = {
|
||||
formatterTagsRegexp: boolean,
|
||||
};
|
||||
|
||||
/** Editor › Inlay Hints › Code Vision position (IDEA's "Default position for metrics"). */
|
||||
export type CodeVisionPosition =
|
||||
/** A row of its own above the declaration. */
|
||||
"top" |
|
||||
/** After the end of the declaration's first line. */
|
||||
"right";
|
||||
|
||||
/** ColorInfo data. */
|
||||
export type ColorInfo = {
|
||||
range: Range,
|
||||
@@ -4017,12 +4014,6 @@ export type DockerVolume = {
|
||||
labels?: { [key in string]: string },
|
||||
};
|
||||
|
||||
/** Encoding and BOM currently applied to an open document. */
|
||||
export type DocumentEncoding = {
|
||||
encoding: string,
|
||||
hasBom: boolean,
|
||||
};
|
||||
|
||||
/** What the UI needs to show an opened document. */
|
||||
export type DocumentInfo = {
|
||||
id: DocId,
|
||||
@@ -4031,7 +4022,6 @@ export type DocumentInfo = {
|
||||
version: number,
|
||||
language: LanguageId,
|
||||
encoding: string,
|
||||
hasBom: boolean,
|
||||
lineEnding: LineEnding,
|
||||
readOnly: boolean,
|
||||
dirty: boolean,
|
||||
@@ -5530,19 +5520,6 @@ export type IndexEntry = {
|
||||
* the IDE before showing it.
|
||||
*/
|
||||
icon?: PluginIcon | null,
|
||||
/** Where to read more: the manifest's homepage, else the registry's source repository. */
|
||||
homepage?: string | null,
|
||||
/** This version's release notes (the manifest's `change-notes`). */
|
||||
notes?: string | null,
|
||||
/** Downloads of the plugin's packages, as counted by whoever serves them. */
|
||||
downloads?: number | null,
|
||||
/** Picked by the marketplace's maintainers. */
|
||||
featured?: boolean,
|
||||
/**
|
||||
* Project-relative paths whose presence makes the plugin worth suggesting
|
||||
* (`pom.xml`, `config/routes.rb`).
|
||||
*/
|
||||
suggest?: string[],
|
||||
};
|
||||
|
||||
export type IndexStatus = {
|
||||
@@ -5590,12 +5567,6 @@ export type InlayHintsSettings = {
|
||||
codeVisionUsages?: boolean,
|
||||
/** Code vision: last author of a declaration (VCS blame) beside its usages. */
|
||||
codeVisionAuthor?: boolean,
|
||||
/** Code vision: "no usages" on declarations nothing uses (IDEA shows it; clicking searches everywhere). */
|
||||
codeVisionNoUsages?: boolean,
|
||||
/** Code vision: where the usages go, above the declaration or at the end of its line. */
|
||||
codeVisionUsagesPosition?: CodeVisionPosition,
|
||||
/** Code vision: where the author goes, above the declaration or at the end of its line. */
|
||||
codeVisionAuthorPosition?: CodeVisionPosition,
|
||||
};
|
||||
|
||||
export type InlayKind = "type" | "parameter" | "other";
|
||||
@@ -6494,8 +6465,6 @@ export type MarketPlugin = {
|
||||
installed: string | null,
|
||||
/** Whether this IDE can load `entry` (the newest version it can, else the newest). */
|
||||
compatible: boolean,
|
||||
/** The publisher's display name, as the index lists it. */
|
||||
publisherName?: string | null,
|
||||
} & IndexEntry;
|
||||
|
||||
export type Markup = {
|
||||
@@ -6665,11 +6634,6 @@ export type McpServerInput = {
|
||||
export type McpServerSettings = {
|
||||
/** Serve the tools on 127.0.0.1 while the IDE runs. */
|
||||
enabled?: boolean,
|
||||
/**
|
||||
* Run the tools that change the project or start processes without asking first
|
||||
* (IDEA's brave mode). Read from the IDE's own settings only, never a project's.
|
||||
*/
|
||||
runWithoutConfirmation?: boolean,
|
||||
};
|
||||
|
||||
/** What Settings › Agents › MCP Server shows. */
|
||||
|
||||
@@ -595,8 +595,6 @@ export interface CodeLens {
|
||||
run?: (view: EditorView, event: MouseEvent) => void;
|
||||
/** Lower first within a line. Default 100. */
|
||||
order?: number;
|
||||
/** The Code Vision setting that places it ("usages", "author"); a lens without one goes above the line. */
|
||||
kind?: string;
|
||||
}
|
||||
|
||||
export const codeLenses = Facet.define<readonly CodeLens[], readonly CodeLens[]>({
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
isTauri,
|
||||
onIdeEvent,
|
||||
type DocId,
|
||||
type DocumentEncoding,
|
||||
type DocumentInfo,
|
||||
type FoldRange,
|
||||
type LanguageInfo_Serialize,
|
||||
@@ -48,10 +47,8 @@ export interface DocBackend {
|
||||
syncFromDisk?(): Promise<void>;
|
||||
snapshot(doc: DocId): Promise<DocumentInfo>;
|
||||
setLineEnding(doc: DocId, lineEnding: LineEnding): Promise<void>;
|
||||
/** "Reload with Encoding" (`reload`) or "Convert to Encoding"; resolves to the new encoding and BOM state. */
|
||||
setEncoding(doc: DocId, encoding: string, reload: boolean): Promise<DocumentEncoding>;
|
||||
/** Adds or removes the BOM on a UTF-8 document; the change is written on save. */
|
||||
setBom(doc: DocId, hasBom: boolean): Promise<DocumentEncoding>;
|
||||
/** "Reload with Encoding" (`reload`) or "Convert to Encoding"; resolves to the new encoding. */
|
||||
setEncoding(doc: DocId, encoding: string, reload: boolean): Promise<string>;
|
||||
outline(doc: DocId): Promise<OutlineItem[]>;
|
||||
folding(doc: DocId): Promise<FoldRange[]>;
|
||||
/** Tree-sitter highlighting, for languages without a CodeMirror mode. */
|
||||
@@ -86,7 +83,6 @@ export const ipcBackend: DocBackend = {
|
||||
snapshot: (doc) => call(commands.docSnapshot(doc)),
|
||||
setLineEnding: async (doc, le) => void (await call(commands.docSetLineEnding(doc, le))),
|
||||
setEncoding: (doc, encoding, reload) => call(commands.docSetEncoding(doc, encoding, reload)),
|
||||
setBom: (doc, hasBom) => call(commands.docSetBom(doc, hasBom)),
|
||||
outline: (doc) => call(commands.docOutline(doc)),
|
||||
folding: (doc) => call(commands.docFolding(doc)),
|
||||
highlights: (doc) => call(commands.docHighlights(doc)),
|
||||
@@ -112,11 +108,9 @@ interface MemDoc {
|
||||
path: string;
|
||||
text: string;
|
||||
saved: string;
|
||||
savedBom: boolean;
|
||||
version: number;
|
||||
refs: number;
|
||||
lineEnding: LineEnding;
|
||||
hasBom: boolean;
|
||||
readOnly: boolean;
|
||||
language: string;
|
||||
uiMode?: string;
|
||||
@@ -383,7 +377,6 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
const dirtyHandlers = new Set<(e: { doc: DocId; dirty: boolean }) => void>();
|
||||
let nextId = 1;
|
||||
const store = new Map(Object.entries(files));
|
||||
const savedBoms = new Map<string, boolean>();
|
||||
|
||||
const info = (d: MemDoc): DocumentInfo => ({
|
||||
id: d.id,
|
||||
@@ -392,10 +385,9 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
version: d.version,
|
||||
language: d.language,
|
||||
encoding: "UTF-8",
|
||||
hasBom: d.hasBom,
|
||||
lineEnding: d.lineEnding,
|
||||
readOnly: d.readOnly,
|
||||
dirty: d.text !== d.saved || d.hasBom !== d.savedBom,
|
||||
dirty: d.text !== d.saved,
|
||||
...(d.uri ? { uri: d.uri } : {}),
|
||||
...(d.uiMode ? { uiMode: d.uiMode } : {}),
|
||||
});
|
||||
@@ -419,7 +411,7 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
return d;
|
||||
};
|
||||
const setDirty = (d: MemDoc, before: boolean) => {
|
||||
const now = d.text !== d.saved || d.hasBom !== d.savedBom;
|
||||
const now = d.text !== d.saved;
|
||||
if (now !== before) dirtyHandlers.forEach((h) => h({ doc: d.id, dirty: now }));
|
||||
};
|
||||
const delay = <T>(v: () => T): Promise<T> =>
|
||||
@@ -447,18 +439,15 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
return info(d);
|
||||
}
|
||||
const text = store.get(path) ?? sampleFor(path);
|
||||
const hasBom = savedBoms.get(path) ?? false;
|
||||
const ext = path.slice(path.lastIndexOf(".") + 1).toLowerCase();
|
||||
const d: MemDoc = {
|
||||
id: nextId++,
|
||||
path,
|
||||
text,
|
||||
saved: text,
|
||||
savedBom: hasBom,
|
||||
version: 0,
|
||||
refs: 1,
|
||||
lineEnding: "lf",
|
||||
hasBom,
|
||||
readOnly: false,
|
||||
language: EXT_LANG[ext] ?? "plaintext",
|
||||
};
|
||||
@@ -484,11 +473,9 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
path: uri,
|
||||
text,
|
||||
saved: text,
|
||||
savedBom: false,
|
||||
version: 0,
|
||||
refs: 1,
|
||||
lineEnding: "lf",
|
||||
hasBom: false,
|
||||
readOnly: true,
|
||||
language: ext === "class" ? "java" : (EXT_LANG[ext] ?? "plaintext"),
|
||||
uri,
|
||||
@@ -509,7 +496,7 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
if (d.readOnly) throw new IpcError({ kind: "permissionDenied", message: "read-only" });
|
||||
if (baseVersion !== d.version)
|
||||
throw new IpcError({ kind: "outOfSync", message: `base ${baseVersion}, document at ${d.version}` });
|
||||
const before = d.text !== d.saved || d.hasBom !== d.savedBom;
|
||||
const before = d.text !== d.saved;
|
||||
d.text = applyChanges(d.text, changes);
|
||||
d.version++;
|
||||
setDirty(d, before);
|
||||
@@ -518,11 +505,9 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
},
|
||||
async save(doc) {
|
||||
const d = get(doc);
|
||||
const before = d.text !== d.saved || d.hasBom !== d.savedBom;
|
||||
const before = d.text !== d.saved;
|
||||
d.saved = d.text;
|
||||
d.savedBom = d.hasBom;
|
||||
store.set(d.path, d.text);
|
||||
savedBoms.set(d.path, d.hasBom);
|
||||
setDirty(d, before);
|
||||
},
|
||||
async snapshot(doc) {
|
||||
@@ -531,16 +516,8 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
async setLineEnding(doc, le) {
|
||||
get(doc).lineEnding = le;
|
||||
},
|
||||
async setEncoding(doc, encoding) {
|
||||
return { encoding, hasBom: get(doc).hasBom };
|
||||
},
|
||||
async setBom(doc, hasBom) {
|
||||
const d = get(doc);
|
||||
if (d.readOnly) throw new IpcError({ kind: "permissionDenied", message: "read-only" });
|
||||
const before = d.text !== d.saved || d.hasBom !== d.savedBom;
|
||||
d.hasBom = hasBom;
|
||||
setDirty(d, before);
|
||||
return { encoding: "utf-8", hasBom: d.hasBom };
|
||||
async setEncoding(_doc, encoding) {
|
||||
return encoding;
|
||||
},
|
||||
async outline(doc) {
|
||||
// Brace-based outline good enough for the dev shell.
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { codeLenses } from "@/editor/api";
|
||||
import { codeLensExtension, codeLensPositions, declarationStart, groupLenses, indentColumns } from "./codeLens";
|
||||
import { declarationStart, groupLenses, indentColumns } from "./codeLens";
|
||||
|
||||
const doc = (text: string) => EditorState.create({ doc: text });
|
||||
|
||||
@@ -36,44 +34,3 @@ describe("code lens layout", () => {
|
||||
expect(indentColumns(" x", 4)).toBe(4);
|
||||
});
|
||||
});
|
||||
|
||||
describe("code lens position", () => {
|
||||
const doc = "@contextmanager\ndef lifespan(app):\n pass\n";
|
||||
const lenses = [
|
||||
{ pos: 16, title: "1 usage", kind: "usages", order: 10 },
|
||||
{ pos: 16, title: "Denis", kind: "author", order: 20 },
|
||||
];
|
||||
const view = (positions: Record<string, "top" | "right">) =>
|
||||
new EditorView({
|
||||
state: EditorState.create({
|
||||
doc,
|
||||
extensions: [codeLensExtension, codeLenses.of(lenses), codeLensPositions.of(positions)],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
const texts = (els: NodeListOf<Element>) => [...els].map((e) => e.textContent);
|
||||
|
||||
it("puts every lens on a row above the declaration by default, with no separators", () => {
|
||||
const v = view({});
|
||||
expect(texts(v.dom.querySelectorAll(".cm-openidea-lens"))).toEqual(["1 usageDenis"]);
|
||||
expect(v.dom.querySelector(".cm-openidea-lens")?.closest(".cm-line")).toBeNull();
|
||||
expect(v.dom.querySelector(".cm-openidea-lensInline")).toBeNull();
|
||||
v.destroy();
|
||||
});
|
||||
|
||||
it("puts each kind where its setting says: usages at the line end, the author above", () => {
|
||||
const v = view({ usages: "right" });
|
||||
expect(texts(v.dom.querySelectorAll(".cm-openidea-lens"))).toEqual(["Denis"]);
|
||||
const inline = v.dom.querySelector(".cm-openidea-lensInline");
|
||||
expect(inline?.textContent).toBe("1 usage");
|
||||
expect(inline?.closest(".cm-line")?.textContent).toBe("@contextmanager1 usage");
|
||||
v.destroy();
|
||||
});
|
||||
|
||||
it("puts both at the line end", () => {
|
||||
const v = view({ usages: "right", author: "right" });
|
||||
expect(v.dom.querySelector(".cm-openidea-lens")).toBeNull();
|
||||
expect(texts(v.dom.querySelectorAll(".cm-openidea-lensInline"))).toEqual(["1 usageDenis"]);
|
||||
v.destroy();
|
||||
});
|
||||
});
|
||||
@@ -1,24 +1,14 @@
|
||||
/**
|
||||
* Renders `codeLenses` (editor/api) as one small hint row above the target
|
||||
* line, indented like the line (IDEA "3 usages Run test" inlays), and those
|
||||
* whose kind is set to "right" (`codeLensPositions`) after the end of that line.
|
||||
* line, indented like the line (IDEA "3 usages | Run test" inlays).
|
||||
*/
|
||||
import { EditorState, Facet, RangeSetBuilder, type Extension } from "@codemirror/state";
|
||||
import { EditorState, RangeSetBuilder, type Extension } from "@codemirror/state";
|
||||
import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view";
|
||||
import { getIndentUnit } from "@codemirror/language";
|
||||
import { codeLenses, type CodeLens } from "@/editor/api";
|
||||
import { guideVars, rainbowGuides } from "./indentGuides";
|
||||
import { LINE_INSET } from "./lineInset";
|
||||
|
||||
/**
|
||||
* Where code lenses of each kind (`CodeLens.kind`) go: a row above the declaration (IDEA's default, also for
|
||||
* kinds not listed) or after the end of its line.
|
||||
*/
|
||||
export const codeLensPositions = Facet.define<
|
||||
Readonly<Record<string, "top" | "right">>,
|
||||
Readonly<Record<string, "top" | "right">>
|
||||
>({ combine: (v) => Object.assign({}, ...v) });
|
||||
|
||||
/** Groups lenses by line start, ordered by line then `order`. Exported for tests. */
|
||||
export function groupLenses(
|
||||
state: EditorState,
|
||||
@@ -81,15 +71,12 @@ class LensWidget extends WidgetType {
|
||||
readonly indent: number,
|
||||
readonly indentUnit: number,
|
||||
readonly rainbow: boolean,
|
||||
/** After the end of the line instead of a row above it. */
|
||||
readonly inline = false,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
private get key(): string {
|
||||
return (
|
||||
(this.inline ? "inline\u0000" : "") +
|
||||
this.indent +
|
||||
"\u0000" +
|
||||
this.indentUnit +
|
||||
@@ -105,9 +92,8 @@ class LensWidget extends WidgetType {
|
||||
}
|
||||
|
||||
override toDOM(view: EditorView): HTMLElement {
|
||||
// The inline one shares no class with the row, so none of the row's block styles reach into the line.
|
||||
const dom = document.createElement(this.inline ? "span" : "div");
|
||||
dom.className = this.inline ? "cm-openidea-lensInline" : "cm-openidea-lens";
|
||||
const dom = document.createElement("div");
|
||||
dom.className = "cm-openidea-lens";
|
||||
this.fill(dom, view);
|
||||
return dom;
|
||||
}
|
||||
@@ -119,11 +105,9 @@ class LensWidget extends WidgetType {
|
||||
|
||||
private fill(dom: HTMLElement, view: EditorView) {
|
||||
dom.textContent = "";
|
||||
dom.style.paddingLeft = `${Math.round(this.indent * view.defaultCharacterWidth) + LINE_INSET}px`;
|
||||
// The guides of the annotated line continue through this row while indent guides are on.
|
||||
const guides = this.inline
|
||||
? null
|
||||
: guideVars(Math.floor(this.indent / this.indentUnit), this.indentUnit, this.rainbow);
|
||||
if (!this.inline) dom.style.paddingLeft = `${Math.round(this.indent * view.defaultCharacterWidth) + LINE_INSET}px`;
|
||||
const guides = guideVars(Math.floor(this.indent / this.indentUnit), this.indentUnit, this.rainbow);
|
||||
if (guides) {
|
||||
dom.style.setProperty("--openidea-guide-images", guides.images);
|
||||
dom.style.setProperty("--openidea-guide-positions", guides.positions);
|
||||
@@ -133,7 +117,14 @@ class LensWidget extends WidgetType {
|
||||
}
|
||||
dom.setAttribute("role", "group");
|
||||
dom.setAttribute("aria-label", "Code lens");
|
||||
for (const lens of this.lenses) {
|
||||
this.lenses.forEach((lens, i) => {
|
||||
if (i > 0) {
|
||||
const sep = document.createElement("span");
|
||||
sep.className = "cm-openidea-lensSep";
|
||||
sep.textContent = "|";
|
||||
sep.setAttribute("aria-hidden", "true");
|
||||
dom.appendChild(sep);
|
||||
}
|
||||
const el = document.createElement(lens.run ? "button" : "span");
|
||||
el.className = lens.run ? "cm-openidea-lensItem cm-openidea-lensAction" : "cm-openidea-lensItem";
|
||||
if (lens.tooltip) el.title = lens.tooltip;
|
||||
@@ -163,11 +154,11 @@ class LensWidget extends WidgetType {
|
||||
});
|
||||
}
|
||||
dom.appendChild(el);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
override get estimatedHeight(): number {
|
||||
return this.inline ? -1 : 16;
|
||||
return 16;
|
||||
}
|
||||
|
||||
override ignoreEvent(): boolean {
|
||||
@@ -178,28 +169,16 @@ class LensWidget extends WidgetType {
|
||||
function buildDecorations(state: EditorState): DecorationSet {
|
||||
const lenses = state.facet(codeLenses);
|
||||
if (!lenses.length) return Decoration.none;
|
||||
const positions = state.facet(codeLensPositions);
|
||||
const right = (l: CodeLens) => !!l.kind && positions[l.kind] === "right";
|
||||
const builder = new RangeSetBuilder<Decoration>();
|
||||
for (const group of groupLenses(state, lenses)) {
|
||||
const line = state.doc.lineAt(group.lineFrom);
|
||||
const indent = indentColumns(line.text, state.tabSize);
|
||||
const unit = Math.max(1, getIndentUnit(state));
|
||||
const rainbow = state.facet(rainbowGuides);
|
||||
const above = group.lenses.filter((l) => !right(l));
|
||||
const after = group.lenses.filter(right);
|
||||
if (above.length)
|
||||
builder.add(
|
||||
line.from,
|
||||
line.from,
|
||||
Decoration.widget({ widget: new LensWidget(above, indent, unit, rainbow), block: true, side: -1 }),
|
||||
);
|
||||
if (after.length)
|
||||
builder.add(
|
||||
line.to,
|
||||
line.to,
|
||||
Decoration.widget({ widget: new LensWidget(after, indent, unit, rainbow, true), side: 1 }),
|
||||
);
|
||||
const widget = new LensWidget(
|
||||
group.lenses,
|
||||
indentColumns(line.text, state.tabSize),
|
||||
Math.max(1, getIndentUnit(state)),
|
||||
state.facet(rainbowGuides),
|
||||
);
|
||||
builder.add(line.from, line.from, Decoration.widget({ widget, block: true, side: -1 }));
|
||||
}
|
||||
return builder.finish();
|
||||
}
|
||||
@@ -208,7 +187,7 @@ const lensTheme = EditorView.theme({
|
||||
".cm-openidea-lens": {
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "12px",
|
||||
gap: "6px",
|
||||
height: "16px",
|
||||
color: "var(--fg-muted)",
|
||||
WebkitUserSelect: "none",
|
||||
@@ -216,37 +195,29 @@ const lensTheme = EditorView.theme({
|
||||
whiteSpace: "nowrap",
|
||||
overflow: "hidden",
|
||||
},
|
||||
// "right": after the line's text, on its baseline, with IDEA's spacing.
|
||||
".cm-openidea-lensInline": {
|
||||
display: "inline-flex",
|
||||
alignItems: "baseline",
|
||||
gap: "12px",
|
||||
marginLeft: "12px",
|
||||
color: "var(--fg-muted)",
|
||||
WebkitUserSelect: "none",
|
||||
userSelect: "none",
|
||||
whiteSpace: "nowrap",
|
||||
},
|
||||
".cm-openidea-lensItem": {
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
gap: "4px",
|
||||
gap: "3px",
|
||||
padding: "0",
|
||||
border: "none",
|
||||
background: "none",
|
||||
font: "inherit",
|
||||
color: "inherit",
|
||||
// The items take the UI font; the row keeps the editor's, so its `ch`-based indent guides line up with the code.
|
||||
},
|
||||
// The row keeps the editor font so its `ch`-based indent guides line up with the code.
|
||||
".cm-openidea-lensItem, .cm-openidea-lensSep": {
|
||||
fontFamily: "var(--font-ui)",
|
||||
fontSize: "var(--fs-tiny)",
|
||||
},
|
||||
".cm-openidea-lensAction": { cursor: "pointer" },
|
||||
".cm-openidea-lensAction:hover": { color: "var(--accent)", textDecoration: "underline" },
|
||||
".cm-openidea-lensSep": { color: "var(--fg-faint)" },
|
||||
".cm-openidea-lensIcon-run": { color: "var(--success)" },
|
||||
});
|
||||
|
||||
/** Base extension (always installed): no cost until a provider contributes lenses. */
|
||||
export const codeLensExtension: Extension = [
|
||||
EditorView.decorations.compute([codeLenses, rainbowGuides, codeLensPositions], buildDecorations),
|
||||
EditorView.decorations.compute([codeLenses, rainbowGuides], buildDecorations),
|
||||
lensTheme,
|
||||
];
|
||||
@@ -355,27 +355,7 @@ export const commentBlock: Command = (view) => {
|
||||
|
||||
/** ⌘/ in a language without line comments (CSS, HTML…): the block comment of the lines. */
|
||||
function blockCommentLines(view: EditorView): boolean {
|
||||
const ranges = selectedLines(view.state);
|
||||
if (uncommentBlock(view, ranges)) return true;
|
||||
const { state } = view;
|
||||
if (
|
||||
ranges.every(
|
||||
(r) =>
|
||||
state.sliceDoc(r.from, r.from + 1) === "{" &&
|
||||
commentPairs(state, state.doc.lineAt(r.from).from)[0]?.open === "{/*",
|
||||
)
|
||||
) {
|
||||
view.dispatch({
|
||||
changes: ranges.flatMap((r) => [
|
||||
{ from: r.from, insert: "{/* " },
|
||||
{ from: r.to, insert: " */}" },
|
||||
]),
|
||||
scrollIntoView: true,
|
||||
userEvent: "input.comment",
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return toggleComment(view);
|
||||
return uncommentBlock(view, selectedLines(view.state)) || toggleComment(view);
|
||||
}
|
||||
|
||||
// --- Enter in a line comment ------------------------------------------------------
|
||||
|
||||
@@ -419,27 +419,6 @@ describe("toggle comment where the tokens depend on the syntax context", () => {
|
||||
// JavaScript, where the tokens are `/* … */`.
|
||||
const wrap = (body: string) => `const a = (\n <div>\n ${body}\n </div>\n);`;
|
||||
|
||||
it.each(["JSX", "TSX"])("comments a JSX expression child with Ctrl+/ in %s", async (name) => {
|
||||
const mode = await languages.find((l) => l.name === name)!.load();
|
||||
const v = make("const view = <section>\n |{label}\n</section>;", mode);
|
||||
commentLine(v);
|
||||
expect(v.state.doc.line(2).text).toBe(" {/* {label} */}");
|
||||
commentLine(v);
|
||||
expect(v.state.doc.toString()).toBe("const view = <section>\n {label}\n</section>;");
|
||||
});
|
||||
|
||||
it.each(["JSX", "TSX"])("comments a selected JSX child subtree with Ctrl+/ in %s", async (name) => {
|
||||
const mode = await languages.find((l) => l.name === name)!.load();
|
||||
const original = "const view = <main>\n <aside>\n <strong>ready</strong>\n </aside>\n</main>;";
|
||||
const v = make(original.replace("<aside>", "[<aside>").replace("</aside>", "</aside>]"), mode);
|
||||
commentLine(v);
|
||||
expect(v.state.doc.toString()).toBe(
|
||||
"const view = <main>\n {/* <aside>\n <strong>ready</strong>\n </aside> */}\n</main>;",
|
||||
);
|
||||
commentLine(v);
|
||||
expect(v.state.doc.toString()).toBe(original);
|
||||
});
|
||||
|
||||
it("takes a JSX line comment back out, with the caret", async () => {
|
||||
const tsx = await languages.find((l) => l.name === "TSX")!.load();
|
||||
const v = make(wrap("|</div>"), tsx);
|
||||
|
||||
@@ -54,7 +54,6 @@ import { skipClosingQuote, smartBackspace, smartBackspaceApplies, tabOut } from
|
||||
import { stringClipboard } from "./stringClipboard";
|
||||
import { filterCopiedText } from "./clipboard";
|
||||
import { LINE_INSET } from "./lineInset";
|
||||
import { codeLensPositions } from "./codeLens";
|
||||
|
||||
// --- soft wraps ---------------------------------------------------------------
|
||||
|
||||
@@ -558,12 +557,7 @@ export function prefsExtension(o: PrefsOptions): Extension {
|
||||
const { prefs } = o;
|
||||
const g = prefs.general;
|
||||
const k = prefs.smartKeys;
|
||||
const out: Extension[] = [
|
||||
codeLensPositions.of({
|
||||
usages: prefs.inlay.codeVisionUsagesPosition,
|
||||
author: prefs.inlay.codeVisionAuthorPosition,
|
||||
}),
|
||||
];
|
||||
const out: Extension[] = [];
|
||||
if (!o.readOnly)
|
||||
out.push(markdownImages({ path: o.path, folder: g.markdownImageFolder, pattern: g.markdownImageNamePattern }));
|
||||
if (g.scrollPastEnd) out.push(scrollPastEnd());
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BlockType, RectangleMarker, type BlockInfo } from "@codemirror/view";
|
||||
import {
|
||||
alignLeftEdges,
|
||||
dropInsetSlivers,
|
||||
cutOutGaps,
|
||||
fillGaps,
|
||||
fillRowEnds,
|
||||
@@ -251,55 +249,3 @@ describe("fillGaps", () => {
|
||||
expect(fillGaps(rows, C, [], 0, 300)).toEqual(rows);
|
||||
});
|
||||
});
|
||||
|
||||
describe("alignLeftEdges", () => {
|
||||
const C = "sel";
|
||||
it("moves rectangles at the real line start to the rounded one and keeps their right edges", () => {
|
||||
const out = alignLeftEdges(
|
||||
[new RectangleMarker(C, 40.5, 0, 100, 20), new RectangleMarker(C, 40, 20, 300, 20)],
|
||||
C,
|
||||
40.5,
|
||||
40,
|
||||
);
|
||||
expect(out.map((m) => [m.left, m.left + m.width!])).toEqual([
|
||||
[40, 140.5],
|
||||
[40, 340],
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaves rectangles that start elsewhere, and everything when the inset is whole", () => {
|
||||
const m = new RectangleMarker(C, 80, 0, 50, 20);
|
||||
expect(alignLeftEdges([m], C, 40.5, 40)).toEqual([m]);
|
||||
const at = new RectangleMarker(C, 40, 0, 50, 20);
|
||||
expect(alignLeftEdges([at], C, 40, 40)).toEqual([at]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("dropInsetSlivers", () => {
|
||||
const C = "sel";
|
||||
it("drops rectangles covering only the inset before the text", () => {
|
||||
const row = new RectangleMarker(C, 40, 0, 300, 20);
|
||||
expect(dropInsetSlivers([row, new RectangleMarker(C, 40, 20, 0.5, 20)], 40, 40.5)).toEqual([row]);
|
||||
});
|
||||
|
||||
it("leaves the middle rows whole when dropped after growing the rows", () => {
|
||||
// Rows of 20px; the selection runs from row 0 to the start of row 3, where CodeMirror draws a sliver.
|
||||
const rowAt = (y: number) => ({ top: Math.floor(y / 20) * 20, bottom: Math.floor(y / 20) * 20 + 20 });
|
||||
const drawn = [
|
||||
new RectangleMarker(C, 60, 2, 280, 16),
|
||||
new RectangleMarker(C, 40, 18, 300, 44),
|
||||
new RectangleMarker(C, 40, 62, 0.5, 16),
|
||||
];
|
||||
const out = dropInsetSlivers(growToLineBoxes(drawn, C, rowAt), 40, 40.5);
|
||||
expect(out.map((m) => [m.top, m.top + m.height])).toEqual([
|
||||
[0, 20],
|
||||
[20, 60],
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps rectangles that reach into the text or start elsewhere", () => {
|
||||
const into = new RectangleMarker(C, 40, 0, 8, 20);
|
||||
const mid = new RectangleMarker(C, 80, 0, 0.5, 20);
|
||||
expect(dropInsetSlivers([into, mid], 40, 40.5)).toEqual([into, mid]);
|
||||
});
|
||||
});
|
||||
@@ -157,35 +157,6 @@ export function cutOutGaps(
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the rectangles that start at `from` to `to`, keeping their right edges. CodeMirror starts the rows a selection
|
||||
* runs through from the line start at the lines' left padding rounded down to whole pixels (`parseInt`), and a row
|
||||
* that starts at a line's first character at the real padding, so with a fractional inset one row of a selection
|
||||
* started a device pixel to the right of the others.
|
||||
*/
|
||||
export function alignLeftEdges(
|
||||
markers: readonly RectangleMarker[],
|
||||
className: string,
|
||||
from: number,
|
||||
to: number,
|
||||
): RectangleMarker[] {
|
||||
if (Math.abs(to - from) < 0.01) return [...markers];
|
||||
return markers.map((m) =>
|
||||
m.width !== null && Math.abs(m.left - from) < 0.01
|
||||
? new RectangleMarker(className, to, m.top, m.width - (to - from), m.height)
|
||||
: m,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the rectangles that start at `from` and end by `to`, covering only the inset before a line's text. A selection
|
||||
* that ends at the start of a line made CodeMirror paint that line from its rounded edge (`from`) to the first
|
||||
* character (`to`): a sliver left of the text, a device pixel wide with a fractional inset. IDEA paints nothing there.
|
||||
*/
|
||||
export function dropInsetSlivers(markers: readonly RectangleMarker[], from: number, to: number): RectangleMarker[] {
|
||||
return markers.filter((m) => m.width === null || Math.abs(m.left - from) >= 0.01 || m.left + m.width > to + 0.01);
|
||||
}
|
||||
|
||||
/** Adds one rectangle from `left` to `right` over each of `gaps` (layer coordinates). */
|
||||
export function fillGaps(
|
||||
markers: readonly RectangleMarker[],
|
||||
@@ -235,21 +206,6 @@ function lineRightEdge(view: EditorView): { rightSide: number; pad: number } {
|
||||
return { rightSide: view.contentDOM.getBoundingClientRect().right - pad - base, pad };
|
||||
}
|
||||
|
||||
/**
|
||||
* Where CodeMirror starts a selection running through a line start (`rounded`: the left padding cut to whole pixels)
|
||||
* and where it starts one beginning at a line's first character (`real`: the padding as it is), in layer coordinates.
|
||||
*/
|
||||
function lineLeftEdge(view: EditorView): { rounded: number; real: number } | null {
|
||||
const line = view.contentDOM.querySelector(".cm-line");
|
||||
if (!line) return null;
|
||||
const style = getComputedStyle(line);
|
||||
const scroller = view.scrollDOM.getBoundingClientRect();
|
||||
const left = view.contentDOM.getBoundingClientRect().left - (scroller.left - view.scrollDOM.scrollLeft * view.scaleX);
|
||||
const rounded = left + parseInt(style.paddingLeft) + Math.min(0, parseInt(style.textIndent));
|
||||
const real = left + parseFloat(style.paddingLeft) + Math.min(0, parseFloat(style.textIndent));
|
||||
return Number.isFinite(rounded) && Number.isFinite(real) ? { rounded, real } : null;
|
||||
}
|
||||
|
||||
/** Layer y = document y + this offset. */
|
||||
function layerOffset(view: EditorView): number {
|
||||
const scroller = view.scrollDOM.getBoundingClientRect();
|
||||
@@ -319,7 +275,6 @@ const snappedSelectionLayer = layer({
|
||||
if (!ranges.length) return [];
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const edge = view.textDirection === Direction.LTR ? lineRightEdge(view) : null;
|
||||
const start = view.textDirection === Direction.LTR ? lineLeftEdge(view) : null;
|
||||
const offset = layerOffset(view);
|
||||
const out: RectangleMarker[] = [];
|
||||
for (const r of ranges) {
|
||||
@@ -330,21 +285,15 @@ const snappedSelectionLayer = layer({
|
||||
first: hasTextBlockAt(view, from, 1),
|
||||
last: hasTextBlockAt(view, to, -1),
|
||||
});
|
||||
// The sliver CodeMirror draws on a line the selection ends at the start of marks that line as the last row for
|
||||
// growToLineBoxes, so it goes only after the rows are grown. Then every row starts at the rounded edge: a pixel
|
||||
// left of the text, as IDEA leaves a gap between them.
|
||||
const aligned = start
|
||||
? alignLeftEdges(dropInsetSlivers(lines, start.rounded, start.real), CLASS, start.real, start.rounded)
|
||||
: lines;
|
||||
if (!aligned.length) continue;
|
||||
if (!lines.length) continue;
|
||||
const full = edge
|
||||
? fillRowEnds(
|
||||
widenToRightEdge(aligned, CLASS, edge.rightSide, edge.pad),
|
||||
widenToRightEdge(lines, CLASS, edge.rightSide, edge.pad),
|
||||
CLASS,
|
||||
rowsPastEnd(view, offset, r),
|
||||
edge.rightSide + edge.pad,
|
||||
)
|
||||
: aligned;
|
||||
: lines;
|
||||
// Block widgets: cut them all out of CodeMirror's rectangles, then paint the ones the selection runs through
|
||||
// with one rectangle each, so a translucent selection colour never doubles up over them.
|
||||
const widgets = lineWidgets(view, offset, r);
|
||||
|
||||
@@ -1463,7 +1463,7 @@ export class EditorController implements SlotHost {
|
||||
}
|
||||
try {
|
||||
const encoding = await this.manager.backend.setEncoding(meta.doc, meta.encoding, true);
|
||||
model.setMeta({ encoding: encoding.encoding, hasBom: encoding.hasBom });
|
||||
model.setMeta({ encoding });
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
|
||||
@@ -82,7 +82,6 @@ export interface DocMeta {
|
||||
language: string;
|
||||
uiMode: string | null;
|
||||
encoding: string;
|
||||
hasBom: boolean;
|
||||
lineEnding: LineEnding;
|
||||
readOnly: boolean;
|
||||
dirty: boolean;
|
||||
@@ -249,7 +248,6 @@ export class DocModel {
|
||||
language: info.language,
|
||||
uiMode: uiMode ?? this.desc?.name ?? null,
|
||||
encoding: info.encoding,
|
||||
hasBom: info.hasBom,
|
||||
lineEnding: info.lineEnding,
|
||||
// Library sources (External Libraries) open read-only, like IDEA's.
|
||||
readOnly: info.readOnly || (!this.virtual && isLibraryPath(info.path)),
|
||||
|
||||
@@ -352,7 +352,6 @@ const ENCODINGS = ENCODING_CHOICES;
|
||||
/** File encoding widget (IDEA: click → choose an encoding, then Reload or Convert). */
|
||||
export function EncodingStatus() {
|
||||
const meta = useActiveMeta();
|
||||
const prefs = useEditorPrefs();
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLButtonElement>(null);
|
||||
if (!meta) return null;
|
||||
@@ -361,7 +360,7 @@ export function EncodingStatus() {
|
||||
if (!model) return;
|
||||
void editorController()
|
||||
.manager.backend.setEncoding(meta.doc, encoding, reload)
|
||||
.then((enc) => model.setMeta({ encoding: enc.encoding, hasBom: enc.hasBom, ...(reload ? {} : { dirty: true }) }))
|
||||
.then((enc) => model.setMeta({ encoding: enc, ...(reload ? {} : { dirty: true }) }))
|
||||
.catch((e: unknown) =>
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
@@ -371,27 +370,6 @@ export function EncodingStatus() {
|
||||
);
|
||||
};
|
||||
const current = meta.encoding.toLowerCase();
|
||||
const nativeToAsciiProperties = prefs.encodings.nativeToAscii && meta.path.endsWith(".properties");
|
||||
const canToggleBom = current === "utf-8" && !nativeToAsciiProperties;
|
||||
const label = ENCODINGS.find(([id]) => id === current)?.[1] ?? meta.encoding;
|
||||
const applyBom = (hasBom: boolean) => {
|
||||
const controller = editorController();
|
||||
const model = controller.manager.get(meta.path);
|
||||
if (!model) return;
|
||||
void controller.manager.backend
|
||||
.setBom(meta.doc, hasBom)
|
||||
.then(async (enc) => {
|
||||
model.setMeta({ encoding: enc.encoding, hasBom: enc.hasBom, dirty: true });
|
||||
if (controller.autoSave()) await model.save("auto");
|
||||
})
|
||||
.catch((e: unknown) =>
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: tx("Cannot change the UTF-8 BOM"),
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
}),
|
||||
);
|
||||
};
|
||||
const group = (reload: boolean) =>
|
||||
ENCODINGS.filter(([id]) => id !== current).map(([id, label]) => ({
|
||||
id: `${reload ? "reload" : "convert"}.${id}`,
|
||||
@@ -407,7 +385,7 @@ export function EncodingStatus() {
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
>
|
||||
{meta.hasBom ? `${label} BOM` : label}
|
||||
{ENCODINGS.find(([id]) => id === current)?.[1] ?? meta.encoding}
|
||||
</BarButton>
|
||||
<Menu
|
||||
open={open}
|
||||
@@ -418,17 +396,6 @@ export function EncodingStatus() {
|
||||
items={[
|
||||
{ id: "reload", label: "Reload with Encoding", disabled: meta.dirty, submenu: group(true) },
|
||||
{ id: "convert", label: "Convert to Encoding", disabled: meta.readOnly, submenu: group(false) },
|
||||
...(canToggleBom
|
||||
? [
|
||||
{ kind: "separator" as const },
|
||||
{
|
||||
id: "toggle-bom",
|
||||
label: meta.hasBom ? "Remove UTF-8 BOM" : "Add UTF-8 BOM",
|
||||
disabled: meta.readOnly,
|
||||
run: () => applyBom(!meta.hasBom),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{ kind: "separator" },
|
||||
{
|
||||
id: "configure",
|
||||
|
||||
@@ -118,18 +118,6 @@ describe("background usage counts", () => {
|
||||
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
|
||||
});
|
||||
|
||||
it('leaves out "no usages" when Show “no usages” is off', async () => {
|
||||
ipc.lspReferences.mockResolvedValue(refs(0));
|
||||
useProject.setState({
|
||||
settings: {
|
||||
editor: { inlay: { codeVisionUsages: true, codeVisionAuthor: false, codeVisionNoUsages: false } },
|
||||
} as never,
|
||||
});
|
||||
const view = editor();
|
||||
await settle();
|
||||
expect(titles(view)).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not cache an incomplete count while indexing, and retries on server refresh", async () => {
|
||||
ipc.lspReferences.mockResolvedValueOnce(refs(0, "indexing"));
|
||||
const view = editor();
|
||||
|
||||
@@ -233,22 +233,14 @@ class UsagesLensPlugin {
|
||||
const offset = posToOffset(text, { line: t.line, col: t.col });
|
||||
const who = lines && authorSummary(lines, t.startLine, t.endLine);
|
||||
if (who)
|
||||
lenses.push({
|
||||
pos: offset,
|
||||
title: authorLabel(who),
|
||||
tooltip: authorTooltip(who),
|
||||
icon: "user",
|
||||
order: 20,
|
||||
kind: "author",
|
||||
});
|
||||
lenses.push({ pos: offset, title: authorLabel(who), tooltip: authorTooltip(who), icon: "user", order: 20 });
|
||||
const n = usages ? this.cache.get(key(t)) : undefined;
|
||||
if (n === undefined || (n === 0 && !editorPrefs().inlay.codeVisionNoUsages)) continue;
|
||||
if (n === undefined) continue;
|
||||
lenses.push({
|
||||
pos: offset,
|
||||
title: usagesLabel(n),
|
||||
tooltip: tx`Show usages of ${t.name}`,
|
||||
order: 10,
|
||||
kind: "usages",
|
||||
run: (v) => openUsages(v, Math.min(offset, v.state.doc.length)),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -32,7 +32,6 @@ import {
|
||||
nodeLabel,
|
||||
profileChecked,
|
||||
withGradleOptions,
|
||||
gradleHasTestTask,
|
||||
type BuildNode,
|
||||
} from "./model";
|
||||
import {
|
||||
@@ -65,9 +64,7 @@ export function nodeConfig(
|
||||
const first = nodes[0];
|
||||
if (!first) return null;
|
||||
if (first.kind === "runConfig")
|
||||
return first.config.kind === "gradle"
|
||||
? withGradleOptions(first.config, settings.gradle, gradleHasTestTask(model.gradle ?? []))
|
||||
: first.config;
|
||||
return first.config.kind === "gradle" ? withGradleOptions(first.config, settings.gradle) : first.config;
|
||||
if ((first.kind === "phase" || first.kind === "goal") && model.maven) {
|
||||
const same = nodes.filter(
|
||||
(n): n is Extract<BuildNode, { kind: "phase" | "goal" }> =>
|
||||
@@ -171,13 +168,15 @@ function Toolbar({ tool, selection }: { tool: BuildTool; selection: BuildNode[]
|
||||
iconSize={16}
|
||||
action={maven ? "maven.analyzeDependencies" : "gradle.analyzeDependencies"}
|
||||
/>
|
||||
<IconButton
|
||||
icon="skip-tests"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
action={`${tool}.toggleSkipTests`}
|
||||
pressed={maven ? settings.maven.skipTests : settings.gradle.skipTests}
|
||||
/>
|
||||
{maven && (
|
||||
<IconButton
|
||||
icon="skip-tests"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
action="maven.toggleSkipTests"
|
||||
pressed={settings.maven.skipTests}
|
||||
/>
|
||||
)}
|
||||
<span className={styles.sep} />
|
||||
<IconButton icon="expand-all" size="small" iconSize={16} action={`${tool}.expandAll`} />
|
||||
<IconButton icon="collapse-all" size="small" iconSize={16} action={`${tool}.collapseAll`} />
|
||||
@@ -235,9 +234,7 @@ function BuildBanner({ info, tool }: { info: MavenModel | GradleModel; tool: Bui
|
||||
|
||||
function NodeRow({ node, state }: { node: BuildNode; state: TreeRowState }) {
|
||||
const choices = useBuild((s) => s.settings.maven.profiles);
|
||||
// Each toggle strikes through only its own tool's tree: the Maven `test` phase, or the Gradle `test` task.
|
||||
const mavenSkipTests = useBuild((s) => s.settings.maven.skipTests);
|
||||
const gradleSkipTests = useBuild((s) => s.settings.gradle.skipTests);
|
||||
const skipTests = useBuild((s) => s.settings.maven.skipTests);
|
||||
if (node.kind === "profile") {
|
||||
return (
|
||||
<span className={styles.row} onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
||||
@@ -260,13 +257,16 @@ function NodeRow({ node, state }: { node: BuildNode; state: TreeRowState }) {
|
||||
: node.kind === "task"
|
||||
? node.task.description
|
||||
: null;
|
||||
const skipped =
|
||||
(mavenSkipTests && node.kind === "phase" && node.phase === "test") ||
|
||||
(gradleSkipTests && node.kind === "task" && node.task.name === "test");
|
||||
return (
|
||||
<span className={styles.row} title={node.kind === "task" ? (node.task.description ?? undefined) : undefined}>
|
||||
<Icon name={nodeIcon(node)} size={16} className={styles.icon} />
|
||||
<span className={clsx(styles.label, state.selected && styles.selectedLabel, skipped && styles.skippedGoal)}>
|
||||
<span
|
||||
className={clsx(
|
||||
styles.label,
|
||||
state.selected && styles.selectedLabel,
|
||||
skipTests && node.kind === "phase" && node.phase === "test" && styles.skippedGoal,
|
||||
)}
|
||||
>
|
||||
{nodeLabel(node)}
|
||||
</span>
|
||||
{detail && <span className={styles.detail}>{detail}</span>}
|
||||
|
||||
@@ -174,64 +174,4 @@ describe("build tools feature", () => {
|
||||
render(<GradleView />);
|
||||
expect(screen.getByText("test")).not.toHaveClass(styles.skippedGoal!);
|
||||
});
|
||||
|
||||
it("toggles Gradle Skip Tests and runs tasks with -x test", async () => {
|
||||
const started: unknown[] = [];
|
||||
const off = registerAction({
|
||||
id: "run.runConfig",
|
||||
title: "Run",
|
||||
hidden: true,
|
||||
run: ({ arg }) => void started.push(arg),
|
||||
});
|
||||
const build = {
|
||||
dir: "",
|
||||
projects: [
|
||||
{
|
||||
path: ":",
|
||||
name: "demo",
|
||||
dir: "",
|
||||
buildFile: "build.gradle.kts",
|
||||
tasks: [{ name: "test", group: "verification", description: null }],
|
||||
},
|
||||
],
|
||||
command: "/p/gradlew",
|
||||
env: {},
|
||||
javaVersion: null,
|
||||
syncedAt: null,
|
||||
stale: false,
|
||||
syncError: null,
|
||||
};
|
||||
const key = gradleProjectKey(build, build.projects[0]!);
|
||||
act(() =>
|
||||
useBuild.setState({
|
||||
root: "/p",
|
||||
model: { maven: mavenModel.maven, gradle: [build] },
|
||||
expanded: { maven: new Set(), gradle: new Set([key, `${key}:tasks`, `${key}:tasks:verification`]) },
|
||||
}),
|
||||
);
|
||||
await executeAction("gradle.toggleSkipTests");
|
||||
expect(useBuild.getState().settings.gradle).toMatchObject({ skipTests: true });
|
||||
expect(JSON.parse(localStorage.getItem("openidea.buildTools:/p")!).gradle.skipTests).toBe(true);
|
||||
expect(
|
||||
allActions()
|
||||
.find((a) => a.id === "gradle.toggleSkipTests")!
|
||||
.toggled?.(),
|
||||
).toBe(true);
|
||||
render(<GradleView />);
|
||||
const task = screen.getByText("test");
|
||||
expect(task).toHaveClass(styles.skippedGoal!);
|
||||
await act(async () => {
|
||||
task.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
|
||||
});
|
||||
off();
|
||||
expect(started).toHaveLength(1);
|
||||
const { config } = started[0] as { config: RunConfig };
|
||||
expect(config).toMatchObject({
|
||||
name: "demo [test]",
|
||||
command: "/p/gradlew",
|
||||
args: ["test", "-x", "test"],
|
||||
kind: "gradle",
|
||||
isTest: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -51,7 +51,6 @@ import {
|
||||
generateSources,
|
||||
syncTool,
|
||||
toggleGradleOffline,
|
||||
toggleGradleSkipTests,
|
||||
toggleMavenOffline,
|
||||
toggleSkipTests,
|
||||
useBuild,
|
||||
@@ -452,17 +451,6 @@ export function activate(): () => void {
|
||||
toggled: () => useBuild.getState().settings.gradle.offline,
|
||||
run: () => toggleGradleOffline(),
|
||||
},
|
||||
{
|
||||
id: "gradle.toggleSkipTests",
|
||||
title: "Toggle 'Skip Tests' Mode",
|
||||
description: "Runs Gradle with -x test",
|
||||
category: "Gradle",
|
||||
icon: "skip-tests",
|
||||
when: GRADLE_WHEN,
|
||||
keywords: ["gradle", "skip tests"],
|
||||
toggled: () => useBuild.getState().settings.gradle.skipTests,
|
||||
run: () => toggleGradleSkipTests(),
|
||||
},
|
||||
{
|
||||
id: "gradle.expandAll",
|
||||
title: "Expand All",
|
||||
|
||||
@@ -378,7 +378,7 @@ it("runs duplicate task paths with the selected build's wrapper, cwd and offline
|
||||
model,
|
||||
expanded: { maven: new Set(), gradle: expanded },
|
||||
current: { gradle: gradleProjectKey(builds[1]!, builds[1]!.projects[1]!) },
|
||||
settings: { ...useBuild.getState().settings, gradle: { offline: true, skipTests: false } },
|
||||
settings: { ...useBuild.getState().settings, gradle: { offline: true } },
|
||||
}),
|
||||
);
|
||||
const started: RunConfig[] = [];
|
||||
|
||||
@@ -20,8 +20,6 @@ import {
|
||||
profilesArg,
|
||||
splitArgs,
|
||||
taskCompletions,
|
||||
withGradleOptions,
|
||||
gradleHasTestTask,
|
||||
type BuildNode,
|
||||
} from "./model";
|
||||
|
||||
@@ -326,7 +324,7 @@ describe("Gradle tree and runs", () => {
|
||||
|
||||
it("runs tasks by path from the build directory", () => {
|
||||
const app = gradle.projects[1]!;
|
||||
const config = gradleTaskConfig(gradle, app, ["test"], { offline: true, skipTests: false });
|
||||
const config = gradleTaskConfig(gradle, app, ["test"], { offline: true });
|
||||
expect(config).toMatchObject({
|
||||
name: "app [test]",
|
||||
kind: "gradle",
|
||||
@@ -337,61 +335,13 @@ describe("Gradle tree and runs", () => {
|
||||
env: {},
|
||||
isTest: true,
|
||||
});
|
||||
expect(
|
||||
gradleTaskConfig(gradle, gradle.projects[0]!, ["wrapper"], { offline: false, skipTests: false }).args,
|
||||
).toEqual(["wrapper"]);
|
||||
expect(gradleTaskConfig(gradle, app, [":lib:jar", "--info"], { offline: false, skipTests: false }).args).toEqual([
|
||||
expect(gradleTaskConfig(gradle, gradle.projects[0]!, ["wrapper"], { offline: false }).args).toEqual(["wrapper"]);
|
||||
expect(gradleTaskConfig(gradle, app, [":lib:jar", "--info"], { offline: false }).args).toEqual([
|
||||
":lib:jar",
|
||||
"--info",
|
||||
]);
|
||||
});
|
||||
|
||||
it("appends -x test to task runs when Skip Tests is on", () => {
|
||||
const app = gradle.projects[1]!;
|
||||
const skipped = gradleTaskConfig(gradle, app, ["build"], { offline: false, skipTests: true });
|
||||
expect(skipped.args).toEqual([":app:build", "-x", "test"]);
|
||||
// Running `test` with Skip Tests on is not a test run for the Run window.
|
||||
const test = gradleTaskConfig(gradle, app, ["test"], { offline: false, skipTests: true });
|
||||
expect(test.args).toEqual([":app:test", "-x", "test"]);
|
||||
expect(test.isTest).toBe(false);
|
||||
// A command line that already excludes tests is not changed again (typed task names keep
|
||||
// the pre-existing project-path prefix).
|
||||
const explicit = gradleTaskConfig(gradle, app, ["build", "-x", "test"], { offline: false, skipTests: true });
|
||||
expect(explicit.args).toEqual([":app:build", "-x", ":app:test"]);
|
||||
const verbose = gradleTaskConfig(gradle, app, ["build", "--exclude-task", "test"], {
|
||||
offline: false,
|
||||
skipTests: true,
|
||||
});
|
||||
expect(verbose.args).toEqual([":app:build", "--exclude-task", ":app:test"]);
|
||||
// A build without a `test` task would fail on `-x test`.
|
||||
const noTests = {
|
||||
...gradle,
|
||||
projects: gradle.projects.map((p) => ({ ...p, tasks: p.tasks.filter((t) => t.name !== "test") })),
|
||||
};
|
||||
expect(gradleHasTestTask([noTests])).toBe(false);
|
||||
expect(
|
||||
gradleTaskConfig(noTests, noTests.projects[1]!, ["build"], { offline: false, skipTests: true }).args,
|
||||
).toEqual([":app:build"]);
|
||||
});
|
||||
|
||||
it("applies the toolbar toggles to saved configurations started from the tree", () => {
|
||||
const saved = runConfig({ id: "g", name: "app [build]", kind: "gradle", args: ["build"] });
|
||||
expect(withGradleOptions(saved, { offline: false, skipTests: false }).args).toEqual(["build"]);
|
||||
expect(withGradleOptions(saved, { offline: true, skipTests: false }).args).toEqual(["build", "--offline"]);
|
||||
expect(withGradleOptions(saved, { offline: true, skipTests: true }).args).toEqual([
|
||||
"build",
|
||||
"--offline",
|
||||
"-x",
|
||||
"test",
|
||||
]);
|
||||
const excluding = withGradleOptions(runConfig({ ...saved, args: ["build", "-x", "test"] }), {
|
||||
offline: false,
|
||||
skipTests: true,
|
||||
});
|
||||
expect(excluding.args).toEqual(["build", "-x", "test"]);
|
||||
expect(withGradleOptions(saved, { offline: false, skipTests: true }, false).args).toEqual(["build"]);
|
||||
});
|
||||
|
||||
it("keeps identical project paths and tasks of independent builds distinct", () => {
|
||||
const builds = ["first", "second"].map((dir) => ({
|
||||
...gradle,
|
||||
@@ -411,7 +361,7 @@ describe("Gradle tree and runs", () => {
|
||||
return gradleChildren(group, builds, [])![0]!;
|
||||
});
|
||||
expect(tasks[0]!.key).not.toBe(tasks[1]!.key);
|
||||
const runs = builds.map((b) => gradleTaskConfig(b, b.projects[1]!, ["test"], { offline: true, skipTests: false }));
|
||||
const runs = builds.map((b) => gradleTaskConfig(b, b.projects[1]!, ["test"], { offline: true }));
|
||||
expect(runs[0]!.id).not.toBe(runs[1]!.id);
|
||||
expect(runs[1]).toMatchObject({
|
||||
command: "/p/second/gradlew",
|
||||
|
||||
@@ -83,8 +83,6 @@ export interface MavenRunOptions {
|
||||
|
||||
export interface GradleRunOptions {
|
||||
offline: boolean;
|
||||
/** Skip Tests toolbar toggle: task runs get `-x test` (no Maven-style toggle exists in IDEA's Gradle window). */
|
||||
skipTests: boolean;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -516,29 +514,6 @@ export function gradleTaskPath(project: GradleProject, task: string): string {
|
||||
return project.path === ":" ? task : `${project.path}:${task}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether one of the builds has a task named `test`: `-x test` fails the whole run with
|
||||
* "Task 'test' not found" in a build without one (Kotlin Multiplatform, non-JVM builds).
|
||||
*/
|
||||
export function gradleHasTestTask(models: readonly GradleModel[]): boolean {
|
||||
return models.some((m) => m.projects.some((p) => p.tasks.some((t) => t.name === "test")));
|
||||
}
|
||||
|
||||
/** Whether the command line already excludes the `test` task (`-x test`, `-xtest`, `--exclude-task test`). */
|
||||
function excludesTest(args: readonly string[]): boolean {
|
||||
return args.some((a, i) => {
|
||||
const value =
|
||||
a === "-x" || a === "--exclude-task"
|
||||
? args[i + 1]
|
||||
: a.startsWith("--exclude-task=")
|
||||
? a.slice("--exclude-task=".length)
|
||||
: a.startsWith("-x")
|
||||
? a.slice(2)
|
||||
: undefined;
|
||||
return value === "test";
|
||||
});
|
||||
}
|
||||
|
||||
export function gradleTaskConfig(
|
||||
model: GradleModel,
|
||||
project: GradleProject,
|
||||
@@ -547,8 +522,6 @@ export function gradleTaskConfig(
|
||||
): RunConfig {
|
||||
const args = tasks.map((t) => (t.startsWith("-") || t.startsWith(":") ? t : gradleTaskPath(project, t)));
|
||||
if (options.offline && !args.includes("--offline")) args.push("--offline");
|
||||
// Typed task names are project-path prefixed above, so the typed line is the one to inspect.
|
||||
if (options.skipTests && gradleHasTestTask([model]) && !excludesTest(tasks)) args.push("-x", "test");
|
||||
const names = tasks.filter((t) => !t.startsWith("-"));
|
||||
return {
|
||||
id: `gradle:task:${JSON.stringify([model.dir, project.path])}:${tasks.join(" ")}`,
|
||||
@@ -560,17 +533,15 @@ export function gradleTaskConfig(
|
||||
// As for Maven: the Gradle JVM / `JAVA_HOME` is derived from Settings at launch, not frozen here.
|
||||
env: {},
|
||||
detected: false,
|
||||
isTest: !options.skipTests && names.some((t) => /(^|:)(test|check|build|integrationTest)$/.test(t)),
|
||||
isTest: names.some((t) => /(^|:)(test|check|build|integrationTest)$/.test(t)),
|
||||
debugAdapter: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Applies the current toggles to a saved configuration started from the tree (`hasTestTask`: see {@link gradleHasTestTask}). */
|
||||
export function withGradleOptions(config: RunConfig, options: GradleRunOptions, hasTestTask = true): RunConfig {
|
||||
let args = config.args;
|
||||
if (options.offline && !args.includes("--offline")) args = [...args, "--offline"];
|
||||
if (options.skipTests && hasTestTask && !excludesTest(args)) args = [...args, "-x", "test"];
|
||||
return args === config.args ? config : { ...config, args };
|
||||
/** Applies the current toggles to a saved configuration started from the tree. */
|
||||
export function withGradleOptions(config: RunConfig, options: GradleRunOptions): RunConfig {
|
||||
if (!options.offline || config.args.includes("--offline")) return config;
|
||||
return { ...config, args: [...config.args, "--offline"] };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -45,7 +45,7 @@ export interface BuildSettings {
|
||||
|
||||
export const DEFAULT_SETTINGS: BuildSettings = {
|
||||
maven: { offline: false, skipTests: false, profiles: {} },
|
||||
gradle: { offline: false, skipTests: false },
|
||||
gradle: { offline: false },
|
||||
};
|
||||
|
||||
interface SyncState {
|
||||
@@ -131,8 +131,6 @@ export const toggleSkipTests = () =>
|
||||
updateSettings((s) => ({ ...s, maven: { ...s.maven, skipTests: !s.maven.skipTests } }));
|
||||
export const toggleGradleOffline = () =>
|
||||
updateSettings((s) => ({ ...s, gradle: { ...s.gradle, offline: !s.gradle.offline } }));
|
||||
export const toggleGradleSkipTests = () =>
|
||||
updateSettings((s) => ({ ...s, gradle: { ...s.gradle, skipTests: !s.gradle.skipTests } }));
|
||||
|
||||
/** Delay before reloading Maven after a profile toggle, so a few toggles in a row reload once. */
|
||||
export const PROFILE_RELOAD_DELAY_MS = 800;
|
||||
|
||||
@@ -3,7 +3,6 @@ import { IpcError } from "@/platform/ipc";
|
||||
import { missingAdapter } from "../missingAdapter";
|
||||
|
||||
const unavailable = (message: string) => new IpcError({ kind: "unavailable", message });
|
||||
const invalid = (message: string) => new IpcError({ kind: "invalidInput", message });
|
||||
|
||||
describe("missing debug adapters", () => {
|
||||
it("offers OpenIDEA's debugpy when the interpreter has none", () => {
|
||||
@@ -42,33 +41,6 @@ describe("missing debug adapters", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("offers to reinstall Delve when it is too old for the Go toolchain", () => {
|
||||
const message =
|
||||
"launch failed: Failed to launch /p/api: Version of Delve is too old for Go version go1.27.0 " +
|
||||
"(maximum supported version 1.26, suppress this error with --check-go-version=false)";
|
||||
// The failed `launch` response arrives as `invalidInput` (a DAP error, not a missing binary).
|
||||
expect(missingAdapter("delve", invalid(message))).toMatchObject({
|
||||
tool: "delve",
|
||||
title: "Delve is too old for Go 1.27.0",
|
||||
action: "Reinstall and Debug",
|
||||
body: `${message}. Reinstalling Delve runs go install github.com/go-delve/delve/cmd/dlv@latest.`,
|
||||
});
|
||||
});
|
||||
|
||||
it("offers the reinstall even when delve exited during startup", () => {
|
||||
const e = unavailable(
|
||||
"debug adapter `delve` exited during startup:\nVersion of Delve is too old for Go version go1.27.0",
|
||||
);
|
||||
expect(missingAdapter("delve", e)).toMatchObject({ tool: "delve", action: "Reinstall and Debug" });
|
||||
});
|
||||
|
||||
it("keeps a Go launch that failed for another reason as a plain error", () => {
|
||||
expect(missingAdapter("delve", invalid("launch failed: could not find project directory"))).toBeNull();
|
||||
expect(
|
||||
missingAdapter("delve", unavailable("debug adapter `delve` exited during startup:\nexit status 1")),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("leaves other failures and adapters without an installer alone", () => {
|
||||
expect(missingAdapter("js-debug", unavailable("connection refused"))).toBeNull();
|
||||
expect(missingAdapter("js-debug", new Error("debug adapter `js-debug` not found"))).toBeNull();
|
||||
|
||||
@@ -65,32 +65,4 @@ describe("debug start failures", () => {
|
||||
expect.objectContaining({ title: "Cannot start debugger for Listen for Xdebug", body: PORT_IN_USE }),
|
||||
);
|
||||
});
|
||||
|
||||
it("offers to reinstall a Delve that is too old for the Go toolchain", async () => {
|
||||
const notify = vi.fn();
|
||||
provideNotificationService({ notify });
|
||||
useDebug.setState({ sessions: {}, active: null, console: {} });
|
||||
const message =
|
||||
"launch failed: Failed to launch /p/api: Version of Delve is too old for Go version go1.27.0 " +
|
||||
"(maximum supported version 1.26, suppress this error with --check-go-version=false)";
|
||||
ipc.debugStart.mockResolvedValueOnce({ status: "error", error: { kind: "invalidInput", message, data: null } });
|
||||
const go: LaunchConfig = {
|
||||
name: "api: go run .",
|
||||
adapter: "delve",
|
||||
request: "launch",
|
||||
program: "/p/api",
|
||||
args: [],
|
||||
cwd: "/p/api",
|
||||
env: {},
|
||||
extraJson: JSON.stringify({ mode: "debug" }),
|
||||
};
|
||||
expect(await startSession(go)).toBeNull();
|
||||
expect(notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
title: "Delve is too old for Go 1.27.0",
|
||||
body: `${message}. Reinstalling Delve runs go install github.com/go-delve/delve/cmd/dlv@latest.`,
|
||||
actions: [expect.objectContaining({ label: "Reinstall and Debug" })],
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,8 @@
|
||||
/**
|
||||
* A debug adapter that is not installed, or an installed one that refuses the Go
|
||||
* toolchain: name it and offer the one-click install / reinstall (ide-tools) followed
|
||||
* by the same launch again, instead of a bare error.
|
||||
* A debug adapter that is not installed: name it and offer the one-click install
|
||||
* (ide-tools) followed by the same launch again, instead of a bare error.
|
||||
*/
|
||||
import { IpcError } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
/** Adapters the tools installer can provide (adapter id → tool name). */
|
||||
const INSTALLABLE: Record<string, { tool: string; title: string }> = {
|
||||
@@ -18,37 +16,16 @@ const INSTALLABLE: Record<string, { tool: string; title: string }> = {
|
||||
"bash-debug": { tool: "bash-debug", title: "Bash Debug is not installed" },
|
||||
};
|
||||
|
||||
/**
|
||||
* Delve refuses a Go toolchain newer than it supports: the adapter starts, but its
|
||||
* `launch` request fails with "Version of Delve is too old for Go version go1.27.0
|
||||
* (maximum supported version 1.26, …)". The managed install is
|
||||
* `go install github.com/go-delve/delve/cmd/dlv@latest`, so reinstalling updates it.
|
||||
*/
|
||||
const DELVE_TOO_OLD = /Version of Delve is too old for Go version go([\d.]+)/;
|
||||
|
||||
export interface MissingAdapter {
|
||||
tool: string;
|
||||
title: string;
|
||||
body: string;
|
||||
/** The action's label when "Install and Debug" doesn't fit (a stale adapter's reinstall). */
|
||||
action?: string;
|
||||
}
|
||||
|
||||
/** The install offer for a failed start, or null when the failure is something else. */
|
||||
export function missingAdapter(adapter: string, e: unknown): MissingAdapter | null {
|
||||
if (!(e instanceof IpcError)) return null;
|
||||
if (adapter === "delve") {
|
||||
const go = DELVE_TOO_OLD.exec(e.message)?.[1];
|
||||
if (go)
|
||||
return {
|
||||
tool: "delve",
|
||||
title: tx`Delve is too old for Go ${go}`,
|
||||
body: `${e.message}. Reinstalling Delve runs go install github.com/go-delve/delve/cmd/dlv@latest.`,
|
||||
action: "Reinstall and Debug",
|
||||
};
|
||||
}
|
||||
const entry = INSTALLABLE[adapter];
|
||||
if (!entry || e.kind !== "unavailable") return null;
|
||||
if (!entry || !(e instanceof IpcError) || e.kind !== "unavailable") return null;
|
||||
if (adapter === "debugpy" && e.message.startsWith("debugpy is not installed")) {
|
||||
return {
|
||||
tool: entry.tool,
|
||||
|
||||
@@ -677,7 +677,7 @@ export async function startSession(
|
||||
sticky: true,
|
||||
actions: [
|
||||
{
|
||||
label: missing.action ?? "Install and Debug",
|
||||
label: "Install and Debug",
|
||||
run: () => void executeAction("tools.install", missing.tool).then(() => startSession(launch, options)),
|
||||
},
|
||||
],
|
||||
|
||||
@@ -34,9 +34,6 @@ const GROUP_ICONS: Record<string, string> = {
|
||||
gems: "file-ruby",
|
||||
};
|
||||
|
||||
/** SDK groups, which IDEA writes in angle brackets (`< 21 >`); library groups (`Maven: g:a:v`) go without. */
|
||||
const SDK_KINDS = new Set(["jdk", "python", "ruby", "go", "rust"]);
|
||||
|
||||
/** An archive's root (`/jdk/lib/src.zip!`): its entries live below `<archive>!/`. */
|
||||
const isArchiveRoot = (path: string) => path.endsWith("!");
|
||||
|
||||
@@ -94,7 +91,7 @@ export function librariesRoot(groups: readonly LibraryGroup[]): ProjectViewRootC
|
||||
order: 5,
|
||||
readOnly: true,
|
||||
children: groups.map((g) => ({
|
||||
label: SDK_KINDS.has(g.kind) ? `< ${g.name} >` : g.name,
|
||||
label: `< ${g.name} >`,
|
||||
icon: GROUP_ICONS[g.kind] ?? "library",
|
||||
children: g.roots.map((r) => ({
|
||||
label: r.name,
|
||||
|
||||
@@ -64,9 +64,7 @@ describe("External Libraries", () => {
|
||||
{ name: "Maven: g:a:1", kind: "maven", roots: [{ name: "a-1-sources.jar", path: "/m2/g/a/1/a-1-sources.jar!" }] },
|
||||
])!;
|
||||
expect(root.children?.[0]?.children?.map((c) => c.icon)).toEqual(["folder-library", "file-archive"]);
|
||||
// As in IDEA: SDKs in angle brackets, dependencies without.
|
||||
expect(root.children?.[0]).toMatchObject({ label: "< temurin-21 >" });
|
||||
expect(root.children?.[1]).toMatchObject({ label: "Maven: g:a:1", icon: "maven-project" });
|
||||
expect(root.children?.[1]).toMatchObject({ label: "< Maven: g:a:1 >", icon: "maven-project" });
|
||||
dispose = setLibraryRoots("test", ["/jdk/lib/src.zip!"]);
|
||||
expect(isLibraryPath("/jdk/lib/src.zip!/java.base/java/lang/String.java")).toBe(true);
|
||||
});
|
||||
|
||||
@@ -26,20 +26,13 @@
|
||||
display: flex;
|
||||
flex: none;
|
||||
flex-direction: column;
|
||||
width: 340px;
|
||||
width: 280px;
|
||||
min-height: 0;
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
.searchRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
.search {
|
||||
margin: 8px;
|
||||
}
|
||||
.searchField {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
@@ -405,89 +398,13 @@
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.marketItem {
|
||||
list-style: none;
|
||||
padding: 4px 8px;
|
||||
}
|
||||
|
||||
.categorySelect {
|
||||
flex: none;
|
||||
width: 150px;
|
||||
}
|
||||
.ownIcon {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.marketRow .rowMain {
|
||||
align-items: flex-start;
|
||||
min-height: 60px;
|
||||
}
|
||||
.marketRow .icon {
|
||||
margin-top: 2px;
|
||||
}
|
||||
.rowTitle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
.rowDescription {
|
||||
overflow: hidden;
|
||||
color: var(--fg-secondary);
|
||||
font-size: var(--fs-small);
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.downloads {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.exampleTag {
|
||||
flex: none;
|
||||
padding: 0 4px;
|
||||
border-radius: var(--radius-small);
|
||||
background: var(--bg-control);
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-tiny);
|
||||
line-height: 14px;
|
||||
}
|
||||
.groupNote {
|
||||
padding: 0 12px 4px;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.suggestNotice {
|
||||
background: color-mix(in srgb, var(--success) 12%, transparent);
|
||||
}
|
||||
|
||||
/* plugins without an icon: their initial on a tint picked by id */
|
||||
.monogram {
|
||||
font-weight: 600;
|
||||
font-size: var(--fs-input-large);
|
||||
--tone: var(--info);
|
||||
background: color-mix(in srgb, var(--tone) 18%, transparent);
|
||||
color: var(--tone);
|
||||
}
|
||||
.iconLarge.monogram {
|
||||
font-size: 24px;
|
||||
}
|
||||
.tone0 {
|
||||
--tone: var(--info);
|
||||
}
|
||||
.tone1 {
|
||||
--tone: var(--success);
|
||||
}
|
||||
.tone2 {
|
||||
--tone: var(--warning);
|
||||
}
|
||||
.tone3 {
|
||||
--tone: var(--danger);
|
||||
}
|
||||
.tone4 {
|
||||
--tone: var(--ansi-magenta);
|
||||
}
|
||||
.tone5 {
|
||||
--tone: var(--ansi-cyan);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.detailsNotice {
|
||||
|
||||
@@ -34,8 +34,6 @@ import {
|
||||
} from "@/ui";
|
||||
import { RISK_LABEL, sortByRisk, capabilityDescription } from "./consent";
|
||||
import { pluginIconName } from "./pluginIcon";
|
||||
import { formatDownloads, groupMarket, isExample, monogram, suggestedFor, suggestionPaths } from "./market";
|
||||
import { projectHas } from "./workspaceContains";
|
||||
import { localizeContributions, usePluginCatalogs, usePluginT } from "./pluginText";
|
||||
import { itemsOf, uiPoint } from "./projection";
|
||||
import {
|
||||
@@ -67,13 +65,7 @@ import { pluginsBackend } from "./backend";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
const STATUS: Record<
|
||||
PluginStatus,
|
||||
{
|
||||
label: string;
|
||||
tone: "success" | "accent" | "neutral" | "danger" | "warning";
|
||||
}
|
||||
> = {
|
||||
const STATUS: Record<PluginStatus, { label: string; tone: "success" | "accent" | "neutral" | "danger" | "warning" }> = {
|
||||
active: { label: "Running", tone: "success" },
|
||||
inactive: { label: "Enabled", tone: "accent" },
|
||||
static: { label: "Enabled", tone: "accent" },
|
||||
@@ -146,47 +138,14 @@ function useMarketUpdate(plugin: PluginInfo): MarketPlugin | undefined {
|
||||
);
|
||||
}
|
||||
|
||||
function PluginIcon({
|
||||
id,
|
||||
icon,
|
||||
large,
|
||||
name,
|
||||
}: {
|
||||
id: string;
|
||||
icon: PluginIconData | null | undefined;
|
||||
large?: boolean;
|
||||
/** Without an icon: its first letter on a tint of its own instead of the generic icon. */
|
||||
name?: string;
|
||||
}) {
|
||||
if (!icon && name) {
|
||||
const { letter, tone } = monogram(id, name);
|
||||
return (
|
||||
<span
|
||||
className={clsx(styles.icon, large && styles.iconLarge, styles.monogram, styles[`tone${tone}`])}
|
||||
aria-hidden
|
||||
>
|
||||
{letter}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
// A plugin's own icon fills the tile, as the initials do; the generic one sits on a plate.
|
||||
function PluginIcon({ id, icon, large }: { id: string; icon: PluginIconData | null | undefined; large?: boolean }) {
|
||||
return (
|
||||
<span className={clsx(styles.icon, large && styles.iconLarge, icon && styles.ownIcon)} aria-hidden>
|
||||
<Icon name={pluginIconName(id, icon)} size={icon ? (large ? 56 : 32) : large ? 32 : 20} />
|
||||
<span className={clsx(styles.icon, large && styles.iconLarge)} aria-hidden>
|
||||
<Icon name={pluginIconName(id, icon)} size={large ? 32 : 20} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ExampleTag() {
|
||||
return (
|
||||
<span className={styles.exampleTag} title={exampleNote()}>
|
||||
<T>Example</T>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const exampleNote = () => tx("Shows how to use the plugin API; not maintained as a product.");
|
||||
|
||||
function ListHeader({ title, count }: { title: string; count: number }) {
|
||||
return (
|
||||
<li className={styles.groupHeader} aria-hidden>
|
||||
@@ -210,10 +169,7 @@ function InstalledRow({ plugin, selected, onSelect }: { plugin: PluginInfo; sele
|
||||
>
|
||||
<PluginIcon id={plugin.id} icon={plugin.icon} />
|
||||
<span className={styles.rowText}>
|
||||
<span className={styles.rowTitle}>
|
||||
<span className={styles.rowName}>{plugin.name}</span>
|
||||
{plugin.source === "installed" && isExample(plugin) && <ExampleTag />}
|
||||
</span>
|
||||
<span className={styles.rowName}>{plugin.name}</span>
|
||||
<span className={styles.rowMeta}>
|
||||
<span className={styles.rowVendor}>{vendorOf(plugin.authors) || plugin.id}</span>
|
||||
<span>{plugin.version}</span>
|
||||
@@ -478,14 +434,7 @@ function ProgramPermission({ plugin, cap, disabled }: { plugin: PluginInfo; cap:
|
||||
const message = reset
|
||||
? tx("Revalidate the default executable? If it is unavailable, this permission will be revoked.")
|
||||
: tx`Allow ${plugin.name} to run ${selected}? This is equivalent to running arbitrary code on this machine.`;
|
||||
if (
|
||||
!(await confirm({
|
||||
title: tx("Approve plugin executable"),
|
||||
message,
|
||||
ok: tx("Allow"),
|
||||
icon: "warning",
|
||||
}))
|
||||
)
|
||||
if (!(await confirm({ title: tx("Approve plugin executable"), message, ok: tx("Allow"), icon: "warning" })))
|
||||
return;
|
||||
await pluginsBackend().chooseProgram(plugin.id, cap.id, scope, selected);
|
||||
await refreshPlugins();
|
||||
@@ -700,7 +649,6 @@ function InstalledDetails({ plugin }: { plugin: PluginInfo }) {
|
||||
{plugin.source !== "installed" && (
|
||||
<Badge tone="warning">{plugin.source === "linked" ? tx("Linked plugin") : tx("Project plugin")}</Badge>
|
||||
)}
|
||||
{plugin.source === "installed" && isExample(plugin) && <ExampleTag />}
|
||||
{plugin.source === "installed" &&
|
||||
(plugin.publisher ? (
|
||||
<Badge tone="success">{tx`Signed by ${plugin.publisher}`}</Badge>
|
||||
@@ -873,27 +821,14 @@ function gearMenu(plugins: readonly PluginInfo[], updates: number, actions: Gear
|
||||
run: () => void updateAllPlugins(),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
{
|
||||
label: "Install Plugin from Disk…",
|
||||
icon: "package",
|
||||
run: () => actions.install(false),
|
||||
},
|
||||
{
|
||||
label: "Install Plugin from Package File…",
|
||||
run: () => actions.install(true),
|
||||
},
|
||||
{ label: "Install Plugin from Disk…", icon: "package", run: () => actions.install(false) },
|
||||
{ label: "Install Plugin from Package File…", run: () => actions.install(true) },
|
||||
{ label: "Plugin Repository…", run: actions.editRepository },
|
||||
...(actions.canImport
|
||||
? [
|
||||
{ kind: "separator" as const },
|
||||
{
|
||||
label: "Import Theme from JetBrains IDE…",
|
||||
run: actions.importInstalledIntellij,
|
||||
},
|
||||
{
|
||||
label: "Import IntelliJ Theme from File…",
|
||||
run: actions.importIntellijFile,
|
||||
},
|
||||
{ label: "Import Theme from JetBrains IDE…", run: actions.importInstalledIntellij },
|
||||
{ label: "Import IntelliJ Theme from File…", run: actions.importIntellijFile },
|
||||
]
|
||||
: []),
|
||||
{ kind: "separator" },
|
||||
@@ -975,11 +910,7 @@ function CategoryFilter({
|
||||
const counts = new Map<Category, number>();
|
||||
for (const m of market) for (const c of categoriesOf(m)) counts.set(c, (counts.get(c) ?? 0) + 1);
|
||||
const options = [
|
||||
{
|
||||
value: "all" as const,
|
||||
label: tx("All Categories"),
|
||||
detail: String(market.length),
|
||||
},
|
||||
{ value: "all" as const, label: tx("All Categories"), detail: String(market.length) },
|
||||
...CATEGORIES.filter((c) => counts.has(c)).map((c) => ({
|
||||
value: c,
|
||||
label: categoryLabel(c),
|
||||
@@ -997,46 +928,10 @@ function CategoryFilter({
|
||||
);
|
||||
}
|
||||
|
||||
const publisherOf = (m: MarketPlugin) => m.publisherName || m.publisher;
|
||||
|
||||
/** Install / Update in a row or the details; what is installed otherwise. */
|
||||
function MarketAction({
|
||||
entry,
|
||||
compact,
|
||||
onInstalled,
|
||||
}: {
|
||||
entry: MarketPlugin;
|
||||
compact?: boolean;
|
||||
onInstalled?: (id: string) => void;
|
||||
}) {
|
||||
const installing = usePlugins((s) => s.installing);
|
||||
const update = isUpdate(entry);
|
||||
if (!entry.compatible) {
|
||||
return compact ? <Badge tone="warning">{tx("Incompatible")}</Badge> : null;
|
||||
}
|
||||
if (entry.installed && !update) {
|
||||
return compact ? <span className={styles.installedTag}>{tx("Installed")}</span> : null;
|
||||
}
|
||||
const label = update ? (compact ? tx("Update") : tx`Update to ${entry.version}`) : tx("Install");
|
||||
return (
|
||||
<Button
|
||||
size="small"
|
||||
variant={update || !compact ? "primary" : "secondary"}
|
||||
disabled={installing}
|
||||
aria-label={compact ? `${update ? tx("Update") : tx("Install")} ${entry.name}` : undefined}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
void installFromMarket(entry.id).then((id) => id && onInstalled?.(id));
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function MarketRow({ entry, selected, onSelect }: { entry: MarketPlugin; selected: boolean; onSelect: () => void }) {
|
||||
const update = isUpdate(entry);
|
||||
return (
|
||||
<li className={clsx(styles.row, styles.marketRow, selected && styles.rowSelected)}>
|
||||
<li className={clsx(styles.row, selected && styles.rowSelected)}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.rowMain}
|
||||
@@ -1044,189 +939,99 @@ function MarketRow({ entry, selected, onSelect }: { entry: MarketPlugin; selecte
|
||||
onClick={onSelect}
|
||||
title={entry.description || entry.name}
|
||||
>
|
||||
<PluginIcon id={entry.id} icon={entry.icon} name={entry.name} />
|
||||
<PluginIcon id={entry.id} icon={entry.icon} />
|
||||
<span className={styles.rowText}>
|
||||
<span className={styles.rowTitle}>
|
||||
<span className={styles.rowName}>{entry.name}</span>
|
||||
{isExample(entry) && <ExampleTag />}
|
||||
</span>
|
||||
{entry.description && <span className={styles.rowDescription}>{entry.description}</span>}
|
||||
<span className={styles.rowName}>{entry.name}</span>
|
||||
<span className={styles.rowMeta}>
|
||||
{!isExample(entry) && <span className={styles.rowVendor}>{publisherOf(entry)}</span>}
|
||||
{entry.downloads != null && (
|
||||
<span className={styles.downloads} title={tx`${entry.downloads} downloads`}>
|
||||
<Icon name="download" size={12} />
|
||||
{formatDownloads(entry.downloads)}
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.rowVendor}>{entry.publisher}</span>
|
||||
<span>{entry.version}</span>
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
<MarketAction entry={entry} compact />
|
||||
{update ? (
|
||||
<Badge tone="accent">{tx("Update")}</Badge>
|
||||
) : entry.installed ? (
|
||||
<Badge tone="neutral">{tx("Installed")}</Badge>
|
||||
) : !entry.compatible ? (
|
||||
<Badge tone="warning">{tx("Incompatible")}</Badge>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function MarketGroup({
|
||||
title,
|
||||
entries,
|
||||
selectedId,
|
||||
onSelect,
|
||||
note,
|
||||
idPrefix,
|
||||
}: {
|
||||
title: string;
|
||||
entries: readonly MarketPlugin[];
|
||||
selectedId: string | undefined;
|
||||
onSelect: (id: string) => void;
|
||||
note?: string;
|
||||
idPrefix: string;
|
||||
}) {
|
||||
if (entries.length === 0) return null;
|
||||
return (
|
||||
<>
|
||||
<ListHeader title={title} count={entries.length} />
|
||||
{note && <li className={styles.groupNote}>{note}</li>}
|
||||
{entries.map((m) => (
|
||||
<MarketRow
|
||||
key={`${idPrefix}:${m.id}`}
|
||||
entry={m}
|
||||
selected={m.id === selectedId}
|
||||
onSelect={() => onSelect(m.id)}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function MarketDetails({
|
||||
entry,
|
||||
suggestedBy,
|
||||
onInstalled,
|
||||
}: {
|
||||
entry: MarketPlugin;
|
||||
suggestedBy: string | undefined;
|
||||
onInstalled: (id: string) => void;
|
||||
}) {
|
||||
const example = isExample(entry);
|
||||
const overview = (
|
||||
<>
|
||||
{entry.description && <p className={styles.description}>{entry.description}</p>}
|
||||
<dl className={styles.facts}>
|
||||
<dt>
|
||||
<T>Id</T>
|
||||
</dt>
|
||||
<dd className={styles.mono}>{entry.id}</dd>
|
||||
<dt>
|
||||
<T>Category</T>
|
||||
</dt>
|
||||
<dd>{categoriesOf(entry).map(categoryLabel).join(", ")}</dd>
|
||||
{entry.homepage && (
|
||||
<>
|
||||
<dt>
|
||||
<T>Homepage</T>
|
||||
</dt>
|
||||
<Homepage value={entry.homepage} />
|
||||
</>
|
||||
)}
|
||||
{entry.installed && (
|
||||
<>
|
||||
<dt>
|
||||
<T>Installed</T>
|
||||
</dt>
|
||||
<dd>{entry.installed}</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
{(entry.capabilities?.length ?? 0) > 0 && (
|
||||
<Section title="Permissions">
|
||||
<ul className={styles.items}>
|
||||
{(entry.capabilities ?? []).map((c) => (
|
||||
<li key={c} className={clsx(styles.item, styles.mono)}>
|
||||
{c}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Section>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
function MarketDetails({ entry, onInstalled }: { entry: MarketPlugin; onInstalled: (id: string) => void }) {
|
||||
const installing = usePlugins((s) => s.installing);
|
||||
const update = isUpdate(entry);
|
||||
const install = async () => {
|
||||
const id = await installFromMarket(entry.id);
|
||||
if (id) onInstalled(id);
|
||||
};
|
||||
return (
|
||||
<div className={styles.details} aria-label={`${entry.name} details`}>
|
||||
<header className={styles.header}>
|
||||
<PluginIcon id={entry.id} icon={entry.icon} name={entry.name} large />
|
||||
<PluginIcon id={entry.id} icon={entry.icon} large />
|
||||
<div className={styles.headerText}>
|
||||
<h2 className={styles.title}>{entry.name}</h2>
|
||||
<div className={styles.authors}>{entry.authors?.length ? vendorOf(entry.authors) : publisherOf(entry)}</div>
|
||||
<div className={styles.authors}>{entry.authors?.length ? vendorOf(entry.authors) : entry.publisher}</div>
|
||||
<div className={styles.titleLine}>
|
||||
<span className={styles.version}>{entry.version}</span>
|
||||
{example && <ExampleTag />}
|
||||
<Badge tone="success">{tx`Signed by ${publisherOf(entry)}`}</Badge>
|
||||
{entry.downloads != null && (
|
||||
<span className={styles.downloads}>
|
||||
<Icon name="download" size={12} />
|
||||
{tx`${formatDownloads(entry.downloads)} downloads`}
|
||||
</span>
|
||||
)}
|
||||
<Badge tone="success">{tx`Signed by ${entry.publisher}`}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.headerActions}>
|
||||
<MarketAction entry={entry} onInstalled={onInstalled} />
|
||||
{entry.compatible && (!entry.installed || update) && (
|
||||
<Button size="small" variant="primary" disabled={installing} onClick={() => void install()}>
|
||||
{update ? tx`Update to ${entry.version}` : tx("Install")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
{!entry.compatible && (
|
||||
<p className={clsx(styles.notice, styles.detailsNotice)} role="note">
|
||||
<Icon name="info" size={14} />
|
||||
<span>{tx`Needs plugin API ${entry.engine}. Update OpenIDEA to install it.`}</span>
|
||||
</p>
|
||||
)}
|
||||
{example && (
|
||||
<p className={clsx(styles.notice, styles.detailsNotice)} role="note">
|
||||
<Icon name="info" size={14} />
|
||||
<span>
|
||||
{tx(
|
||||
"This plugin shows how to use the plugin API and is not maintained as a product. Build on it in your own repository.",
|
||||
)}
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
{suggestedBy && (
|
||||
<p className={clsx(styles.notice, styles.suggestNotice, styles.detailsNotice)} role="note">
|
||||
<Icon name="info" size={14} />
|
||||
<span>{tx`Suggested because this project has ${suggestedBy}.`}</span>
|
||||
</p>
|
||||
)}
|
||||
<DetailTabs notes={entry.notes ?? null} overview={overview} />
|
||||
<div className={styles.marketOverview}>
|
||||
{!entry.compatible && (
|
||||
<p className={clsx(styles.notice, styles.detailsNotice)} role="note">
|
||||
<Icon name="info" size={14} />
|
||||
<span>{tx`Needs plugin API ${entry.engine}. Update OpenIDEA to install it.`}</span>
|
||||
</p>
|
||||
)}
|
||||
{entry.description && <p className={styles.description}>{entry.description}</p>}
|
||||
<dl className={styles.facts}>
|
||||
<dt>
|
||||
<T>Id</T>
|
||||
</dt>
|
||||
<dd className={styles.mono}>{entry.id}</dd>
|
||||
<dt>
|
||||
<T>Category</T>
|
||||
</dt>
|
||||
<dd>{categoriesOf(entry).map(categoryLabel).join(", ")}</dd>
|
||||
{entry.installed && (
|
||||
<>
|
||||
<dt>
|
||||
<T>Installed</T>
|
||||
</dt>
|
||||
<dd>{entry.installed}</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
{(entry.capabilities?.length ?? 0) > 0 && (
|
||||
<Section title="Permissions">
|
||||
<ul className={styles.items}>
|
||||
{(entry.capabilities ?? []).map((c) => (
|
||||
<li key={c} className={clsx(styles.item, styles.mono)}>
|
||||
{c}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Each marketplace plugin the open project has a suggestion path for (id → path). */
|
||||
function useSuggestions(market: readonly MarketPlugin[] | null): Map<string, string> {
|
||||
const root = useProject((s) => s.project?.root);
|
||||
const [present, setPresent] = useState<ReadonlySet<string>>(new Set());
|
||||
const paths = useMemo(() => suggestionPaths(market ?? []), [market]);
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
if (!root || paths.length === 0) {
|
||||
setPresent(new Set());
|
||||
return;
|
||||
}
|
||||
void projectHas(paths).then((found) => {
|
||||
if (live) setPresent(found);
|
||||
});
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [root, paths]);
|
||||
return useMemo(() => suggestedFor(market ?? [], present), [market, present]);
|
||||
}
|
||||
|
||||
/** Opens on Available, where plugins are found; `initialTab` picks another. */
|
||||
export function PluginsPage({ initialTab = "marketplace" }: { initialTab?: Tab } = {}) {
|
||||
export function PluginsPage() {
|
||||
const { plugins, loaded, loading, error, installing, catalog, catalogError, market, marketUrl, marketError } =
|
||||
usePlugins();
|
||||
const [tab, setTab] = useState<Tab>(initialTab);
|
||||
const [tab, setTab] = useState<Tab>("installed");
|
||||
const [query, setQuery] = useState("");
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [selectedCatalogId, setSelectedCatalogId] = useState<string | null>(null);
|
||||
@@ -1247,13 +1052,7 @@ export function PluginsPage({ initialTab = "marketplace" }: { initialTab?: Tab }
|
||||
}),
|
||||
[market, query, category],
|
||||
);
|
||||
const suggestions = useSuggestions(market);
|
||||
const browsing = !query.trim() && category === "all";
|
||||
const groups = useMemo(
|
||||
() => groupMarket(marketShown, query, browsing, suggestions),
|
||||
[marketShown, query, browsing, suggestions],
|
||||
);
|
||||
const marketOrder = [...groups.suggested, ...groups.featured, ...groups.community, ...groups.examples];
|
||||
const selectedMarket = marketShown.find((m) => m.id === selectedMarketId) ?? null;
|
||||
|
||||
const shown = useMemo(() => filterPlugins(plugins, query), [plugins, query]);
|
||||
const downloaded = shown.filter((p) => p.source === "installed");
|
||||
@@ -1266,16 +1065,7 @@ export function PluginsPage({ initialTab = "marketplace" }: { initialTab?: Tab }
|
||||
() => (category === "all" ? filterCatalog(catalog ?? [], query) : []),
|
||||
[catalog, query, category],
|
||||
);
|
||||
// The clicked plugin; else the first one listed, so the details are never empty.
|
||||
const pickedCatalog = catalogShown.find((c) => c.id === selectedCatalogId) ?? null;
|
||||
const selectedMarket = pickedCatalog
|
||||
? null
|
||||
: (marketShown.find((m) => m.id === selectedMarketId) ?? marketOrder[0] ?? null);
|
||||
const selectedEntry = selectedMarket ? null : (pickedCatalog ?? catalogShown[0] ?? null);
|
||||
const selectMarket = (id: string) => {
|
||||
setSelectedCatalogId(null);
|
||||
setSelectedMarketId(id);
|
||||
};
|
||||
const selectedEntry = catalogShown.find((c) => c.id === selectedCatalogId) ?? catalogShown[0] ?? null;
|
||||
|
||||
const showInstalled = (id: string | null) => {
|
||||
if (!id) return;
|
||||
@@ -1315,6 +1105,11 @@ export function PluginsPage({ initialTab = "marketplace" }: { initialTab?: Tab }
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<span title={tx("The plugin system is a preview: its API and the plugins may still change.")}>
|
||||
<Badge tone="accent">
|
||||
<T>Preview</T>
|
||||
</Badge>
|
||||
</span>
|
||||
<span className={styles.spacer} />
|
||||
{(loading || installing) && <Spinner size={14} label={installing ? "Installing plugin" : "Loading plugins"} />}
|
||||
<IconButton icon="settings" title="Manage Plugins" aria-haspopup="menu" onClick={openGear} />
|
||||
@@ -1328,18 +1123,13 @@ export function PluginsPage({ initialTab = "marketplace" }: { initialTab?: Tab }
|
||||
|
||||
<div className={styles.body}>
|
||||
<div className={styles.side}>
|
||||
<div className={styles.searchRow}>
|
||||
<SearchField
|
||||
className={styles.searchField}
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder={tab === "installed" ? "Search installed plugins" : "Search plugins"}
|
||||
aria-label="Filter plugins"
|
||||
/>
|
||||
{tab === "marketplace" && (market?.length ?? 0) > 0 && (
|
||||
<CategoryFilter market={market ?? []} value={category} onChange={setCategory} />
|
||||
)}
|
||||
</div>
|
||||
<SearchField
|
||||
className={styles.search}
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder={tab === "installed" ? "Search installed plugins" : "Search plugins"}
|
||||
aria-label="Filter plugins"
|
||||
/>
|
||||
{tab === "installed" ? (
|
||||
<ul className={styles.list} aria-label={tx("Installed plugins")}>
|
||||
{downloaded.length > 0 && <ListHeader title="Downloaded" count={downloaded.length} />}
|
||||
@@ -1377,36 +1167,21 @@ export function PluginsPage({ initialTab = "marketplace" }: { initialTab?: Tab }
|
||||
</ul>
|
||||
) : (
|
||||
<ul className={styles.list} aria-label={tx("Available plugins")}>
|
||||
{(market?.length ?? 0) > 0 && (
|
||||
<li className={styles.marketItem}>
|
||||
<CategoryFilter market={market ?? []} value={category} onChange={setCategory} />
|
||||
</li>
|
||||
)}
|
||||
{marketError && <li className={clsx(styles.listEmpty, styles.errorText)}>{marketError}</li>}
|
||||
<MarketGroup
|
||||
idPrefix="suggested"
|
||||
title={tx("Suggested for This Project")}
|
||||
entries={groups.suggested}
|
||||
selectedId={selectedMarket?.id}
|
||||
onSelect={selectMarket}
|
||||
/>
|
||||
<MarketGroup
|
||||
idPrefix="featured"
|
||||
title={tx("Featured")}
|
||||
entries={groups.featured}
|
||||
selectedId={selectedMarket?.id}
|
||||
onSelect={selectMarket}
|
||||
/>
|
||||
<MarketGroup
|
||||
idPrefix="community"
|
||||
title={browsing ? tx("All Plugins") : tx("Marketplace")}
|
||||
entries={groups.community}
|
||||
selectedId={selectedMarket?.id}
|
||||
onSelect={selectMarket}
|
||||
/>
|
||||
<MarketGroup
|
||||
idPrefix="examples"
|
||||
title={tx("Examples")}
|
||||
note={exampleNote()}
|
||||
entries={groups.examples}
|
||||
selectedId={selectedMarket?.id}
|
||||
onSelect={selectMarket}
|
||||
/>
|
||||
{marketShown.length > 0 && <ListHeader title="Marketplace" count={marketShown.length} />}
|
||||
{marketShown.map((m) => (
|
||||
<MarketRow
|
||||
key={`market:${m.id}`}
|
||||
entry={m}
|
||||
selected={m.id === selectedMarket?.id}
|
||||
onSelect={() => setSelectedMarketId(m.id)}
|
||||
/>
|
||||
))}
|
||||
{catalogShown.length > 0 && <ListHeader title="Local" count={catalogShown.length} />}
|
||||
{catalogShown.map((c) => (
|
||||
<CatalogRow
|
||||
@@ -1443,7 +1218,6 @@ export function PluginsPage({ initialTab = "marketplace" }: { initialTab?: Tab }
|
||||
<MarketDetails
|
||||
key={`market:${selectedMarket.id}`}
|
||||
entry={selectedMarket}
|
||||
suggestedBy={suggestions.get(selectedMarket.id)}
|
||||
onInstalled={(id) => {
|
||||
setTab("installed");
|
||||
setSelectedId(id);
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { MarketPlugin } from "@/bindings";
|
||||
import { formatDownloads, groupMarket, monogram, suggestedFor, suggestionPaths } from "../market";
|
||||
|
||||
const plugin = (id: string, more: Partial<MarketPlugin> = {}): MarketPlugin => ({
|
||||
id,
|
||||
name: id.split(".")[1]!,
|
||||
version: "1.0.0",
|
||||
description: "",
|
||||
authors: [],
|
||||
publisher: id.split(".")[0]!,
|
||||
download: `${id}.oiplugin`,
|
||||
digest: "x",
|
||||
capabilities: [],
|
||||
engine: "^1.0",
|
||||
categories: [],
|
||||
icon: null,
|
||||
installed: null,
|
||||
compatible: true,
|
||||
publisherName: null,
|
||||
...more,
|
||||
});
|
||||
|
||||
const ids = (list: readonly MarketPlugin[]) => list.map((m) => m.id);
|
||||
|
||||
describe("groupMarket", () => {
|
||||
const market = [
|
||||
plugin("openidea.checkstyle", {
|
||||
downloads: 9000,
|
||||
featured: true,
|
||||
suggest: ["pom.xml"],
|
||||
}),
|
||||
plugin("acme.rare", { downloads: 3 }),
|
||||
plugin("acme.popular", { downloads: 500, featured: true }),
|
||||
plugin("bob.maven", { suggest: ["pom.xml"] }),
|
||||
plugin("bob.done", { suggest: ["pom.xml"], installed: "1.0.0" }),
|
||||
];
|
||||
const suggested = suggestedFor(market, new Set(["pom.xml"]));
|
||||
|
||||
it("browses suggestions and picks, then community plugins by downloads, then the examples", () => {
|
||||
const g = groupMarket(market, "", true, suggested);
|
||||
expect(ids(g.suggested)).toEqual(["bob.maven"]);
|
||||
expect(ids(g.featured)).toEqual(["acme.popular"]);
|
||||
expect(ids(g.community)).toEqual(["acme.popular", "acme.rare", "bob.done", "bob.maven"]);
|
||||
expect(ids(g.examples)).toEqual(["openidea.checkstyle"]);
|
||||
});
|
||||
|
||||
it("lists matches by name first when searching, examples still last", () => {
|
||||
const shown = [plugin("acme.zeta", { downloads: 100 }), plugin("acme.lint-z"), plugin("openidea.z-ex")];
|
||||
const g = groupMarket(shown, "z", false, suggested);
|
||||
expect(g.suggested).toEqual([]);
|
||||
expect(g.featured).toEqual([]);
|
||||
expect(ids(g.community)).toEqual(["acme.zeta", "acme.lint-z"]);
|
||||
expect(ids(g.examples)).toEqual(["openidea.z-ex"]);
|
||||
});
|
||||
|
||||
it("never suggests an example", () => {
|
||||
expect(suggestionPaths(market)).toEqual(["pom.xml"]);
|
||||
expect([...suggested.keys()]).toEqual(["bob.maven", "bob.done"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("helpers", () => {
|
||||
it("formats downloads compactly", () => {
|
||||
expect(formatDownloads(42)).toBe("42");
|
||||
expect(formatDownloads(1234)).toMatch(/^1\.2\s?K$/);
|
||||
});
|
||||
|
||||
it("gives a plugin without an icon a stable initial and tone", () => {
|
||||
expect(monogram("acme.tool", ".env files").letter).toBe("E");
|
||||
expect(monogram("acme.tool", "x").tone).toBe(monogram("acme.tool", "renamed").tone);
|
||||
});
|
||||
});
|
||||
@@ -813,7 +813,7 @@ describe("plugin prompts", () => {
|
||||
describe("PluginsPage", () => {
|
||||
it("lists plugins, shows details, toggles and applies themes", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
const list = await screen.findByRole("list", { name: "Installed plugins" });
|
||||
await waitFor(() => expect(within(list).getAllByRole("listitem")).toHaveLength(3));
|
||||
|
||||
@@ -841,7 +841,7 @@ describe("PluginsPage", () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<>
|
||||
<PluginsPage initialTab="installed" />
|
||||
<PluginsPage />
|
||||
<ContextMenuHost />
|
||||
</>,
|
||||
);
|
||||
@@ -866,7 +866,7 @@ describe("PluginsPage", () => {
|
||||
it("shows a plugin's own icon in its row and details", async () => {
|
||||
const icon = { light: '<svg viewBox="0 0 16 16"><circle cx="8" cy="8" r="8"/></svg>', dark: null };
|
||||
setPluginsBackend(createMemoryPluginsBackend([plugin({ id: "iconic", name: "Iconic", icon })]));
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
const list = await screen.findByRole("list", { name: "Installed plugins" });
|
||||
await waitFor(() => expect(within(list).getByText("Iconic")).toBeInTheDocument());
|
||||
expect(list.querySelector("circle")).not.toBeNull();
|
||||
@@ -879,7 +879,7 @@ describe("PluginsPage", () => {
|
||||
const catalog = { ...sampleCatalog()[0]!, id: entry.id, name: entry.name, homepage };
|
||||
setPluginsBackend(createMemoryPluginsBackend(source === "installed" ? [entry] : [], [catalog]));
|
||||
const user = userEvent.setup();
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
if (source === "catalog") await user.click(screen.getByRole("tab", { name: /Available/ }));
|
||||
await screen.findByRole("heading", { level: 2, name: entry.name });
|
||||
return user;
|
||||
@@ -925,14 +925,14 @@ describe("PluginsPage", () => {
|
||||
it("restarts a failed plugin instead of disabling it", async () => {
|
||||
setPluginsBackend(createMemoryPluginsBackend([plugin({ id: "broken", status: "failed", error: "trap" })]));
|
||||
const user = userEvent.setup();
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
await user.click(await screen.findByRole("button", { name: "Restart" }));
|
||||
await waitFor(() => expect(usePlugins.getState().plugins[0]).toMatchObject({ enabled: true, status: "inactive" }));
|
||||
});
|
||||
|
||||
it("uninstalls after confirmation", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
await screen.findByRole("heading", { level: 2 });
|
||||
await user.click(screen.getByRole("button", { name: "Uninstall…" }));
|
||||
await user.click(screen.getByRole("button", { name: "Confirm uninstall Hello" }));
|
||||
@@ -961,7 +961,7 @@ describe("PluginsPage", () => {
|
||||
await uninstall(id);
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
await screen.findByRole("heading", { level: 2 });
|
||||
await user.click(screen.getByRole("button", { name: "Uninstall…" }));
|
||||
await user.click(screen.getByRole("button", { name: "Confirm uninstall Hello" }));
|
||||
@@ -983,7 +983,7 @@ describe("PluginsPage", () => {
|
||||
setPluginsBackend(
|
||||
createMemoryPluginsBackend([plugin({ id: "hello", name: "Hello", changeNotes: "Added word count." })]),
|
||||
);
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
await screen.findByRole("heading", { level: 2 });
|
||||
expect(screen.queryByText("Added word count.")).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole("tab", { name: "What's New" }));
|
||||
@@ -994,7 +994,7 @@ describe("PluginsPage", () => {
|
||||
const user = userEvent.setup();
|
||||
const catalog = sampleCatalog();
|
||||
setPluginsBackend(createMemoryPluginsBackend([], catalog));
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
await user.click(screen.getByRole("tab", { name: /Available/ }));
|
||||
const list = await screen.findByRole("list", { name: "Available plugins" });
|
||||
await waitFor(() => expect(within(list).getByText("Toy Language")).toBeInTheDocument());
|
||||
@@ -1013,7 +1013,7 @@ describe("PluginsPage", () => {
|
||||
marketUrl: () => Promise.reject({ kind: "unavailable", message: "Index unreachable", data: null }),
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
await user.click(screen.getByRole("tab", { name: /Available/ }));
|
||||
const list = await screen.findByRole("list", { name: "Available plugins" });
|
||||
expect(await within(list).findByText("Index unreachable")).toBeInTheDocument();
|
||||
@@ -1111,10 +1111,10 @@ describe("marketplace", () => {
|
||||
},
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
await user.click(screen.getByRole("tab", { name: /Available/ }));
|
||||
const list = await screen.findByRole("list", { name: "Available plugins" });
|
||||
await waitFor(() => expect(within(list).getByText("All Plugins")).toBeInTheDocument());
|
||||
await waitFor(() => expect(within(list).getByText("Marketplace")).toBeInTheDocument());
|
||||
expect(within(list).queryByText(new RegExp(NO_REPOSITORY))).not.toBeInTheDocument();
|
||||
await user.click(within(list).getAllByText("Hello")[0]!);
|
||||
expect(screen.getByText("Signed by acme")).toBeInTheDocument();
|
||||
@@ -1124,55 +1124,6 @@ describe("marketplace", () => {
|
||||
expect(asked[0]).toMatchObject({ pluginId: "hello", kind: "install" });
|
||||
});
|
||||
|
||||
it("lists community plugins before the examples, selects the first and installs from a row", async () => {
|
||||
setConsentPrompt(async () => ({ optional: [] }));
|
||||
const entry = (id: string, name: string, more: object = {}) => ({
|
||||
id,
|
||||
name,
|
||||
version: "1.0.0",
|
||||
description: `${name} does things`,
|
||||
authors: [],
|
||||
publisher: id.split(".")[0]!,
|
||||
download: `${id}.oiplugin`,
|
||||
digest: "x",
|
||||
capabilities: [],
|
||||
engine: "^1.0",
|
||||
installed: null,
|
||||
compatible: true,
|
||||
...more,
|
||||
});
|
||||
const downloads: string[] = [];
|
||||
setPluginsBackend({
|
||||
...createMemoryPluginsBackend([], sampleCatalog()),
|
||||
marketUrl: async () => "https://plugins.example/index.json",
|
||||
market: async () => [
|
||||
entry("openidea.sample", "Sample"),
|
||||
entry("acme.rare", "Rare", { downloads: 2 }),
|
||||
entry("acme.popular", "Popular", { downloads: 1500, featured: true, publisherName: "Acme Inc." }),
|
||||
],
|
||||
marketDownload: async (id) => {
|
||||
downloads.push(id);
|
||||
return "plugins/hello";
|
||||
},
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
await user.click(screen.getByRole("tab", { name: /Available/ }));
|
||||
const list = await screen.findByRole("list", { name: "Available plugins" });
|
||||
await waitFor(() => expect(within(list).getByText("Examples")).toBeInTheDocument());
|
||||
const headers = within(list)
|
||||
.getAllByText(/^(Featured|All Plugins|Examples|Local)$/)
|
||||
.map((h) => h.textContent);
|
||||
expect(headers).toEqual(["Featured", "All Plugins", "Examples", "Local"]);
|
||||
// The first listed plugin is shown without a click.
|
||||
expect(screen.getByRole("heading", { name: "Popular" })).toBeInTheDocument();
|
||||
expect(screen.getByText("Signed by Acme Inc.")).toBeInTheDocument();
|
||||
await user.click(within(list).getByText("Sample"));
|
||||
expect(screen.getByRole("note")).toHaveTextContent("not maintained as a product");
|
||||
await user.click(within(list).getByRole("button", { name: "Install Rare" }));
|
||||
await waitFor(() => expect(downloads).toEqual(["acme.rare"]));
|
||||
});
|
||||
|
||||
it("doesn't claim there is no repository while one is configured", async () => {
|
||||
setPluginsBackend({
|
||||
...createMemoryPluginsBackend([], []),
|
||||
@@ -1180,7 +1131,7 @@ describe("marketplace", () => {
|
||||
market: async () => [],
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
await user.click(screen.getByRole("tab", { name: /Available/ }));
|
||||
expect(await screen.findByText("No plugin selected")).toBeInTheDocument();
|
||||
expect(screen.queryByText(new RegExp(NO_REPOSITORY))).not.toBeInTheDocument();
|
||||
@@ -1199,7 +1150,7 @@ describe("marketplace", () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<>
|
||||
<PluginsPage initialTab="installed" />
|
||||
<PluginsPage />
|
||||
<ContextMenuHost />
|
||||
<InputDialogsHost />
|
||||
</>,
|
||||
@@ -1246,11 +1197,11 @@ describe("marketplace", () => {
|
||||
],
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
await user.click(screen.getByRole("tab", { name: /Available/ }));
|
||||
const list = await screen.findByRole("list", { name: "Available plugins" });
|
||||
await waitFor(() => expect(within(list).getByText("Dusk")).toBeInTheDocument());
|
||||
await user.click(screen.getByRole("button", { name: "Category" }));
|
||||
await user.click(within(list).getByRole("button", { name: "Category" }));
|
||||
const options = within(screen.getByRole("listbox"))
|
||||
.getAllByRole("option")
|
||||
.map((o) => o.textContent);
|
||||
@@ -1284,7 +1235,7 @@ describe("marketplace", () => {
|
||||
],
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
await user.click(screen.getByRole("tab", { name: /Available/ }));
|
||||
const list = await screen.findByRole("list", { name: "Available plugins" });
|
||||
await waitFor(() => expect(within(list).getByText("Incompatible")).toBeInTheDocument());
|
||||
@@ -1393,7 +1344,7 @@ describe("marketplace", () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<>
|
||||
<PluginsPage initialTab="installed" />
|
||||
<PluginsPage />
|
||||
<ContextMenuHost />
|
||||
</>,
|
||||
);
|
||||
@@ -1407,7 +1358,7 @@ describe("marketplace", () => {
|
||||
setConsentPrompt(async () => ({ optional: [] }));
|
||||
const consents = updatesBackend({ a: preview("a", "1.1.0"), b: preview("b", "2.0.0") });
|
||||
const user = userEvent.setup();
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
await waitFor(() => expect(usePlugins.getState().market).toHaveLength(3));
|
||||
const list = screen.getByRole("list", { name: "Installed plugins" });
|
||||
expect(within(list).getAllByText("Update")).toHaveLength(2);
|
||||
@@ -1449,7 +1400,7 @@ describe("marketplace", () => {
|
||||
]);
|
||||
const revokeNetHost = vi.fn((id: string, host: string) => base.revokeNetHost(id, host));
|
||||
setPluginsBackend({ ...base, revokeNetHost });
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
await screen.findByText("net:relay.example.org");
|
||||
expect(screen.getAllByText(`net:${host}`)).toHaveLength(host === "ask" ? 2 : 1);
|
||||
expect(screen.getByText("net:relay.example.org")).toBeInTheDocument();
|
||||
@@ -1474,7 +1425,7 @@ describe("marketplace", () => {
|
||||
},
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
expect(await screen.findByText("Unsigned")).toBeInTheDocument();
|
||||
await user.click(await screen.findByRole("button", { name: "Roll Back to 1.0.0" }));
|
||||
await waitFor(() => expect(rolled).toEqual(["p"]));
|
||||
@@ -1504,7 +1455,7 @@ describe("marketplace", () => {
|
||||
}),
|
||||
]),
|
||||
);
|
||||
render(<PluginsPage initialTab="installed" />);
|
||||
render(<PluginsPage />);
|
||||
expect(await screen.findByText("Blocked")).toBeInTheDocument();
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("Requires base ^1.0, but version 2.0.0 is installed");
|
||||
|
||||
@@ -1533,7 +1484,7 @@ describe("marketplace", () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<>
|
||||
<PluginsPage initialTab="installed" />
|
||||
<PluginsPage />
|
||||
<MessagesHost />
|
||||
</>,
|
||||
);
|
||||
@@ -1564,7 +1515,7 @@ describe("marketplace", () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<>
|
||||
<PluginsPage initialTab="installed" />
|
||||
<PluginsPage />
|
||||
<MessagesHost />
|
||||
</>,
|
||||
);
|
||||
@@ -1585,7 +1536,7 @@ describe("marketplace", () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<>
|
||||
<PluginsPage initialTab="installed" />
|
||||
<PluginsPage />
|
||||
<MessagesHost />
|
||||
</>,
|
||||
);
|
||||
|
||||
@@ -4,7 +4,6 @@ import { useProject } from "@/platform/project";
|
||||
import { usePlugins } from "../store";
|
||||
import {
|
||||
affectsWorkspaceContains,
|
||||
projectHas,
|
||||
refreshWorkspaceContains,
|
||||
startWorkspaceContains,
|
||||
workspaceContainsKeys,
|
||||
@@ -154,16 +153,10 @@ describe.each(["menus", "views"])("startWorkspaceContains (%s)", (point) => {
|
||||
let stop: () => void;
|
||||
|
||||
beforeEach(() => {
|
||||
ipc.files = {
|
||||
"/p": ["src"],
|
||||
"/q": [".devcontainer"],
|
||||
"/q/.devcontainer": ["devcontainer.json"],
|
||||
};
|
||||
ipc.files = { "/p": ["src"], "/q": [".devcontainer"], "/q/.devcontainer": ["devcontainer.json"] };
|
||||
ipc.readDir.mockReset();
|
||||
ipc.readDir.mockImplementation(async (dir: string) => (ipc.files[dir] ?? []).map((name) => ({ name })));
|
||||
usePlugins.setState({
|
||||
ui: [{ pluginId: "x", point, key: "k", decl: { when: key } }] as never,
|
||||
});
|
||||
usePlugins.setState({ ui: [{ pluginId: "x", point, key: "k", decl: { when: key } }] as never });
|
||||
setProject("/p");
|
||||
setContext(key, undefined);
|
||||
stop = startWorkspaceContains();
|
||||
@@ -175,19 +168,11 @@ describe.each(["menus", "views"])("startWorkspaceContains (%s)", (point) => {
|
||||
await keyIs(false);
|
||||
ipc.files["/p"] = [".devcontainer"];
|
||||
ipc.files["/p/.devcontainer"] = ["devcontainer.json"];
|
||||
emit("fsChanged", {
|
||||
created: ["/p/.devcontainer"],
|
||||
modified: [],
|
||||
removed: [],
|
||||
});
|
||||
emit("fsChanged", { created: ["/p/.devcontainer"], modified: [], removed: [] });
|
||||
await keyIs(true);
|
||||
|
||||
ipc.files["/p/.devcontainer"] = [];
|
||||
emit("fsChanged", {
|
||||
created: [],
|
||||
modified: [],
|
||||
removed: ["/p/.devcontainer/devcontainer.json"],
|
||||
});
|
||||
emit("fsChanged", { created: [], modified: [], removed: ["/p/.devcontainer/devcontainer.json"] });
|
||||
await keyIs(false);
|
||||
});
|
||||
|
||||
@@ -219,18 +204,3 @@ describe.each(["menus", "views"])("startWorkspaceContains (%s)", (point) => {
|
||||
expect(ipc.handlers.excludedDirsChanged).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("projectHas", () => {
|
||||
afterEach(() => useProject.setState({ project: null }));
|
||||
|
||||
it("finds which relative paths the project's roots have, ignoring ones outside it", async () => {
|
||||
useProject.setState({ project: { root: "/p" } as never });
|
||||
const files: Record<string, string[]> = {
|
||||
"/p": ["pom.xml"],
|
||||
"/p/config": ["routes.rb"],
|
||||
};
|
||||
const list = async (dir: string) => files[dir] ?? [];
|
||||
const found = await projectHas(["pom.xml", "config/routes.rb", "go.mod", "../pom.xml"], list);
|
||||
expect([...found].sort()).toEqual(["config/routes.rb", "pom.xml"]);
|
||||
});
|
||||
});
|
||||
@@ -1,85 +0,0 @@
|
||||
/** How the Available tab orders and groups the marketplace. */
|
||||
import type { MarketPlugin } from "@/bindings";
|
||||
|
||||
/** The official plugins: examples of the plugin API, not maintained products. */
|
||||
export const EXAMPLE_PUBLISHER = "openidea";
|
||||
|
||||
export const isExample = (m: { publisher?: string | null }) => m.publisher === EXAMPLE_PUBLISHER;
|
||||
|
||||
const SUGGESTED_MAX = 5;
|
||||
const FEATURED_MAX = 6;
|
||||
|
||||
export interface MarketGroups {
|
||||
/** Not installed, and the project has a file the plugin is suggested for. */
|
||||
suggested: MarketPlugin[];
|
||||
featured: MarketPlugin[];
|
||||
/** Every community plugin shown, most downloaded first (best match first when searching). */
|
||||
community: MarketPlugin[];
|
||||
/** The official plugins, always last. */
|
||||
examples: MarketPlugin[];
|
||||
}
|
||||
|
||||
const byPopularity = (a: MarketPlugin, b: MarketPlugin) =>
|
||||
(b.downloads ?? 0) - (a.downloads ?? 0) || a.name.localeCompare(b.name);
|
||||
|
||||
/** 0 = name starts with the query, 1 = name contains it, 2 = matched elsewhere. */
|
||||
function rank(m: MarketPlugin, q: string): number {
|
||||
const name = m.name.toLowerCase();
|
||||
return name.startsWith(q) ? 0 : name.includes(q) ? 1 : 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits the shown plugins: suggestions and picks only while browsing (no query,
|
||||
* no category); community plugins before the examples.
|
||||
*/
|
||||
export function groupMarket(
|
||||
shown: readonly MarketPlugin[],
|
||||
query: string,
|
||||
browsing: boolean,
|
||||
suggestedFor: ReadonlyMap<string, string>,
|
||||
): MarketGroups {
|
||||
const q = query.trim().toLowerCase();
|
||||
const order = q ? (a: MarketPlugin, b: MarketPlugin) => rank(a, q) - rank(b, q) || byPopularity(a, b) : byPopularity;
|
||||
const community = shown.filter((m) => !isExample(m)).sort(order);
|
||||
const examples = shown.filter(isExample).sort(order);
|
||||
if (!browsing) return { suggested: [], featured: [], community, examples };
|
||||
return {
|
||||
suggested: community.filter((m) => !m.installed && suggestedFor.has(m.id)).slice(0, SUGGESTED_MAX),
|
||||
featured: community.filter((m) => m.featured).slice(0, FEATURED_MAX),
|
||||
community,
|
||||
examples,
|
||||
};
|
||||
}
|
||||
|
||||
/** 1234 → "1.2K", in the UI's number style. */
|
||||
export function formatDownloads(n: number): string {
|
||||
return new Intl.NumberFormat(undefined, {
|
||||
notation: "compact",
|
||||
maximumFractionDigits: 1,
|
||||
}).format(n);
|
||||
}
|
||||
|
||||
/** The paths any entry is suggested for. */
|
||||
export function suggestionPaths(market: readonly MarketPlugin[]): string[] {
|
||||
return [...new Set(market.flatMap((m) => (isExample(m) ? [] : (m.suggest ?? []))))];
|
||||
}
|
||||
|
||||
/** Each plugin's first suggestion path the project has. */
|
||||
export function suggestedFor(market: readonly MarketPlugin[], present: ReadonlySet<string>): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
for (const m of market) {
|
||||
const hit = isExample(m) ? undefined : m.suggest?.find((p) => present.has(p));
|
||||
if (hit) out.set(m.id, hit);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Tints for plugins without an icon, picked by id so each keeps its own. */
|
||||
export const MONOGRAM_TONES = 6;
|
||||
|
||||
export function monogram(id: string, name: string): { letter: string; tone: number } {
|
||||
let h = 0;
|
||||
for (let i = 0; i < id.length; i++) h = (Math.imul(h, 31) + id.charCodeAt(i)) | 0;
|
||||
const letter = [...name.trim().replace(/^[^\p{L}\p{N}]+/u, "")][0] ?? "?";
|
||||
return { letter: letter.toUpperCase(), tone: Math.abs(h) % MONOGRAM_TONES };
|
||||
}
|
||||
@@ -31,20 +31,6 @@ export function affectsWorkspaceContains(
|
||||
return changed.some((p) => targets.some((t) => t === p || t.startsWith(`${p}/`)));
|
||||
}
|
||||
|
||||
/** Whether `path` (relative) exists under any of `roots`. */
|
||||
async function existsUnder(roots: readonly string[], path: string, list: (dir: string) => Promise<string[]>) {
|
||||
const slash = path.lastIndexOf("/");
|
||||
const parent = slash < 0 ? "" : path.slice(0, slash);
|
||||
const name = path.slice(slash + 1);
|
||||
const found = await Promise.all(
|
||||
roots.map(async (root) => {
|
||||
const names: string[] = await list(parent ? `${root}/${parent}` : root).catch(() => []);
|
||||
return names.includes(name);
|
||||
}),
|
||||
);
|
||||
return found.some(Boolean);
|
||||
}
|
||||
|
||||
export async function refreshWorkspaceContains(
|
||||
roots: readonly string[],
|
||||
keys: readonly string[],
|
||||
@@ -54,7 +40,19 @@ export async function refreshWorkspaceContains(
|
||||
const results = await Promise.all(
|
||||
keys.map(async (key) => {
|
||||
const path = relativePath(key);
|
||||
return [key, path !== null && (await existsUnder(roots, path, list))] as const;
|
||||
if (path === null) {
|
||||
return [key, false] as const;
|
||||
}
|
||||
const slash = path.lastIndexOf("/");
|
||||
const parent = slash < 0 ? "" : path.slice(0, slash);
|
||||
const name = path.slice(slash + 1);
|
||||
const found = await Promise.all(
|
||||
roots.map(async (root) => {
|
||||
const names: string[] = await list(parent ? `${root}/${parent}` : root).catch(() => []);
|
||||
return names.includes(name);
|
||||
}),
|
||||
);
|
||||
return [key, found.some(Boolean)] as const;
|
||||
}),
|
||||
);
|
||||
if (!isCurrent()) {
|
||||
@@ -65,17 +63,6 @@ export async function refreshWorkspaceContains(
|
||||
}
|
||||
}
|
||||
|
||||
/** Which of the relative `paths` the open project has. */
|
||||
export async function projectHas(
|
||||
paths: readonly string[],
|
||||
list: (dir: string) => Promise<string[]> = listNames,
|
||||
): Promise<Set<string>> {
|
||||
const roots = projectRoots();
|
||||
const valid = paths.filter((p) => relativePath(`${PREFIX}${p}`) !== null);
|
||||
const found = await Promise.all(valid.map(async (p) => [p, await existsUnder(roots, p, list)] as const));
|
||||
return new Set(found.filter(([, ok]) => ok).map(([p]) => p));
|
||||
}
|
||||
|
||||
const listNames = (dir: string) => call(commands.fsReadDir(dir)).then((entries) => entries.map((e) => e.name));
|
||||
|
||||
const projectRoots = () => {
|
||||
|
||||
@@ -43,22 +43,6 @@ afterEach(() => {
|
||||
|
||||
const childLabels = (key: string) => (currentModel().children.get(key) ?? []).map((n) => n.label);
|
||||
|
||||
it("retains cached types only for members that remain in the same workspace", () => {
|
||||
initProjectTree("/workspace", "Workspace", ["/go", "/web"]);
|
||||
useProjectTree.setState({
|
||||
projectTypes: new Map([
|
||||
["/go", "go"],
|
||||
["/web", "node"],
|
||||
]),
|
||||
});
|
||||
|
||||
initProjectTree("/workspace", "Workspace", ["/go", "/new"]);
|
||||
expect([...useProjectTree.getState().projectTypes]).toEqual([["/go", "go"]]);
|
||||
|
||||
initProjectTree("/other-workspace", "Other workspace", ["/go"]);
|
||||
expect(useProjectTree.getState().projectTypes.size).toBe(0);
|
||||
});
|
||||
|
||||
describe("lazy loading", () => {
|
||||
it("loads folders on demand and shares concurrent requests", async () => {
|
||||
const spy = vi.spyOn(fs, "readDir");
|
||||
|
||||
@@ -321,25 +321,16 @@ export function initProjectTree(
|
||||
clearTimeout(persistTimer);
|
||||
modeExpanded.clear();
|
||||
autoExpanded.clear();
|
||||
const previous = get();
|
||||
const previousMode = previous.mode;
|
||||
const previousMode = get().mode;
|
||||
const mode =
|
||||
unity && previousMode === "project" ? "unity" : !unity && previousMode === "unity" ? "project" : previousMode;
|
||||
// Keep the remaining members' types visible while the workspace is rescanned.
|
||||
const projectTypes = new Map<string, ProjectType>();
|
||||
if (root === previous.root && members) {
|
||||
for (const member of members) {
|
||||
const type = previous.projectTypes.get(member);
|
||||
if (type) projectTypes.set(member, type);
|
||||
}
|
||||
}
|
||||
set({
|
||||
unity,
|
||||
mode,
|
||||
root,
|
||||
name,
|
||||
members,
|
||||
projectTypes,
|
||||
projectTypes: new Map(),
|
||||
listings: new Map(),
|
||||
expanded: initialExpanded(root, mode, members),
|
||||
selected: new Set(),
|
||||
|
||||
@@ -34,14 +34,6 @@
|
||||
gap: 2px;
|
||||
padding: 4px 0;
|
||||
border-right: 1px solid var(--border);
|
||||
min-height: 0;
|
||||
/* A pane shorter than the buttons (the Services detail) scrolls them with the wheel
|
||||
instead of growing the pane and adding a second scrollbar. */
|
||||
overflow-y: auto;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.toolbar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
.toolbarSep {
|
||||
width: 16px;
|
||||
|
||||
@@ -59,11 +59,15 @@ export function sessionIcon(s: RunSession): string {
|
||||
|
||||
export function SessionPanel({
|
||||
session,
|
||||
showLifecycle = true,
|
||||
onRerun,
|
||||
onDebug,
|
||||
onStop,
|
||||
}: {
|
||||
session: RunSession;
|
||||
/** False in the Services detail: the window's own toolbar already offers Run/Debug/Stop for the selection. */
|
||||
showLifecycle?: boolean;
|
||||
onRerun?: (() => void) | null;
|
||||
/** Override the Debug button (Services: rerun the attached debugger's launch); null disables it. */
|
||||
onDebug?: (() => void) | null;
|
||||
onStop?: () => void;
|
||||
}) {
|
||||
const updating = useApplicationUpdates((s) => s.ids.has(session.id));
|
||||
const version = useRun((s) => s.versions[session.id] ?? 0);
|
||||
@@ -165,50 +169,48 @@ export function SessionPanel({
|
||||
return (
|
||||
<div className={styles.session}>
|
||||
<div className={styles.toolbar} role="toolbar" aria-orientation="vertical" aria-label={tx("Run actions")}>
|
||||
{showLifecycle && (
|
||||
<>
|
||||
<IconButton
|
||||
icon="rerun"
|
||||
title="Rerun"
|
||||
shortcut={shortcutLabel("run.rerun")}
|
||||
onClick={() => rerunSession(session.id)}
|
||||
/>
|
||||
{/* Switch the launch mode: the same configuration started under the debugger. */}
|
||||
<IconButton
|
||||
icon="debug"
|
||||
title="Debug"
|
||||
shortcut={shortcutLabel("run.debug")}
|
||||
onClick={() => void debugSession(session.id)}
|
||||
/>
|
||||
{rt.tests && (
|
||||
<IconButton
|
||||
icon="rerun"
|
||||
tone="danger"
|
||||
title="Rerun Failed Tests"
|
||||
shortcut={shortcutLabel("run.rerunFailed")}
|
||||
disabled={!canRerunFailed}
|
||||
onClick={() => void rerunFailed(session.id)}
|
||||
/>
|
||||
)}
|
||||
<IconButton
|
||||
icon="stop"
|
||||
title={session.status === "stopping" ? tx`Stopping… (click to kill)` : "Stop"}
|
||||
tone={running ? "danger" : "default"}
|
||||
disabled={!running}
|
||||
onClick={() => void stopSession(session.id)}
|
||||
/>
|
||||
{isUpdatable(session.config) && (
|
||||
<IconButton
|
||||
icon="refresh"
|
||||
title="Update Application"
|
||||
shortcut={shortcutLabel("run.updateApplication")}
|
||||
disabled={session.status !== "running" || updating}
|
||||
onClick={() => showApplicationUpdate(session.id)}
|
||||
/>
|
||||
)}
|
||||
<div className={styles.toolbarSep} />
|
||||
</>
|
||||
<IconButton
|
||||
icon="rerun"
|
||||
title="Rerun"
|
||||
shortcut={shortcutLabel("run.rerun")}
|
||||
disabled={onRerun === null}
|
||||
onClick={onRerun ?? (() => rerunSession(session.id))}
|
||||
/>
|
||||
{/* Switch the launch mode: the same configuration started under the debugger. */}
|
||||
<IconButton
|
||||
icon="debug"
|
||||
title="Debug"
|
||||
shortcut={shortcutLabel("run.debug")}
|
||||
disabled={onDebug === null}
|
||||
onClick={onDebug ?? (() => void debugSession(session.id))}
|
||||
/>
|
||||
{rt.tests && (
|
||||
<IconButton
|
||||
icon="rerun"
|
||||
tone="danger"
|
||||
title="Rerun Failed Tests"
|
||||
shortcut={shortcutLabel("run.rerunFailed")}
|
||||
disabled={!canRerunFailed}
|
||||
onClick={() => void rerunFailed(session.id)}
|
||||
/>
|
||||
)}
|
||||
<IconButton
|
||||
icon="stop"
|
||||
title={session.status === "stopping" ? tx`Stopping… (click to kill)` : "Stop"}
|
||||
tone={running || onStop ? "danger" : "default"}
|
||||
disabled={!running && !onStop}
|
||||
onClick={onStop ?? (() => void stopSession(session.id))}
|
||||
/>
|
||||
{isUpdatable(session.config) && (
|
||||
<IconButton
|
||||
icon="refresh"
|
||||
title="Update Application"
|
||||
shortcut={shortcutLabel("run.updateApplication")}
|
||||
disabled={session.status !== "running" || updating}
|
||||
onClick={() => showApplicationUpdate(session.id)}
|
||||
/>
|
||||
)}
|
||||
<div className={styles.toolbarSep} />
|
||||
{!rt.terminal && (
|
||||
<>
|
||||
<IconButton
|
||||
|
||||
@@ -44,7 +44,7 @@ import { invalidateGoModules } from "./goModules";
|
||||
import { invalidatePythonPackages } from "./pythonPackages";
|
||||
import { RunWidget } from "./RunWidget";
|
||||
import { runConfigsRunAnything } from "./runAnything";
|
||||
import { cleanupRemovedProject, registerRunServiceActions, runServiceProvider } from "./services";
|
||||
import { cleanupRemovedProject, recordRun, registerRunServiceActions, runServiceProvider } from "./services";
|
||||
import { liveServiceSession, serviceSessions } from "./serviceSessions";
|
||||
import { ServiceImportHost } from "./serviceImport";
|
||||
import { cmakeBuildId } from "./cmake";
|
||||
@@ -158,6 +158,7 @@ async function debugConfig(config: RunConfig, chain: readonly string[] = [], sho
|
||||
}
|
||||
if (remoteDebugBlocked(config)) return;
|
||||
if (!(await prepareLaunch(config, chain, show))) return;
|
||||
recordRun(config.id);
|
||||
// Python on a Docker / Compose target: debugpy in the container, the debugger attaches.
|
||||
if (containerDebuggable(config) && getAction("debug.attach")) {
|
||||
await debugInContainer(config);
|
||||
|
||||
@@ -63,6 +63,7 @@ import {
|
||||
} from "./remote";
|
||||
import { onRunExited, resetRuns, saveUserConfigs, startRun, useRun } from "./store";
|
||||
import { newConfigOfType } from "./types";
|
||||
import { readRan } from "./services";
|
||||
|
||||
const cfg = (id: string, extra: Partial<RunConfig> = {}): RunConfig => ({
|
||||
id,
|
||||
@@ -356,6 +357,14 @@ describe("remote debugging", () => {
|
||||
await executeAction("run.debugConfig", local.id);
|
||||
expect(startConfig).toHaveBeenCalledWith(local);
|
||||
});
|
||||
|
||||
it("remembers a non-Spring-Boot configuration accepted for debugging", async () => {
|
||||
useProject.setState({ project: { root: "/remember-debug" } as never });
|
||||
const local = cfg("python:debug", { debugAdapter: "debugpy" });
|
||||
useRun.setState({ configs: [local], loaded: true });
|
||||
await executeAction("run.debugConfig", local.id);
|
||||
expect(readRan("/remember-debug")).toContain(local.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe("coverage and profiling", () => {
|
||||
|
||||
@@ -18,7 +18,9 @@ import {
|
||||
categorizedTypes,
|
||||
runServiceProvider,
|
||||
registerRunServiceActions,
|
||||
DEFAULT_TYPES,
|
||||
readHidden,
|
||||
readRan,
|
||||
readTypes,
|
||||
runServiceItems,
|
||||
sessionDetail,
|
||||
@@ -105,7 +107,7 @@ describe("run configurations in Services", () => {
|
||||
rerun: null,
|
||||
show: () => {},
|
||||
};
|
||||
const build = (status: DebugServiceSession["status"]) => runServiceItems([c], [], [kind], {}, [{ ...d, status }]);
|
||||
const build = (status: DebugServiceSession["status"]) => runServiceItems([c], [], [], [], {}, [{ ...d, status }]);
|
||||
expect(build("running")[0]?.children?.[0]).toMatchObject({
|
||||
key: "run:config:debug-app",
|
||||
detail: "Debugging",
|
||||
@@ -130,10 +132,12 @@ describe("run configurations in Services", () => {
|
||||
rerun: null,
|
||||
show: () => {},
|
||||
};
|
||||
const direct = runServiceItems([c], [r], ["spring-boot"], {}, [d]);
|
||||
const direct = runServiceItems([c], [r], DEFAULT_TYPES, [], {}, [d]);
|
||||
expect(direct[0]?.detail).toBe("1 running");
|
||||
expect(direct[0]?.children?.[0]?.detail).toBe("Debugging");
|
||||
const attached = runServiceItems([c], [{ ...r, status: "running" }], ["spring-boot"], {}, [{ ...d, processId: 7 }]);
|
||||
const attached = runServiceItems([c], [{ ...r, status: "running" }], DEFAULT_TYPES, [], {}, [
|
||||
{ ...d, processId: 7 },
|
||||
]);
|
||||
expect(attached[0]?.detail).toBe("1 running");
|
||||
expect(attached[0]?.children).toHaveLength(1);
|
||||
expect(attached[0]?.children?.[0]?.detail).toBe(":8080");
|
||||
@@ -152,15 +156,15 @@ describe("run configurations in Services", () => {
|
||||
rerun: null,
|
||||
show: () => {},
|
||||
};
|
||||
expect(runServiceItems([c], [], ["spring-boot"], {}, [d])[0]?.children?.[0]).toMatchObject({
|
||||
expect(runServiceItems([c], [], DEFAULT_TYPES, [], {}, [d])[0]?.children?.[0]).toMatchObject({
|
||||
detail: ":8080",
|
||||
icon: "debug",
|
||||
dim: false,
|
||||
});
|
||||
// A paused debugger still wins over the announced port.
|
||||
expect(runServiceItems([c], [], ["spring-boot"], {}, [{ ...d, status: "paused" }])[0]?.children?.[0]?.detail).toBe(
|
||||
"Suspended",
|
||||
);
|
||||
expect(
|
||||
runServiceItems([c], [], DEFAULT_TYPES, [], {}, [{ ...d, status: "paused" }])[0]?.children?.[0]?.detail,
|
||||
).toBe("Suspended");
|
||||
});
|
||||
|
||||
it("applies display order to detected and saved configurations of every language", () => {
|
||||
@@ -172,7 +176,7 @@ describe("run configurations in Services", () => {
|
||||
config("py-a", "python"),
|
||||
config("py-b", "python"),
|
||||
];
|
||||
const items = runServiceItems(configs, [], ["spring-boot", "npm", "python"], {
|
||||
const items = runServiceItems(configs, [], ["spring-boot", "npm", "python"], [], {
|
||||
"spring-boot": ["java-b", "java-a"],
|
||||
npm: ["node-b", "node-a"],
|
||||
python: ["py-b", "py-a"],
|
||||
@@ -190,17 +194,23 @@ describe("run configurations in Services", () => {
|
||||
const second = { ...config("workspace:two:app", kind), cwd: "/workspace/two", module: "two" };
|
||||
const fresh = config("workspace:two:new", kind);
|
||||
const configs = [first, second, fresh];
|
||||
const items = runServiceItems(configs, [], [kind], { [kind]: [second.id, first.id] });
|
||||
const items = runServiceItems(configs, [], [kind], [], { [kind]: [second.id, first.id] });
|
||||
expect(items[0]!.children!.map((c) => c.key)).toEqual([second, first, fresh].map((c) => `run:config:${c.id}`));
|
||||
expect(configs).toEqual([first, second, fresh]);
|
||||
});
|
||||
|
||||
it("orders remembered configurations when their type was not explicitly added", () => {
|
||||
const items = runServiceItems([build, test], [], [], ["build", "test"], { cargo: ["test", "build"] });
|
||||
expect(items[0]!.children!.map((c) => c.key)).toEqual(["run:config:test", "run:config:build"]);
|
||||
});
|
||||
|
||||
it("keeps stable service identity and session details after refresh and rename", () => {
|
||||
const renamed = { ...build, name: "Renamed build" };
|
||||
const items = runServiceItems(
|
||||
[renamed, test],
|
||||
[session("s1", renamed, "running", 1, { httpPort: 8080 })],
|
||||
["cargo"],
|
||||
[],
|
||||
{ cargo: ["test", "build"] },
|
||||
);
|
||||
expect(items[0]!.children!.map((c) => [c.key, c.label, c.detail])).toEqual([
|
||||
@@ -209,23 +219,27 @@ describe("run configurations in Services", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists added types fully and keeps other types out", () => {
|
||||
it("lists added types fully and other types only with their runs", () => {
|
||||
const sessions = [
|
||||
session("s1", dev, "finished", 1),
|
||||
session("s2", dev, "running", 2),
|
||||
session("s3", scratch, "failed", 3, { exitCode: 2 }),
|
||||
];
|
||||
const items = runServiceItems([build, test, dev], sessions, ["cargo"]);
|
||||
expect(items.map((i) => [i.key, i.label, i.detail])).toEqual([["run:type:cargo", "Cargo", undefined]]);
|
||||
expect(items.map((i) => [i.key, i.label, i.detail])).toEqual([
|
||||
["run:type:cargo", "Cargo", undefined],
|
||||
["run:type:npm", "npm", "1 running"],
|
||||
["run:type:python", "Python", undefined],
|
||||
]);
|
||||
expect(items[0]!.children!.map((c) => [c.key, c.detail, c.dim])).toEqual([
|
||||
["run:config:build", undefined, true],
|
||||
["run:config:test", undefined, true],
|
||||
]);
|
||||
// The newest session of a configuration decides its state once its type is added.
|
||||
const npm = runServiceItems([dev], sessions, ["npm"]);
|
||||
expect(npm[0]!.children!.map((c) => [c.label, c.detail, c.dim, c.icon])).toEqual([
|
||||
// The newest session of a configuration decides its state.
|
||||
expect(items[1]!.children!.map((c) => [c.label, c.detail, c.dim, c.icon])).toEqual([
|
||||
["dev", "Running", false, "run"],
|
||||
]);
|
||||
expect(items[2]!.children!.map((c) => [c.key, c.detail])).toEqual([["run:config:context:file", "Failed (exit 2)"]]);
|
||||
});
|
||||
|
||||
it("has no groups without added types or sessions", () => {
|
||||
@@ -239,14 +253,12 @@ describe("run configurations in Services", () => {
|
||||
expect(sessionStatus(session("a", build, "finished", 0))).toBe("Finished");
|
||||
});
|
||||
|
||||
it("shows nothing for a type that was never added", () => {
|
||||
it("shows Spring Boot by default, hidden while the project has none", () => {
|
||||
const app = config("spring:app", "spring-boot");
|
||||
expect(runServiceItems([build, app], [], [])).toEqual([]);
|
||||
const items = runServiceItems([build, app], [], ["spring-boot"]);
|
||||
expect(runServiceItems([build], [], DEFAULT_TYPES)).toEqual([]);
|
||||
const items = runServiceItems([build, app], [], DEFAULT_TYPES);
|
||||
expect(items.map((i) => [i.key, i.label, i.expanded])).toEqual([["run:type:spring-boot", "Spring Boot", true]]);
|
||||
expect(items[0]!.children!.map((c) => [c.label, c.detail, c.dim])).toEqual([["spring:app", undefined, true]]);
|
||||
// An added type stays listed without configurations until it is removed again.
|
||||
expect(runServiceItems([build], [], ["spring-boot"])[0]!.children).toEqual([]);
|
||||
});
|
||||
|
||||
it("shows the HTTP port of a running application instead of its state", () => {
|
||||
@@ -255,39 +267,62 @@ describe("run configurations in Services", () => {
|
||||
expect(sessionDetail(running)).toBe(":8080");
|
||||
expect(sessionDetail(session("s1", app, "running", 1))).toBe("Running");
|
||||
expect(sessionDetail(session("s1", app, "finished", 1, { httpPort: 8080, stopped: true }))).toBe("Stopped");
|
||||
expect(runServiceItems([app], [running], ["spring-boot"])[0]!.children![0]!.detail).toBe(":8080");
|
||||
expect(runServiceItems([app], [running], DEFAULT_TYPES)[0]!.children![0]!.detail).toBe(":8080");
|
||||
});
|
||||
});
|
||||
|
||||
describe("types added to Services", () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
|
||||
it("starts empty and persists the user's list per project", () => {
|
||||
expect(readTypes("/p")).toEqual([]);
|
||||
it("defaults to Spring Boot and persists the user's list per project", () => {
|
||||
expect(readTypes("/p")).toEqual(["spring-boot"]);
|
||||
localStorage.setItem("openidea.services.runTypes:/p", JSON.stringify(["npm"]));
|
||||
expect(readTypes("/p")).toEqual(["npm"]);
|
||||
localStorage.setItem("openidea.services.runTypes:/p", "[]");
|
||||
expect(readTypes("/p")).toEqual([]);
|
||||
expect(readTypes("/q")).toEqual([]);
|
||||
expect(readTypes("/q")).toEqual(["spring-boot"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sessions of types not added", () => {
|
||||
describe("configurations that ran", () => {
|
||||
const dev = config("dev", "npm");
|
||||
const scratch = config("context:file", "python");
|
||||
beforeEach(() => localStorage.clear());
|
||||
|
||||
it("keeps the type out of Services", () => {
|
||||
expect(runServiceItems([dev], [session("s1", dev, "running", 1)], [])).toEqual([]);
|
||||
it("persists the ran configuration ids per project", () => {
|
||||
expect(readRan("/p")).toEqual([]);
|
||||
localStorage.setItem("openidea.services.ran:/p", JSON.stringify(["dev"]));
|
||||
expect(readRan("/p")).toEqual(["dev"]);
|
||||
expect(readRan("/q")).toEqual([]);
|
||||
});
|
||||
|
||||
it("lists previously run configurations without a session", () => {
|
||||
const items = runServiceItems([dev, scratch], [], [], ["dev", "context:file"]);
|
||||
expect(items.map((i) => [i.key, i.label])).toEqual([
|
||||
["run:type:npm", "npm"],
|
||||
["run:type:python", "Python"],
|
||||
]);
|
||||
expect(items[0]!.children!.map((c) => [c.label, c.dim])).toEqual([["dev", true]]);
|
||||
expect(items[1]!.children!.map((c) => c.key)).toEqual(["run:config:context:file"]);
|
||||
});
|
||||
|
||||
it("ignores ran ids whose configuration is gone and merges sessions", () => {
|
||||
const gone = runServiceItems([dev], [], [], ["missing"]);
|
||||
expect(gone).toEqual([]);
|
||||
const running = session("s1", dev, "running", 1);
|
||||
const items = runServiceItems([dev], [running], [], ["dev"]);
|
||||
expect(items).toHaveLength(1);
|
||||
expect(items[0]!.children!.map((c) => [c.label, c.detail])).toEqual([["dev", "Running"]]);
|
||||
});
|
||||
|
||||
it("drops a deleted configuration once its run has ended (#1497)", () => {
|
||||
const removed = (id: string) => id === "dev";
|
||||
const ended = runServiceItems([], [session("s1", dev, "finished", 1)], ["npm"], {}, [], removed);
|
||||
expect(ended[0]!.children).toEqual([]);
|
||||
const live = runServiceItems([], [session("s1", dev, "running", 1)], ["npm"], {}, [], removed);
|
||||
const ended = runServiceItems([], [session("s1", dev, "finished", 1)], [], ["dev"], {}, [], removed);
|
||||
expect(ended).toEqual([]);
|
||||
const live = runServiceItems([], [session("s1", dev, "running", 1)], [], ["dev"], {}, [], removed);
|
||||
expect(live[0]!.children!.map((c) => [c.label, c.detail])).toEqual([["dev", "Running"]]);
|
||||
// Never a saved configuration (a build task, an external tool): its finished run stays.
|
||||
const adHoc = runServiceItems([], [session("s2", scratch, "finished", 1)], ["python"], {}, [], removed);
|
||||
const adHoc = runServiceItems([], [session("s2", scratch, "finished", 1)], [], [], {}, [], removed);
|
||||
expect(adHoc[0]!.children!.map((c) => c.key)).toEqual(["run:config:context:file"]);
|
||||
});
|
||||
});
|
||||
@@ -310,24 +345,25 @@ describe("hidden configurations", () => {
|
||||
const a = config("a", "spring-boot");
|
||||
const b = config("b", "spring-boot");
|
||||
|
||||
it("hides a configuration even while it runs", () => {
|
||||
it("hides a configuration unless it runs", () => {
|
||||
const hidden = { "spring-boot": ["a"] };
|
||||
const stopped = runServiceItems([a, b], [], ["spring-boot"], {}, [], () => false, hidden);
|
||||
const stopped = runServiceItems([a, b], [], DEFAULT_TYPES, [], {}, [], () => false, hidden);
|
||||
expect(stopped[0]!.children!.map((c) => c.key)).toEqual(["run:config:b"]);
|
||||
const running = runServiceItems(
|
||||
[a, b],
|
||||
[session("s1", a, "running", 1)],
|
||||
["spring-boot"],
|
||||
DEFAULT_TYPES,
|
||||
[],
|
||||
{},
|
||||
[],
|
||||
() => false,
|
||||
hidden,
|
||||
);
|
||||
expect(running[0]!.children!.map((c) => c.key)).toEqual(["run:config:b"]);
|
||||
expect(running[0]!.children!.map((c) => c.key)).toEqual(["run:config:a", "run:config:b"]);
|
||||
});
|
||||
|
||||
it("keeps an added type's group whose configurations are all hidden", () => {
|
||||
const items = runServiceItems([a], [], ["spring-boot"], {}, [], () => false, { "spring-boot": ["a"] });
|
||||
it("keeps an empty default group whose configurations are all hidden", () => {
|
||||
const items = runServiceItems([a], [], DEFAULT_TYPES, [], {}, [], () => false, { "spring-boot": ["a"] });
|
||||
expect(items).toHaveLength(1);
|
||||
expect(items[0]!.children).toEqual([]);
|
||||
});
|
||||
@@ -348,7 +384,8 @@ describe("hidden configurations", () => {
|
||||
const items = runServiceItems(
|
||||
[compose, dockerfile, image],
|
||||
[session("s1", compose, "running", 1), session("s2", dockerfile, "finished", 2)],
|
||||
["docker-compose", "docker-dockerfile", "docker-image"],
|
||||
[...DEFAULT_TYPES, "docker-compose", "docker-dockerfile", "docker-image"],
|
||||
[compose.id, dockerfile.id, image.id],
|
||||
);
|
||||
expect(items).toEqual([]);
|
||||
});
|
||||
@@ -547,7 +584,6 @@ describe("group batch actions", () => {
|
||||
|
||||
it("uses the saved display order and leaves other types alone", async () => {
|
||||
useProject.setState({ project: { root: "/group-order" } as never });
|
||||
localStorage.setItem("openidea.services.runTypes:/group-order", JSON.stringify(["spring-boot"]));
|
||||
localStorage.setItem("openidea.services.runOrder:/group-order", JSON.stringify({ "spring-boot": ["c", "a", "b"] }));
|
||||
const configs = [
|
||||
config("a", "spring-boot"),
|
||||
@@ -635,6 +671,7 @@ describe("removing a workspace member from Services", () => {
|
||||
sessions: [session("s1", main, "finished", 1), session("s2", vue, "running", 2, { runId: 7 })],
|
||||
});
|
||||
localStorage.setItem("openidea.services.runTypes:/w/main", JSON.stringify(["spring-boot", "npm"]));
|
||||
localStorage.setItem("openidea.services.ran:/w/main", JSON.stringify(["app", "dev"]));
|
||||
|
||||
await cleanupRemovedProject("/w/vue");
|
||||
|
||||
@@ -643,6 +680,7 @@ describe("removing a workspace member from Services", () => {
|
||||
expect(s.configs.map((c) => c.id)).toEqual(["app"]);
|
||||
expect(s.temporary).toEqual([]);
|
||||
expect(readTypes("/w/main")).toEqual(["spring-boot"]);
|
||||
expect(readRan("/w/main")).toEqual(["app"]);
|
||||
expect(ipc.runConfigs).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -720,6 +758,6 @@ describe("service selection", () => {
|
||||
await pending;
|
||||
await Promise.resolve();
|
||||
expect(readHidden("/other-selection")).toEqual({});
|
||||
expect(readTypes("/other-selection")).toEqual([]);
|
||||
expect(readTypes("/other-selection")).toEqual(DEFAULT_TYPES);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* Run configurations in the Services tool window (IDEA's Run Dashboard): the
|
||||
* configuration types added there ("Add Service › Run Configuration Type"), one
|
||||
* group each, with run / debug / stop / rerun per configuration. Nothing else is
|
||||
* listed, and what is removed leaves at once; a run it started keeps its console
|
||||
* in the Run tool window. A configuration that ran shows its console in the
|
||||
* detail pane, a running web application its HTTP port.
|
||||
* Run configurations in the Services tool window (IDEA's Run Dashboard): Spring
|
||||
* Boot by default, the configuration types added there ("Add Service › Run
|
||||
* Configuration Type"), the types of this window's run sessions and the
|
||||
* configurations that ran before (kept per project across restarts), one group
|
||||
* each, with run / debug / stop / rerun per configuration. A configuration that
|
||||
* ran shows its console in the detail pane, a running web application its HTTP port.
|
||||
*/
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { create } from "zustand";
|
||||
@@ -33,6 +33,7 @@ import { showApplicationUpdate } from "./applicationUpdate";
|
||||
import { isUpdatable } from "./updatePolicies";
|
||||
import {
|
||||
configRemoved,
|
||||
debugSession,
|
||||
loadConfigs,
|
||||
persistTemporary,
|
||||
rerunConfig,
|
||||
@@ -67,6 +68,9 @@ export const RUN_PROVIDER = "runConfigurations";
|
||||
const TYPE_PREFIX = "run:type:";
|
||||
const CONFIG_PREFIX = "run:config:";
|
||||
const STORAGE_KEY = "openidea.services.runTypes:";
|
||||
const RAN_KEY = "openidea.services.ran:";
|
||||
/** Types shown in Services until the user changes the list. */
|
||||
export const DEFAULT_TYPES: readonly string[] = ["spring-boot"];
|
||||
/** Docker run kinds whose containers/deployments are already shown under the Docker provider in Services. */
|
||||
const DOCKER_PROVIDER_KINDS: ReadonlySet<string> = new Set(["docker-compose", "docker-dockerfile", "docker-image"]);
|
||||
|
||||
@@ -75,15 +79,15 @@ const DOCKER_PROVIDER_KINDS: ReadonlySet<string> = new Set(["docker-compose", "d
|
||||
|
||||
const useAddedTypes = create<{ root: string | null; types: string[] }>(() => ({ root: null, types: [] }));
|
||||
|
||||
/** The project's types; empty until the user adds one with "Add Service". */
|
||||
/** The project's types; Spring Boot until the user changes the list. */
|
||||
export function readTypes(root: string): string[] {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY + root);
|
||||
if (raw === null) return [];
|
||||
if (raw === null) return [...DEFAULT_TYPES];
|
||||
const v: unknown = JSON.parse(raw);
|
||||
return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
|
||||
} catch {
|
||||
return [];
|
||||
return [...DEFAULT_TYPES];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,6 +118,41 @@ export function removeType(kind: string) {
|
||||
setAddedTypes(currentTypes().filter((t) => t !== kind));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Configurations that ran, per project (shown again after a restart)
|
||||
|
||||
const useRanConfigs = create<{ root: string | null; ids: string[] }>(() => ({ root: null, ids: [] }));
|
||||
|
||||
/** The project's previously run configuration ids, most recent last. */
|
||||
export function readRan(root: string): string[] {
|
||||
try {
|
||||
const raw = localStorage.getItem(RAN_KEY + root);
|
||||
if (raw === null) return [];
|
||||
const v: unknown = JSON.parse(raw);
|
||||
return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function ranIds(root: string | null): string[] {
|
||||
const s = useRanConfigs.getState();
|
||||
return s.root === root ? s.ids : root ? readRan(root) : [];
|
||||
}
|
||||
|
||||
/** Records a run, so its configuration is back in Services after a restart. */
|
||||
export function recordRun(configId: string) {
|
||||
const root = useProject.getState().project?.root ?? null;
|
||||
const ids = [...ranIds(root).filter((id) => id !== configId), configId];
|
||||
useRanConfigs.setState({ root, ids });
|
||||
if (!root) return;
|
||||
try {
|
||||
localStorage.setItem(RAN_KEY + root, JSON.stringify(ids));
|
||||
} catch {
|
||||
/* storage unavailable */
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Project removal: a workspace member's data leaves with it
|
||||
|
||||
@@ -126,7 +165,7 @@ function insideRoot(path: string, root: string): boolean {
|
||||
* Drops a removed workspace member's data from Services: stops and forgets its
|
||||
* sessions (a finished one still groups the tree), removes its temporary
|
||||
* configurations, reloads (the backend no longer lists the member) and clears
|
||||
* the added types that would otherwise render empty groups.
|
||||
* the added types and remembered runs that would otherwise render empty groups.
|
||||
*/
|
||||
export async function cleanupRemovedProject(removedRoot: string): Promise<void> {
|
||||
const { configs, sessions, temporary } = useRun.getState();
|
||||
@@ -157,6 +196,20 @@ export async function cleanupRemovedProject(removedRoot: string): Promise<void>
|
||||
const { configs: fresh, sessions: liveSessions } = useRun.getState();
|
||||
const liveKinds = new Set([...fresh.map((c) => c.kind), ...liveSessions.map((s) => s.config.kind)]);
|
||||
for (const kind of kinds) if (!liveKinds.has(kind)) removeType(kind);
|
||||
|
||||
const root = useProject.getState().project?.root ?? null;
|
||||
if (root) {
|
||||
const freshIds = new Set(fresh.map((c) => c.id));
|
||||
const ids = ranIds(root).filter((id) => freshIds.has(id));
|
||||
if (ids.length !== ranIds(root).length) {
|
||||
useRanConfigs.setState({ root, ids });
|
||||
try {
|
||||
localStorage.setItem(RAN_KEY + root, JSON.stringify(ids));
|
||||
} catch {
|
||||
/* storage unavailable */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Configurations hidden from Services, per project (removed one by one; "Add Service" restores)
|
||||
@@ -200,7 +253,7 @@ function saveHidden(hidden: Record<string, string[]>) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes one configuration from Services at once, even while it runs (its console is in the Run window). */
|
||||
/** Removes one configuration from Services; it reappears while it runs (its console stays reachable). */
|
||||
function hideConfig(kind: string, id: string) {
|
||||
const hidden = currentHidden();
|
||||
if ((hidden[kind] ?? []).includes(id)) return;
|
||||
@@ -258,15 +311,15 @@ function executionDetail(s: ServiceSession | undefined): string | undefined {
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups by configuration type: only the types added in this window list their
|
||||
* configurations, and a configuration removed from the window stays out even
|
||||
* while it runs (its console is in the Run tool window). A configuration deleted
|
||||
* since it ran (`removed`) stays only while its run is live.
|
||||
* Groups by configuration type: added types list all their configurations, other
|
||||
* types only those that ran. A default type (Spring Boot) without configurations is hidden.
|
||||
* A configuration deleted since it ran (`removed`) stays only while its run is live.
|
||||
*/
|
||||
export function runServiceItems(
|
||||
configs: readonly RunConfig[],
|
||||
sessions: readonly RunSession[],
|
||||
added: readonly string[],
|
||||
ran: readonly string[] = [],
|
||||
order: ServiceOrder = {},
|
||||
debug: readonly DebugServiceSession[] = [],
|
||||
removed: (id: string) => boolean = () => false,
|
||||
@@ -276,12 +329,28 @@ export function runServiceItems(
|
||||
const latest = currentServiceSessions(executions);
|
||||
const kinds = added.filter((kind) => !DOCKER_PROVIDER_KINDS.has(kind));
|
||||
const shown = (s: ServiceSession) => liveServiceSession(s) || !removed(s.config.id);
|
||||
for (const s of executions)
|
||||
if (shown(s) && !DOCKER_PROVIDER_KINDS.has(s.config.kind) && !kinds.includes(s.config.kind))
|
||||
kinds.push(s.config.kind);
|
||||
for (const id of ran) {
|
||||
const kind = configs.find((c) => c.id === id)?.kind;
|
||||
if (kind && !DOCKER_PROVIDER_KINDS.has(kind) && !kinds.includes(kind)) kinds.push(kind);
|
||||
}
|
||||
return kinds.flatMap((kind) => {
|
||||
const entries: RunConfig[] = configs.filter((c) => c.kind === kind);
|
||||
const entries: RunConfig[] = added.includes(kind)
|
||||
? configs.filter((c) => c.kind === kind)
|
||||
: ran.map((id) => configs.find((c) => c.id === id)).filter((c): c is RunConfig => !!c && c.kind === kind);
|
||||
for (const s of latest.values())
|
||||
if (s.config.kind === kind && shown(s) && !entries.some((c) => c.id === s.config.id)) entries.push(s.config);
|
||||
// Hidden configurations reappear only while they run (their console stays reachable).
|
||||
const hiddenIds = new Set(hidden[kind] ?? []);
|
||||
const visible = entries.filter((c) => !hiddenIds.has(c.id));
|
||||
const visible = entries.filter((c) => {
|
||||
if (!hiddenIds.has(c.id)) return true;
|
||||
const s = latest.get(c.id);
|
||||
return !!s && liveServiceSession(s);
|
||||
});
|
||||
// Keep an empty group only when its existing configurations can be restored.
|
||||
if (!visible.length && DEFAULT_TYPES.includes(kind) && !configs.some((c) => c.kind === kind)) return [];
|
||||
const children = orderServices(visible, order[kind]).map((c): ServiceTreeItem => {
|
||||
const s = latest.get(c.id);
|
||||
return {
|
||||
@@ -319,24 +388,28 @@ function useRoots(): ServiceTreeItem[] {
|
||||
const debug = useDebugRunSessions((s) => s.serviceSessions);
|
||||
const types = useAddedTypes((s) => s.types);
|
||||
const typesRoot = useAddedTypes((s) => s.root);
|
||||
const ran = useRanConfigs((s) => s.ids);
|
||||
const ranRoot = useRanConfigs((s) => s.root);
|
||||
const hidden = useHiddenConfigs((s) => s.hidden);
|
||||
const hiddenLocation = useHiddenConfigs((s) => s.location);
|
||||
useEffect(() => {
|
||||
if (typesRoot !== root) useAddedTypes.setState({ root, types: root ? readTypes(root) : [] });
|
||||
if (ranRoot !== root) useRanConfigs.setState({ root, ids: root ? readRan(root) : [] });
|
||||
if (hiddenLocation !== location) useHiddenConfigs.setState({ location, hidden: readHidden(location) });
|
||||
}, [root, typesRoot, hiddenLocation, location]);
|
||||
}, [root, typesRoot, ranRoot, hiddenLocation, location]);
|
||||
return useMemo(
|
||||
() =>
|
||||
runServiceItems(
|
||||
configs,
|
||||
sessions,
|
||||
typesRoot === root ? types : [],
|
||||
ranRoot === root ? ran : [],
|
||||
order,
|
||||
debug,
|
||||
configRemoved,
|
||||
hiddenLocation === location ? hidden : {},
|
||||
),
|
||||
[configs, sessions, types, typesRoot, root, order, debug, hidden, hiddenLocation, location],
|
||||
[configs, sessions, types, typesRoot, ran, ranRoot, root, order, debug, hidden, hiddenLocation, location],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -404,6 +477,7 @@ function groupConfigs(kind: string): RunConfig[] {
|
||||
configs,
|
||||
sessions,
|
||||
currentTypes(),
|
||||
ranIds(root),
|
||||
location ? currentServiceOrder(location) : {},
|
||||
debug,
|
||||
configRemoved,
|
||||
@@ -670,11 +744,20 @@ function RunDetail({ item }: { item: ServiceTreeItem }) {
|
||||
</div>
|
||||
</EmptyState>
|
||||
);
|
||||
// The configuration ran: its console, as in the Run tool window. Run / Debug / Stop
|
||||
// come from this window's toolbar (the selection), so the console strip leaves them out.
|
||||
// The configuration ran: its console, as in the Run tool window.
|
||||
if (r.session?.run) {
|
||||
const execution = r.session;
|
||||
return <SessionPanel key={execution.run!.id} session={execution.run!} showLifecycle={false} />;
|
||||
const d = serviceDebugger(execution);
|
||||
const rerun = d ? (d.rerunInPlace ?? d.rerun) : undefined;
|
||||
return (
|
||||
<SessionPanel
|
||||
key={execution.run!.id}
|
||||
session={execution.run!}
|
||||
onRerun={d ? rerun : () => run(r)}
|
||||
onDebug={d ? rerun : () => debugSession(execution.run!.id, { show: false })}
|
||||
onStop={d ? () => void stopServiceSessions([execution]) : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const d = r.session?.debug[0];
|
||||
if (d && Console)
|
||||
@@ -825,6 +908,7 @@ export const runServiceProvider: ServiceProviderContribution = {
|
||||
configs,
|
||||
sessions,
|
||||
currentTypes(),
|
||||
ranIds(useProject.getState().project?.root ?? null),
|
||||
order,
|
||||
useDebugRunSessions.getState().serviceSessions,
|
||||
configRemoved,
|
||||
|
||||
@@ -59,6 +59,7 @@ import { remoteLabel, startWithRemedies } from "./remote";
|
||||
import { TerminalOutput } from "./terminalOutput";
|
||||
import { typeFor } from "./types";
|
||||
import { loadRunTemplates } from "./runTemplates";
|
||||
import { recordRun } from "./services";
|
||||
import { startedPort } from "@/platform/serverPort";
|
||||
import { tomcatBrowserUrl } from "./tomcat";
|
||||
import { gradleBootLaunch, gradleDelegation, gradleTestLaunch } from "./gradleRun";
|
||||
@@ -831,6 +832,8 @@ export async function startRun(
|
||||
useRun.setState((s) => ({ sessions: [...s.sessions, created], activeSession: created.id }));
|
||||
}
|
||||
bump(session.id);
|
||||
// The Services tool window lists the configuration again after a restart.
|
||||
recordRun(config.id);
|
||||
const sessionId = session.id;
|
||||
const rt = runtimes.get(sessionId)!;
|
||||
const generation = rt.generation;
|
||||
|
||||
@@ -56,8 +56,6 @@ let dispose: () => void;
|
||||
let disposeActions: () => void;
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
// The types are added by hand, as in the real window (nothing shows by default).
|
||||
localStorage.setItem("openidea.services.runTypes:/services-debug", JSON.stringify(["spring-boot", "shell"]));
|
||||
useProject.setState({
|
||||
project: { root: "/services-debug", name: "app", isGit: false, settings: validateSettings({}) } as never,
|
||||
});
|
||||
@@ -146,7 +144,7 @@ it("reruns a debug service in place from the Services panel", () => {
|
||||
expect(d.rerun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("starts a debug session in place from the Services toolbar", async () => {
|
||||
it("starts a debug session in place from a run service's detail toolbar", async () => {
|
||||
const start = vi.fn();
|
||||
const disposeAction = registerActions([
|
||||
{ id: "run.debugConfig", title: "Debug Configuration", run: ({ arg }) => start(arg) },
|
||||
@@ -155,18 +153,18 @@ it("starts a debug session in place from the Services toolbar", async () => {
|
||||
const s = await startRun(c);
|
||||
expect(s).not.toBeNull();
|
||||
useRun.setState({ configs: [c], sessions: [{ ...s!, config: c, status: "running" as const }] });
|
||||
useServicesTree.setState({ expanded: new Set(["run:type:shell"]) });
|
||||
try {
|
||||
render(<ServicesTreeView />);
|
||||
select();
|
||||
fireEvent.click(toolbar().getByRole("button", { name: "Debug" }));
|
||||
const actions = within(screen.getByRole("toolbar", { name: "Run actions" }));
|
||||
fireEvent.click(actions.getByRole("button", { name: "Debug" }));
|
||||
await vi.waitFor(() => expect(start).toHaveBeenCalledWith({ config: c, show: false }));
|
||||
} finally {
|
||||
disposeAction();
|
||||
}
|
||||
});
|
||||
|
||||
it("reruns a plain run service in place from the Services toolbar", async () => {
|
||||
it("reruns a plain run service in place from its detail toolbar", async () => {
|
||||
const c = { ...config, kind: "shell", command: "echo", debugAdapter: null };
|
||||
const s = await startRun(c);
|
||||
expect(s).not.toBeNull();
|
||||
@@ -177,12 +175,12 @@ it("reruns a plain run service in place from the Services toolbar", async () =>
|
||||
const previousRuntime = runtime(s!.id);
|
||||
render(<ServicesTreeView />);
|
||||
select();
|
||||
fireEvent.click(toolbar().getByRole("button", { name: /^(Run|Rerun)$/ }));
|
||||
fireEvent.click(within(screen.getByRole("toolbar", { name: "Run actions" })).getByRole("button", { name: "Rerun" }));
|
||||
await vi.waitFor(() => expect(runtime(s!.id)).not.toBe(previousRuntime));
|
||||
expect(show).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reruns an attached debugger in place from the Services toolbar", async () => {
|
||||
it("reruns an attached debugger in place from a run service's detail toolbar", async () => {
|
||||
const c = { ...config, kind: "shell", command: "echo", debugAdapter: null };
|
||||
const s = await startRun(c);
|
||||
expect(s).not.toBeNull();
|
||||
@@ -193,7 +191,8 @@ it("reruns an attached debugger in place from the Services toolbar", async () =>
|
||||
useDebugRunSessions.setState({ serviceSessions: [d] });
|
||||
render(<ServicesTreeView />);
|
||||
select();
|
||||
fireEvent.click(toolbar().getByRole("button", { name: "Debug" }));
|
||||
const actions = within(screen.getByRole("toolbar", { name: "Run actions" }));
|
||||
fireEvent.click(actions.getByRole("button", { name: "Debug" }));
|
||||
expect(d.rerunInPlace).toHaveBeenCalledOnce();
|
||||
expect(d.rerun).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -216,7 +215,7 @@ it("keeps the other parallel instance alive and then displays it", async () => {
|
||||
expect(screen.getByRole("log")).toHaveTextContent("first instance");
|
||||
});
|
||||
|
||||
it("shows the owning Run output for attached debugging and routes the controls through the Services toolbar", async () => {
|
||||
it("shows the owning Run output for attached debugging and overrides both sets of controls", async () => {
|
||||
const stopRun = vi.spyOn(commands, "runStop").mockImplementation(async (id) => {
|
||||
queueMicrotask(() => onRunExited(id, 130));
|
||||
return { status: "ok", data: null };
|
||||
@@ -232,14 +231,8 @@ it("shows the owning Run output for attached debugging and routes the controls t
|
||||
render(<ServicesTreeView />);
|
||||
select();
|
||||
expect(screen.getByRole("log")).toHaveTextContent("Maven application log");
|
||||
// The console strip keeps only console controls: the window toolbar owns Run / Debug / Stop.
|
||||
const strip = within(screen.getByRole("toolbar", { name: "Run actions" }));
|
||||
expect(strip.queryByRole("button", { name: "Rerun" })).toBeNull();
|
||||
expect(strip.queryByRole("button", { name: "Debug" })).toBeNull();
|
||||
expect(strip.queryByRole("button", { name: "Stop" })).toBeNull();
|
||||
expect(strip.getByRole("button", { name: "Clear All" })).toBeTruthy();
|
||||
const actions = toolbar();
|
||||
fireEvent.click(actions.getByRole("button", { name: /^(Run|Rerun)$/ }));
|
||||
const actions = within(screen.getByRole("toolbar", { name: "Run actions" }));
|
||||
fireEvent.click(actions.getByRole("button", { name: "Rerun" }));
|
||||
expect(d.rerun).toHaveBeenCalledOnce();
|
||||
await act(async () => fireEvent.click(actions.getByRole("button", { name: "Stop" })));
|
||||
expect(stopRun).toHaveBeenCalledExactlyOnceWith(7);
|
||||
|
||||
@@ -272,14 +272,7 @@ export function ServicesTreeView() {
|
||||
</div>
|
||||
</SplitPanel>
|
||||
<SplitHandle />
|
||||
<SplitPanel
|
||||
id="services-detail"
|
||||
minSize="200px"
|
||||
// The panel library puts `overflow: auto` inline; the detail content
|
||||
// (a console, a log) owns its scrolling, so the pane must not add a second
|
||||
// bar. A column flex box lets that content fill the pane.
|
||||
style={{ overflow: "hidden", height: "100%", display: "flex", flexDirection: "column" }}
|
||||
>
|
||||
<SplitPanel id="services-detail" minSize="200px">
|
||||
{selected && Detail && shown ? (
|
||||
<Detail key={selected.item.key} item={selected.item} />
|
||||
) : (
|
||||
|
||||
@@ -140,8 +140,6 @@ export function dockerItems(
|
||||
icon: snap?.availability.kind === "ready" ? "docker-connected" : "file-docker",
|
||||
detail: connectionDetail(state),
|
||||
dim: snap?.availability.kind !== "ready",
|
||||
// A connection the user just added opens once, so its groups are in sight.
|
||||
expanded: true,
|
||||
children: children(root)?.map(convert) ?? [],
|
||||
};
|
||||
});
|
||||
|
||||
@@ -21,7 +21,7 @@ export const useServicesTree = create<TreeState>(() => ({
|
||||
roots: {},
|
||||
selectedKey: null,
|
||||
selectedKeys: new Set(),
|
||||
expanded: new Set(),
|
||||
expanded: new Set(["docker:default", "docker:default:group:containers"]),
|
||||
}));
|
||||
|
||||
/** Keys of nodes asking to start expanded that were shown once (collapsing them then sticks). */
|
||||
|
||||
@@ -116,55 +116,12 @@ describe("scheme actions", () => {
|
||||
it("shows a malformed-file error without staging any changes", async () => {
|
||||
mocks.read.mockResolvedValueOnce({ status: "ok", data: '<scheme name="bad">' });
|
||||
await run("import");
|
||||
await waitFor(() =>
|
||||
expect(mocks.error).toHaveBeenCalledWith("Import Scheme", expect.stringContaining("Invalid .icls color scheme")),
|
||||
);
|
||||
await waitFor(() => expect(mocks.error).toHaveBeenCalledWith("Color Scheme", "Invalid .icls color scheme"));
|
||||
expect(useSettingsDialog.getState().staged).toEqual({});
|
||||
});
|
||||
|
||||
it("offers .xml scheme files in the chooser and imports one (#2714)", async () => {
|
||||
mocks.open.mockResolvedValueOnce("/downloads/Material Darker.xml");
|
||||
mocks.read.mockResolvedValueOnce({
|
||||
status: "ok",
|
||||
data: readFileSync("src/platform/__fixtures__/colorSchemes/material-darker.xml", "utf8"),
|
||||
});
|
||||
await run("import");
|
||||
expect(mocks.open).toHaveBeenCalledWith({
|
||||
multiple: false,
|
||||
filters: [{ name: "IntelliJ Color Scheme", extensions: ["icls", "xml"] }],
|
||||
});
|
||||
expect(value("colorScheme")).toMatch(/^custom-/);
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Applied 12 values; skipped 3");
|
||||
const schemes = value("customSchemes") as Record<string, { name: string }>;
|
||||
expect(Object.values(schemes).some((s) => s.name === "Material Darker")).toBe(true);
|
||||
});
|
||||
|
||||
it("names a scheme without a name attribute after its file (#2714)", async () => {
|
||||
mocks.open.mockResolvedValueOnce("/downloads/one-dark-wrapped.xml");
|
||||
mocks.read.mockResolvedValueOnce({
|
||||
status: "ok",
|
||||
data: readFileSync("src/platform/__fixtures__/colorSchemes/one-dark-wrapped.xml", "utf8"),
|
||||
});
|
||||
await run("import");
|
||||
const schemes = value("customSchemes") as Record<string, { name: string }>;
|
||||
expect(Object.values(schemes).some((s) => s.name === "one-dark-wrapped")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("python scheme attributes", () => {
|
||||
it("groups Python attributes as PyCharm does", () => {
|
||||
schemePage("editor.colorScheme.python");
|
||||
const tree = screen.getByRole("tree", { name: "Color scheme attributes" });
|
||||
// The tree virtualizes; a collapsed group renders before its siblings, so a group near
|
||||
// the top is enough to prove grouping, and expanding it shows its leaves.
|
||||
expect(within(tree).getByRole("treeitem", { name: "Functions" })).toBeInTheDocument();
|
||||
for (const flat of ["Byte string", "F-string", "Method call"])
|
||||
expect(within(tree).queryByRole("treeitem", { name: flat })).toBeNull();
|
||||
const functions = within(tree).getByRole("treeitem", { name: "Functions" });
|
||||
act(() => fireEvent.mouseDown(within(functions).getByText("Functions").previousElementSibling!, { button: 0 }));
|
||||
expect(within(tree).getByRole("treeitem", { name: "Method call" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe("doc comment scheme attributes", () => {
|
||||
it("selects Python docstring tags and keywords from their preview", () => {
|
||||
schemePage("editor.colorScheme.python");
|
||||
const preview = screen.getByLabelText("Color scheme preview");
|
||||
@@ -177,9 +134,7 @@ describe("python scheme attributes", () => {
|
||||
act(() => fireEvent.click(keyword));
|
||||
expect(screen.getByRole("treeitem", { name: "Keyword", selected: true })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("doc comment scheme attributes", () => {
|
||||
it.each([
|
||||
["en", "Doc comment", "Tag", "Tag value", "Markup"],
|
||||
["zh", "文档注释", "标签", "标签值", "标记"],
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { NotificationService } from "@/workbench/contributions";
|
||||
|
||||
const ok = (data: string[]) => ({ status: "ok", data }) as const;
|
||||
const systemProbeHotkeys = vi.fn(async (_combos: string[]) => ok([]));
|
||||
const openSettings = vi.fn();
|
||||
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const actual = await orig<typeof import("@/platform/ipc")>();
|
||||
return { ...actual, isTauri: () => true, commands: { ...actual.commands, systemProbeHotkeys } };
|
||||
});
|
||||
|
||||
vi.mock("@/workbench/contributions", () => ({
|
||||
notifications: (): Pick<NotificationService, "notify"> => ({ notify: (n) => void notes.push(n) }),
|
||||
}));
|
||||
|
||||
vi.mock("../model/staging", () => ({ openSettings }));
|
||||
|
||||
type Note = Parameters<NotificationService["notify"]>[0];
|
||||
let notes: Note[];
|
||||
|
||||
const { SYSTEM_HOTKEY_KEY, _resetSystemHotkeyProbeForTests, maybeWarnSystemHotkeys, systemHotkeyCandidates } =
|
||||
await import("../keymap/systemHotkeys");
|
||||
const { useKeymap } = await import("@/platform/keymap");
|
||||
const { usePlatform } = await import("@/platform/platformInfo");
|
||||
|
||||
beforeEach(() => {
|
||||
notes = [];
|
||||
systemProbeHotkeys.mockReset().mockResolvedValue(ok([]));
|
||||
openSettings.mockClear();
|
||||
_resetSystemHotkeyProbeForTests();
|
||||
usePlatform.setState({ os: "windows" });
|
||||
useKeymap.setState({ preset: "intellij-windows", overrides: {}, extensions: {} });
|
||||
});
|
||||
|
||||
describe("systemHotkeyCandidates", () => {
|
||||
it("keeps single-stroke Alt bindings and drops the rest", () => {
|
||||
expect(
|
||||
systemHotkeyCandidates([
|
||||
["Alt+Shift+R", "rename"],
|
||||
["Shift+Alt+R", "other"],
|
||||
["Alt+R Alt+S", "chord"],
|
||||
["Shift Shift", "double"],
|
||||
["Alt+Button4", "mouse"],
|
||||
["Meta+R", "win"],
|
||||
["Ctrl+S", "save"],
|
||||
["Alt+F7", "find"],
|
||||
]),
|
||||
).toEqual(["Alt+Shift+R", "Alt+F7"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("maybeWarnSystemHotkeys", () => {
|
||||
it("warns once per session with an action opening Keymap", async () => {
|
||||
useKeymap.setState({ overrides: { "t.probe": ["Alt+Shift+R"] } });
|
||||
systemProbeHotkeys.mockResolvedValue(ok(["Alt+Shift+R"]));
|
||||
await maybeWarnSystemHotkeys();
|
||||
expect(systemProbeHotkeys).toHaveBeenCalledTimes(1);
|
||||
expect(notes).toHaveLength(1);
|
||||
expect(notes[0]).toMatchObject({
|
||||
level: "warning",
|
||||
key: SYSTEM_HOTKEY_KEY,
|
||||
title: "Some shortcuts are already used by another app",
|
||||
});
|
||||
expect(String(notes[0]!.body)).toContain("Alt+Shift+R");
|
||||
expect(notes[0]!.actions).toHaveLength(1);
|
||||
expect(notes[0]!.actions![0]!.label).toBe("Open Keymap");
|
||||
notes[0]!.actions![0]!.run();
|
||||
expect(openSettings).toHaveBeenCalledWith("keymap");
|
||||
await maybeWarnSystemHotkeys();
|
||||
expect(systemProbeHotkeys).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("stays quiet when nothing is grabbed or not on Windows", async () => {
|
||||
useKeymap.setState({ overrides: { "t.probe": ["Alt+Shift+R"] } });
|
||||
await maybeWarnSystemHotkeys();
|
||||
expect(notes).toEqual([]);
|
||||
_resetSystemHotkeyProbeForTests();
|
||||
systemProbeHotkeys.mockClear();
|
||||
usePlatform.setState({ os: "linux" });
|
||||
systemProbeHotkeys.mockResolvedValue(ok(["Alt+Shift+R"]));
|
||||
await maybeWarnSystemHotkeys();
|
||||
expect(systemProbeHotkeys).not.toHaveBeenCalled();
|
||||
expect(notes).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Warns when another Windows app grabbed one of our Alt shortcuts (e.g.
|
||||
* NVIDIA's overlay swallowing `Alt+Shift+R`, so Rename never reaches the IDE).
|
||||
*
|
||||
* At startup the backend probes each single-stroke Alt binding with
|
||||
* `RegisterHotKey`: success means it is free (released immediately), refusal
|
||||
* means another app owns it. One aggregated notification opens Keymap, where
|
||||
* the conflicting shortcuts can be reassigned.
|
||||
*/
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import {
|
||||
effectiveBindings,
|
||||
formatBinding,
|
||||
isMouseBinding,
|
||||
normalizeBinding,
|
||||
parseDoubleModifier,
|
||||
} from "@/platform/keymap";
|
||||
import { isPageSwipe } from "@/platform/pageSwipe";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { openSettings } from "../model/staging";
|
||||
|
||||
export const SYSTEM_HOTKEY_KEY = "keymap.systemHotkeys";
|
||||
|
||||
/**
|
||||
* The effective bindings worth probing: single-stroke Alt shortcuts (chords,
|
||||
* double-modifier gestures, mouse buttons and swipe gestures have no
|
||||
* `RegisterHotKey` equivalent; Meta combos are not stolen this way).
|
||||
*/
|
||||
export function systemHotkeyCandidates(bindings: Array<[string, string]>): string[] {
|
||||
const out = new Set<string>();
|
||||
for (const [binding] of bindings) {
|
||||
if (binding.includes(" ")) continue;
|
||||
if (parseDoubleModifier(binding) || isMouseBinding(binding) || isPageSwipe(binding)) continue;
|
||||
const parts = normalizeBinding(binding).split("+");
|
||||
const mods = parts.slice(0, -1);
|
||||
if (!mods.includes("Alt") || mods.includes("Meta")) continue;
|
||||
out.add(parts.join("+"));
|
||||
}
|
||||
return [...out];
|
||||
}
|
||||
|
||||
let probed = false;
|
||||
|
||||
/** Probes once per session (Windows desktop only) and warns about grabs. */
|
||||
export async function maybeWarnSystemHotkeys(): Promise<void> {
|
||||
if (probed) return;
|
||||
probed = true;
|
||||
try {
|
||||
if (!isTauri() || usePlatform.getState().os !== "windows") return;
|
||||
const candidates = systemHotkeyCandidates(effectiveBindings());
|
||||
if (!candidates.length) return;
|
||||
const grabbed = await call(commands.systemProbeHotkeys(candidates));
|
||||
if (!grabbed.length) return;
|
||||
const shortcuts = grabbed.map((b) => formatBinding(b)).join(", ");
|
||||
notifications().notify({
|
||||
level: "warning",
|
||||
key: SYSTEM_HOTKEY_KEY,
|
||||
title: "Some shortcuts are already used by another app",
|
||||
body: tx`These shortcuts never reach the IDE: ${shortcuts}. Open Keymap to reassign them.`,
|
||||
actions: [{ label: "Open Keymap", run: () => openSettings("keymap") }],
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn("cannot probe system hotkeys", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Tests only: resets the once-per-session guard. */
|
||||
export function _resetSystemHotkeyProbeForTests(): void {
|
||||
probed = false;
|
||||
}
|
||||
@@ -104,7 +104,7 @@ export interface ValidSettings extends WorkflowSettings {
|
||||
/** Tools › Agents › Chat: the meters in an agent task's header. */
|
||||
agents: Required<AgentSettings>;
|
||||
/** Agents › IDE MCP Server (global). */
|
||||
mcpServer: { enabled: boolean; runWithoutConfirmation: boolean };
|
||||
mcpServer: { enabled: boolean };
|
||||
}
|
||||
|
||||
/** One `languageServers.<name>` entry; every field optional, like in settings.toml. */
|
||||
@@ -193,7 +193,7 @@ export const DEFAULT_SETTINGS: ValidSettings = {
|
||||
defaults: {},
|
||||
mcpServers: {},
|
||||
},
|
||||
mcpServer: { enabled: false, runWithoutConfirmation: false },
|
||||
mcpServer: { enabled: false },
|
||||
...DEFAULT_WORKFLOW,
|
||||
};
|
||||
|
||||
@@ -359,10 +359,7 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
|
||||
defaults: agentDefaults(agents.defaults),
|
||||
mcpServers: agentMcpServers(agents.mcpServers),
|
||||
},
|
||||
mcpServer: {
|
||||
enabled: bool(obj(root.mcpServer).enabled, d.mcpServer.enabled),
|
||||
runWithoutConfirmation: bool(obj(root.mcpServer).runWithoutConfirmation, d.mcpServer.runWithoutConfirmation),
|
||||
},
|
||||
mcpServer: { enabled: bool(obj(root.mcpServer).enabled, d.mcpServer.enabled) },
|
||||
...validateWorkflow(root),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ import styles from "./Editor.module.css";
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { ask, confirm, showError } from "@/workbench/messages";
|
||||
import { parseIcls, SchemeParseError, importScheme, deleteScheme, exportIcls } from "@/platform/icls";
|
||||
import { parseIcls, importScheme, deleteScheme, exportIcls } from "@/platform/icls";
|
||||
import { tx, useTx } from "@/platform/i18n";
|
||||
import { selectPage } from "../../model/staging";
|
||||
|
||||
@@ -1158,17 +1158,10 @@ function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landi
|
||||
file ??
|
||||
(await open({
|
||||
multiple: false,
|
||||
// IDEA schemes ship as .icls, but the ones people download are frequently .xml.
|
||||
filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls", "xml"] }],
|
||||
filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls"] }],
|
||||
}));
|
||||
if (!path) return;
|
||||
// A scheme element without a name is named after its file, as IntelliJ does.
|
||||
const fallbackName =
|
||||
path
|
||||
.split(/[\\/]/)
|
||||
.at(-1)
|
||||
?.replace(/\.[^.]+$/, "") || "Imported scheme";
|
||||
const parsed = parseIcls(await call(commands.fsReadText(path)), fallbackName);
|
||||
const parsed = parseIcls(await call(commands.fsReadText(path)));
|
||||
let overwrite = false;
|
||||
if (schemes.some((s) => s.name === parsed.scheme.name)) {
|
||||
const canOverwrite = Object.values(customs).some((s) => s.name === parsed.scheme.name);
|
||||
@@ -1239,9 +1232,9 @@ function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landi
|
||||
await handlers.current[name]!(typeof arg === "string" ? arg : undefined);
|
||||
} catch (error) {
|
||||
await showError(
|
||||
tx("Import Scheme"),
|
||||
error instanceof SchemeParseError
|
||||
? `${tx("Invalid .icls color scheme")}: ${error.message}`
|
||||
tx("Color Scheme"),
|
||||
error instanceof Error && error.message === "Invalid .icls color scheme"
|
||||
? tx("Invalid .icls color scheme")
|
||||
: String(error),
|
||||
);
|
||||
} finally {
|
||||
|
||||
@@ -835,11 +835,6 @@ const INLAY: Item[] = [
|
||||
},
|
||||
];
|
||||
|
||||
const CODE_VISION_POSITIONS = [
|
||||
{ value: "top", label: "Top" },
|
||||
{ value: "right", label: "Right" },
|
||||
];
|
||||
|
||||
const INLAY_HINTS = editorPage({
|
||||
id: "editor.inlayHints",
|
||||
title: "Inlay Hints",
|
||||
@@ -850,33 +845,8 @@ const INLAY_HINTS = editorPage({
|
||||
{
|
||||
title: "Code Vision",
|
||||
items: [
|
||||
{
|
||||
t: "check",
|
||||
key: `${P}.inlay.codeVisionUsages`,
|
||||
label: "Usages",
|
||||
children: [
|
||||
{
|
||||
t: "select",
|
||||
key: `${P}.inlay.codeVisionUsagesPosition`,
|
||||
label: "Position",
|
||||
options: CODE_VISION_POSITIONS,
|
||||
},
|
||||
{ t: "check", key: `${P}.inlay.codeVisionNoUsages`, label: "Show “no usages”" },
|
||||
],
|
||||
},
|
||||
{
|
||||
t: "check",
|
||||
key: `${P}.inlay.codeVisionAuthor`,
|
||||
label: "Code author",
|
||||
children: [
|
||||
{
|
||||
t: "select",
|
||||
key: `${P}.inlay.codeVisionAuthorPosition`,
|
||||
label: "Position",
|
||||
options: CODE_VISION_POSITIONS,
|
||||
},
|
||||
],
|
||||
},
|
||||
{ t: "check", key: `${P}.inlay.codeVisionUsages`, label: "Usages" },
|
||||
{ t: "check", key: `${P}.inlay.codeVisionAuthor`, label: "Code author" },
|
||||
],
|
||||
},
|
||||
{ title: "Languages", items: [{ t: "custom", label: "Show inlay hints for:", component: InlayLanguages }] },
|
||||
|
||||
@@ -128,12 +128,6 @@ export const MCP_SERVER_PAGE: PageSpec = {
|
||||
label: "Enable MCP server",
|
||||
hint: "Agents can read, edit, and run projects open in OpenIDEA through its built-in tools. Run tools ask for confirmation. The server listens on 127.0.0.1 only and requires a token.",
|
||||
},
|
||||
{
|
||||
kind: "toggle",
|
||||
key: "mcpServer.runWithoutConfirmation",
|
||||
label: "Run tools without confirmation (brave mode)",
|
||||
hint: "Run configurations, terminal commands and other tools that change a project start without asking, for unattended agents. Only the IDE's own settings can turn this on, not a project's.",
|
||||
},
|
||||
{
|
||||
kind: "custom",
|
||||
label: "Endpoint",
|
||||
|
||||
@@ -13,11 +13,14 @@ import { isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { applyKeymapSettings } from "@/platform/keymap";
|
||||
import { loadSettings, useProject } from "@/platform/project";
|
||||
import { applyAppearanceOptions, installAltDragGuard, installIdleSave } from "./appearanceRuntime";
|
||||
import { maybeWarnSystemHotkeys } from "./keymap/systemHotkeys";
|
||||
import { validateSettings } from "./model/schema";
|
||||
|
||||
export function applyRuntimeSettings(raw: unknown, root: HTMLElement = document.documentElement): void {
|
||||
const s = validateSettings(raw);
|
||||
applyKeymapSettings(s.keymap, s.keymapOverrides, s.customKeymaps);
|
||||
// The keymap just took effect: probe it once for OS-grabbed shortcuts.
|
||||
void maybeWarnSystemHotkeys();
|
||||
|
||||
applyAppearanceOptions(s, root);
|
||||
|
||||
|
||||
@@ -738,6 +738,12 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
e.stopPropagation();
|
||||
void deleteFiles(deletable);
|
||||
}
|
||||
} else if (e.key === "F4") {
|
||||
const n = selectedNodes().find((x) => x.type === "file");
|
||||
if (n?.path) {
|
||||
e.preventDefault();
|
||||
void editorService().openFile(n.path, { focus: true });
|
||||
}
|
||||
} else {
|
||||
// IDEA: Ctrl+C copies the file names, Ctrl+Shift+C the absolute paths (#1877).
|
||||
const stroke = strokeOf(e.nativeEvent);
|
||||
@@ -782,10 +788,6 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
followSelection(nodes);
|
||||
}}
|
||||
onActivate={(n) => openNode(n, roots, mode === "dialog")}
|
||||
onJumpToSource={(n) => {
|
||||
const file = n.type === "file" ? n : selectedNodes().find((x) => x.type === "file");
|
||||
if (file?.path && file.kind !== "deleted") void editorService().openFile(file.path, { focus: true });
|
||||
}}
|
||||
onContextMenu={(node, sel, e: MouseEvent) => {
|
||||
if (!node) return;
|
||||
if (node.type === "group" && node.changelist) {
|
||||
|
||||
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача