дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 18:17:15 +02:00
Порівняти коміти
16
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
314997cdd7 | ||
|
|
833ae4c3c4 | ||
|
|
584baa3f71 | ||
|
|
98010e6513 | ||
|
|
a3640f655f | ||
|
|
8aaa7daf83 | ||
|
|
6a9a970df4 | ||
|
|
a309b7e6fa | ||
|
|
6971936f78 | ||
|
|
9d781a2f83 | ||
|
|
3260e5e224 | ||
|
|
ed575a00d9 | ||
|
|
2b41e61ce9 | ||
|
|
908740b3f2 | ||
|
|
e702e4da7b | ||
|
|
91023de207 |
No files matched your search
@@ -0,0 +1,2 @@
|
||||
custom:
|
||||
- https://github.com/l0ng-ai/openidea#sponsor
|
||||
Бінарний файл не відображається.
|
Після Ширина: | Висота: | Розмір: 70 KiB |
Бінарний файл не відображається.
|
Після Ширина: | Висота: | Розмір: 97 KiB |
Створено
+44
-44
@@ -4145,7 +4145,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4169,7 +4169,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4183,7 +4183,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4194,7 +4194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4212,7 +4212,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4226,7 +4226,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4236,7 +4236,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4253,7 +4253,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4267,7 +4267,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4293,7 +4293,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"bb8",
|
||||
"blake3",
|
||||
@@ -4323,7 +4323,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4336,7 +4336,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4357,7 +4357,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4369,7 +4369,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4382,7 +4382,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4400,7 +4400,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4469,7 +4469,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4488,7 +4488,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4510,7 +4510,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4522,7 +4522,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4539,7 +4539,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4548,7 +4548,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4559,7 +4559,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4615,7 +4615,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4642,7 +4642,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4661,7 +4661,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4684,7 +4684,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4707,7 +4707,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4720,7 +4720,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"globset",
|
||||
@@ -4739,7 +4739,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4763,7 +4763,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4779,7 +4779,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4799,7 +4799,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4820,7 +4820,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4833,7 +4833,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4854,7 +4854,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4869,7 +4869,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4882,7 +4882,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4895,7 +4895,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4916,7 +4916,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4937,7 +4937,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4961,7 +4961,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"open",
|
||||
@@ -4977,7 +4977,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6555,7 +6555,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.41"
|
||||
version = "0.1.42"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
<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
|
||||
@@ -68,6 +70,17 @@ 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,15 +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);
|
||||
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.
|
||||
if let Some(peer) = live {
|
||||
let _ = tokio::time::timeout(EXIT_WAIT, peer.exited()).await;
|
||||
}
|
||||
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")));
|
||||
@@ -1252,7 +1243,17 @@ impl AgentManager {
|
||||
{
|
||||
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.
|
||||
if let Some(peer) = live {
|
||||
let _ = tokio::time::timeout(EXIT_WAIT, peer.exited()).await;
|
||||
}
|
||||
let worktrees = self.shared.paths.worktrees_dir.clone();
|
||||
blocking(move || worktree::remove(&root, &worktrees, &cwd)).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -93,8 +93,9 @@ 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 = repo.numstat_with_worktree(base)?;
|
||||
let stat = |rel: &str| stats.iter().find(|(p, ..)| p == rel).map_or((0, 0), |&(_, a, r)| (a, r));
|
||||
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 mut out: Vec<AgentChange> = repo
|
||||
.diff_with_worktree(base)?
|
||||
.into_iter()
|
||||
@@ -103,8 +104,9 @@ 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) && !out.iter().any(|c| c.rel_path == s.rel_path) {
|
||||
if s.unstaged == Some(ChangeKind::Untracked) && !tracked.contains(&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 });
|
||||
}
|
||||
@@ -124,7 +126,10 @@ 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>> {
|
||||
Ok(changes(cwd, "HEAD")?.into_iter().map(|c| (c.rel_path, stamp(&c.path))).collect())
|
||||
// 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())
|
||||
}
|
||||
|
||||
/// Drops the changes that were there before the task and haven't been touched since.
|
||||
|
||||
@@ -333,6 +333,23 @@ 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 {
|
||||
@@ -344,6 +361,9 @@ 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,6 +261,9 @@ 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.
|
||||
|
||||
@@ -19,6 +19,9 @@ const CHUNK_SLOT_BITS: u32 = 17;
|
||||
const WORD_BITS: u64 = 64;
|
||||
const WORDS_PER_CHUNK: usize = (1 << CHUNK_SLOT_BITS) / WORD_BITS as usize;
|
||||
|
||||
// The bit table is matched in hot paths; boxing the big variant would only add
|
||||
// an indirection to save stack space `IdMap` never holds by value in bulk.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
enum Repr {
|
||||
Bits {
|
||||
/// Chunk number of the first table entry.
|
||||
|
||||
@@ -51,7 +51,12 @@ 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::{DocumentInfo, HistoryEntry};
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, HistoryEntry};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Runs blocking work (disk I/O, parsing, large copies) on the blocking pool,
|
||||
@@ -29,18 +29,24 @@ 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 label.
|
||||
/// "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding and BOM state.
|
||||
pub async fn doc_set_encoding(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
encoding: String,
|
||||
reload: bool,
|
||||
) -> IdeResult<String> {
|
||||
) -> IdeResult<DocumentEncoding> {
|
||||
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)
|
||||
}
|
||||
@@ -175,6 +181,7 @@ 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
|
||||
});
|
||||
|
||||
@@ -246,6 +246,7 @@ 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);
|
||||
|
||||
@@ -416,3 +416,40 @@ 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");
|
||||
}
|
||||
@@ -439,6 +439,46 @@ 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> {
|
||||
@@ -1903,6 +1943,67 @@ 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());
|
||||
|
||||
@@ -21,6 +21,7 @@ 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,
|
||||
@@ -41,6 +42,14 @@ 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 {
|
||||
@@ -326,6 +335,7 @@ 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,
|
||||
@@ -822,7 +832,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<String> {
|
||||
pub fn set_encoding(&self, doc: DocId, encoding: &str, reload: bool) -> IdeResult<DocumentEncoding> {
|
||||
self.with_doc(doc, |st| {
|
||||
if st.uri.is_some() {
|
||||
return Err(read_only_error(&st.path));
|
||||
@@ -842,7 +852,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(loaded.encoding);
|
||||
return Ok(DocumentEncoding { encoding: st.encoding.clone(), has_bom: st.has_bom });
|
||||
}
|
||||
if st.read_only {
|
||||
return Err(read_only_error(&st.path));
|
||||
@@ -856,7 +866,24 @@ impl Documents {
|
||||
st.encoding = encoding.to_owned();
|
||||
st.has_bom = has_bom;
|
||||
self.set_dirty(doc, st, true);
|
||||
Ok(st.encoding.clone())
|
||||
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 })
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ pub mod unity;
|
||||
pub mod window_groups;
|
||||
pub mod workspace;
|
||||
|
||||
pub use documents::{DetectLanguage, DocumentInfo, Documents, TextSnapshot};
|
||||
pub use documents::{DetectLanguage, DocumentEncoding, DocumentInfo, Documents, TextSnapshot};
|
||||
pub use editorconfig::{EditorConfig, EditorConfigProps};
|
||||
pub use file_defaults::FileDefaults;
|
||||
pub use file_moves::{FileMove, FileMoves, UndoOutcome};
|
||||
|
||||
@@ -486,11 +486,15 @@ fn reload_and_convert_encoding() {
|
||||
let (bytes, _, _) = encoding_rs::GBK.encode("中文内容");
|
||||
fs::write(&path, &bytes).unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
assert_eq!(f.docs.set_encoding(info.id, "gbk", true).unwrap(), "gbk");
|
||||
let encoding = f.docs.set_encoding(info.id, "gbk", true).unwrap();
|
||||
assert_eq!(encoding.encoding, "gbk");
|
||||
assert!(!encoding.has_bom);
|
||||
assert_eq!(f.docs.snapshot(info.id).unwrap().text, "中文内容");
|
||||
|
||||
// Convert: same text, written in the new encoding on save.
|
||||
assert_eq!(f.docs.set_encoding(info.id, "utf-8", false).unwrap(), "utf-8");
|
||||
let encoding = f.docs.set_encoding(info.id, "utf-8", false).unwrap();
|
||||
assert_eq!(encoding.encoding, "utf-8");
|
||||
assert!(!encoding.has_bom);
|
||||
f.docs.save(info.id).unwrap();
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "中文内容");
|
||||
|
||||
@@ -501,6 +505,29 @@ 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() {
|
||||
|
||||
@@ -147,3 +147,13 @@ 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);
|
||||
});
|
||||
@@ -134,3 +134,68 @@ 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!({}));
|
||||
});
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.41",
|
||||
"version": "0.1.42",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -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::{DocumentInfo, HistoryEntry};
|
||||
use ide_workspace::{DocumentEncoding, 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 label.
|
||||
/// "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding and BOM state.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn doc_set_encoding(
|
||||
@@ -96,10 +96,21 @@ pub async fn doc_set_encoding(
|
||||
doc: DocId,
|
||||
encoding: String,
|
||||
reload: bool,
|
||||
) -> IdeResult<String> {
|
||||
) -> IdeResult<DocumentEncoding> {
|
||||
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(
|
||||
|
||||
@@ -194,6 +194,7 @@ 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,
|
||||
|
||||
@@ -83,7 +83,6 @@ 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;
|
||||
@@ -93,7 +92,10 @@ pub async fn app_metrics(app: AppHandle, state: State<'_, AppState>) -> IdeResul
|
||||
pid,
|
||||
category: MemoryCategory::LanguageServer,
|
||||
label: s.name,
|
||||
detail: Some(project.clone()),
|
||||
// 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())),
|
||||
with_children: true,
|
||||
});
|
||||
}
|
||||
@@ -233,3 +235,24 @@ 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");
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.41",
|
||||
"version": "0.1.42",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
+28
-2
@@ -298,8 +298,9 @@ 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 label. */
|
||||
docSetEncoding: (doc: DocId, encoding: string, reload: boolean) => typedError<string, IdeError>(__TAURI_INVOKE("doc_set_encoding", { doc, encoding, reload })),
|
||||
/** "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 })),
|
||||
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
|
||||
@@ -2714,6 +2715,13 @@ 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,
|
||||
@@ -4009,6 +4017,12 @@ 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,
|
||||
@@ -4017,6 +4031,7 @@ export type DocumentInfo = {
|
||||
version: number,
|
||||
language: LanguageId,
|
||||
encoding: string,
|
||||
hasBom: boolean,
|
||||
lineEnding: LineEnding,
|
||||
readOnly: boolean,
|
||||
dirty: boolean,
|
||||
@@ -5575,6 +5590,12 @@ 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";
|
||||
@@ -6644,6 +6665,11 @@ 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,6 +595,8 @@ 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,6 +12,7 @@ import {
|
||||
isTauri,
|
||||
onIdeEvent,
|
||||
type DocId,
|
||||
type DocumentEncoding,
|
||||
type DocumentInfo,
|
||||
type FoldRange,
|
||||
type LanguageInfo_Serialize,
|
||||
@@ -47,8 +48,10 @@ 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. */
|
||||
setEncoding(doc: DocId, encoding: string, reload: boolean): Promise<string>;
|
||||
/** "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>;
|
||||
outline(doc: DocId): Promise<OutlineItem[]>;
|
||||
folding(doc: DocId): Promise<FoldRange[]>;
|
||||
/** Tree-sitter highlighting, for languages without a CodeMirror mode. */
|
||||
@@ -83,6 +86,7 @@ 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)),
|
||||
@@ -108,9 +112,11 @@ interface MemDoc {
|
||||
path: string;
|
||||
text: string;
|
||||
saved: string;
|
||||
savedBom: boolean;
|
||||
version: number;
|
||||
refs: number;
|
||||
lineEnding: LineEnding;
|
||||
hasBom: boolean;
|
||||
readOnly: boolean;
|
||||
language: string;
|
||||
uiMode?: string;
|
||||
@@ -377,6 +383,7 @@ 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,
|
||||
@@ -385,9 +392,10 @@ 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,
|
||||
dirty: d.text !== d.saved || d.hasBom !== d.savedBom,
|
||||
...(d.uri ? { uri: d.uri } : {}),
|
||||
...(d.uiMode ? { uiMode: d.uiMode } : {}),
|
||||
});
|
||||
@@ -411,7 +419,7 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
return d;
|
||||
};
|
||||
const setDirty = (d: MemDoc, before: boolean) => {
|
||||
const now = d.text !== d.saved;
|
||||
const now = d.text !== d.saved || d.hasBom !== d.savedBom;
|
||||
if (now !== before) dirtyHandlers.forEach((h) => h({ doc: d.id, dirty: now }));
|
||||
};
|
||||
const delay = <T>(v: () => T): Promise<T> =>
|
||||
@@ -439,15 +447,18 @@ 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",
|
||||
};
|
||||
@@ -473,9 +484,11 @@ 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,
|
||||
@@ -496,7 +509,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;
|
||||
const before = d.text !== d.saved || d.hasBom !== d.savedBom;
|
||||
d.text = applyChanges(d.text, changes);
|
||||
d.version++;
|
||||
setDirty(d, before);
|
||||
@@ -505,9 +518,11 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
},
|
||||
async save(doc) {
|
||||
const d = get(doc);
|
||||
const before = d.text !== d.saved;
|
||||
const before = d.text !== d.saved || d.hasBom !== d.savedBom;
|
||||
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) {
|
||||
@@ -516,8 +531,16 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
|
||||
async setLineEnding(doc, le) {
|
||||
get(doc).lineEnding = le;
|
||||
},
|
||||
async setEncoding(_doc, encoding) {
|
||||
return encoding;
|
||||
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 outline(doc) {
|
||||
// Brace-based outline good enough for the dev shell.
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { declarationStart, groupLenses, indentColumns } from "./codeLens";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { codeLenses } from "@/editor/api";
|
||||
import { codeLensExtension, codeLensPositions, declarationStart, groupLenses, indentColumns } from "./codeLens";
|
||||
|
||||
const doc = (text: string) => EditorState.create({ doc: text });
|
||||
|
||||
@@ -34,3 +36,44 @@ 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,14 +1,24 @@
|
||||
/**
|
||||
* Renders `codeLenses` (editor/api) as one small hint row above the target
|
||||
* line, indented like the line (IDEA "3 usages | Run test" inlays).
|
||||
* 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.
|
||||
*/
|
||||
import { EditorState, RangeSetBuilder, type Extension } from "@codemirror/state";
|
||||
import { EditorState, Facet, 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,
|
||||
@@ -71,12 +81,15 @@ 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 +
|
||||
@@ -92,8 +105,9 @@ class LensWidget extends WidgetType {
|
||||
}
|
||||
|
||||
override toDOM(view: EditorView): HTMLElement {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = "cm-openidea-lens";
|
||||
// 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";
|
||||
this.fill(dom, view);
|
||||
return dom;
|
||||
}
|
||||
@@ -105,9 +119,11 @@ 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 = guideVars(Math.floor(this.indent / this.indentUnit), this.indentUnit, this.rainbow);
|
||||
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`;
|
||||
if (guides) {
|
||||
dom.style.setProperty("--openidea-guide-images", guides.images);
|
||||
dom.style.setProperty("--openidea-guide-positions", guides.positions);
|
||||
@@ -117,14 +133,7 @@ class LensWidget extends WidgetType {
|
||||
}
|
||||
dom.setAttribute("role", "group");
|
||||
dom.setAttribute("aria-label", "Code lens");
|
||||
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);
|
||||
}
|
||||
for (const lens of this.lenses) {
|
||||
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;
|
||||
@@ -154,11 +163,11 @@ class LensWidget extends WidgetType {
|
||||
});
|
||||
}
|
||||
dom.appendChild(el);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
override get estimatedHeight(): number {
|
||||
return 16;
|
||||
return this.inline ? -1 : 16;
|
||||
}
|
||||
|
||||
override ignoreEvent(): boolean {
|
||||
@@ -169,16 +178,28 @@ 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 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 }));
|
||||
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 }),
|
||||
);
|
||||
}
|
||||
return builder.finish();
|
||||
}
|
||||
@@ -187,7 +208,7 @@ const lensTheme = EditorView.theme({
|
||||
".cm-openidea-lens": {
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "6px",
|
||||
gap: "12px",
|
||||
height: "16px",
|
||||
color: "var(--fg-muted)",
|
||||
WebkitUserSelect: "none",
|
||||
@@ -195,29 +216,37 @@ 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: "3px",
|
||||
gap: "4px",
|
||||
padding: "0",
|
||||
border: "none",
|
||||
background: "none",
|
||||
font: "inherit",
|
||||
color: "inherit",
|
||||
},
|
||||
// The row keeps the editor font so its `ch`-based indent guides line up with the code.
|
||||
".cm-openidea-lensItem, .cm-openidea-lensSep": {
|
||||
// The items take the UI font; the row keeps the editor's, so its `ch`-based indent guides line up with the code.
|
||||
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], buildDecorations),
|
||||
EditorView.decorations.compute([codeLenses, rainbowGuides, codeLensPositions], buildDecorations),
|
||||
lensTheme,
|
||||
];
|
||||
@@ -355,7 +355,27 @@ export const commentBlock: Command = (view) => {
|
||||
|
||||
/** ⌘/ in a language without line comments (CSS, HTML…): the block comment of the lines. */
|
||||
function blockCommentLines(view: EditorView): boolean {
|
||||
return uncommentBlock(view, selectedLines(view.state)) || toggleComment(view);
|
||||
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);
|
||||
}
|
||||
|
||||
// --- Enter in a line comment ------------------------------------------------------
|
||||
|
||||
@@ -419,6 +419,27 @@ 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,6 +54,7 @@ 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 ---------------------------------------------------------------
|
||||
|
||||
@@ -557,7 +558,12 @@ export function prefsExtension(o: PrefsOptions): Extension {
|
||||
const { prefs } = o;
|
||||
const g = prefs.general;
|
||||
const k = prefs.smartKeys;
|
||||
const out: Extension[] = [];
|
||||
const out: Extension[] = [
|
||||
codeLensPositions.of({
|
||||
usages: prefs.inlay.codeVisionUsagesPosition,
|
||||
author: prefs.inlay.codeVisionAuthorPosition,
|
||||
}),
|
||||
];
|
||||
if (!o.readOnly)
|
||||
out.push(markdownImages({ path: o.path, folder: g.markdownImageFolder, pattern: g.markdownImageNamePattern }));
|
||||
if (g.scrollPastEnd) out.push(scrollPastEnd());
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BlockType, RectangleMarker, type BlockInfo } from "@codemirror/view";
|
||||
import {
|
||||
alignLeftEdges,
|
||||
dropInsetSlivers,
|
||||
cutOutGaps,
|
||||
fillGaps,
|
||||
fillRowEnds,
|
||||
@@ -249,3 +251,55 @@ 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,6 +157,35 @@ 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[],
|
||||
@@ -206,6 +235,21 @@ 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();
|
||||
@@ -275,6 +319,7 @@ 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) {
|
||||
@@ -285,15 +330,21 @@ const snappedSelectionLayer = layer({
|
||||
first: hasTextBlockAt(view, from, 1),
|
||||
last: hasTextBlockAt(view, to, -1),
|
||||
});
|
||||
if (!lines.length) continue;
|
||||
// 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;
|
||||
const full = edge
|
||||
? fillRowEnds(
|
||||
widenToRightEdge(lines, CLASS, edge.rightSide, edge.pad),
|
||||
widenToRightEdge(aligned, CLASS, edge.rightSide, edge.pad),
|
||||
CLASS,
|
||||
rowsPastEnd(view, offset, r),
|
||||
edge.rightSide + edge.pad,
|
||||
)
|
||||
: lines;
|
||||
: aligned;
|
||||
// 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 });
|
||||
model.setMeta({ encoding: encoding.encoding, hasBom: encoding.hasBom });
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
|
||||
@@ -82,6 +82,7 @@ export interface DocMeta {
|
||||
language: string;
|
||||
uiMode: string | null;
|
||||
encoding: string;
|
||||
hasBom: boolean;
|
||||
lineEnding: LineEnding;
|
||||
readOnly: boolean;
|
||||
dirty: boolean;
|
||||
@@ -248,6 +249,7 @@ 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,6 +352,7 @@ 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;
|
||||
@@ -360,7 +361,7 @@ export function EncodingStatus() {
|
||||
if (!model) return;
|
||||
void editorController()
|
||||
.manager.backend.setEncoding(meta.doc, encoding, reload)
|
||||
.then((enc) => model.setMeta({ encoding: enc, ...(reload ? {} : { dirty: true }) }))
|
||||
.then((enc) => model.setMeta({ encoding: enc.encoding, hasBom: enc.hasBom, ...(reload ? {} : { dirty: true }) }))
|
||||
.catch((e: unknown) =>
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
@@ -370,6 +371,27 @@ 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}`,
|
||||
@@ -385,7 +407,7 @@ export function EncodingStatus() {
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
>
|
||||
{ENCODINGS.find(([id]) => id === current)?.[1] ?? meta.encoding}
|
||||
{meta.hasBom ? `${label} BOM` : label}
|
||||
</BarButton>
|
||||
<Menu
|
||||
open={open}
|
||||
@@ -396,6 +418,17 @@ 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,6 +118,18 @@ 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,14 +233,22 @@ 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 });
|
||||
lenses.push({
|
||||
pos: offset,
|
||||
title: authorLabel(who),
|
||||
tooltip: authorTooltip(who),
|
||||
icon: "user",
|
||||
order: 20,
|
||||
kind: "author",
|
||||
});
|
||||
const n = usages ? this.cache.get(key(t)) : undefined;
|
||||
if (n === undefined) continue;
|
||||
if (n === undefined || (n === 0 && !editorPrefs().inlay.codeVisionNoUsages)) 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)),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { ProgressBar } from "@/ui";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { tx, useTx } from "@/platform/i18n";
|
||||
import { call, commands, IpcError } from "@/platform/ipc";
|
||||
import { open as openDialog, save as saveDialog } from "@/platform/dialog";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
import { basename } from "@/platform/project";
|
||||
import { isRemoteWindow, useRemote } from "@/platform/remote";
|
||||
@@ -43,8 +44,7 @@ export async function openHeapDump(): Promise<void> {
|
||||
}
|
||||
// One file at a time; the running open keeps its progress notification.
|
||||
if (useHeap.getState().opening) return;
|
||||
const { open } = await import("@tauri-apps/plugin-dialog");
|
||||
const picked = await open({ multiple: false, directory: false, filters: FILTERS() });
|
||||
const picked = await openDialog({ multiple: false, directory: false, filters: FILTERS() });
|
||||
if (typeof picked !== "string" || useHeap.getState().opening) return;
|
||||
const path = ipcPath(picked);
|
||||
const name = basename(path);
|
||||
@@ -85,8 +85,7 @@ export async function openHeapDump(): Promise<void> {
|
||||
export async function saveHeapDump(id: number): Promise<void> {
|
||||
const entry = useHeap.getState().snapshots[id];
|
||||
if (!entry || entry.info.origin.kind !== "captured" || isRemoteWindow()) return;
|
||||
const { save } = await import("@tauri-apps/plugin-dialog");
|
||||
const picked = await save({
|
||||
const picked = await saveDialog({
|
||||
defaultPath: `${entry.info.label.replace(/[/\\:*?"<>|]/g, "-")}.hprof`,
|
||||
filters: FILTERS(),
|
||||
});
|
||||
|
||||
@@ -43,6 +43,22 @@ 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,16 +321,25 @@ export function initProjectTree(
|
||||
clearTimeout(persistTimer);
|
||||
modeExpanded.clear();
|
||||
autoExpanded.clear();
|
||||
const previousMode = get().mode;
|
||||
const previous = get();
|
||||
const previousMode = previous.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: new Map(),
|
||||
projectTypes,
|
||||
listings: new Map(),
|
||||
expanded: initialExpanded(root, mode, members),
|
||||
selected: new Set(),
|
||||
|
||||
@@ -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 };
|
||||
mcpServer: { enabled: boolean; runWithoutConfirmation: 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 },
|
||||
mcpServer: { enabled: false, runWithoutConfirmation: false },
|
||||
...DEFAULT_WORKFLOW,
|
||||
};
|
||||
|
||||
@@ -359,7 +359,10 @@ 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) },
|
||||
mcpServer: {
|
||||
enabled: bool(obj(root.mcpServer).enabled, d.mcpServer.enabled),
|
||||
runWithoutConfirmation: bool(obj(root.mcpServer).runWithoutConfirmation, d.mcpServer.runWithoutConfirmation),
|
||||
},
|
||||
...validateWorkflow(root),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -835,6 +835,11 @@ 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",
|
||||
@@ -845,8 +850,33 @@ const INLAY_HINTS = editorPage({
|
||||
{
|
||||
title: "Code Vision",
|
||||
items: [
|
||||
{ t: "check", key: `${P}.inlay.codeVisionUsages`, label: "Usages" },
|
||||
{ t: "check", key: `${P}.inlay.codeVisionAuthor`, label: "Code author" },
|
||||
{
|
||||
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,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{ title: "Languages", items: [{ t: "custom", label: "Show inlay hints for:", component: InlayLanguages }] },
|
||||
|
||||
@@ -128,6 +128,12 @@ 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",
|
||||
|
||||
@@ -738,12 +738,6 @@ 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);
|
||||
@@ -788,6 +782,10 @@ 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) {
|
||||
|
||||
@@ -2745,6 +2745,10 @@ export function CommitDetails({ commits }: { commits: Commit[] }) {
|
||||
}}
|
||||
renderNode={(n) => <ChangedFileRow node={n} flat={!groupByDirectory} />}
|
||||
onActivate={(n) => n.file && void showChangesDiff([n.file])}
|
||||
onJumpToSource={(n, sel) => {
|
||||
const files = sel.has(n.key) ? filesUnder(tree, sel) : filesUnder([n]);
|
||||
void executeAction("vcs.log.changes.jumpToSource", files);
|
||||
}}
|
||||
onContextMenu={onFileMenu}
|
||||
aria-label="Changed files"
|
||||
className={styles.fileTree}
|
||||
|
||||
@@ -9,7 +9,7 @@ it("opens every file picker through the platform wrapper", () => {
|
||||
(file) =>
|
||||
/\.[jt]sx?$/.test(file) &&
|
||||
!/\.test\.[jt]sx?$/.test(file) &&
|
||||
file !== "platform/dialog.ts" &&
|
||||
file.replace(/\\/g, "/") !== "platform/dialog.ts" &&
|
||||
readFileSync(resolve(src, file), "utf8").includes("@tauri-apps/plugin-" + "dialog"),
|
||||
);
|
||||
expect(offenders).toEqual([]);
|
||||
|
||||
@@ -179,6 +179,9 @@ export const EDITOR_EXTRA_DEFAULTS = {
|
||||
disabledLanguages: [] as string[],
|
||||
codeVisionUsages: true,
|
||||
codeVisionAuthor: true,
|
||||
codeVisionNoUsages: true,
|
||||
codeVisionUsagesPosition: "top" as "top" | "right",
|
||||
codeVisionAuthorPosition: "top" as "top" | "right",
|
||||
},
|
||||
inlineCompletion: { enabled: true, onlyOnPause: false, pauseMs: 500, disabledLanguages: [] as string[] },
|
||||
gutterIconsDisabled: [] as string[],
|
||||
@@ -260,6 +263,8 @@ export function validateEditorExtras(raw: unknown): EditorExtras {
|
||||
const out = coerceLike(raw, EDITOR_EXTRA_DEFAULTS);
|
||||
if (!["ask", "always", "never"].includes(out.autoImport.importsOnPaste)) out.autoImport.importsOnPaste = "ask";
|
||||
if (!DOCSTRING_FORMATS.includes(out.docstringFormat)) out.docstringFormat = "rest";
|
||||
for (const k of ["codeVisionUsagesPosition", "codeVisionAuthorPosition"] as const)
|
||||
if (!["top", "right"].includes(out.inlay[k])) out.inlay[k] = "top";
|
||||
out.fontWeight = fontWeightOf(out.fontWeight, EDITOR_EXTRA_DEFAULTS.fontWeight);
|
||||
out.boldFontWeight = fontWeightOf(out.boldFontWeight, EDITOR_EXTRA_DEFAULTS.boldFontWeight);
|
||||
return out;
|
||||
|
||||
@@ -117,6 +117,9 @@
|
||||
"Move the worktree at {path} to {to}?": "Move the worktree at {path} to {to}?",
|
||||
"Cannot move a worktree containing the open project.": "Cannot move a worktree containing the open project.",
|
||||
"Add Environment File": "Add Environment File",
|
||||
"Add UTF-8 BOM": "Add UTF-8 BOM",
|
||||
"Remove UTF-8 BOM": "Remove UTF-8 BOM",
|
||||
"Cannot change the UTF-8 BOM": "Cannot change the UTF-8 BOM",
|
||||
"Convert to cURL and Copy": "Convert to cURL and Copy",
|
||||
"Add Environment to Public File": "Add Environment to Public File",
|
||||
"Add Environment to Private File": "Add Environment to Private File",
|
||||
@@ -670,6 +673,8 @@
|
||||
"Gradle Tasks": "Gradle Tasks",
|
||||
"IDE MCP Server": "IDE MCP Server",
|
||||
"Enable MCP server": "Enable MCP server",
|
||||
"Run tools without confirmation (brave mode)": "Run tools without confirmation (brave mode)",
|
||||
"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.": "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.",
|
||||
"Status": "Status",
|
||||
"Running on port {port}": "Running on port {port}",
|
||||
"Failed to start: {error}": "Failed to start: {error}",
|
||||
|
||||
@@ -2374,6 +2374,8 @@
|
||||
"more": "más",
|
||||
"Usages": "Usos",
|
||||
"Code author": "Autor del código",
|
||||
"Position": "Posición",
|
||||
"Show “no usages”": "Mostrar «sin usos»",
|
||||
"Usages Detected": "Usos detectados",
|
||||
"Usages actions": "Acciones de usos",
|
||||
"Usages of '{symbol}'": "Usos de '{symbol}'",
|
||||
|
||||
@@ -2278,6 +2278,8 @@
|
||||
"more": "de plus",
|
||||
"Usages": "Utilisations",
|
||||
"Code author": "Auteur du code",
|
||||
"Position": "Position",
|
||||
"Show “no usages”": "Afficher « aucune utilisation »",
|
||||
"Usages Detected": "Utilisations détectées",
|
||||
"Usages actions": "Actions sur les utilisations",
|
||||
"Usages of '{symbol}'": "Utilisations de '{symbol}'",
|
||||
|
||||
@@ -2430,6 +2430,8 @@
|
||||
"more": "더보기",
|
||||
"Usages": "사용 위치",
|
||||
"Code author": "코드 작성자",
|
||||
"Position": "위치",
|
||||
"Show “no usages”": "‘사용 위치 없음’ 표시",
|
||||
"Usages Detected": "사용 위치 감지됨",
|
||||
"Usages actions": "사용 위치 액션",
|
||||
"Usages of '{symbol}'": "'{symbol}'의 사용 위치",
|
||||
|
||||
@@ -2353,6 +2353,8 @@
|
||||
"more": "więcej",
|
||||
"Usages": "Użycia",
|
||||
"Code author": "Autor kodu",
|
||||
"Position": "Pozycja",
|
||||
"Show “no usages”": "Pokazuj „brak użyć”",
|
||||
"Usages Detected": "Wykryto użycia",
|
||||
"Usages actions": "Akcje użyć",
|
||||
"Usages of '{symbol}'": "Użycia symbolu '{symbol}'",
|
||||
|
||||
@@ -2354,6 +2354,8 @@
|
||||
"more": "mais",
|
||||
"Usages": "Usos",
|
||||
"Code author": "Autor do código",
|
||||
"Position": "Posição",
|
||||
"Show “no usages”": "Mostrar “sem usos”",
|
||||
"Usages Detected": "Usos detectados",
|
||||
"Usages actions": "Ações de usos",
|
||||
"Usages of '{symbol}'": "Usos de '{symbol}'",
|
||||
|
||||
@@ -844,6 +844,9 @@
|
||||
"Continue Revert": "继续还原",
|
||||
"Contributes": "贡献",
|
||||
"Convert to Encoding": "转换为编码",
|
||||
"Add UTF-8 BOM": "添加 UTF-8 BOM",
|
||||
"Remove UTF-8 BOM": "移除 UTF-8 BOM",
|
||||
"Cannot change the UTF-8 BOM": "无法更改 UTF-8 BOM",
|
||||
"Copied code keeps the editor's syntax colors and font when pasted into documents and mail.": "复制的代码粘贴到文档和邮件中时会保留编辑器的语法颜色和字体。",
|
||||
"Copy": "复制",
|
||||
"Copy / Paste Special": "复制/选择性粘贴",
|
||||
@@ -2830,6 +2833,8 @@
|
||||
"more": "更多",
|
||||
"Usages": "用法",
|
||||
"Code author": "代码作者",
|
||||
"Position": "位置",
|
||||
"Show “no usages”": "显示“无用法”",
|
||||
"Usages Detected": "检测到用法",
|
||||
"Usages actions": "用法操作",
|
||||
"Usages of '{symbol}'": "'{symbol}' 的用法",
|
||||
@@ -7010,6 +7015,8 @@
|
||||
"Gradle Tasks": "Gradle 任务",
|
||||
"IDE MCP Server": "IDE MCP 服务器",
|
||||
"Enable MCP server": "启用 MCP 服务器",
|
||||
"Run tools without confirmation (brave mode)": "运行工具时不再确认(勇敢模式)",
|
||||
"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.": "运行配置、终端命令以及其他会修改项目的工具直接执行、不再询问,适合无人值守的智能体。只能在 IDE 自身的设置里开启,项目设置无法开启。",
|
||||
"Running on port {port}": "正在端口 {port} 上运行",
|
||||
"Failed to start: {error}": "启动失败:{error}",
|
||||
"Not running": "未运行",
|
||||
|
||||
@@ -181,6 +181,17 @@ describe("Tree keyboard navigation", () => {
|
||||
expect(onActivate).toHaveBeenLastCalledWith(expect.objectContaining({ id: "README.md" }), expect.anything());
|
||||
});
|
||||
|
||||
it("F4 and ⌘↓ go to onJumpToSource instead of activating when the tree has one", () => {
|
||||
const onJumpToSource = vi.fn();
|
||||
const { key, onActivate } = setup({ onJumpToSource });
|
||||
key("End");
|
||||
key("F4");
|
||||
key("ArrowDown", { metaKey: true });
|
||||
expect(onActivate).not.toHaveBeenCalled();
|
||||
expect(onJumpToSource).toHaveBeenCalledTimes(2);
|
||||
expect(onJumpToSource).toHaveBeenLastCalledWith(expect.objectContaining({ id: "README.md" }), expect.any(Set));
|
||||
});
|
||||
|
||||
it("extends the selection with Shift+Arrow", () => {
|
||||
const onSelectionChange = vi.fn();
|
||||
const { key } = setup({ defaultExpanded: ["src"], onSelectionChange });
|
||||
|
||||
+10
-2
@@ -105,6 +105,11 @@ export interface TreeProps<T> {
|
||||
/** Enter / double-click on a leaf (or on nodes `activateExpandable` accepts). */
|
||||
onActivate?: (node: T, e: KeyboardEvent | MouseEvent) => void;
|
||||
activateExpandable?: boolean | ((node: T) => boolean);
|
||||
/**
|
||||
* Jump to Source (F4 / ⌘↓) on the lead row. Without it the key activates like Enter; trees
|
||||
* whose activation opens a diff pass this to open the file itself.
|
||||
*/
|
||||
onJumpToSource?: (node: T, selection: ReadonlySet<string>) => void;
|
||||
/** Nodes Next / Previous Occurrence stops at (`TreeHandle.selectOccurrence`); default: leaves. */
|
||||
isOccurrence?: (node: T) => boolean;
|
||||
onContextMenu?: (node: T | null, selection: Set<string>, e: MouseEvent) => void;
|
||||
@@ -247,6 +252,7 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
getColor,
|
||||
multiSelect = true,
|
||||
onActivate,
|
||||
onJumpToSource,
|
||||
activateExpandable = false,
|
||||
onContextMenu,
|
||||
speedSearch = true,
|
||||
@@ -495,11 +501,13 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
return;
|
||||
}
|
||||
const range = e.shiftKey && multiSelect;
|
||||
// Jump to Source (F4 / ⌘↓) activates like Enter.
|
||||
// Jump to Source (F4 / ⌘↓): the tree's own handler, else it activates like Enter.
|
||||
if (e.key === "F4" || (e.key === "ArrowDown" && e.metaKey && !e.shiftKey && !e.altKey)) {
|
||||
if (!row) return;
|
||||
setQuery("");
|
||||
activate(row, e);
|
||||
if (onJumpToSource) {
|
||||
if (!row.loading) onJumpToSource(row.node, selected);
|
||||
} else activate(row, e);
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return;
|
||||
|
||||
Reference in new issue
Заблокувати користувача