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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 727249e143 fix(keymap): Navigate Back / Forward with the mouse side buttons
The keymap had no notion of mouse buttons, so the back / forward side
buttons did nothing anywhere in the window.

Keymaps can now hold mouse shortcuts (`Button4`, `Shift+Button5`, buttons
numbered 1-based as DOM `button` + 1). Every preset binds Button4 to
Navigate Back and Button5 to Navigate Forward. The global dispatcher runs
them on mousedown from any component, keeps side-button press / release /
auxclick away from the target (no editor selection or focus change) and
cancels the webview's own history navigation. Menus and tooltips keep
showing the first keyboard binding; the keymap list shows "Button4 Click".

Fixes #75

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 14:53:31 +08:00
123 змінених файлів з 386 додано та 6479 видалено

No files matched your search

Створено
+30 -41
Переглянути файл
@@ -3962,7 +3962,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"ide-core",
"ide-jsonrpc",
@@ -3980,7 +3980,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -3994,7 +3994,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"dirs 6.0.0",
"dunce",
@@ -4009,11 +4009,11 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.16"
version = "0.1.15"
[[package]]
name = "ide-core"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"dunce",
"serde",
@@ -4025,7 +4025,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"ide-core",
"ide-run",
@@ -4039,7 +4039,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"ide-core",
"ide-jsonrpc",
@@ -4056,7 +4056,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"dirs 6.0.0",
"futures",
@@ -4076,7 +4076,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"ide-core",
"libc",
@@ -4090,7 +4090,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4104,7 +4104,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"ide-core",
"parking_lot",
@@ -4122,7 +4122,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"blake3",
"criterion",
@@ -4144,7 +4144,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"futures",
"ide-core",
@@ -4159,7 +4159,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"blake3",
"criterion",
@@ -4180,7 +4180,6 @@ dependencies = [
"tree-sitter-css",
"tree-sitter-dart",
"tree-sitter-elixir",
"tree-sitter-gdscript",
"tree-sitter-go",
"tree-sitter-graphql",
"tree-sitter-haskell",
@@ -4212,7 +4211,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"futures",
"globset",
@@ -4235,7 +4234,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"ide-core",
"ide-language",
@@ -4253,7 +4252,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"ide-core",
"ide-run",
@@ -4266,7 +4265,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4286,7 +4285,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"dunce",
"ide-core",
@@ -4305,7 +4304,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"criterion",
"globset",
@@ -4325,7 +4324,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"ide-core",
"parking_lot",
@@ -4338,7 +4337,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"ide-core",
"ide-language",
@@ -4353,7 +4352,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"ide-core",
"libc",
@@ -4366,7 +4365,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"criterion",
"ide-core",
@@ -4378,7 +4377,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"flate2",
"hex",
@@ -4398,7 +4397,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"dunce",
"gix",
@@ -4415,7 +4414,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"chardetng",
"dunce",
@@ -4436,7 +4435,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"ide-core",
"open",
@@ -4452,7 +4451,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"blake3",
"dunce",
@@ -5877,7 +5876,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.16"
version = "0.1.15"
dependencies = [
"dirs 6.0.0",
"dunce",
@@ -9296,16 +9295,6 @@ dependencies = [
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-gdscript"
version = "6.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7a37fe8c0a10c0c39ecd5b2f7db53933f691488f5572409a4d3c0dfeb3f6108"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-go"
version = "0.25.0"
+1 -1
Переглянути файл
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "src-tauri"]
[workspace.package]
version = "0.1.16"
version = "0.1.15"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+1 -1
Переглянути файл
@@ -25,7 +25,7 @@ const BUILTIN: &[(&str, &str, &[&str], &str)] = &[
&["npx", "-y", "@agentclientprotocol/[email protected]"],
"Run `claude` in a terminal and sign in.",
),
("codex", "Codex", &["npx", "-y", "@agentclientprotocol/codex-acp@2.3.0"], "Run `codex login` in a terminal."),
("codex", "Codex", &["npx", "-y", "@zed-industries/codex-acp@0.16.0"], "Run `codex login` in a terminal."),
("gemini", "Gemini CLI", &["gemini", "--experimental-acp"], "Run `gemini` in a terminal and sign in."),
("copilot", "GitHub Copilot", &["copilot", "--acp"], "Run `copilot` in a terminal and sign in."),
("cursor", "Cursor", &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
-33
Переглянути файл
@@ -1,8 +1,6 @@
//! Child-process helpers shared by every crate that spawns tools.
use std::ffi::{OsStr, OsString};
use std::process::Command;
use std::sync::OnceLock;
/// Windows `CREATE_NO_WINDOW` creation flag, for call sites that combine it
/// with other flags. Prefer [`no_window`] otherwise.
@@ -20,34 +18,3 @@ pub fn no_window(cmd: &mut Command) -> &mut Command {
}
cmd
}
static SHELL_ENV: OnceLock<Vec<(OsString, OsString)>> = OnceLock::new();
/// Records the login shell's environment, read once at startup off the main thread.
pub fn set_shell_env(vars: Vec<(OsString, OsString)>) {
let _ = SHELL_ENV.set(vars);
}
/// The login shell's variables this process lacks: an app started from Finder/Dock gets only
/// PATH from the shell, not what rc files export (API keys and provider switches, SDK homes...).
/// Apply before a call site's own variables so those win. Empty until the shell has been read.
pub fn shell_env() -> impl Iterator<Item = (&'static OsStr, &'static OsStr)> {
SHELL_ENV
.get()
.into_iter()
.flatten()
.filter(|(k, _)| std::env::var_os(k).is_none())
.map(|(k, v)| (k.as_os_str(), v.as_os_str()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shell_env_adds_only_what_the_process_lacks() {
set_shell_env(vec![("OPENIDEA_SHELL_ONLY_VAR".into(), "1".into()), ("PATH".into(), "/from/shell".into())]);
let vars: Vec<_> = shell_env().collect();
assert_eq!(vars, [(OsStr::new("OPENIDEA_SHELL_ONLY_VAR"), OsStr::new("1"))]);
}
}
+4 -56
Переглянути файл
@@ -18,8 +18,6 @@ use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, BufReader};
use tokio::process::{Child, Command};
pub const PORT_PLACEHOLDER: &str = "${port}";
/// Replaced by the session's working directory (the project) in adapter arguments.
pub const ROOT_PLACEHOLDER: &str = "${root}";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Transport {
@@ -40,9 +38,6 @@ pub struct AdapterSpec {
pub env: Vec<(String, String)>,
/// Host of an adapter that is already running (`debugServer`); `None` is the loopback interface.
pub server_host: Option<String>,
/// `host:port` of an adapter inside another program (the Godot editor): connected to
/// when it accepts, else `command` is started.
pub connect: Option<String>,
}
/// Built-in adapters used when no language definition names `adapter`.
@@ -52,7 +47,6 @@ fn builtin(adapter: &str) -> Option<DebuggerConfig> {
command: command.to_owned(),
args: args.iter().map(|a| (*a).to_owned()).collect(),
transport: transport.to_owned(),
connect: None,
install_hint: Some(hint.to_owned()),
};
Some(match adapter {
@@ -125,7 +119,6 @@ pub fn resolve(config: &DebuggerConfig, cwd: PathBuf) -> AdapterSpec {
cwd,
env: Vec::new(),
server_host: None,
connect: config.connect.clone(),
}
}
@@ -134,19 +127,6 @@ pub fn substitute_port(args: &[String], port: u16) -> Vec<String> {
args.iter().map(|a| a.replace(PORT_PLACEHOLDER, &port.to_string())).collect()
}
/// Replaces every `${root}` occurrence with `root`.
pub fn substitute_root(args: &[String], root: &Path) -> Vec<String> {
let root = root.to_string_lossy();
args.iter().map(|a| a.replace(ROOT_PLACEHOLDER, &root)).collect()
}
/// Splits `host:port` (`[v6]:port`).
pub fn parse_address(addr: &str) -> Option<(String, u16)> {
let (host, port) = addr.trim().rsplit_once(':')?;
let host = host.trim_start_matches('[').trim_end_matches(']');
Some((host.to_owned(), port.parse().ok().filter(|p| *p != 0)?))
}
/// A port that was free a moment ago on the loopback interface.
pub fn free_port() -> std::io::Result<u16> {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?;
@@ -326,10 +306,6 @@ pub trait AdapterLauncher: Send + Sync + 'static {
pub struct ProcessLauncher;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
/// How long an adapter inside another program (a headless Godot editor) may take to listen.
const EMBEDDED_START_TIMEOUT: Duration = Duration::from_secs(120);
/// Probe of a `connect` address before starting the command.
const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
impl AdapterLauncher for ProcessLauncher {
fn launch(&self, mut spec: AdapterSpec, reuse_port: Option<u16>) -> LaunchFuture {
@@ -351,28 +327,6 @@ impl AdapterLauncher for ProcessLauncher {
stderr,
});
}
let embedded = match spec.connect.as_deref().filter(|_| spec.transport == Transport::Tcp) {
Some(addr) => Some(
parse_address(addr)
.ok_or_else(|| IdeError::invalid(format!("invalid debug adapter address `{addr}`")))?,
),
None => None,
};
// An adapter inside a program the user runs (the Godot editor): use it, never stop it.
if let Some((host, port)) = &embedded
&& let Ok(Ok(stream)) =
tokio::time::timeout(PROBE_TIMEOUT, tokio::net::TcpStream::connect((host.as_str(), *port))).await
{
let _ = stream.set_nodelay(true);
let (r, w) = stream.into_split();
return Ok(AdapterIo {
reader: Box::new(r),
writer: Box::new(w),
child: None,
port: Some(*port),
stderr,
});
}
if spec.adapter == DEBUGPY_TOOL {
prepare_debugpy(&mut spec).await?;
}
@@ -383,17 +337,12 @@ impl AdapterLauncher for ProcessLauncher {
.flatten()
.ok_or_else(|| missing(&spec))?;
let port = match spec.transport {
// An embedded adapter started without `${port}` listens on its usual address.
Transport::Tcp => match &embedded {
Some((_, port)) if !spec.args.iter().any(|a| a.contains(PORT_PLACEHOLDER)) => Some(*port),
_ => Some(free_port()?),
},
Transport::Tcp => Some(free_port()?),
Transport::Stdio => None,
};
let args = substitute_root(&spec.args, &spec.cwd);
let args = match port {
Some(port) => substitute_port(&args, port),
None => args,
Some(port) => substitute_port(&spec.args, port),
None => spec.args.clone(),
};
let mut cmd = Command::new(&binary);
ide_core::process::no_window(cmd.as_std_mut());
@@ -425,8 +374,7 @@ impl AdapterLauncher for ProcessLauncher {
if let Some(out) = child.stdout.take() {
pump_lines(out, spec.adapter.clone(), stderr.clone());
}
let timeout = if embedded.is_some() { EMBEDDED_START_TIMEOUT } else { CONNECT_TIMEOUT };
let stream = match connect_with_retries(LOOPBACK, port, Some(&mut child), timeout).await {
let stream = match connect_with_retries(LOOPBACK, port, Some(&mut child), CONNECT_TIMEOUT).await {
Ok(s) => s,
Err(e) => {
let _ = child.start_kill();
+7 -18
Переглянути файл
@@ -620,14 +620,6 @@ impl DebugManager {
if config.adapter == "js-debug" && arguments.get("__workspaceFolder").is_none() {
arguments["__workspaceFolder"] = json!(cwd);
}
// Godot compares `project` with its own (resolved) project path: `/tmp/game` is
// rejected by an editor that opened `/private/tmp/game`.
if config.adapter == "godot"
&& let Some(project) = arguments.get("project").and_then(Value::as_str)
&& let Ok(real) = std::fs::canonicalize(project)
{
arguments["project"] = json!(real);
}
if config.adapter == "codelldb" && arguments.get("sourceLanguages").is_none() {
arguments["sourceLanguages"] = json!(["rust"]);
}
@@ -992,8 +984,8 @@ impl DebugManager {
}
pub async fn stack_trace(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<Vec<StackFrame>> {
let session = self.session(s)?;
let body = session
let body = self
.session(s)?
.conn
.request_timeout(
"stackTrace",
@@ -1001,14 +993,11 @@ impl DebugManager {
REQUEST_TIMEOUT,
)
.await?;
let frame = |f: &Value| {
let mut frame = frame_from(f);
if let Some(client) = frame.path.as_deref().and_then(|p| session.client_path(&p.to_string_lossy())) {
frame.path = Some(client.into());
}
frame
};
Ok(body.get("stackFrames").and_then(Value::as_array).map(|f| f.iter().map(frame).collect()).unwrap_or_default())
Ok(body
.get("stackFrames")
.and_then(Value::as_array)
.map(|f| f.iter().map(frame_from).collect())
.unwrap_or_default())
}
pub async fn scopes(&self, s: DebugSessionId, frame_id: i64) -> IdeResult<Vec<Scope>> {
+3 -39
Переглянути файл
@@ -51,16 +51,9 @@ pub(crate) struct Session {
pub pending_restore: Mutex<PendingRestore>,
/// Adapter breakpoint id → (file, index in the stored list).
pub breakpoint_ids: Mutex<HashMap<i64, (PathBuf, usize)>>,
/// Resolved path → the path as the IDE knows it, for adapters given resolved paths.
resolved_paths: Mutex<HashMap<PathBuf, PathBuf>>,
progress: Mutex<HashMap<String, TaskId>>,
}
/// Adapters that only match files by their resolved path: Godot maps a script to
/// `res://` by prefix and silently never stops at a breakpoint set through a
/// symlinked path (`/tmp/game` while the editor has `/private/tmp/game`).
const RESOLVES_PATHS: &[&str] = &["godot"];
impl Session {
#[allow(clippy::too_many_arguments)]
pub fn new(
@@ -93,7 +86,6 @@ impl Session {
terminated: AtomicBool::new(false),
pending_restore: Mutex::default(),
breakpoint_ids: Mutex::new(HashMap::new()),
resolved_paths: Mutex::new(HashMap::new()),
progress: Mutex::new(HashMap::new()),
}
}
@@ -102,25 +94,6 @@ impl Session {
self.owner.sink.emit(IdeEvent::Debug { session: self.id, event });
}
/// `path` as sent to the adapter (resolved for [`RESOLVES_PATHS`] adapters).
pub fn adapter_path(&self, path: &Path) -> PathBuf {
if !RESOLVES_PATHS.contains(&self.adapter.as_str()) {
return path.to_path_buf();
}
match std::fs::canonicalize(path) {
Ok(real) if real != path => {
self.resolved_paths.lock().insert(real.clone(), path.to_path_buf());
real
}
_ => path.to_path_buf(),
}
}
/// A path from the adapter as the IDE knows it (undoes [`Session::adapter_path`]).
pub fn client_path(&self, path: &str) -> Option<PathBuf> {
self.resolved_paths.lock().get(Path::new(path)).cloned()
}
pub fn supports(&self, cap: &str) -> bool {
self.caps.lock().get(cap).and_then(Value::as_bool).unwrap_or(false)
}
@@ -162,7 +135,7 @@ impl Session {
.request_timeout(
"setBreakpoints",
json!({
"source": { "path": self.adapter_path(path), "name": name },
"source": { "path": path, "name": name },
"breakpoints": source_bps,
"sourceModified": false,
}),
@@ -338,11 +311,7 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, body:
s.emit(DebugEvent::BreakpointsChanged { path: path.into() });
}
}
// Godot repeats `exited` / `terminated` when the client disconnects afterwards.
"exited" if !s.terminated.load(Ordering::Acquire) => {
s.emit(DebugEvent::Exited { code: int("exitCode").unwrap_or(0) as i32 })
}
"exited" => {}
"exited" => s.emit(DebugEvent::Exited { code: int("exitCode").unwrap_or(0) as i32 }),
"terminated" => {
if !s.terminated.swap(true, Ordering::AcqRel) {
s.emit(DebugEvent::Terminated);
@@ -422,12 +391,7 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
};
let mut cmd = tokio::process::Command::new(program);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(rest)
.envs(ide_core::process::shell_env())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
cmd.args(rest).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
if let Some(cwd) = args.get("cwd").and_then(Value::as_str).filter(|c| !c.is_empty()) {
cmd.current_dir(cwd);
}
-134
Переглянути файл
@@ -881,137 +881,3 @@ async fn hot_swap_only_for_java_debug() {
let failed = hot_swap_result(&json!({"changedClasses": [], "errorMessage": "boom"}));
assert_eq!(failed.error_message.as_deref(), Some("boom"));
}
fn godot_registry(port: u16, command: &str, args: &[&str]) -> Arc<LanguageRegistry> {
let lang = ide_language::LanguageConfig {
id: ide_core::LanguageId::new("gdscript"),
name: "GDScript".into(),
extensions: vec!["gd".into()],
filenames: vec![],
first_line: None,
line_comment: None,
block_comment: None,
indent: None,
ui_mode: None,
tree_sitter: None,
language_servers: vec![],
debugger: Some(ide_language::DebuggerConfig {
adapter: "godot".into(),
command: command.into(),
args: args.iter().map(|a| (*a).to_owned()).collect(),
transport: "tcp".into(),
connect: Some(format!("127.0.0.1:{port}")),
install_hint: Some("Open the project in the Godot editor".into()),
}),
};
Arc::new(LanguageRegistry::from_configs(vec![lang]))
}
fn godot_launch(project: &std::path::Path) -> LaunchConfig {
LaunchConfig {
name: "Main Scene".into(),
adapter: "godot".into(),
request: "launch".into(),
program: None,
args: vec![],
cwd: Some(project.to_path_buf().into()),
env: BTreeMap::new(),
extra_json: Some(json!({"project": project, "scene": "main"}).to_string()),
}
}
/// Godot's debug adapter runs inside the editor (port 6006): an open editor is
/// used as is, nothing is started.
#[tokio::test]
async fn godot_connects_to_the_editor_adapter() {
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let log: Log = Arc::default();
let server_log = log.clone();
tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
fake_adapter(stream, server_log, Script::default()).await;
});
let (owner, _events) = recording_owner("main");
let manager = DebugManager::new(godot_registry(port, "openidea-no-such-godot", &[]));
let project = std::env::temp_dir();
let id = manager.start(godot_launch(&project), owner).await.unwrap();
let launch = log.lock().iter().find(|m| m["command"] == "launch").cloned().unwrap();
assert_eq!(launch["arguments"]["scene"], "main");
assert_eq!(launch["arguments"]["project"], json!(std::fs::canonicalize(&project).unwrap()));
assert!(log.lock().iter().any(|m| m["command"] == "configurationDone"));
manager.stop(id).await.unwrap();
}
#[tokio::test]
async fn godot_without_editor_or_executable_says_what_to_do() {
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let (owner, _events) = recording_owner("main");
let manager = DebugManager::new(godot_registry(port, "openidea-no-such-godot", &[]));
let err = manager.start(godot_launch(&std::env::temp_dir()), owner).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
assert!(err.message.contains("Open the project in the Godot editor"), "{}", err.message);
}
/// No editor open: the command (a headless editor) is started for the project and
/// the client connects once it listens; the started process ends with the session.
#[cfg(unix)]
#[tokio::test]
async fn godot_starts_a_headless_editor_when_none_is_open() {
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let log: Log = Arc::default();
let server_log = log.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.unwrap();
let (stream, _) = listener.accept().await.unwrap();
fake_adapter(stream, server_log, Script::default()).await;
});
let (owner, _events) = recording_owner("main");
// `sleep` stands in for `godot --headless --editor --path ${root} …`.
let manager = DebugManager::new(godot_registry(port, "sleep", &["30"]));
let id = manager.start(godot_launch(&std::env::temp_dir()), owner).await.unwrap();
assert!(log.lock().iter().any(|m| m["command"] == "launch"));
manager.stop(id).await.unwrap();
}
/// Godot never stops at a breakpoint given through a symlinked path (it maps scripts
/// to `res://` by its resolved project path): breakpoints and `project` go out resolved.
#[cfg(unix)]
#[tokio::test]
async fn godot_gets_resolved_paths() {
let real = std::env::temp_dir().join(format!("openidea-godot-real-{}", std::process::id()));
let link = std::env::temp_dir().join(format!("openidea-godot-link-{}", std::process::id()));
std::fs::create_dir_all(&real).unwrap();
std::fs::write(real.join("player.gd"), "extends Node\n").unwrap();
let _ = std::fs::remove_file(&link);
std::os::unix::fs::symlink(&real, &link).unwrap();
let real = std::fs::canonicalize(&real).unwrap();
let log: Log = Arc::default();
let (owner, _events) = recording_owner("main");
let manager = DebugManager::with_launcher(
godot_registry(1, "godot", &[]),
Arc::new(FakeLauncher { log: log.clone(), script: Script::default() }),
);
let bp = Breakpoint { line: 0, condition: None, hit_condition: None, log_message: None, enabled: true };
manager.set_breakpoints(link.join("player.gd"), vec![bp]).await.unwrap();
let id = manager.start(godot_launch(&link), owner).await.unwrap();
let sent = log.lock().iter().find(|m| m["command"] == "setBreakpoints").cloned().unwrap();
assert_eq!(sent["arguments"]["source"]["path"], json!(real.join("player.gd")));
let launch = log.lock().iter().find(|m| m["command"] == "launch").cloned().unwrap();
assert_eq!(launch["arguments"]["project"], json!(real));
manager.stop(id).await.unwrap();
std::fs::remove_file(&link).ok();
std::fs::remove_dir_all(&real).ok();
}
#[test]
fn root_and_address_placeholders() {
let args: Vec<String> = ["--path", "${root}", "--dap-port", "${port}"].iter().map(|s| s.to_string()).collect();
let args = adapter::substitute_port(&adapter::substitute_root(&args, std::path::Path::new("/g")), 6010);
assert_eq!(args, ["--path", "/g", "--dap-port", "6010"]);
assert_eq!(adapter::parse_address("127.0.0.1:6006"), Some(("127.0.0.1".into(), 6006)));
assert_eq!(adapter::parse_address("[::1]:6006"), Some(("::1".into(), 6006)));
assert_eq!(adapter::parse_address("6006"), None);
}
-157
Переглянути файл
@@ -1,157 +0,0 @@
//! Drives Godot's debug adapter (inside the Godot editor) with the GDScript
//! language definition: a headless editor is started for the project, the main
//! scene is played, a breakpoint hits, stack / variables / stepping work, and the
//! game and the editor end with the session.
//!
//! Ignored by default (needs Godot 4). Run with
//! `GODOT_BIN=<godot executable> cargo test -p ide-dap --test godot -- --ignored --nocapture`.
use ide_core::event::DebugEvent;
use ide_core::{IdeEvent, SharedSink};
use ide_dap::*;
use ide_language::{LanguageConfig, LanguageRegistry};
use parking_lot::Mutex;
use std::collections::BTreeMap;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
const SCRIPT: &str = "extends Node
var health: int = 3
func _ready() -> void:
\tvar total := add(2, 3)
\tprint(\"total = \", total)
\thealth -= 1
\tget_tree().quit()
func add(a: int, b: int) -> int:
\treturn a + b
";
/// 0-based line of `return a + b`.
const BREAK_LINE: u32 = 11;
fn project(dir: &Path) {
std::fs::write(
dir.join("project.godot"),
"config_version=5\n\n[application]\nconfig/name=\"Probe\"\nrun/main_scene=\"res://main.tscn\"\n",
)
.unwrap();
std::fs::write(
dir.join("main.tscn"),
"[gd_scene load_steps=2 format=3]\n\n[ext_resource type=\"Script\" path=\"res://player.gd\" id=\"1\"]\n\n[node name=\"Main\" type=\"Node\"]\nscript = ExtResource(\"1\")\n",
)
.unwrap();
std::fs::write(dir.join("player.gd"), SCRIPT).unwrap();
}
/// The built-in GDScript definition, with the editor's usual port moved aside so an
/// open editor can't answer instead of the one this test starts.
fn registry() -> Arc<LanguageRegistry> {
let builtin = LanguageRegistry::load(None).unwrap();
let mut gd: LanguageConfig = builtin.get(&ide_core::LanguageId::new("gdscript")).unwrap();
let dbg = gd.debugger.as_mut().unwrap();
let unused = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
dbg.connect = Some(format!("127.0.0.1:{unused}"));
Arc::new(LanguageRegistry::from_configs(vec![gd]))
}
async fn wait_for(events: &Mutex<Vec<IdeEvent>>, timeout: Duration, pred: impl Fn(&DebugEvent) -> bool) -> DebugEvent {
let start = Instant::now();
loop {
if let Some(e) = events.lock().iter().find_map(|e| match e {
IdeEvent::Debug { event, .. } if pred(event) => Some(event.clone()),
_ => None,
}) {
return e;
}
assert!(start.elapsed() < timeout, "timed out; events: {:#?}", events.lock());
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
fn godot_processes(project: &Path) -> usize {
let out = std::process::Command::new("pgrep").args(["-f", &project.to_string_lossy()]).output().unwrap();
String::from_utf8_lossy(&out.stdout).lines().count()
}
#[tokio::test(flavor = "multi_thread")]
#[ignore]
async fn breakpoints_stepping_and_variables_in_a_real_godot() {
let Ok(godot) = std::env::var("GODOT_BIN") else {
eprintln!("GODOT_BIN not set; skipping");
return;
};
let dir = std::env::temp_dir().join(format!("openidea-godot-dap-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let root = std::fs::canonicalize(&dir).unwrap();
project(&root);
let manager = DebugManager::new(registry());
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
let sink: SharedSink = {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let script_as_opened = dir.join("player.gd");
manager
.set_breakpoints(
script_as_opened.clone(),
vec![Breakpoint {
line: BREAK_LINE,
condition: None,
hit_condition: None,
log_message: None,
enabled: true,
}],
)
.await
.unwrap();
// As the UI builds it for "Godot Project" (`godot --path .`).
let config = LaunchConfig {
name: "Godot Project".into(),
adapter: "godot".into(),
request: "launch".into(),
program: None,
args: vec![],
// The project as opened, through a symlink on macOS (`/var` → `/private/var`).
cwd: Some(dir.clone().into()),
env: BTreeMap::new(),
extra_json: Some(serde_json::json!({ "project": dir, "scene": "main" }).to_string()),
};
let id = manager
.start_with(config, SessionOwner::new("main", sink), |_| Some(godot.clone()))
.await
.unwrap_or_else(|e| panic!("start: {e:?}"));
let stopped = wait_for(&events, Duration::from_secs(120), |e| matches!(e, DebugEvent::Stopped { .. })).await;
let DebugEvent::Stopped { thread_id, .. } = stopped else { unreachable!() };
let frames = manager.stack_trace(id, thread_id).await.unwrap();
assert_eq!(frames[0].name, "add");
assert_eq!(frames[0].line, BREAK_LINE);
// Frames name the file as the IDE opened it, not Godot's resolved path.
assert_eq!(frames[0].path.as_deref().map(Path::new), Some(script_as_opened.as_path()));
assert_eq!(frames[1].name, "_ready");
let scopes = manager.scopes(id, frames[0].id).await.unwrap();
let locals = scopes.iter().find(|s| s.name == "Locals").expect("Locals scope");
let vars = manager.variables(id, locals.variables_reference).await.unwrap();
let value = |n: &str| vars.iter().find(|v| v.name == n).map(|v| v.value.clone());
assert_eq!((value("a").as_deref(), value("b").as_deref()), (Some("2"), Some("3")), "{vars:?}");
events.lock().clear();
manager.step(id, thread_id, StepKind::Over).await.unwrap();
wait_for(&events, Duration::from_secs(30), |e| matches!(e, DebugEvent::Stopped { .. })).await;
let frames = manager.stack_trace(id, thread_id).await.unwrap();
assert_eq!((frames[0].name.as_str(), frames[0].line), ("_ready", 6), "stepped back into `_ready`, at the print");
manager.resume(id, thread_id).await.unwrap();
// (The game's last output is not always forwarded when it quits right away.)
wait_for(&events, Duration::from_secs(30), |e| matches!(e, DebugEvent::Terminated)).await;
let _ = manager.stop(id).await;
// The headless editor started for the session ends with it, the game too.
let start = Instant::now();
while godot_processes(&root) > 0 {
assert!(start.elapsed() < Duration::from_secs(10), "Godot still running for {}", root.display());
tokio::time::sleep(Duration::from_millis(200)).await;
}
std::fs::remove_dir_all(&root).ok();
}
+2 -27
Переглянути файл
@@ -312,7 +312,6 @@ impl Peer {
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(args)
.current_dir(cwd)
.envs(ide_core::process::shell_env())
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
@@ -345,13 +344,7 @@ impl Peer {
});
}
peer.supervise(child);
Ok(peer)
}
/// Kills `child` when the connection is torn down; closes the connection when it exits.
fn supervise(&self, mut child: tokio::process::Child) {
let inner = self.inner.clone();
let inner = peer.inner.clone();
tokio::spawn(async move {
let status = tokio::select! {
status = child.wait() => status.ok(),
@@ -362,6 +355,7 @@ impl Peer {
};
inner.mark_closed(status.and_then(|s| s.code()));
});
Ok(peer)
}
/// Speaks JSON-RPC over arbitrary byte streams (in-memory pipes in tests, TCP sockets).
@@ -385,25 +379,6 @@ impl Peer {
Self::start(reader, writer, handler, true, None, framing)
}
/// [`Peer::connect`] over streams served by `child` (a server reached over a socket
/// it listens on): the child is killed with the connection, and its exit closes it.
///
/// Must be called from within a Tokio runtime.
pub fn connect_with_child<R, W>(
reader: R,
writer: W,
handler: Arc<dyn Handler>,
child: tokio::process::Child,
) -> Self
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
let peer = Self::start(reader, writer, handler, true, child.id(), Framing::ContentLength);
peer.supervise(child);
peer
}
fn start<R, W>(
reader: R,
mut writer: W,
-1
Переглянути файл
@@ -53,7 +53,6 @@ tree-sitter-xml = "0.7.0"
tree-sitter-haskell = "0.23.1"
tree-sitter-dart = "0.2.0"
tree-sitter-graphql = "0.3.0"
tree-sitter-gdscript = "6.1.0"
[dev-dependencies]
criterion = { version = "0.5", default-features = false }
-60
Переглянути файл
@@ -1,60 +0,0 @@
; GDScript highlighting (the grammar crate ships no query). Later patterns win.
(identifier) @variable
(name) @variable
(comment) @comment
[(region_start) (region_end)] @comment
(string) @string
(escape_sequence) @string.escape
[(string_name) (node_path) (get_node)] @string.special
(integer) @number
(float) @number
[(true) (false) (null)] @constant.builtin
(type) @type
(type (identifier) @type)
(extends_statement (type) @type)
(class_name_statement name: (name) @type)
(class_definition name: (name) @type)
(enum_definition name: (name) @type)
(enumerator left: (identifier) @constant)
(function_definition name: (name) @function.definition)
(constructor_definition "_init" @function.definition)
(lambda name: (name) @function.definition)
(signal_statement name: (name) @function.definition)
(call (identifier) @function)
(attribute_call (identifier) @function)
(base_call (identifier) @function)
(attribute (identifier) (identifier) @variable.member)
((identifier) @constant
(#lua-match? @constant "^[A-Z][A-Z_0-9]*$"))
((identifier) @variable.builtin
(#lua-match? @variable.builtin "^self$"))
(const_statement name: (name) @constant)
(typed_parameter (identifier) @variable.parameter)
(default_parameter (identifier) @variable.parameter)
(typed_default_parameter (identifier) @variable.parameter)
(annotation "@" @attribute (identifier) @attribute)
[(remote_keyword) (static_keyword)] @keyword
[(breakpoint_statement) (pass_statement) (break_statement) (continue_statement)] @keyword
[
"if" "elif" "else" "for" "while" "match" "when" "return" "await"
"func" "class" "class_name" "extends" "signal" "enum" "const" "var"
"set" "get" "setget" "onready" "export" "in" "is" "as" "and" "or" "not"
] @keyword
[
"+" "-" "*" "/" "%" "**" "<<" ">>" "&" "|" "^" "~" "!" "&&" "||"
"==" "!=" "<" "<=" ">" ">=" "=" ":=" "+=" "-=" "*=" "/=" "%=" "**="
"<<=" ">>=" "&=" "|=" "^=" "->"
] @operator
["(" ")" "[" "]" "{" "}"] @punctuation.bracket
["," "." ":" ";"] @punctuation.delimiter
-14
Переглянути файл
@@ -1,14 +0,0 @@
(class_name_statement name: (name) @name) @def.class
(class_definition name: (name) @name) @def.class
(function_definition name: (name) @name parameters: (parameters) @detail) @def.function
(constructor_definition "_init" @name parameters: (parameters) @detail) @def.constructor
(signal_statement name: (name) @name) @def.event
(enum_definition name: (name) @name) @def.enum
(enumerator left: (identifier) @name) @def.enum_member
(const_statement name: (name) @name) @def.constant
(source (variable_statement name: (name) @name) @def.field)
(source (export_variable_statement name: (name) @name) @def.field)
(source (onready_variable_statement name: (name) @name) @def.field)
(class_body (variable_statement name: (name) @name) @def.field)
(class_body (export_variable_statement name: (name) @name) @def.field)
(class_body (onready_variable_statement name: (name) @name) @def.field)
-12
Переглянути файл
@@ -75,14 +75,6 @@ pub struct LanguageServerConfig {
/// Human hint shown when the binary is missing.
#[serde(default)]
pub install_hint: Option<String>,
/// `host:port` of a server that speaks LSP over TCP (Godot's editor). Connects
/// there when something listens; otherwise starts `command` (when installed)
/// and connects once it accepts: to `127.0.0.1:${port}` when the arguments
/// contain `${port}` (a free port), else to this address. `${root}` in the
/// arguments is the workspace root. A server reached without starting it is
/// never shut down or killed by the IDE.
#[serde(default)]
pub connect: Option<String>,
/// An alternative to the servers listed before it (pyright after
/// basedpyright): only used while none of those is installed.
#[serde(default)]
@@ -104,10 +96,6 @@ pub struct DebuggerConfig {
/// `stdio` or `tcp`.
#[serde(default = "default_transport")]
pub transport: String,
/// `tcp` only: `host:port` of an adapter running inside another program (the
/// Godot editor). Used when it accepts connections; otherwise `command` is started.
#[serde(default)]
pub connect: Option<String>,
#[serde(default)]
pub install_hint: Option<String>,
}
-38
Переглянути файл
@@ -22,12 +22,9 @@ const BUILTIN: &[(&str, &str)] = &[
("erlang", include_str!("../../../languages/erlang.toml")),
("fsharp", include_str!("../../../languages/fsharp.toml")),
("gitattributes", include_str!("../../../languages/gitattributes.toml")),
("gdscript", include_str!("../../../languages/gdscript.toml")),
("gdshader", include_str!("../../../languages/gdshader.toml")),
("go", include_str!("../../../languages/go.toml")),
("gomod", include_str!("../../../languages/gomod.toml")),
("gowork", include_str!("../../../languages/gowork.toml")),
("godot-resource", include_str!("../../../languages/godot-resource.toml")),
("graphql", include_str!("../../../languages/graphql.toml")),
("groovy", include_str!("../../../languages/groovy.toml")),
("haskell", include_str!("../../../languages/haskell.toml")),
@@ -545,17 +542,10 @@ mod tests {
}
for ls in &cfg.language_servers {
assert!(!ls.command.is_empty() && ls.install_hint.is_some(), "{name}: {} incomplete", ls.name);
if let Some(addr) = &ls.connect {
assert!(addr.parse::<std::net::SocketAddr>().is_ok(), "{name}: bad connect address {addr}");
}
}
if let Some(d) = &cfg.debugger {
assert!(matches!(d.transport.as_str(), "stdio" | "tcp"), "{name}: bad transport");
assert!(d.install_hint.is_some(), "{name}: debugger without install hint");
if let Some(addr) = &d.connect {
assert_eq!(d.transport, "tcp", "{name}: `connect` needs the tcp transport");
assert!(addr.parse::<std::net::SocketAddr>().is_ok(), "{name}: bad connect address {addr}");
}
}
for ext in &cfg.extensions {
assert_eq!(ext, &ext.to_ascii_lowercase(), "{name}: extensions must be lower case");
@@ -689,13 +679,6 @@ mod tests {
(".gitignore", "ignore"),
(".gitattributes", "gitattributes"),
("server.log", "log"),
("player.gd", "gdscript"),
("main.tscn", "godot-resource"),
("theme.tres", "godot-resource"),
("project.godot", "godot-resource"),
("icon.svg.import", "godot-resource"),
("export_presets.cfg", "godot-resource"),
("water.gdshader", "gdshader"),
("notes.txt", "plaintext"),
];
for (path, id) in cases {
@@ -703,27 +686,6 @@ mod tests {
}
}
#[test]
fn gdscript_definition() {
let reg = reg();
let gd = reg.get(&LanguageId::new("gdscript")).unwrap();
assert_eq!(gd.line_comment.as_deref(), Some("#"));
let indent = gd.indent.unwrap();
assert!(!indent.insert_spaces, "Godot indents with tabs");
assert_eq!(gd.tree_sitter.as_deref(), Some("gdscript"));
let ls = &gd.language_servers[0];
assert_eq!((ls.name.as_str(), ls.command.as_str()), ("godot", "godot"));
assert_eq!(ls.connect.as_deref(), Some("127.0.0.1:6005"));
assert_eq!(ls.root_markers, ["project.godot"]);
assert!(ls.args.iter().any(|a| a == "${port}") && ls.args.iter().any(|a| a == "${root}"));
let dbg = gd.debugger.as_ref().unwrap();
assert_eq!((dbg.adapter.as_str(), dbg.transport.as_str()), ("godot", "tcp"));
assert_eq!(dbg.connect.as_deref(), Some("127.0.0.1:6006"));
assert!(dbg.args.iter().any(|a| a == "--dap-port"));
let res = reg.get(&LanguageId::new("godot-resource")).unwrap();
assert_eq!(res.line_comment.as_deref(), Some(";"));
}
#[test]
fn detects_shebangs() {
let reg = reg();
-10
Переглянути файл
@@ -450,14 +450,4 @@ pub(crate) static SPECS: &[Spec] = &[
imports: NONE,
constructors: NONE,
},
Spec {
name: "gdscript",
language: tree_sitter_gdscript::LANGUAGE,
outline: outline!("gdscript"),
highlights: Some(Highlights { query: highlights!("gdscript"), first_wins: false }),
fold_nodes: &["string"],
fold_bodies: &["body", "class_body", "match_body"],
imports: NONE,
constructors: &["_init"],
},
];
-25
Переглянути файл
@@ -440,31 +440,6 @@ mod tests {
],
),
("make", "# hi\nCC := gcc\nall: main.o\n\t$(CC) -o app main.o\n", &[("# hi", K::Comment)]),
(
"gdscript",
"extends Node2D\nclass_name Player\n# hi\n@export var speed: float = 1.5\nconst MAX_HP = 10\nsignal died(cause)\n\nfunc _ready() -> void:\n\tvar label = $Label\n\tself.position.x += speed\n\tprint(\"ready\", &\"name\", 3)\n",
&[
("extends", K::Keyword),
("Node2D", K::Type),
("class_name", K::Keyword),
("Player", K::Type),
("# hi", K::Comment),
("@export", K::Attribute),
("var", K::Keyword),
("float", K::Type),
("1.5", K::Number),
("MAX_HP", K::Constant),
("signal", K::Keyword),
("func", K::Keyword),
("_ready", K::Function),
("$Label", K::StringSpecial),
("self", K::SelfVariable),
("print", K::FunctionCall),
("\"ready\"", K::String),
("&\"name\"", K::StringSpecial),
("3", K::Number),
],
),
];
for (lang, src, expect) in cases {
let got = spans(lang, src);
-18
Переглянути файл
@@ -902,24 +902,6 @@ fn outline_more_languages() {
Function build
",
);
check_outline(
"gdscript",
"class_name Player\nextends Node\n\nsignal died\nenum State { IDLE, RUN }\nconst SPEED = 2\n@export var hp := 3\n\nfunc _init(a):\n\tpass\n\nfunc jump(height: float) -> void:\n\tvar local = 1\n\nclass Inner:\n\tvar x = 0\n\tfunc go():\n\t\tpass\n",
"
Class Player
Event died
Enum State
EnumMember IDLE
EnumMember RUN
Constant SPEED
Field hp
Constructor _init
Function jump
Class Inner
Field x
Method go
",
);
check_outline(
"cmake",
"project(Foo)\nfunction(my_fn arg)\n message(${arg})\nendfunction()\nadd_executable(app main.c)\n",
+1 -1
Переглянути файл
@@ -14,7 +14,7 @@ lsp-types.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
tokio = { workspace = true, features = ["net"] }
tokio.workspace = true
parking_lot.workspace = true
tracing.workspace = true
futures.workspace = true
-8
Переглянути файл
@@ -75,12 +75,8 @@ impl ClientHandler {
_ => return,
}
};
let ended = matches!(&event, IdeEvent::Task { done: true, .. });
mgr.sink().emit(event);
self.server.refresh_busy_status(mgr.sink());
if ended {
self.server.progress_ended();
}
}
fn publish_diagnostics(&self, mgr: &LspManager, params: Value) {
@@ -92,10 +88,6 @@ impl ClientHandler {
}
};
let Some(path) = uri_to_path(params.uri.as_str()) else { return };
// Files opened only for a request (references search) are not the user's problems.
if self.server.suppresses_diagnostics(&path) {
return;
}
let conv = mgr.conv(self.encoding());
let items = params
.diagnostics
+3 -44
Переглянути файл
@@ -1,6 +1,5 @@
//! Starting server processes: binary resolution and the [`Launcher`] seam.
use ide_core::CancellationToken;
use ide_jsonrpc::{Handler, Peer};
use ide_language::LanguageServerConfig;
use std::ffi::OsString;
@@ -28,28 +27,13 @@ pub trait Launcher: Send + Sync + 'static {
on_stderr: Box<dyn Fn(String) + Send + Sync>,
) -> Result<Peer, LaunchError>;
/// [`Launcher::launch`] that gives up once `cancel` fires (the server was stopped
/// while still starting). Launchers that return at once need not override it.
fn launch_cancellable(
&self,
config: &LanguageServerConfig,
root: &Path,
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
cancel: &CancellationToken,
) -> Result<Peer, LaunchError> {
let _ = cancel;
self.launch(config, root, handler, on_stderr)
}
/// Whether `config` could start without a `Missing` error.
fn available(&self, _config: &LanguageServerConfig, _root: &Path) -> bool {
true
}
}
/// Resolves `command` on an augmented `PATH` and spawns it with stdio transport,
/// or for a `connect` server reaches it over TCP (see [`crate::tcp`]).
/// Resolves `command` on an augmented `PATH` and spawns it with stdio transport.
pub struct ProcessLauncher;
impl Launcher for ProcessLauncher {
@@ -59,37 +43,12 @@ impl Launcher for ProcessLauncher {
root: &Path,
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
) -> Result<Peer, LaunchError> {
self.launch_cancellable(config, root, handler, on_stderr, &CancellationToken::new())
}
fn launch_cancellable(
&self,
config: &LanguageServerConfig,
root: &Path,
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
cancel: &CancellationToken,
) -> Result<Peer, LaunchError> {
let search = server_search_path(config);
let binary = which::which_in(&config.command, Some(&search), root)
.ok()
.map(|b| resolve_rustup_proxy(&config.command, b));
let binary = which::which_in(&config.command, Some(&search), root).map_err(|_| LaunchError::Missing)?;
let binary = resolve_rustup_proxy(&config.command, binary);
let mut env: Vec<(String, String)> = vec![("PATH".into(), search.to_string_lossy().into_owned())];
env.extend(config.env.iter().filter(|(k, _)| *k != "PATH").map(|(k, v)| (k.clone(), v.clone())));
if let Some(addr) = &config.connect {
return crate::tcp::connect_or_start(
config,
addr,
binary.as_deref(),
&env,
root,
handler,
on_stderr,
cancel,
);
}
let binary = binary.ok_or(LaunchError::Missing)?;
Peer::spawn(&binary.to_string_lossy(), &config.args, root, &env, handler, on_stderr)
.map_err(|e| LaunchError::Failed(format!("failed to start {}: {e}", binary.display())))
}
+77 -151
Переглянути файл
@@ -13,9 +13,7 @@ mod handler;
mod inspect;
pub mod jdtls;
mod launch;
mod scope;
mod server;
mod tcp;
mod text;
mod tsserver_bridge;
pub mod types;
@@ -24,7 +22,6 @@ mod virtual_doc;
pub use inspect::{FileInspection, InspectHost, InspectOptions};
pub use launch::{LaunchError, Launcher, ProcessLauncher, search_path};
pub use scope::{CandidateFiles, CandidateFn, CandidateQuery, MAX_CANDIDATES};
pub use uri::{is_virtual_uri, path_to_uri_string, uri_target, uri_to_path};
use caps::{ServerCaps, SyncKind};
@@ -145,7 +142,6 @@ pub struct LspManager {
docs: Mutex<HashMap<DocId, DocState>>,
apply_edit_hook: RwLock<Option<ApplyEditHook>>,
config_hook: RwLock<Option<ConfigHook>>,
candidates_hook: RwLock<Option<Arc<CandidateFn>>>,
shutting_down: AtomicBool,
/// `window/showMessage` texts already surfaced; servers repeat them on every restart/reconfigure.
shown_messages: Mutex<HashSet<(String, String)>>,
@@ -186,19 +182,6 @@ fn rpc_err(server: &str, method: &str, e: RpcError) -> IdeError {
}
}
/// Sends the user's `didOpen` for `path`, closing a transient copy of the file
/// first (one a references search opened).
fn user_did_open(server: &Server, run: &Running, path: &Path, uri: &lsp::Uri, params: Value) {
if server.take_transient(path, run.generation)
&& let Err(e) = run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": uri } }))
{
tracing::debug!("{}: didClose: {e}", server.name);
}
if let Err(e) = run.peer.notify("textDocument/didOpen", params) {
tracing::debug!("{}: didOpen: {e}", server.name);
}
}
fn unsupported(feature: &str) -> IdeError {
IdeError::unavailable(format!("no running language server supports {feature}"))
}
@@ -251,7 +234,6 @@ impl LspManager {
docs: Mutex::new(HashMap::new()),
apply_edit_hook: RwLock::new(None),
config_hook: RwLock::new(None),
candidates_hook: RwLock::new(None),
shutting_down: AtomicBool::new(false),
shown_messages: Mutex::new(HashSet::new()),
virtual_origins: Mutex::new(HashMap::new()),
@@ -316,8 +298,10 @@ impl LspManager {
}
let mut attached = Attached { server: server.clone(), opened_gen: None };
if let Some(run) = server.running() {
if run.caps.read().open_close {
user_did_open(&server, &run, &d.path, &d.uri, d.did_open_params());
if run.caps.read().open_close
&& let Err(e) = run.peer.notify("textDocument/didOpen", d.did_open_params())
{
tracing::debug!("{}: didOpen: {e}", server.name);
}
attached.opened_gen = Some(run.generation);
}
@@ -348,9 +332,7 @@ impl LspManager {
let handler = Arc::new(handler::ClientHandler::new(self.me.clone(), server.clone(), generation));
let me = self.clone();
let tail = server.clone();
let cancel = server.start_token();
// The settings hook may touch the filesystem (e.g. scanning for JDKs); TCP
// servers may take a while to start listening.
// The settings hook may touch the filesystem (e.g. scanning for JDKs).
let launched = tokio::task::spawn_blocking(move || {
let cfg = me.configured(&tail);
tail.set_effective_config(cfg.clone());
@@ -360,7 +342,7 @@ impl LspManager {
let missing = !me.launcher.available(&cfg, &root);
return Err(if missing { LaunchError::Missing } else { LaunchError::Config(message.clone()) });
}
me.launcher.launch_cancellable(&cfg, &root, handler, Box::new(move |line| tail.push_stderr(line)), &cancel)
me.launcher.launch(&cfg, &root, handler, Box::new(move |line| tail.push_stderr(line)))
})
.await
.unwrap_or_else(|e| Err(LaunchError::Failed(e.to_string())));
@@ -462,11 +444,9 @@ impl LspManager {
return;
}
let tail = server.stderr_tail(5);
let cfg = server.effective_config();
let mut message = match (code, &cfg.connect) {
(Some(c), _) => format!("{} exited with code {c}", server.name),
(None, Some(addr)) => format!("{}: the connection to the server ({addr}) closed", server.name),
(None, None) => format!("{} terminated unexpectedly", server.name),
let mut message = match code {
Some(c) => format!("{} exited with code {c}", server.name),
None => format!("{} terminated unexpectedly", server.name),
};
if !tail.is_empty() {
message.push_str(":\n");
@@ -496,7 +476,6 @@ impl LspManager {
for (id, title) in server.take_progress() {
self.sink.emit(ide_core::IdeEvent::Task { id, title, message: None, fraction: None, done: true });
}
server.progress_ended();
for path in server.take_diagnostic_paths() {
self.sink.emit(ide_core::IdeEvent::Diagnostics {
path: path.into(),
@@ -612,8 +591,10 @@ impl LspManager {
let params = state.did_open_params();
for a in &mut state.servers {
if let Some(run) = a.server.running() {
if run.caps.read().open_close {
user_did_open(&a.server, &run, &state.path, &state.uri, params.clone());
if run.caps.read().open_close
&& let Err(e) = run.peer.notify("textDocument/didOpen", params.clone())
{
tracing::debug!("{}: didOpen: {e}", a.server.name);
}
a.opened_gen = Some(run.generation);
}
@@ -959,61 +940,40 @@ impl LspManager {
out.finish(Vec::new())
}
/// References of the symbol at `pos`. With `project_wide`, files outside
/// the servers' analysis scope that mention the name are opened for the
/// search (see [`scope`]); without, only what the servers analyse counts
/// (cheap, for bulk scans over many symbols).
pub async fn references(
&self,
doc: DocId,
pos: Pos,
include_declaration: bool,
project_wide: bool,
cancel: CancellationToken,
) -> IdeResult<References> {
pub async fn references(&self, doc: DocId, pos: Pos, include_declaration: bool) -> IdeResult<Vec<Location>> {
let (snap, targets) = self.doc_targets(doc, "find references", |c| c.has("referencesProvider")).await?;
let requests = targets.iter().map(|t| {
let (snap, cancel) = (&snap, &cancel);
let mut params = snap.pos_params(t, pos);
params["context"] = json!({ "includeDeclaration": include_declaration });
async move {
let query = || async move {
let mut params = snap.pos_params(t, pos);
params["context"] = json!({ "includeDeclaration": include_declaration });
let locs: Option<Vec<lsp::Location>> =
self.call(t, "textDocument/references", params, Some(cancel), LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
Ok(locs.unwrap_or_default().iter().filter_map(|l| conv.location(l)).collect::<Vec<Location>>())
};
let files =
|v: &Vec<Location>| v.iter().filter(|l| l.uri.is_none()).map(|l| l.path.to_path_buf()).collect();
let result = if project_wide {
self.widened(snap, t, pos, cancel, query, files).await
} else {
query().await.map(|first| {
let empty = first.is_empty();
scope::Widened::only(first, empty, &t.server)
})
};
(t, result)
(
t,
self.call::<_, Option<Vec<lsp::Location>>>(
t,
"textDocument/references",
params,
None,
LONG_TIMEOUT,
)
.await,
)
}
});
let mut out = Outcome::new();
for (t, r) in join_all(requests).await {
match r {
Ok(w) => {
let acc = out.value.get_or_insert_with(References::default);
let locs: Vec<Location> = w.first.into_iter().chain(w.second.into_iter().flatten()).collect();
Ok(locs) => {
let conv = self.conv(t.enc());
let locs: Vec<Location> =
locs.unwrap_or_default().iter().filter_map(|l| conv.location(l)).collect();
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
acc.locations.extend(locs);
acc.incomplete = acc.incomplete.or(w.incomplete);
out.value.get_or_insert_with(Vec::new).extend(locs);
}
Err(e) => out.fail(e),
}
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut v = out.finish(References::default())?;
convert::dedup_locations(&mut v.locations);
let mut v = out.finish(Vec::new())?;
convert::dedup_locations(&mut v);
Ok(v)
}
@@ -1243,29 +1203,13 @@ impl LspManager {
})
}
/// Renames across the project: like [`Self::references`], files outside the
/// server's analysis scope that mention the name are opened for the request.
pub async fn rename(&self, doc: DocId, pos: Pos, new_name: String) -> IdeResult<WorkspaceEdit> {
let (snap, targets) = self.doc_targets(doc, "rename", |c| c.has("renameProvider")).await?;
let t = &targets[0];
let query = || async {
let mut params = snap.pos_params(t, pos);
params["newName"] = json!(new_name);
let r: Option<lsp::WorkspaceEdit> = self.call(t, "textDocument/rename", params, None, LONG_TIMEOUT).await?;
Ok(r.map(|e| convert::workspace_edit(&self.conv(t.enc()), e)).unwrap_or_default())
};
let files = |e: &WorkspaceEdit| {
e.files
.iter()
.filter_map(|f| match f {
ide_core::FileEdit::Edit { path, .. } => Some(path.to_path_buf()),
_ => None,
})
.collect()
};
let w = self.widened(&snap, t, pos, &CancellationToken::new(), query, files).await?;
// The second edit covers the first: its files stay analysed.
Ok(w.second.unwrap_or(w.first))
let mut params = snap.pos_params(t, pos);
params["newName"] = json!(new_name);
let r: Option<lsp::WorkspaceEdit> = self.call(t, "textDocument/rename", params, None, LONG_TIMEOUT).await?;
Ok(r.map(|e| convert::workspace_edit(&self.conv(t.enc()), e)).unwrap_or_default())
}
// ---- file operations (`workspace/willRenameFiles`, `workspace/didRenameFiles`) ----
@@ -1314,17 +1258,16 @@ impl LspManager {
/// Some servers (tsserver) only answer for files of a loaded project: when
/// `t` has no document open, one moved file of its languages is opened for the request.
fn open_for_file_op(&self, t: &Target, moves: &[(PathBuf, PathBuf, bool)]) -> scope::TransientFiles<'_> {
let mut opened = scope::TransientFiles::empty(self, t);
fn open_for_file_op(&self, t: &Target, moves: &[(PathBuf, PathBuf, bool)]) -> Option<lsp::Uri> {
if !t.caps().open_close {
return opened;
return None;
}
let busy =
self.docs.lock().values().any(|d| {
d.servers.iter().any(|a| a.server.id == t.server.id && a.opened_gen == Some(t.run.generation))
});
let docs = self.docs.lock();
let busy = docs
.values()
.any(|d| d.servers.iter().any(|a| a.server.id == t.server.id && a.opened_gen == Some(t.run.generation)));
if busy {
return opened;
return None;
}
let languages = t.server.languages();
let candidate =
@@ -1339,10 +1282,14 @@ impl LspManager {
continue;
}
let Ok(text) = std::fs::read_to_string(&file) else { continue };
opened.hold(&file, &language, &text);
break;
let uri = uri::path_to_uri(&file);
let params =
json!({ "textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text } });
if t.run.peer.notify("textDocument/didOpen", params).is_ok() {
return Some(uri);
}
}
opened
None
}
/// Asks the servers for the edits that keep references intact when files or
@@ -1368,7 +1315,9 @@ impl LspManager {
let opened = self.open_for_file_op(&t, &moves);
let r: IdeResult<Option<lsp::WorkspaceEdit>> =
self.call(&t, "workspace/willRenameFiles", params, Some(&cancel), LONG_TIMEOUT).await;
drop(opened);
if let Some(uri) = opened {
let _ = t.run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": uri } }));
}
match r {
Ok(Some(edit)) => out.edit.files.extend(convert::workspace_edit(&self.conv(t.enc()), edit).files),
Ok(None) => {}
@@ -1565,46 +1514,32 @@ impl LspManager {
let items: Option<Vec<lsp::CallHierarchyItem>> =
self.call(t, "textDocument/prepareCallHierarchy", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await?;
let items = items.filter(|i| !i.is_empty()).ok_or_else(no_hierarchy_target)?;
let query = || async {
let mut out = Vec::new();
for item in &items {
let params = json!({ "item": item });
match direction {
HierarchyDirection::Incoming => {
let calls: Option<Vec<lsp::CallHierarchyIncomingCall>> =
self.call(t, "callHierarchy/incomingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
for c in calls.unwrap_or_default() {
let (path, _) = uri_target(c.from.uri.as_str());
let ranges = c.from_ranges.iter().map(|r| conv.range(&path, *r)).collect();
out.extend(convert::call_item(&conv, &c.from, ranges));
}
let mut out = Vec::new();
for item in items {
let params = json!({ "item": item });
match direction {
HierarchyDirection::Incoming => {
let calls: Option<Vec<lsp::CallHierarchyIncomingCall>> =
self.call(t, "callHierarchy/incomingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
for c in calls.unwrap_or_default() {
let (path, _) = uri_target(c.from.uri.as_str());
let ranges = c.from_ranges.iter().map(|r| conv.range(&path, *r)).collect();
out.extend(convert::call_item(&conv, &c.from, ranges));
}
HierarchyDirection::Outgoing => {
let calls: Option<Vec<lsp::CallHierarchyOutgoingCall>> =
self.call(t, "callHierarchy/outgoingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
let (src, _) = uri_target(item.uri.as_str());
for c in calls.unwrap_or_default() {
let ranges = c.from_ranges.iter().map(|r| conv.range(&src, *r)).collect();
out.extend(convert::call_item(&conv, &c.to, ranges));
}
}
HierarchyDirection::Outgoing => {
let calls: Option<Vec<lsp::CallHierarchyOutgoingCall>> =
self.call(t, "callHierarchy/outgoingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
let (src, _) = uri_target(item.uri.as_str());
for c in calls.unwrap_or_default() {
let ranges = c.from_ranges.iter().map(|r| conv.range(&src, *r)).collect();
out.extend(convert::call_item(&conv, &c.to, ranges));
}
}
}
Ok(out)
};
let out = match direction {
// Callers are references: they may sit in files outside the server's scope.
HierarchyDirection::Incoming => {
let files = |v: &Vec<HierarchyItem>| {
v.iter().filter(|i| i.uri.is_none()).map(|i| i.path.to_path_buf()).collect()
};
let w = self.widened(&snap, t, pos, &CancellationToken::new(), query, files).await?;
w.second.unwrap_or(w.first)
}
HierarchyDirection::Outgoing => query().await?,
};
}
self.note_virtual(&t.server, out.iter().map(|i| i.uri.as_deref()));
Ok(out)
}
@@ -1818,15 +1753,6 @@ impl LspManager {
return;
};
let peer = run.peer.clone();
// A server we connected to without starting it (an open Godot editor) is not
// ours to shut down: only the connection closes.
if peer.pid().is_none() && server.effective_config().connect.is_some() {
peer.kill();
server.end_stop(run.generation);
self.clear_server_state(server);
server.set_status(&self.sink, ide_core::event::ServerStatus::Stopped, None);
return;
}
let graceful = async {
peer.request::<_, Value>("shutdown", (), None).await.ok();
peer.notify("exit", ()).ok();
-248
Переглянути файл
@@ -1,248 +0,0 @@
//! Reference searches beyond a server's analysis scope.
//!
//! Servers answer `textDocument/references` (and rename, incoming calls) from
//! the files they analyse: their configured scope (Pyright's `include`, a
//! `tsconfig.json`, a compilation database) plus the open documents. Usages in
//! other project files are silently missing. So, as a word index would, the
//! project files of the server's languages that contain the symbol's name as a
//! whole word (found through the host's [`CandidateFn`]) and that the first
//! answer did not cover are opened on the server for a second request, then
//! closed again. Diagnostics the server publishes for them are dropped.
use crate::server::{Running, Server};
use crate::types::ReferencesIncomplete;
use crate::{DocSnap, LspManager, Target};
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId, Pos};
use lsp_types as lsp;
use serde_json::json;
use std::collections::HashSet;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
/// Files opened for one search at most.
pub const MAX_CANDIDATES: usize = 300;
/// Larger files (generated code, bundles) are not opened.
const MAX_CANDIDATE_BYTES: u64 = 1 << 20;
/// How long a search that found nothing waits for a server to finish indexing.
const INDEX_WAIT: Duration = Duration::from_secs(10);
/// Project files that may mention a symbol.
#[derive(Clone, Debug)]
pub struct CandidateQuery {
/// Matched as a whole word, case-sensitively.
pub word: String,
/// Only files under this directory (the server's workspace root).
pub root: PathBuf,
/// Only files of these languages.
pub languages: Vec<LanguageId>,
pub limit: usize,
}
#[derive(Clone, Debug, Default)]
pub struct CandidateFiles {
pub files: Vec<PathBuf>,
/// More files matched than `limit`.
pub limit_hit: bool,
}
/// Finds [`CandidateFiles`] (honouring the project's ignore rules); runs on a
/// blocking thread and should stop early when cancelled.
pub type CandidateFn = dyn Fn(&CandidateQuery, &CancellationToken) -> CandidateFiles + Send + Sync;
/// A reference-based answer and, when files were opened for it, the second one.
pub(crate) struct Widened<R> {
pub first: R,
pub second: Option<R>,
pub incomplete: Option<ReferencesIncomplete>,
}
impl<R> Widened<R> {
/// An answer from the server's analysis scope alone; `empty`: it found nothing.
pub fn only(first: R, empty: bool, server: &Server) -> Self {
let incomplete = (empty && server.is_busy()).then_some(ReferencesIncomplete::Indexing);
Self { first, second: None, incomplete }
}
}
/// The name a search is about: the word at `pos` (a PHP `$` sigil dropped).
fn search_word(snap: &DocSnap, pos: Pos) -> Option<String> {
let r = snap.text.word_range_at(pos)?;
let text = snap.text.as_str();
let word = text.get(snap.text.byte_offset(r.start)..snap.text.byte_offset(r.end))?.trim_start_matches('$');
(!word.is_empty() && !word.chars().all(|c| c.is_ascii_digit())).then(|| word.to_owned())
}
impl LspManager {
/// Finds the project files a references search may open (see the module docs).
pub fn set_candidates_hook(&self, hook: Box<CandidateFn>) {
*self.candidates_hook.write() = Some(Arc::from(hook));
}
async fn candidates(&self, t: &Target, word: String, cancel: &CancellationToken) -> Option<CandidateFiles> {
let hook = self.candidates_hook.read().clone()?;
let query = CandidateQuery {
word,
root: t.server.root.clone(),
languages: t.server.languages(),
limit: MAX_CANDIDATES,
};
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || hook(&query, &cancel)).await.ok()
}
/// Runs `query` on `t`; then again with the project files that mention the
/// symbol at `pos` and are not in `covered(first)` opened on the server.
/// A first answer that is empty while the server indexes is retried once
/// indexing ends.
pub(crate) async fn widened<R, F, Fut>(
&self,
snap: &DocSnap,
t: &Target,
pos: Pos,
cancel: &CancellationToken,
query: F,
covered: impl Fn(&R) -> Vec<PathBuf>,
) -> IdeResult<Widened<R>>
where
F: Fn() -> Fut,
Fut: Future<Output = IdeResult<R>>,
{
let busy = t.server.is_busy();
let word = search_word(snap, pos).filter(|_| t.caps().open_close);
let candidates = async {
match word {
Some(w) => self.candidates(t, w, cancel).await,
None => None,
}
};
let (first, candidates) = futures::join!(query(), candidates);
let mut first = first?;
if busy && covered(&first).is_empty() && t.server.wait_idle(INDEX_WAIT, cancel).await {
first = query().await?;
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// Servers report analysis progress often; only "nothing found" while it lasts is suspect.
let mut incomplete =
(t.server.is_busy() && covered(&first).is_empty()).then_some(ReferencesIncomplete::Indexing);
let Some(candidates) = candidates else { return Ok(Widened { first, second: None, incomplete }) };
if candidates.limit_hit {
incomplete = incomplete.or(Some(ReferencesIncomplete::TooManyFiles));
}
let known: HashSet<PathBuf> = covered(&first).into_iter().chain([snap.path.clone()]).collect();
let files: Vec<PathBuf> = candidates.files.into_iter().filter(|f| !known.contains(f)).collect();
if files.is_empty() {
return Ok(Widened { first, second: None, incomplete });
}
let opened = self.open_transient(t, files, cancel).await;
if opened.files.is_empty() {
return Ok(Widened { first, second: None, incomplete });
}
tracing::debug!("{}: opened {} more files for a references search", t.server.name, opened.files.len());
let second = query().await;
drop(opened);
match second {
Ok(second) => {
if !covered(&second).is_empty() && incomplete == Some(ReferencesIncomplete::Indexing) {
incomplete = None;
}
Ok(Widened { first, second: Some(second), incomplete })
}
Err(e) if cancel.is_cancelled() => Err(e),
Err(e) => {
tracing::debug!("{}: widened references search: {}", t.server.name, e.message);
Ok(Widened { first, second: None, incomplete })
}
}
}
/// Opens `files` on `t` (read from disk) unless the user has them open;
/// they are closed when the returned guard drops.
async fn open_transient(&self, t: &Target, files: Vec<PathBuf>, cancel: &CancellationToken) -> TransientFiles<'_> {
let read = {
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
files
.into_iter()
.take_while(|_| !cancel.is_cancelled())
.filter(|f| std::fs::metadata(f).is_ok_and(|m| m.is_file() && m.len() <= MAX_CANDIDATE_BYTES))
.filter_map(|f| std::fs::read_to_string(&f).ok().map(|text| (f, text)))
.collect::<Vec<_>>()
})
.await
.unwrap_or_default()
};
let mut guard = TransientFiles { mgr: self, server: t.server.clone(), run: t.run.clone(), files: Vec::new() };
if cancel.is_cancelled() {
return guard;
}
let docs = self.docs.lock();
for (path, text) in read {
if docs.values().any(|d| d.path == path) {
continue;
}
let uri = crate::uri::path_to_uri(&path);
if t.server.hold_transient(&path, t.run.generation) {
let language = self.languages.detect(&path, text.lines().next());
let params = json!({
"textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text }
});
if let Err(e) = t.run.peer.notify("textDocument/didOpen", params) {
tracing::debug!("{}: didOpen: {e}", t.server.name);
}
}
guard.files.push((path, uri));
}
guard
}
}
/// Files opened by [`LspManager::open_transient`]; closed on drop.
pub(crate) struct TransientFiles<'a> {
mgr: &'a LspManager,
server: Arc<Server>,
run: Running,
pub files: Vec<(PathBuf, lsp::Uri)>,
}
impl TransientFiles<'_> {
/// Opens one file outside a references search (a file operation needs a loaded project).
pub(crate) fn hold(&mut self, path: &Path, language: &LanguageId, text: &str) {
let _docs = self.mgr.docs.lock();
let uri = crate::uri::path_to_uri(path);
if self.server.hold_transient(path, self.run.generation) {
let params =
json!({ "textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text } });
if let Err(e) = self.run.peer.notify("textDocument/didOpen", params) {
tracing::debug!("{}: didOpen: {e}", self.server.name);
}
}
self.files.push((path.to_owned(), uri));
}
}
impl<'a> TransientFiles<'a> {
pub(crate) fn empty(mgr: &'a LspManager, t: &Target) -> Self {
Self { mgr, server: t.server.clone(), run: t.run.clone(), files: Vec::new() }
}
}
impl Drop for TransientFiles<'_> {
fn drop(&mut self) {
if self.files.is_empty() {
return;
}
// Under the documents lock, so a user `didOpen` of the same file can't interleave.
let _docs = self.mgr.docs.lock();
for (path, uri) in self.files.drain(..) {
if self.server.release_transient(&path, self.run.generation)
&& let Err(e) = self.run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": uri } }))
{
tracing::debug!("{}: didClose: {e}", self.server.name);
}
}
}
}
+1 -119
Переглянути файл
@@ -2,7 +2,7 @@
use crate::caps::ServerCaps;
use ide_core::event::ServerStatus;
use ide_core::{CancellationToken, IdeEvent, LanguageId, ServerId, SharedSink, TaskId};
use ide_core::{IdeEvent, LanguageId, ServerId, SharedSink, TaskId};
use ide_jsonrpc::Peer;
use ide_language::LanguageServerConfig;
use lsp_types as lsp;
@@ -17,9 +17,6 @@ use tokio::sync::{Notify, watch};
const STABLE_UPTIME: Duration = Duration::from_secs(180);
const MAX_RESTARTS: usize = 3;
const STDERR_LINES: usize = 50;
/// Diagnostics a server publishes for a transiently opened file shortly after
/// its `didClose` (analysis that was already running) are dropped too.
const TRANSIENT_GRACE: Duration = Duration::from_secs(3);
/// A live, initialized instance.
#[derive(Clone)]
@@ -52,17 +49,6 @@ struct State {
conn: Conn,
}
/// A file opened on the server by the client itself (not by the user) for the
/// duration of a request, e.g. to widen a references search.
struct Transient {
/// Requests holding the file open.
holders: usize,
generation: u64,
/// The user opened the file meanwhile: its `didOpen` replaced ours.
taken: bool,
closed_at: Option<Instant>,
}
pub struct Progress {
pub task: TaskId,
pub title: String,
@@ -79,8 +65,6 @@ pub struct Server {
effective: Mutex<Option<LanguageServerConfig>>,
languages: Mutex<Vec<LanguageId>>,
state: Mutex<State>,
/// Fired when the instance being started is abandoned (stop / restart while starting).
start_cancel: Mutex<CancellationToken>,
phase: watch::Sender<Phase>,
status: Mutex<(ServerStatus, Option<String>)>,
/// Consecutive crashes of short-lived instances.
@@ -94,9 +78,6 @@ pub struct Server {
published: Mutex<HashMap<PathBuf, Instant>>,
/// Woken on every `publishDiagnostics` (Inspect Code waits on it).
pub published_notify: Notify,
/// Woken when the last `$/progress` task ends.
idle_notify: Notify,
transient: Mutex<HashMap<PathBuf, Transient>>,
}
impl Server {
@@ -109,7 +90,6 @@ impl Server {
effective: Mutex::new(None),
languages: Mutex::new(vec![language]),
state: Mutex::new(State { generation: 0, conn: Conn::Idle }),
start_cancel: Mutex::new(CancellationToken::new()),
phase: watch::channel(Phase::Down).0,
status: Mutex::new((ServerStatus::Stopped, None)),
crashes: Mutex::new(0),
@@ -119,8 +99,6 @@ impl Server {
diagnostics: Mutex::new(HashMap::new()),
published: Mutex::new(HashMap::new()),
published_notify: Notify::new(),
idle_notify: Notify::new(),
transient: Mutex::new(HashMap::new()),
}
}
@@ -154,7 +132,6 @@ impl Server {
}
st.generation += 1;
st.conn = Conn::Starting;
*self.start_cancel.lock() = CancellationToken::new();
*self.started.lock() = Some(Instant::now());
self.phase.send_replace(Phase::Starting);
Some(st.generation)
@@ -220,7 +197,6 @@ impl Server {
}
Conn::Starting => {
st.generation += 1; // invalidates the in-flight start
self.start_cancel.lock().cancel();
self.phase.send_replace(Phase::Down);
None
}
@@ -231,11 +207,6 @@ impl Server {
}
}
/// Cancelled when the current start is abandoned.
pub fn start_token(&self) -> CancellationToken {
self.start_cancel.lock().clone()
}
pub fn end_stop(&self, generation: u64) {
let mut st = self.state.lock();
if st.generation == generation && matches!(st.conn, Conn::Stopping) {
@@ -324,95 +295,6 @@ impl Server {
self.set_status(sink, if busy { ServerStatus::Busy } else { ServerStatus::Ready }, None);
}
/// Whether the server reports work in progress (indexing, analysis).
pub fn is_busy(&self) -> bool {
!self.progress.lock().is_empty()
}
/// Called after a `$/progress` task ended.
pub fn progress_ended(&self) {
if !self.is_busy() {
self.idle_notify.notify_waiters();
}
}
/// Waits until no `$/progress` task is active; false on timeout or cancellation.
pub async fn wait_idle(&self, timeout: Duration, cancel: &CancellationToken) -> bool {
let deadline = tokio::time::Instant::now() + timeout;
loop {
let notified = self.idle_notify.notified();
if !self.is_busy() || self.running().is_none() {
return !self.is_busy();
}
tokio::select! {
() = notified => {}
() = tokio::time::sleep_until(deadline) => return !self.is_busy(),
() = cancel.cancelled() => return false,
}
}
}
// ---- transiently opened files ----
/// Registers a holder of the transient file `path` on instance `generation`;
/// true when the caller must send `didOpen` (first holder).
pub fn hold_transient(&self, path: &Path, generation: u64) -> bool {
let mut map = self.transient.lock();
map.retain(|_, t| t.holders > 0 || t.closed_at.is_some_and(|c| c.elapsed() < TRANSIENT_GRACE));
let t =
map.entry(path.to_owned()).or_insert(Transient { holders: 0, generation, taken: false, closed_at: None });
if t.holders == 0 || t.generation != generation {
*t = Transient { holders: 1, generation, taken: false, closed_at: None };
return true;
}
t.holders += 1;
false
}
/// Drops a holder of `path`; true when the caller must send `didClose`
/// (last holder, same instance, and the user did not open the file meanwhile).
pub fn release_transient(&self, path: &Path, generation: u64) -> bool {
let mut map = self.transient.lock();
let Some(t) = map.get_mut(path) else { return false };
if t.holders == 0 {
return false;
}
t.holders -= 1;
if t.holders > 0 {
return false;
}
let close = !t.taken && t.generation == generation;
if close {
t.closed_at = Some(Instant::now());
} else {
map.remove(path);
}
close
}
/// The user opens `path` on instance `generation`: true when a transient
/// copy is open there and must be closed before the user's `didOpen`.
pub fn take_transient(&self, path: &Path, generation: u64) -> bool {
let mut map = self.transient.lock();
let Some(t) = map.get_mut(path) else { return false };
let open = t.holders > 0 && !t.taken && t.generation == generation;
if t.holders > 0 {
t.taken = true;
} else {
map.remove(path);
}
open
}
/// Whether diagnostics published for `path` belong to a transient copy
/// and must not reach the Problems view.
pub fn suppresses_diagnostics(&self, path: &Path) -> bool {
self.transient
.lock()
.get(path)
.is_some_and(|t| !t.taken && (t.holders > 0 || t.closed_at.is_some_and(|c| c.elapsed() < TRANSIENT_GRACE)))
}
// ---- bookkeeping ----
pub fn push_stderr(&self, line: String) {
-188
Переглянути файл
@@ -1,188 +0,0 @@
//! LSP over TCP, for servers living inside another program (the Godot editor's
//! GDScript server). Mirrors `ide-dap`'s `tcp` transport: connect to the
//! configured address when something listens there, else start the configured
//! command (`${port}` → a free port, `${root}` → the workspace root) and connect
//! once it accepts. The framing and session are the same as over stdio.
use crate::launch::LaunchError;
use ide_core::CancellationToken;
use ide_jsonrpc::{Handler, Peer};
use ide_language::LanguageServerConfig;
use parking_lot::Mutex;
use std::collections::VecDeque;
use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::io::{AsyncBufReadExt, AsyncRead, BufReader};
pub(crate) const PORT_PLACEHOLDER: &str = "${port}";
pub(crate) const ROOT_PLACEHOLDER: &str = "${root}";
const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
/// A headless Godot editor imports the project before it listens.
const START_TIMEOUT: Duration = Duration::from_secs(120);
const POLL: Duration = Duration::from_millis(200);
const TAIL_LINES: usize = 20;
/// `${port}` / `${root}` substituted in every argument.
pub(crate) fn substitute_args(args: &[String], port: Option<u16>, root: &Path) -> Vec<String> {
let root = root.to_string_lossy();
args.iter()
.map(|a| {
let a = a.replace(ROOT_PLACEHOLDER, &root);
match port {
Some(p) => a.replace(PORT_PLACEHOLDER, &p.to_string()),
None => a,
}
})
.collect()
}
pub(crate) fn resolve_addr(addr: &str) -> Result<SocketAddr, LaunchError> {
addr.to_socket_addrs()
.ok()
.and_then(|mut a| a.next())
.ok_or_else(|| LaunchError::Config(format!("invalid language server address `{addr}`")))
}
/// A connection to `addr` if something accepts there right now.
pub(crate) fn probe(addr: &SocketAddr) -> Option<TcpStream> {
let stream = TcpStream::connect_timeout(addr, PROBE_TIMEOUT).ok()?;
let _ = stream.set_nodelay(true);
Some(stream)
}
/// A port that was free a moment ago on the loopback interface.
pub(crate) fn free_port() -> std::io::Result<u16> {
Ok(std::net::TcpListener::bind(("127.0.0.1", 0))?.local_addr()?.port())
}
fn into_tokio(stream: TcpStream) -> std::io::Result<tokio::net::TcpStream> {
stream.set_nonblocking(true)?;
tokio::net::TcpStream::from_std(stream)
}
/// Connects to the server of `config` (whose `connect` is set), starting `binary` when
/// nothing listens yet. Blocking; must run on a thread inside a Tokio runtime.
#[allow(clippy::too_many_arguments)]
pub(crate) fn connect_or_start(
config: &LanguageServerConfig,
addr: &str,
binary: Option<&Path>,
env: &[(String, String)],
root: &Path,
handler: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
cancel: &CancellationToken,
) -> Result<Peer, LaunchError> {
let addr = resolve_addr(addr)?;
if let Some(stream) = probe(&addr) {
tracing::info!("{}: connected to the server running at {addr}", config.name);
let (r, w) = into_tokio(stream).map_err(|e| LaunchError::Failed(e.to_string()))?.into_split();
return Ok(Peer::connect(r, w, handler));
}
let binary = binary.ok_or(LaunchError::Missing)?;
let port = config
.args
.iter()
.any(|a| a.contains(PORT_PLACEHOLDER))
.then(free_port)
.transpose()
.map_err(|e| LaunchError::Failed(format!("no free port: {e}")))?;
let target = port.map_or(addr, |p| SocketAddr::from(([127, 0, 0, 1], p)));
let args = substitute_args(&config.args, port, root);
let mut cmd = tokio::process::Command::new(binary);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(&args)
.current_dir(root)
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true);
let mut child =
cmd.spawn().map_err(|e| LaunchError::Failed(format!("failed to start {}: {e}", binary.display())))?;
tracing::info!("{}: started {} {}, waiting for {target}", config.name, binary.display(), args.join(" "));
let tail: Arc<Mutex<VecDeque<String>>> = Arc::default();
let on_line: Arc<dyn Fn(String) + Send + Sync> = {
let tail = tail.clone();
Arc::new(move |line: String| {
{
let mut t = tail.lock();
if t.len() == TAIL_LINES {
t.pop_front();
}
t.push_back(line.clone());
}
on_stderr(line);
})
};
if let Some(out) = child.stdout.take() {
pump_lines(out, on_line.clone());
}
if let Some(err) = child.stderr.take() {
pump_lines(err, on_line);
}
let failed = |message: String| {
let tail: Vec<String> = tail.lock().iter().cloned().collect();
LaunchError::Failed(if tail.is_empty() { message } else { format!("{message}:\n{}", tail.join("\n")) })
};
let deadline = Instant::now() + START_TIMEOUT;
loop {
if cancel.is_cancelled() {
let _ = child.start_kill();
return Err(LaunchError::Failed(format!("{}: start cancelled", config.name)));
}
if let Some(stream) = probe(&target) {
let (r, w) = into_tokio(stream).map_err(|e| LaunchError::Failed(e.to_string()))?.into_split();
return Ok(Peer::connect_with_child(r, w, handler, child));
}
if let Ok(Some(status)) = child.try_wait() {
return Err(failed(format!("{} exited before accepting connections on {target} ({status})", config.name)));
}
if Instant::now() >= deadline {
let _ = child.start_kill();
return Err(failed(format!(
"{} did not accept connections on {target} within {}s",
config.name,
START_TIMEOUT.as_secs()
)));
}
std::thread::sleep(POLL);
}
}
fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(stream: R, on_line: Arc<dyn Fn(String) + Send + Sync>) {
tokio::spawn(async move {
let mut lines = BufReader::new(stream).lines();
while let Ok(Some(line)) = lines.next_line().await {
on_line(line);
}
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn placeholders_are_substituted() {
let args: Vec<String> =
["--path", "${root}", "--lsp-port", "${port}", "--x=${port}"].iter().map(|s| s.to_string()).collect();
assert_eq!(
substitute_args(&args, Some(6010), Path::new("/p/game")),
["--path", "/p/game", "--lsp-port", "6010", "--x=6010"]
);
assert_eq!(substitute_args(&args, None, Path::new("/p"))[3], "${port}");
}
#[test]
fn addresses_resolve() {
assert_eq!(resolve_addr("127.0.0.1:6005").unwrap().port(), 6005);
assert!(matches!(resolve_addr("nonsense"), Err(LaunchError::Config(_))));
}
}
-17
Переглянути файл
@@ -322,20 +322,3 @@ pub struct FileRenameEdits {
/// Servers that failed; their references are not updated.
pub errors: Vec<String>,
}
/// Why a references search may have missed usages.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum ReferencesIncomplete {
/// A language server was still indexing.
Indexing,
/// More project files mention the name than were checked.
TooManyFiles,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct References {
pub locations: Vec<Location>,
pub incomplete: Option<ReferencesIncomplete>,
}
+4 -350
Переглянути файл
@@ -27,13 +27,9 @@ struct MockState {
/// uri → text as reconstructed by the mock from didOpen/didChange.
docs: Mutex<HashMap<String, String>>,
responses: Mutex<HashMap<String, Value>>,
/// Computes a response from the request and the open documents (before `responses`).
responder: Mutex<Option<Responder>>,
peer: Mutex<Option<Peer>>,
}
type Responder = Arc<dyn Fn(&MockState, &str, &Value) -> Option<Value> + Send + Sync>;
impl MockState {
fn notified(&self, method: &str) -> Vec<Value> {
self.notifications.lock().iter().filter(|(m, _)| m == method).map(|(_, p)| p.clone()).collect()
@@ -115,17 +111,11 @@ impl Handler for MockHandler {
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
let s = &self.0;
s.requests.lock().push((method.to_owned(), params.clone()));
s.requests.lock().push((method.to_owned(), params));
match method {
"initialize" => Ok(json!({ "capabilities": s.caps.lock().clone(), "serverInfo": { "name": "mock" } })),
"shutdown" => Ok(Value::Null),
_ => {
let responder = s.responder.lock().clone();
if let Some(v) = responder.and_then(|f| f(s, method, &params)) {
return Ok(v);
}
Ok(s.responses.lock().get(method).cloned().unwrap_or(Value::Null))
}
_ => Ok(s.responses.lock().get(method).cloned().unwrap_or(Value::Null)),
}
}
}
@@ -202,7 +192,6 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
root_markers: vec!["mock.toml".into()],
initialization_options: Some(toml::Value::Table(toml::toml! { flag = true nested = { deep = 1 } })),
install_hint: Some(format!("install {name}")),
connect: None,
fallback: false,
launch_error: None,
}
@@ -811,7 +800,7 @@ async fn navigation_rename_format_and_decorations() {
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
s.respond("textDocument/references", json!([{ "uri": uri, "range": r(0,3,0,6) }, { "uri": uri, "range": r(1,0,1,3) }, { "uri": uri, "range": r(1,0,1,3) }]));
let refs = h.mgr.references(doc, Pos::new(1, 1), true, true, Default::default()).await.unwrap().locations;
let refs = h.mgr.references(doc, Pos::new(1, 1), true).await.unwrap();
assert_eq!(refs.len(), 2);
assert_eq!(s.requested("textDocument/references")[0]["context"]["includeDeclaration"], true);
@@ -997,7 +986,7 @@ async fn virtual_locations_and_text_document_content() {
"textDocument/references",
json!([{ "uri": uri_of(&path), "range": r(0, 4, 0, 9) }, { "uri": lib, "range": r(2, 4, 2, 9) }]),
);
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap().locations;
let refs = h.mgr.references(doc, Pos::new(0, 5), true).await.unwrap();
assert_eq!(refs.iter().map(|l| l.uri.is_some()).collect::<Vec<_>>(), vec![false, true]);
s.respond(
"textDocument/prepareTypeHierarchy",
@@ -1311,338 +1300,3 @@ async fn css_family_configuration_returns_default_objects() {
assert_eq!(state.requested("initialize")[0]["initializationOptions"]["provideFormatter"], true);
}
}
// ------------------------------------------------------------------ references beyond the analysis scope
const WORD: &str = "target";
/// Locations of [`WORD`] in `text` (ASCII, so UTF-16 columns are byte offsets).
fn occurrences(uri: &str, text: &str) -> Vec<Value> {
let mut out = Vec::new();
for (line, l) in text.lines().enumerate() {
for (col, _) in l.match_indices(WORD) {
let end = col + WORD.len();
out.push(json!({ "uri": uri, "range": {
"start": { "line": line, "character": col }, "end": { "line": line, "character": end } } }));
}
}
out
}
/// A server that only analyses its open documents (minus `blind` URIs), like
/// Pyright for files outside its `include`.
fn open_files_only(blind: Vec<String>) -> Responder {
Arc::new(move |s, method, _| {
let docs: Vec<(String, String)> =
s.docs.lock().iter().filter(|(u, _)| !blind.contains(u)).map(|(u, t)| (u.clone(), t.clone())).collect();
let locs = || docs.iter().flat_map(|(u, t)| occurrences(u, t));
match method {
"textDocument/references" => Some(Value::Array(locs().collect())),
"textDocument/rename" => {
let mut changes = serde_json::Map::new();
for loc in locs() {
let edits = changes.entry(loc["uri"].as_str().unwrap()).or_insert_with(|| json!([]));
edits.as_array_mut().unwrap().push(json!({ "range": loc["range"], "newText": "renamed" }));
}
Some(json!({ "changes": changes }))
}
_ => None,
}
})
}
/// Candidate files: those directly under the root that contain the word; records the queries.
fn grep_candidates(h: &Harness) -> Arc<Mutex<Vec<ide_lsp::CandidateQuery>>> {
let seen = Arc::new(Mutex::new(Vec::new()));
let log = seen.clone();
h.mgr.set_candidates_hook(Box::new(move |q, _| {
log.lock().push(q.clone());
let mut files: Vec<PathBuf> = std::fs::read_dir(&q.root)
.unwrap()
.flatten()
.map(|e| e.path())
.filter(|p| std::fs::read_to_string(p).is_ok_and(|t| t.contains(&q.word)))
.collect();
files.sort();
ide_lsp::CandidateFiles { files, limit_hit: false }
}));
seen
}
fn uris(params: &[Value]) -> Vec<String> {
params.iter().map(|p| p["textDocument"]["uri"].as_str().unwrap().to_owned()).collect()
}
fn diagnostics_for(h: &Harness, path: &Path) -> usize {
h.events.lock().iter().filter(|e| matches!(e, IdeEvent::Diagnostics { path: p, .. } if p == path)).count()
}
fn scope_harness() -> (Harness, Arc<MockState>) {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
*s.responder.lock() = Some(open_files_only(vec![]));
(h, s)
}
#[tokio::test(flavor = "multi_thread")]
async fn references_open_unopened_files_that_mention_the_name() {
let (h, s) = scope_harness();
let seen = grep_candidates(&h);
let b = h.root.join("b.mk");
let c = h.root.join("c.mk");
std::fs::write(&b, "call target\n").unwrap();
std::fs::write(&c, "nothing here\n").unwrap();
let (doc, a) = h.open("a.mk", "def target\n");
let (_, d) = h.open("d.mk", "use target\n");
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 2).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
let mut paths: Vec<PathBuf> = refs.locations.iter().map(|l| l.path.to_path_buf()).collect();
paths.sort();
assert_eq!(paths, vec![a.clone(), b.clone(), d.clone()]);
assert_eq!(refs.incomplete, None);
let q = seen.lock()[0].clone();
assert_eq!((q.word.as_str(), q.root.as_path(), q.limit), (WORD, h.root.as_path(), ide_lsp::MAX_CANDIDATES));
assert_eq!(q.languages, vec![h.lang.clone()]);
// Only the unopened candidate was opened (from disk), then closed again.
let opens = s.notified("textDocument/didOpen");
let temp: Vec<&Value> = opens.iter().filter(|p| p["textDocument"]["uri"] == uri_of(&b)).collect();
assert_eq!(temp.len(), 1);
assert_eq!(temp[0]["textDocument"]["version"], 0);
assert_eq!(temp[0]["textDocument"]["text"], "call target\n");
assert!(!uris(&opens).contains(&uri_of(&c)));
assert_eq!(uris(&opens).iter().filter(|u| **u == uri_of(&d)).count(), 1);
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
assert_eq!(s.requested("textDocument/references").len(), 2);
assert_eq!(s.docs.lock().len(), 2);
// When every candidate file is already in the answer, no second request is made.
std::fs::remove_file(&b).unwrap();
h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(s.requested("textDocument/references").len(), 3);
// Without project_wide only the server's scope counts: no project search.
std::fs::write(&b, "call target\n").unwrap();
let refs = h.mgr.references(doc, Pos::new(0, 5), true, false, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 2);
assert_eq!(seen.lock().len(), 2);
}
#[tokio::test(flavor = "multi_thread")]
async fn references_never_reopen_or_close_the_users_files() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
grep_candidates(&h);
let (doc, _) = h.open("a.mk", "def target\n");
// Open, mentions the name, but the server does not report it.
let (_, d) = h.open("d.mk", "use target\n");
*s.responder.lock() = Some(open_files_only(vec![uri_of(&d)]));
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 2).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 1);
assert_eq!(uris(&s.notified("textDocument/didOpen")).iter().filter(|u| **u == uri_of(&d)).count(), 1);
assert!(s.notified("textDocument/didClose").is_empty());
assert_eq!(s.requested("textDocument/references").len(), 1);
assert!(s.docs.lock().contains_key(&uri_of(&d)));
}
#[tokio::test(flavor = "multi_thread")]
async fn references_report_a_capped_candidate_search() {
let (h, s) = scope_harness();
h.mgr.set_candidates_hook(Box::new(|q, _| ide_lsp::CandidateFiles {
files: vec![q.root.join("b.mk")],
limit_hit: true,
}));
std::fs::write(h.root.join("b.mk"), "target\n").unwrap();
let (doc, _) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 2);
assert_eq!(refs.incomplete, Some(ReferencesIncomplete::TooManyFiles));
}
#[tokio::test(flavor = "multi_thread")]
async fn cancelling_a_references_search_stops_the_candidate_search_and_closes_files() {
let (h, s) = scope_harness();
h.mgr.set_candidates_hook(Box::new(|_, cancel| {
while !cancel.is_cancelled() {
std::thread::sleep(Duration::from_millis(5));
}
ide_lsp::CandidateFiles::default()
}));
let (doc, _) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
let cancel = ide_core::CancellationToken::new();
let later = cancel.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(100)).await;
later.cancel();
});
let err = h.mgr.references(doc, Pos::new(0, 5), true, true, cancel).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
// Cancelled while the server answers with a file opened for the search.
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
grep_candidates(&h);
let slow = uri_of(&b);
let inner = open_files_only(vec![]);
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if s.docs.lock().contains_key(&slow) {
std::thread::sleep(Duration::from_millis(600));
}
inner(s, method, params)
}));
let cancel = ide_core::CancellationToken::new();
let later = cancel.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(200)).await;
later.cancel();
});
let started = std::time::Instant::now();
let err = h.mgr.references(doc, Pos::new(0, 5), true, true, cancel).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
assert!(started.elapsed() < Duration::from_millis(550));
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn diagnostics_of_files_opened_for_a_search_stay_out_of_problems() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
grep_candidates(&h);
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
let (doc, a) = h.open("a.mk", "def target\n");
let diag = json!([{ "range": {"start":{"line":0,"character":0},"end":{"line":0,"character":1}}, "message": "e" }]);
let inner = open_files_only(vec![]);
let (temp, user, d) = (uri_of(&b), uri_of(&a), diag.clone());
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if s.docs.lock().contains_key(&temp) {
for uri in [&temp, &user] {
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri, "diagnostics": d })).unwrap();
}
}
inner(s, method, params)
}));
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 2);
// Published right after the didClose (analysis still running): dropped too.
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri_of(&b), "diagnostics": diag })).unwrap();
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri_of(&a), "diagnostics": [] })).unwrap();
eventually(|| diagnostics_for(&h, &a) == 2).await;
assert_eq!(diagnostics_for(&h, &b), 0);
}
#[tokio::test(flavor = "multi_thread")]
async fn opening_a_file_during_a_search_takes_it_over() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
grep_candidates(&h);
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
let (doc, _) = h.open("a.mk", "def target\n");
let slow = uri_of(&b);
let inner = open_files_only(vec![]);
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if s.docs.lock().get(&slow).is_some_and(|t| t.starts_with("call")) {
std::thread::sleep(Duration::from_millis(400));
}
inner(s, method, params)
}));
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let mgr = h.mgr.clone();
let search = tokio::spawn(async move { mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await });
eventually(|| s.docs.lock().contains_key(&uri_of(&b))).await;
let user_doc = DocId::next();
h.mgr.did_open(user_doc, &b, &h.lang, 7, "edited target\n");
search.await.unwrap().unwrap();
// The temporary copy was closed before the user's didOpen, and the user's stays open.
let events: Vec<(String, Value)> = s
.notifications
.lock()
.iter()
.filter(|(m, p)| m.starts_with("textDocument/did") && p["textDocument"]["uri"] == uri_of(&b))
.map(|(m, p)| (m.clone(), p["textDocument"]["version"].clone()))
.collect();
assert_eq!(
events,
vec![
("textDocument/didOpen".to_owned(), json!(0)),
("textDocument/didClose".to_owned(), Value::Null),
("textDocument/didOpen".to_owned(), json!(7)),
]
);
assert_eq!(s.docs.lock().get(&uri_of(&b)).map(String::as_str), Some("edited target\n"));
// Its diagnostics are the user's again.
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri_of(&b), "diagnostics": [] })).unwrap();
eventually(|| diagnostics_for(&h, &b) == 1).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn an_empty_answer_while_indexing_is_retried_when_indexing_ends() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
let (doc, path) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
let peer = s.peer();
peer.notify("$/progress", json!({ "token": "idx", "value": { "kind": "begin", "title": "Indexing" } })).unwrap();
h.wait_status("mock", ServerStatus::Busy).await;
let (state, uri) = (s.clone(), uri_of(&path));
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(200)).await;
state.respond("textDocument/references", Value::Array(occurrences(&uri, "def target\n")));
peer.notify("$/progress", json!({ "token": "idx", "value": { "kind": "end" } })).unwrap();
});
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 1);
assert_eq!(refs.incomplete, None);
assert_eq!(s.requested("textDocument/references").len(), 2);
// While the server works, results are taken as they are; finding nothing is flagged.
s.peer()
.notify("$/progress", json!({ "token": "again", "value": { "kind": "begin", "title": "Indexing" } }))
.unwrap();
h.wait_status("mock", ServerStatus::Busy).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!((refs.locations.len(), refs.incomplete), (1, None));
s.respond("textDocument/references", json!([]));
let refs = h.mgr.references(doc, Pos::new(0, 5), true, false, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 0);
assert_eq!(refs.incomplete, Some(ReferencesIncomplete::Indexing));
}
#[tokio::test(flavor = "multi_thread")]
async fn rename_edits_files_outside_the_analysis_scope() {
let (h, s) = scope_harness();
grep_candidates(&h);
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
let (doc, a) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let edit = h.mgr.rename(doc, Pos::new(0, 5), "renamed".into()).await.unwrap();
let mut paths: Vec<PathBuf> = edit
.files
.iter()
.map(|f| match f {
FileEdit::Edit { path, .. } => path.to_path_buf(),
_ => panic!("unexpected {f:?}"),
})
.collect();
paths.sort();
assert_eq!(paths, vec![a, b.clone()]);
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
}
-3
Переглянути файл
@@ -71,7 +71,6 @@ async fn missing_binary_is_reported_with_install_hint() {
root_markers: vec![],
initialization_options: None,
install_hint: Some("npm i -g nope-ls".into()),
connect: None,
fallback: false,
launch_error: None,
};
@@ -199,7 +198,6 @@ async fn typescript_language_server_end_to_end() {
root_markers: vec!["tsconfig.json".into()],
initialization_options: None,
install_hint: None,
connect: None,
fallback: false,
launch_error: None,
};
@@ -241,7 +239,6 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
root_markers: vec!["package.json".into()],
initialization_options: init.map(|v| toml::Value::try_from(v).unwrap()),
install_hint: None,
connect: None,
fallback: false,
launch_error: None,
}
-241
Переглянути файл
@@ -1,241 +0,0 @@
//! Language servers reached over TCP (`connect`, the Godot editor's GDScript
//! server) against a mock LSP server on a local socket.
use ide_core::event::ServerStatus;
use ide_core::{CancellationToken, DocId, IdeEvent, LanguageId, Pos};
use ide_jsonrpc::{Handler, Peer};
use ide_language::{LanguageConfig, LanguageRegistry, LanguageServerConfig};
use ide_lsp::{LaunchError, Launcher, LspManager, ProcessLauncher};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
#[derive(Default)]
struct ServerLog {
requests: Mutex<Vec<String>>,
notifications: Mutex<Vec<String>>,
/// Server ends of the accepted connections.
peers: Mutex<Vec<Peer>>,
}
struct MockHandler(Arc<ServerLog>);
impl Handler for MockHandler {
fn on_notification(&self, method: &str, _params: Value) {
self.0.notifications.lock().push(method.to_owned());
}
fn on_request(&self, method: &str, _params: Value) -> Result<Value, (i64, String)> {
self.0.requests.lock().push(method.to_owned());
match method {
"initialize" => Ok(json!({
"capabilities": { "textDocumentSync": 1, "hoverProvider": true },
"serverInfo": { "name": "mock-godot" }
})),
"textDocument/hover" => Ok(json!({ "contents": { "kind": "markdown", "value": "**Node2D**" } })),
_ => Ok(Value::Null),
}
}
}
/// Accepts LSP connections on a local port, like the Godot editor on 6005.
async fn mock_server() -> (u16, Arc<ServerLog>, tokio::task::JoinHandle<()>) {
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let log = Arc::new(ServerLog::default());
let accept = {
let log = log.clone();
tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let (r, w) = stream.into_split();
let peer = Peer::connect(r, w, Arc::new(MockHandler(log.clone())));
log.peers.lock().push(peer);
}
})
};
(port, log, accept)
}
fn godot_cfg(port: u16, command: &str) -> LanguageServerConfig {
toml::from_str(&format!(
"name = \"godot\"\ncommand = \"{command}\"\nconnect = \"127.0.0.1:{port}\"\nroot-markers = [\"project.godot\"]\ninstall-hint = \"Open the project in the Godot editor\""
))
.unwrap()
}
struct Harness {
_dir: tempfile::TempDir,
root: PathBuf,
mgr: Arc<LspManager>,
events: Arc<Mutex<Vec<IdeEvent>>>,
}
fn harness(server: LanguageServerConfig) -> Harness {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().to_path_buf();
std::fs::write(root.join("project.godot"), "config_version=5\n").unwrap();
let lang: LanguageConfig = toml::from_str("id = \"gdscript\"\nname = \"GDScript\"\nextensions = [\"gd\"]").unwrap();
let lang = LanguageConfig { language_servers: vec![server], ..lang };
let registry = Arc::new(LanguageRegistry::from_configs(vec![lang]));
let events = Arc::new(Mutex::new(Vec::new()));
let sink = {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let mgr = LspManager::with_launcher(root.clone(), registry, sink, Arc::new(ProcessLauncher));
Harness { _dir: dir, root, mgr, events }
}
impl Harness {
fn open(&self, name: &str, text: &str) -> DocId {
let path = self.root.join(name);
std::fs::write(&path, text).unwrap();
let doc = DocId::next();
self.mgr.did_open(doc, &path, &LanguageId::new("gdscript"), 1, text);
doc
}
fn statuses(&self) -> Vec<(ServerStatus, Option<String>)> {
self.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::LanguageServer { status, message, .. } => Some((*status, message.clone())),
_ => None,
})
.collect()
}
async fn wait_status(&self, status: ServerStatus, count: usize) {
eventually(|| self.statuses().iter().filter(|(s, _)| *s == status).count() >= count).await;
}
}
async fn eventually(mut f: impl FnMut() -> bool) {
for _ in 0..1000 {
if f() {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("condition not reached in time");
}
#[tokio::test(flavor = "multi_thread")]
async fn connects_to_a_running_server_requests_and_reconnects() {
let (port, log, _accept) = mock_server().await;
let h = harness(godot_cfg(port, "openidea-no-such-godot"));
let doc = h.open("player.gd", "extends Node2D\n");
h.wait_status(ServerStatus::Ready, 1).await;
assert_eq!(log.requests.lock().first().map(String::as_str), Some("initialize"));
eventually(|| log.notifications.lock().iter().any(|m| m == "textDocument/didOpen")).await;
let hover = h.mgr.hover(doc, Pos::new(0, 9), CancellationToken::new()).await.unwrap().unwrap();
assert!(format!("{hover:?}").contains("Node2D"), "{hover:?}");
// Attached to a server it didn't start: no process id.
assert_eq!(h.mgr.servers()[0].pid, None);
// The editor drops the connection (closed or restarted): the client reconnects and reopens.
log.peers.lock().remove(0).kill();
h.wait_status(ServerStatus::Crashed, 1).await;
let (_, message) = h.statuses().into_iter().rfind(|(s, _)| *s == ServerStatus::Crashed).unwrap();
assert!(message.unwrap().contains(&format!("127.0.0.1:{port}")));
h.wait_status(ServerStatus::Ready, 2).await;
eventually(|| log.notifications.lock().iter().filter(|m| *m == "textDocument/didOpen").count() == 2).await;
assert_eq!(log.requests.lock().iter().filter(|m| *m == "initialize").count(), 2);
// Shutting down leaves a server it didn't start running: no `shutdown` / `exit`.
h.mgr.shutdown_all().await;
eventually(|| log.peers.lock().iter().all(Peer::is_closed)).await;
assert!(!log.requests.lock().iter().any(|m| m == "shutdown"));
assert!(!log.notifications.lock().iter().any(|m| m == "exit"));
}
#[tokio::test(flavor = "multi_thread")]
async fn nothing_listening_and_no_executable_reports_how_to_fix_it() {
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let h = harness(godot_cfg(port, "openidea-no-such-godot"));
h.open("player.gd", "extends Node\n");
h.wait_status(ServerStatus::Missing, 1).await;
let (_, message) = h.statuses().into_iter().rfind(|(s, _)| *s == ServerStatus::Missing).unwrap();
assert_eq!(message.as_deref(), Some("Open the project in the Godot editor"));
}
/// The command is started when nothing listens yet, the client waits until the
/// port accepts, and the started process belongs to the connection.
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn starts_the_command_and_waits_until_it_listens() {
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let cfg = LanguageServerConfig { args: vec!["30".into()], ..godot_cfg(port, "sleep") };
let root = tempfile::tempdir().unwrap();
// The "server" (`sleep`) never listens itself; a listener comes up a moment later.
let log = Arc::new(ServerLog::default());
let server = {
let log = log.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(400)).await;
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.unwrap();
let (stream, _) = listener.accept().await.unwrap();
let (r, w) = stream.into_split();
log.peers.lock().push(Peer::connect(r, w, Arc::new(MockHandler(log.clone()))));
})
};
let path = root.path().to_path_buf();
let peer = tokio::task::spawn_blocking(move || {
ProcessLauncher.launch(&cfg, &path, Arc::new(ide_jsonrpc::NoopHandler), Box::new(|_| {}))
})
.await
.unwrap()
.unwrap_or_else(|e| panic!("{e:?}"));
server.await.unwrap();
let pid = peer.pid().expect("owns the started process");
let init: Value = peer.request("initialize", json!({}), None).await.unwrap();
assert_eq!(init["serverInfo"]["name"], "mock-godot");
peer.kill();
peer.closed().await;
eventually(|| !process_alive(pid)).await;
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_command_that_exits_without_listening_fails_and_cancel_stops_waiting() {
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let root = tempfile::tempdir().unwrap();
let path = root.path().to_path_buf();
let cfg = godot_cfg(port, "false");
let err = tokio::task::spawn_blocking(move || {
ProcessLauncher.launch(&cfg, &path, Arc::new(ide_jsonrpc::NoopHandler), Box::new(|_| {}))
})
.await
.unwrap()
.err()
.expect("fails");
assert!(matches!(&err, LaunchError::Failed(m) if m.contains("exited before accepting connections")), "{err:?}");
let cfg = LanguageServerConfig { args: vec!["30".into()], ..godot_cfg(port, "sleep") };
let path = root.path().to_path_buf();
let cancel = CancellationToken::new();
let token = cancel.clone();
let started = std::time::Instant::now();
let waiting = tokio::task::spawn_blocking(move || {
ProcessLauncher.launch_cancellable(&cfg, &path, Arc::new(ide_jsonrpc::NoopHandler), Box::new(|_| {}), &token)
});
tokio::time::sleep(Duration::from_millis(300)).await;
cancel.cancel();
let err = waiting.await.unwrap().err().expect("cancelled");
assert!(matches!(&err, LaunchError::Failed(m) if m.contains("cancelled")), "{err:?}");
assert!(started.elapsed() < Duration::from_secs(10));
}
#[cfg(unix)]
fn process_alive(pid: u32) -> bool {
std::process::Command::new("kill")
.args(["-0", &pid.to_string()])
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|s| s.success())
}
-19
Переглянути файл
@@ -19,7 +19,6 @@ pub(crate) fn detect(root: &Path) -> Vec<RunConfig> {
detect_python(root, &mut out);
detect_make(root, &mut out);
detect_just(root, &mut out);
detect_godot(root, &mut out);
let mut seen = HashSet::new();
out.retain(|c| seen.insert(c.id.clone()));
@@ -800,24 +799,6 @@ pub(crate) fn just_recipes(src: &str) -> Vec<String> {
recipes
}
// ---------------------------------------------------------------- godot
/// Godot projects (`project.godot`) at the root or one level down: "Godot Project"
/// runs the main scene (`godot --path .`), debuggable through the editor's adapter.
fn detect_godot(root: &Path, out: &mut Vec<RunConfig>) {
let dirs = std::iter::once(root.to_path_buf()).chain(subdirs(root));
for dir in dirs.filter(|d| d.join("project.godot").is_file()) {
let rel = relative(root, &dir);
let (id, name, cwd) = if rel.as_os_str().is_empty() {
("godot:project".to_owned(), "Godot Project".to_owned(), None)
} else {
let r = rel.to_string_lossy();
(format!("godot:project:{r}"), format!("Godot Project ({r})"), Some(rel.clone()))
};
out.push(config(id, name, "godot", "godot", &["--path", "."]).debug("godot").in_dir(cwd));
}
}
fn detect_just(root: &Path, out: &mut Vec<RunConfig>) {
let Some(path) = first_existing(root, &["justfile", "Justfile", ".justfile"]) else { return };
let Some(src) = read(&path) else { return };
-6
Переглянути файл
@@ -406,10 +406,6 @@ impl ProcessManager {
cmd.cwd(cwd);
if env.clear {
cmd.env_clear();
} else {
for (k, v) in ide_core::process::shell_env() {
cmd.env(k, v);
}
}
cmd.env("TERM", "xterm-256color");
cmd.env("COLORTERM", "truecolor");
@@ -614,8 +610,6 @@ fn launch_env(root: &Path, config: &RunConfig) -> IdeResult<LaunchEnv> {
fn apply_env(cmd: &mut Command, env: &LaunchEnv) {
if env.clear {
cmd.env_clear();
} else {
cmd.envs(ide_core::process::shell_env());
}
cmd.envs(&env.vars);
}
-15
Переглянути файл
@@ -294,21 +294,6 @@ fn deno_tasks() {
assert!(c[1].is_test);
}
#[test]
fn godot_projects_run_their_main_scene() {
let dir = project(&[("project.godot", "config_version=5\n"), ("demo/project.godot", "config_version=5\n")]);
let c = detect(dir.path());
let root = find(&c, "godot:project");
assert_eq!((root.name.as_str(), root.kind.as_str()), ("Godot Project", "godot"));
assert_eq!(cmdline(root), "godot --path .");
assert_eq!(root.cwd, None);
assert_eq!(root.debug_adapter.as_deref(), Some("godot"));
let demo = find(&c, "godot:project:demo");
assert_eq!(demo.name, "Godot Project (demo)");
assert_eq!(demo.cwd, Some(std::path::PathBuf::from("demo").into()));
assert!(detect(project(&[("main.gd", "extends Node\n")]).path()).is_empty());
}
#[test]
fn just_recipes() {
let justfile = "\
+2 -23
Переглянути файл
@@ -3,8 +3,8 @@
use crate::discover::{project_venv_python, workspace_tsdk};
use crate::exec::{path_with, search_path};
use crate::vue;
use crate::{bin_dir, exe, venv_of};
use crate::{godot, vue};
use ide_core::settings::Settings;
use ide_language::LanguageServerConfig;
use ide_run::RunConfig;
@@ -169,28 +169,8 @@ pub(crate) fn merge_init_options(cfg: &mut LanguageServerConfig, layer: Value) {
/// paths, toolchain `PATH`, env (`GOROOT`, `RUST_SRC_PATH`, `VIRTUAL_ENV`) and
/// server settings (`python.pythonPath`, rust-analyzer `check.command`, `typescript.tsdk`).
/// `root` is the project root, `server_root` the server's workspace root.
/// The executable to launch for `command`: the one chosen in settings, else for
/// commands with well-known install locations (Godot) the one found there.
pub fn tool_command(root: &Path, s: &Settings, command: &str) -> Option<PathBuf> {
let custom = s.tool_path(command).and_then(|p| setting_path(root, p));
if command == godot::COMMAND {
return godot::find(custom);
}
custom
}
/// Points a run configuration launching a bare tool name at the executable from
/// [`tool_command`] (Godot apps live outside the search path).
pub fn resolve_run_command(config: &mut RunConfig, root: &Path, s: &Settings) {
if config.command == godot::COMMAND
&& let Some(path) = tool_command(root, s, &config.command)
{
config.command = path.to_string_lossy().into_owned();
}
}
pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root: &Path, s: &Settings) {
if let Some(custom) = tool_command(root, s, &cfg.command) {
if let Some(custom) = s.tool_path(&cfg.command).and_then(|p| setting_path(root, p)) {
cfg.command = custom.to_string_lossy().into_owned();
}
let mut path_dirs: Vec<PathBuf> = Vec::new();
@@ -349,7 +329,6 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
let mvn_options = maven_options(root, s);
for c in configs.iter_mut() {
resolve_run_command(c, root, s);
let mut path_dirs: Vec<PathBuf> = Vec::new();
match c.kind.as_str() {
"python" | "pytest" => {
-109
Переглянути файл
@@ -1,109 +0,0 @@
//! Locating the Godot editor executable: the GDScript language server and debug
//! adapter run inside it, and run configurations launch games with it.
//!
//! Order: the executable chosen in settings (`tools.godot`), the search path
//! (`godot`, `godot4`, distro names), then the usual install locations per OS
//! (app bundles, Flatpak / Snap exports, Steam, Scoop / WinGet).
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
/// The command language definitions and run configurations launch.
pub const COMMAND: &str = "godot";
pub const NOT_FOUND: &str = "Godot was not found. Install Godot 4 (https://godotengine.org/download), or set \
the Godot executable in Settings › Languages & Frameworks › Language Servers › godot.";
/// Names Godot is installed under on the search path.
const PATH_NAMES: &[&str] = &["godot", "godot4", "godot-4", "Godot", "godot-mono", "godot4-mono"];
/// The Godot executable: `custom` (from settings) when set, else the search path,
/// else a well-known install location.
pub fn find(custom: Option<PathBuf>) -> Option<PathBuf> {
if let Some(p) = custom {
return Some(p);
}
find_in(&crate::search_path(), &install_locations(crate::home_dir().as_deref()))
}
pub(crate) fn find_in(search: &OsStr, locations: &[PathBuf]) -> Option<PathBuf> {
PATH_NAMES
.iter()
.find_map(|n| ide_run::which::find_executable(n, search))
.or_else(|| locations.iter().find(|p| p.is_file()).cloned())
}
/// Well-known install locations, most specific first.
pub(crate) fn install_locations(home: Option<&Path>) -> Vec<PathBuf> {
let mut out: Vec<PathBuf> = Vec::new();
let home_join = |rel: &str| home.map(|h| h.join(rel));
if cfg!(target_os = "macos") {
for app in ["Godot.app", "Godot_mono.app", "Godot 4.app"] {
let rel = format!("{app}/Contents/MacOS/Godot");
out.push(Path::new("/Applications").join(&rel));
out.extend(home_join(&format!("Applications/{rel}")));
}
out.extend(home_join(
"Library/Application Support/Steam/steamapps/common/Godot Engine/Godot.app/Contents/MacOS/Godot",
));
} else if cfg!(windows) {
out.extend(home_join("scoop/shims/godot.exe"));
if let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) {
out.push(local.join("Microsoft/WinGet/Links/godot.exe"));
out.push(local.join("Programs/Godot/godot.exe"));
}
for base in ["C:/Program Files", "C:/Program Files (x86)"] {
out.push(Path::new(base).join("Godot/godot.exe"));
out.push(Path::new(base).join("Steam/steamapps/common/Godot Engine/godot.windows.opt.tools.64.exe"));
}
} else {
out.extend(home_join(".local/share/flatpak/exports/bin/org.godotengine.Godot"));
out.push("/var/lib/flatpak/exports/bin/org.godotengine.Godot".into());
out.push("/snap/bin/godot-4".into());
out.push("/snap/bin/godot".into());
out.extend(home_join(".local/share/Steam/steamapps/common/Godot Engine/godot.x11.opt.tools.64"));
}
out
}
/// A Godot project directory: it holds `project.godot`.
pub fn is_project(dir: &Path) -> bool {
dir.join("project.godot").is_file()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn search_path_wins_over_install_locations() {
let tmp = tempfile::tempdir().unwrap();
let bin = tmp.path().join("bin");
let app = tmp.path().join("Godot.app/Contents/MacOS");
std::fs::create_dir_all(&bin).unwrap();
std::fs::create_dir_all(&app).unwrap();
let installed = app.join("Godot");
std::fs::write(&installed, "").unwrap();
let search = std::env::join_paths([&bin]).unwrap();
assert_eq!(find_in(&search, std::slice::from_ref(&installed)), Some(installed.clone()));
let on_path = bin.join(if cfg!(windows) { "godot4.exe" } else { "godot4" });
std::fs::write(&on_path, "").unwrap();
assert_eq!(find_in(&search, std::slice::from_ref(&installed)), Some(on_path));
assert_eq!(find_in(OsStr::new(""), &[tmp.path().join("missing")]), None);
}
#[test]
fn custom_path_is_used_as_is() {
assert_eq!(find(Some("/opt/godot/bin/godot".into())), Some(PathBuf::from("/opt/godot/bin/godot")));
}
#[test]
fn install_locations_cover_the_platform() {
let locations = install_locations(Some(Path::new("/home/u")));
assert!(!locations.is_empty());
if cfg!(target_os = "macos") {
assert!(locations.contains(&PathBuf::from("/Applications/Godot.app/Contents/MacOS/Godot")));
assert!(locations.contains(&PathBuf::from("/home/u/Applications/Godot.app/Contents/MacOS/Godot")));
}
}
}
-1
Переглянути файл
@@ -8,7 +8,6 @@
pub mod apply;
mod discover;
mod exec;
pub mod godot;
pub mod java;
pub mod libraries;
pub mod locate;
-1
Переглянути файл
@@ -89,7 +89,6 @@ pub fn locate_tools_in(names: &[String], near: Option<&Path>, search: &std::ffi:
near.and_then(|n| local_bin(n, name))
.or_else(|| on_path(name, search))
.or_else(|| jdk_tool(name, &crate::java::installed_jdks()))
.or_else(|| (name == crate::godot::COMMAND).then(|| crate::godot::find(None)).flatten())
})
.flatten();
LocatedTool { name: name.clone(), path: path.map(Into::into), version: None }
-31
Переглянути файл
@@ -29,7 +29,6 @@ fn server(name: &str) -> LanguageServerConfig {
root_markers: vec![],
initialization_options: None,
install_hint: None,
connect: None,
fallback: false,
launch_error: None,
}
@@ -293,36 +292,6 @@ fn custom_tool_path_replaces_the_command() {
assert_eq!(cfg.command, "zls");
}
#[test]
fn the_godot_setting_applies_to_server_debugger_and_run_configurations() {
let tmp = tempfile::tempdir().unwrap();
let mut s = Settings::default();
s.tools.insert("godot".into(), ide_core::settings::ToolSettings { path: "~/Godot/godot".into() });
let expected = crate::home_dir().unwrap().join("Godot/godot");
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "godot"), Some(expected.clone()));
let mut cfg = LanguageServerConfig { command: "godot".into(), ..server("godot") };
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(Path::new(&cfg.command), expected);
let mut run = RunConfig {
id: "godot:project".into(),
name: "Godot Project".into(),
kind: "godot".into(),
command: "godot".into(),
args: vec!["--path".into(), ".".into()],
cwd: None,
env: BTreeMap::new(),
detected: true,
is_test: false,
debug_adapter: Some("godot".into()),
allow_parallel: false,
extras: Default::default(),
};
apply_to_run_configs(std::slice::from_mut(&mut run), tmp.path(), &s);
assert_eq!(Path::new(&run.command), expected);
// Other commands keep their name without a setting.
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "zls"), None);
}
#[test]
fn python_library_paths_are_parsed_and_deduplicated() {
let tmp = tempfile::tempdir().unwrap();
-2
Переглянути файл
@@ -14,7 +14,6 @@ mod mask;
mod pattern;
mod query;
mod replace;
mod words;
pub use files::{ScopeFile, scope_files};
pub use mask::FileMask;
@@ -23,7 +22,6 @@ pub use replace::{
ReplaceEvent, ReplaceHost, ReplacePreview, ReplaceSummary, ReplaceTarget, apply_edits, preserve_case, preview,
replace_files, replacement_edits,
};
pub use words::{WordFiles, WordQuery, files_with_word};
use grep_matcher::{Captures, Matcher};
use ide_core::{CancellationToken, IdeError, IdeResult};
-118
Переглянути файл
@@ -1,118 +0,0 @@
//! Files that mention an identifier: the candidates a reference search checks.
use crate::{Overlay, PathFilter, SearchContext, SearchQuery, SearchScope};
use ide_core::{CancellationToken, IdeResult};
use std::path::PathBuf;
use std::sync::Mutex;
#[derive(Clone, Debug)]
pub struct WordQuery {
/// Matched as a whole word, case-sensitively.
pub word: String,
/// Directory searched (absolute, or relative to the search root).
pub dir: PathBuf,
/// File masks never searched (excluded roots, ignored names).
pub exclude: Vec<String>,
/// Files returned at most.
pub limit: usize,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct WordFiles {
pub files: Vec<PathBuf>,
/// More files matched than `limit`; the search stopped early.
pub limit_hit: bool,
}
/// Files under `query.dir` containing `query.word` as a whole word, in walk
/// order (unsaved buffers through `overlay`, `.gitignore`d and hidden files
/// skipped like Find in Files). Stops at `query.limit` files or when cancelled.
pub fn files_with_word(
root: &std::path::Path,
query: &WordQuery,
filter: Option<PathFilter<'_>>,
overlay: Overlay<'_>,
cancel: &CancellationToken,
) -> IdeResult<WordFiles> {
let search = SearchQuery {
pattern: query.word.clone(),
is_regex: false,
case_sensitive: true,
whole_word: true,
include: Vec::new(),
exclude: query.exclude.clone(),
scope: SearchScope::Directory { path: query.dir.clone().into() },
max_matches: u32::MAX,
context: SearchContext::Any,
};
let stop = cancel.child_token();
let found = Mutex::new(WordFiles::default());
crate::search_filtered(root, &search, filter, overlay, &stop, &|file| {
let mut found = found.lock().unwrap_or_else(|e| e.into_inner());
if found.files.len() < query.limit {
found.files.push(file.path.into_path_buf());
} else {
found.limit_hit = true;
stop.cancel();
}
})?;
Ok(found.into_inner().unwrap_or_else(|e| e.into_inner()))
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn query(word: &str, limit: usize) -> WordQuery {
WordQuery { word: word.into(), dir: PathBuf::from("."), exclude: vec!["build/**".into()], limit }
}
#[test]
fn whole_word_matches_in_kept_files_only() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
fs::create_dir_all(root.join("pkg/ignored")).unwrap();
fs::create_dir_all(root.join("build")).unwrap();
fs::write(root.join(".gitignore"), "ignored/\n").unwrap();
fs::write(root.join("pkg/use.py"), "x.get_value(1)\n").unwrap();
fs::write(root.join("pkg/longer.py"), "get_values()\n").unwrap();
fs::write(root.join("pkg/case.py"), "Get_Value()\n").unwrap();
fs::write(root.join("pkg/notes.txt"), "get_value\n").unwrap();
fs::write(root.join("pkg/ignored/gen.py"), "get_value\n").unwrap();
fs::write(root.join("build/out.py"), "get_value\n").unwrap();
fs::write(root.join("pkg/open.py"), "nothing on disk\n").unwrap();
let unsaved = root.join("pkg/open.py");
let overlay = |p: &std::path::Path| (p == unsaved).then(|| "get_value()".to_owned());
let py = |rel: &str| rel.ends_with(".py");
let mut found =
files_with_word(root, &query("get_value", 10), Some(&py), &overlay, &CancellationToken::new()).unwrap();
found.files.sort();
assert_eq!(
found,
WordFiles { files: vec![root.join("pkg/open.py"), root.join("pkg/use.py")], limit_hit: false }
);
}
#[test]
fn stops_at_the_limit() {
let dir = tempfile::tempdir().unwrap();
for i in 0..5 {
fs::write(dir.path().join(format!("f{i}.py")), "name\n").unwrap();
}
let found = files_with_word(dir.path(), &query("name", 2), None, &|_| None, &CancellationToken::new()).unwrap();
assert_eq!((found.files.len(), found.limit_hit), (2, true));
let all = files_with_word(dir.path(), &query("name", 5), None, &|_| None, &CancellationToken::new()).unwrap();
assert_eq!((all.files.len(), all.limit_hit), (5, false));
}
#[test]
fn a_cancelled_search_finds_nothing() {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join("a.py"), "name\n").unwrap();
let cancel = CancellationToken::new();
cancel.cancel();
let found = files_with_word(dir.path(), &query("name", 5), None, &|_| None, &cancel).unwrap();
assert!(found.files.is_empty());
}
}
+2 -10
Переглянути файл
@@ -284,8 +284,6 @@ pub struct Tools {
platform: Platform,
/// Executables chosen in settings, by command.
custom: BTreeMap<String, PathBuf>,
/// Executables found outside the search path (app bundles), by command.
found: BTreeMap<String, PathBuf>,
}
impl Tools {
@@ -299,7 +297,7 @@ impl Tools {
let system: Vec<PathBuf> = std::env::split_paths(&search_path).filter(|d| !ours.contains(d)).collect();
let system_path = std::env::join_paths(&system).unwrap_or_default();
let child_path = std::env::join_paths(ours.iter().chain(system.iter())).unwrap_or_default();
Self { root, system_path, child_path, platform, custom: BTreeMap::new(), found: BTreeMap::new() }
Self { root, system_path, child_path, platform, custom: BTreeMap::new() }
}
/// Reports the executables chosen in settings (command → path) as the tools' location.
@@ -308,12 +306,6 @@ impl Tools {
self
}
/// Reports executables located outside the search path (command → path) as on the PATH.
pub fn with_found_paths(mut self, found: BTreeMap<String, PathBuf>) -> Self {
self.found = found;
self
}
pub fn root(&self) -> &Path {
&self.root
}
@@ -437,7 +429,7 @@ impl Tools {
let Some(spec) = spec else {
let u = usage?;
let command = u.command.clone()?;
let path = self.which(&command).or_else(|| self.found.get(&command).cloned());
let path = self.which(&command);
return Some(ToolInfo {
name: name.to_string(),
display_name: name.to_string(),
-5
Переглянути файл
@@ -507,11 +507,6 @@ impl Repo {
pub fn branch_info(&self) -> IdeResult<BranchInfo> {
refs::branch_info(self)
}
/// Current branch (short name; `None` when detached) and HEAD commit, without
/// upstream tracking (cheap enough to call for every repository on each refresh).
pub fn head(&self) -> IdeResult<(Option<String>, Option<String>)> {
refs::head(&self.gix()?)
}
/// Merge / rebase / cherry-pick… in progress (cheap: no ref walking).
pub fn operation(&self) -> IdeResult<Option<String>> {
Ok(refs::operation(&self.gix()?))
-5
Переглянути файл
@@ -30,11 +30,6 @@ pub(crate) fn branch_info(r: &Repo) -> IdeResult<BranchInfo> {
Ok(info)
}
pub(crate) fn head(repo: &gix::Repository) -> IdeResult<(Option<String>, Option<String>)> {
let name = repo.head_name().map_err(gx)?.map(|n| to_string(n.as_ref().shorten()));
Ok((name, repo.head_id().ok().map(|id| id.to_string())))
}
pub(crate) fn operation(repo: &gix::Repository) -> Option<String> {
use gix::state::InProgress::*;
let op = match repo.state()? {
-2
Переглянути файл
@@ -865,7 +865,6 @@ fn checkout_create_detached_delete_rebase() {
repo.checkout("topic", true).unwrap();
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("topic"));
assert_eq!(repo.head().unwrap(), (Some("topic".to_string()), Some(c1.clone())));
fx.write("t", "topic\n");
fx.commit_all("topic work");
repo.checkout("main", false).unwrap();
@@ -880,7 +879,6 @@ fn checkout_create_detached_delete_rebase() {
let info = repo.branch_info().unwrap();
assert_eq!(info.head, None);
assert_eq!(info.head_commit.as_deref(), Some(c1.as_str()));
assert_eq!(repo.head().unwrap(), (None, Some(c1.clone())));
assert!(
repo.log(&LogQuery { branch: Some("HEAD".into()), ..Default::default() }).unwrap()[0]
.refs
+2 -5
Переглянути файл
@@ -10,15 +10,12 @@
<body>
<div id="root"></div>
<div id="splash" class="splash" data-tauri-drag-region>
<svg class="splash-logo" viewBox="0 0 64 64" aria-hidden="true">
<svg viewBox="0 0 64 64" aria-hidden="true">
<rect width="64" height="64" rx="15" fill="#0E0E10" />
<circle cx="26" cy="32" r="11" fill="none" stroke="#FFFFFF" stroke-width="8" />
<rect x="43" y="18" width="8" height="28" rx="1.5" fill="#FF4F1A" />
</svg>
<!-- "OpenIDEA" in Inter 500 as outlines: the web font loads late in dev and would swap in. -->
<svg class="splash-wordmark" viewBox="0 -1984 9994 2478" role="img" aria-label="OpenIDEA">
<path fill="currentColor" d="M785.8 20Q592.6 20 440.4 -71.7Q288.2 -163.4 200.4 -334.7Q112.6 -506 112.6 -744Q112.6 -983.2 200.4 -1154.6Q288.2 -1326 440.4 -1418Q592.6 -1510 785.8 -1510Q979 -1510 1130.7 -1418Q1282.4 -1326 1369.8 -1154.6Q1457.3 -983.2 1457.3 -744Q1457.3 -505.8 1369.8 -334.5Q1282.4 -163.2 1130.7 -71.6Q979 20 785.8 20ZM785.8 -187.7Q913 -187.7 1013.5 -251.6Q1114 -315.5 1172.4 -439.9Q1230.7 -564.3 1230.7 -744Q1230.7 -925.6 1172.4 -1050Q1114 -1174.5 1013.5 -1238.4Q913 -1302.3 785.8 -1302.3Q657.9 -1302.3 557 -1238Q456.1 -1173.7 397.7 -1049.2Q339.2 -924.7 339.2 -744Q339.2 -564.3 397.7 -440.3Q456.1 -316.3 557 -252Q657.9 -187.7 785.8 -187.7ZM1717.9 418V-1118H1932.2V-935.9H1950.4Q1970 -970.8 2005.4 -1016.7Q2040.9 -1062.7 2104.6 -1097.3Q2168.3 -1132 2272.6 -1132Q2407.4 -1132 2512.7 -1064Q2617.9 -996 2678.8 -867Q2739.8 -738 2739.8 -556.4Q2739.8 -375.7 2679.8 -246.2Q2619.8 -116.7 2514.5 -47.3Q2409.1 22.2 2272.7 22.2Q2171.8 22.2 2107.4 -12.4Q2043 -47 2006.6 -93.2Q1970.2 -139.3 1950.4 -175H1937.9V418ZM2224 -165.3Q2320.1 -165.3 2384.9 -217.3Q2449.6 -269.3 2482.4 -358.3Q2515.2 -447.3 2515.2 -558Q2515.2 -668.1 2482.8 -755.4Q2450.4 -842.8 2385.7 -893.7Q2321 -944.5 2224 -944.5Q2129.6 -944.5 2065 -896.1Q2000.4 -847.7 1967.4 -761.2Q1934.4 -674.6 1934.4 -558Q1934.4 -441.7 1967.8 -353.2Q2001.2 -264.7 2066.2 -215Q2131.2 -165.3 2224 -165.3ZM3465.8 23.3Q3300.7 23.3 3181.1 -48.1Q3061.4 -119.5 2996.9 -248.5Q2932.4 -377.5 2932.4 -551.1Q2932.4 -723.3 2995.8 -854Q3059.1 -984.7 3175.1 -1058.4Q3291 -1132 3446.8 -1132Q3542.6 -1132 3632 -1100.7Q3721.4 -1069.4 3792.3 -1002.3Q3863.3 -935.2 3904.7 -828.3Q3946.2 -721.5 3946.2 -570.3V-492.2H3054.8V-656.5H3832.8L3730.1 -602.3Q3730.1 -704.7 3698.2 -783.2Q3666.3 -861.7 3603.5 -905.9Q3540.8 -950 3447.5 -950Q3354.2 -950 3288.2 -905Q3222.1 -860 3187.4 -786.5Q3152.6 -712.9 3152.6 -626.1V-514.4Q3152.6 -399.4 3192.1 -319.8Q3231.6 -240.1 3302.9 -199.4Q3374.2 -158.7 3468.1 -158.7Q3529.6 -158.7 3579.9 -176.3Q3630.2 -194 3666.5 -229.4Q3702.8 -264.9 3722.2 -317.2L3928.6 -268.5Q3902.2 -181.6 3838.6 -115.9Q3775 -50.2 3680.4 -13.4Q3585.8 23.3 3465.8 23.3ZM4406.9 -662.4V0H4186.9V-1118H4396.6L4398.9 -844.3H4376.2Q4424.9 -994.3 4517.8 -1063.1Q4610.7 -1132 4742.5 -1132Q4856.6 -1132 4942 -1084.2Q5027.5 -1036.3 5075.1 -942.5Q5122.7 -848.8 5122.7 -710.4V0H4902.7V-682.9Q4902.7 -803.7 4839.8 -872.1Q4776.9 -940.5 4667.3 -940.5Q4592.9 -940.5 4533.8 -907.9Q4474.8 -875.3 4440.8 -813.3Q4406.9 -751.2 4406.9 -662.4ZM5664.4 -1490V0H5435.9V-1490ZM6478.5 0H6109.9V-199.7H6465.8Q6635 -199.7 6747.1 -263Q6859.2 -326.3 6915 -448.6Q6970.8 -571 6970.8 -747.3Q6970.8 -922.1 6915.2 -1043.3Q6859.7 -1164.4 6750.5 -1227.4Q6641.3 -1290.3 6478.4 -1290.3H6102.2V-1490H6493Q6713.2 -1490 6869.9 -1400.9Q7026.7 -1311.8 7110.7 -1145.2Q7194.7 -978.6 7194.7 -747.3Q7194.7 -514.5 7110.4 -347.1Q7026 -179.6 6865.8 -89.8Q6705.5 0 6478.5 0ZM6222.4 -1490V0H5993.9V-1490ZM7471.9 0V-1490H8409.8V-1293.6H7700.4V-849.7H8359.5V-654.7H7700.4V-196.4H8416.4V0ZM8592.9 0 9123.5 -1490H9403.2L9942.8 0H9696.3L9406.1 -828.9Q9372.2 -930 9331.8 -1066.9Q9291.4 -1203.8 9238.4 -1395.6H9284.5Q9232.7 -1202.2 9192.5 -1063.6Q9152.4 -925.1 9121.4 -828.9L8839.9 0ZM8880.4 -392.6V-583.1H9655.3V-392.6Z" />
</svg>
<span>OpenIDEA</span>
<div class="splash-bar" role="progressbar" aria-label="Loading"><i></i></div>
</div>
<script type="module" src="/src/main.tsx"></script>
-26
Переглянути файл
@@ -1,26 +0,0 @@
id = "gdscript"
name = "GDScript"
extensions = ["gd"]
line-comment = "#"
# Godot's default (Editor Settings › Text Editor › Behavior › Indent › Type).
indent = { tab-size = 4, insert-spaces = false }
tree-sitter = "gdscript"
# The language server runs inside the Godot editor and speaks LSP over TCP only:
# connect to an open editor, else start a headless editor for the project on a free port.
[[language-servers]]
name = "godot"
command = "godot"
args = ["--headless", "--editor", "--path", "${root}", "--lsp-port", "${port}"]
connect = "127.0.0.1:6005"
root-markers = ["project.godot"]
install-hint = "Open the project in the Godot editor, or install Godot 4 and set the Godot executable in Settings › Languages & Frameworks › Language Servers › godot"
# Godot's debug adapter also lives in the editor (DAP over TCP, port 6006).
[debugger]
adapter = "godot"
command = "godot"
args = ["--headless", "--editor", "--path", "${root}", "--dap-port", "${port}"]
transport = "tcp"
connect = "127.0.0.1:6006"
install-hint = "Open the project in the Godot editor, or install Godot 4 and set the Godot executable in Settings › Languages & Frameworks › Language Servers › godot"
-8
Переглянути файл
@@ -1,8 +0,0 @@
id = "gdshader"
name = "Godot Shader"
extensions = ["gdshader", "gdshaderinc"]
line-comment = "//"
block-comment = ["/*", "*/"]
indent = { tab-size = 4, insert-spaces = false }
# GLSL-like: the C mode colours keywords, types, numbers and comments.
ui-mode = "C"
-8
Переглянути файл
@@ -1,8 +0,0 @@
id = "godot-resource"
name = "Godot Resource"
# Text scenes / resources, `project.godot`, import metadata and export presets (INI-like).
extensions = ["tscn", "tres", "godot", "import"]
filenames = ["export_presets.cfg", "override.cfg", "extension_list.cfg"]
line-comment = ";"
indent = { tab-size = 4, insert-spaces = false }
ui-mode = "Properties files"
+1 -2
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.16",
"version": "0.1.15",
"license": "Apache-2.0",
"type": "module",
"scripts": {
@@ -52,7 +52,6 @@
"emmet": "2.4.11",
"immer": "^11.1.21",
"marked": "^18.1.1",
"mermaid": "12.1.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-resizable-panels": "^4.14.6",
Створено
-850
File diff suppressed because it is too large. Load diff
+2 -3
Переглянути файл
@@ -17,6 +17,7 @@ body, .splash { background: #e9eaee; }
gap: 14px;
padding-bottom: 38px;
box-sizing: border-box;
font: 500 15px/1.2 "Inter Variable", Inter, system-ui, -apple-system, sans-serif;
color: #6c707e;
-webkit-user-select: none;
user-select: none;
@@ -26,9 +27,7 @@ body, .splash { background: #e9eaee; }
}
.splash.splash-out { opacity: 0; pointer-events: none; }
:root[data-theme^="dark"] .splash { color: #8c8f95; }
.splash-logo { width: 56px; height: 56px; }
/* 15px Inter: 2048 units per em, the line box from ascender to descender. */
.splash-wordmark { width: 73.2px; height: 18.15px; }
.splash svg { width: 56px; height: 56px; }
.splash-bar { width: 120px; height: 2px; border-radius: 1px; overflow: hidden; background: rgb(127 127 127 / 0.18); }
/* Fake progress: eases towards ~90% over the 4 s cap; hideSplash() fills it before fading out. */
.splash-bar > i {
+1 -1
Переглянути файл
@@ -20,7 +20,7 @@ pub async fn debug_start(
};
let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
let custom = |command: &str| {
let path = ide_sdk::apply::tool_command(&root, &settings, command)?;
let path = ide_sdk::apply::setting_path(&root, settings.tool_path(command)?)?;
Some(path.to_string_lossy().into_owned())
};
state.debugger.start_with(config, owner, custom).await
+2 -11
Переглянути файл
@@ -106,25 +106,16 @@ pub async fn lsp_virtual_document(
project!(window, state).lsp.virtual_document(&uri).await
}
/// References of the symbol at `pos`. `project_wide` also searches project files
/// outside the language server's analysis scope; bulk scans over many symbols
/// leave it off. Cancel with `cancel_request(request)`.
#[tauri::command]
#[specta::specta]
pub async fn lsp_references(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
pos: Pos,
include_declaration: bool,
project_wide: bool,
) -> IdeResult<References> {
let lsp = project!(window, state).lsp.clone();
let cancel = state.begin_request(request);
let result = lsp.references(doc, pos, include_declaration, project_wide, cancel).await;
state.end_request(request);
result
) -> IdeResult<Vec<Location>> {
project!(window, state).lsp.references(doc, pos, include_declaration).await
}
#[tauri::command]
+1 -8
Переглянути файл
@@ -61,14 +61,7 @@ pub fn run_start(
if config.command.is_empty() {
return Err(IdeError::invalid("run configuration has no command"));
}
let settings = project.settings.effective();
// Configurations made in the UI name bare tools (`godot`) that may live outside PATH.
let mut config = config;
ide_sdk::apply::resolve_run_command(&mut config, &root, &settings);
if config.command == ide_sdk::godot::COMMAND {
return Err(IdeError::unavailable(ide_sdk::godot::NOT_FOUND));
}
let encoding = settings.console.encoding;
let encoding = project.settings.effective().console.encoding;
let options = StartOptions { encoding: Some(encoding).filter(|e| !e.trim().is_empty()) };
state.processes.start(
&root,
+1 -3
Переглянути файл
@@ -21,9 +21,7 @@ fn tools(app: &AppHandle, state: &AppState, window: &Window) -> IdeResult<Tools>
.iter()
.filter_map(|(command, t)| Some((command.clone(), ide_sdk::apply::setting_path(&root, &t.path)?)))
.collect();
// Godot is usually an app bundle / Flatpak outside the search path.
let found = ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p));
Ok(Tools::new(&data).with_custom_paths(custom).with_found_paths(found.into_iter().collect()))
Ok(Tools::new(&data).with_custom_paths(custom))
}
fn join_err(e: impl std::fmt::Display) -> IdeError {
+1 -8
Переглянути файл
@@ -41,10 +41,6 @@ pub struct VcsRoot {
pub root: ide_core::IpcPath,
/// Merge / rebase / cherry-pick / revert in progress.
pub operation: Option<String>,
/// Current branch; `None` when HEAD is detached (or unreadable).
pub head: Option<String>,
/// HEAD commit; `None` before the first commit.
pub head_commit: Option<String>,
}
/// The project's repositories, the primary one first.
@@ -57,10 +53,7 @@ pub fn vcs_roots(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<Vc
all.sort_by_key(|r| Some(r.root()) != primary.as_deref());
Ok(all
.into_iter()
.map(|r| {
let (head, head_commit) = r.head().unwrap_or_default();
VcsRoot { root: r.root().to_path_buf().into(), operation: r.operation().ok().flatten(), head, head_commit }
})
.map(|r| VcsRoot { root: r.root().to_path_buf().into(), operation: r.operation().ok().flatten() })
.collect())
}
+9 -47
Переглянути файл
@@ -5,13 +5,6 @@
//! Spawning an interactive login shell costs ~1 s with typical rc files, so the
//! value is cached: a warm start uses the cached PATH immediately and refreshes
//! the cache in the background for the next launch.
//!
//! The rest of the shell's environment (API keys, provider switches, SDK homes)
//! goes to child processes through `ide_core::process::shell_env`. It stays in
//! memory, never in the cache: it may hold secrets.
#[cfg(unix)]
use std::ffi::{OsStr, OsString};
#[cfg(unix)]
/// Returns a refresh to run once the environment is final (it spawns a
@@ -29,9 +22,7 @@ pub fn inherit_login_shell_path(identifier: &str) -> Option<impl FnOnce() + use<
Some(path) => path,
None => {
// Slow shell rc files must not delay the first start indefinitely.
let env = read_login_env(Duration::from_secs(3))?;
let fresh = login_path(&env)?;
ide_core::process::set_shell_env(env);
let fresh = read_login_path(Duration::from_secs(3))?;
if let Some(cache) = &cache {
write_cache(cache, &fresh);
}
@@ -43,11 +34,9 @@ pub fn inherit_login_shell_path(identifier: &str) -> Option<impl FnOnce() + use<
let cache = cache.filter(|_| refresh)?;
Some(move || {
std::thread::spawn(move || {
let Some(env) = read_login_env(Duration::from_secs(10)) else { return };
if let Some(fresh) = login_path(&env) {
if let Some(fresh) = read_login_path(Duration::from_secs(10)) {
write_cache(&cache, &fresh);
}
ide_core::process::set_shell_env(env);
});
})
}
@@ -61,37 +50,20 @@ fn write_cache(cache: &std::path::Path, path: &str) {
}
#[cfg(unix)]
fn login_path(env: &[(OsString, OsString)]) -> Option<String> {
env.iter().find(|(k, _)| k == "PATH").and_then(|(_, v)| v.to_str()).filter(|p| !p.is_empty()).map(str::to_owned)
}
/// Variables the shell sets for itself rather than the user's configuration.
#[cfg(unix)]
const SHELL_OWN: &[&str] = &["PWD", "OLDPWD", "SHLVL", "_"];
/// The login shell's environment; PATH included, the shell's own bookkeeping left out.
#[cfg(unix)]
fn read_login_env(timeout: std::time::Duration) -> Option<Vec<(OsString, OsString)>> {
fn read_login_path(timeout: std::time::Duration) -> Option<String> {
use std::io::Read;
use std::os::unix::ffi::OsStrExt;
use std::process::{Command, Stdio};
use std::time::Instant;
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/zsh".into());
const MARK: &str = "__OPENIDEA_ENV__";
const MARK: &str = "__OPENIDEA_PATH__";
let mut child = Command::new(&shell)
.args(["-ilc", &format!("printf '{MARK}'; /usr/bin/env -0; printf '{MARK}'")])
.args(["-ilc", &format!("printf '{MARK}%s{MARK}' \"$PATH\"")])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.ok()?;
// Read while waiting: a large environment would fill the pipe and stall the shell.
let mut stdout = child.stdout.take()?;
let reader = std::thread::spawn(move || {
let mut out = Vec::new();
stdout.read_to_end(&mut out).map(|_| out)
});
let deadline = Instant::now() + timeout;
loop {
match child.try_wait() {
@@ -99,24 +71,14 @@ fn read_login_env(timeout: std::time::Duration) -> Option<Vec<(OsString, OsStrin
Ok(None) if Instant::now() < deadline => std::thread::sleep(std::time::Duration::from_millis(20)),
_ => {
let _ = child.kill();
tracing::warn!("timed out reading the environment from {shell}");
tracing::warn!("timed out reading PATH from {shell}");
return None;
}
}
}
let out = reader.join().ok()?.ok()?;
let mark = MARK.as_bytes();
let start = out.windows(mark.len()).position(|w| w == mark)? + mark.len();
let len = out[start..].windows(mark.len()).position(|w| w == mark)?;
let vars = out[start..start + len]
.split(|&b| b == 0)
.filter_map(|entry| {
let eq = entry.iter().position(|&b| b == b'=')?;
let (k, v) = (OsStr::from_bytes(&entry[..eq]), OsStr::from_bytes(&entry[eq + 1..]));
(!k.is_empty() && !SHELL_OWN.iter().any(|s| k == *s)).then(|| (k.to_owned(), v.to_owned()))
})
.collect();
Some(vars)
let mut out = String::new();
child.stdout.take()?.read_to_string(&mut out).ok()?;
out.split(MARK).nth(1).filter(|p| !p.is_empty()).map(str::to_owned)
}
#[cfg(not(unix))]
-33
Переглянути файл
@@ -442,12 +442,6 @@ impl AppState {
content_watchers: Mutex::new(content_watchers),
_scratch_watcher: scratch_watcher,
});
{
let weak = Arc::downgrade(&project);
project.lsp.set_candidates_hook(Box::new(move |q, cancel| {
weak.upgrade().map(|p| p.reference_candidates(q, cancel)).unwrap_or_default()
}));
}
self.projects.write().insert(window.to_owned(), project.clone());
Ok(project)
}
@@ -615,33 +609,6 @@ impl Project {
out
}
/// Project files of `q.languages` under `q.root` containing `q.word` as a whole
/// word (unsaved buffers included; excluded roots, ignored names and
/// `.gitignore`d files skipped): the files a references search opens on its server.
pub fn reference_candidates(
&self,
q: &ide_lsp::CandidateQuery,
cancel: &CancellationToken,
) -> ide_lsp::CandidateFiles {
if !q.root.starts_with(&self.root) {
return ide_lsp::CandidateFiles::default();
}
let query = ide_search::WordQuery {
word: q.word.clone(),
dir: q.root.clone(),
exclude: self.search_excludes(),
limit: q.limit,
};
let filter = |rel: &str| q.languages.contains(&self.languages.detect(&self.root.join(rel), None));
match ide_search::files_with_word(&self.root, &query, Some(&filter), &|p| self.documents.text_of(p), cancel) {
Ok(found) => ide_lsp::CandidateFiles { files: found.files, limit_hit: found.limit_hit },
Err(e) => {
tracing::debug!("reference candidates: {}", e.message);
ide_lsp::CandidateFiles::default()
}
}
}
/// `files.exclude`, the ignored names and the effective excluded roots (user-marked and detected).
pub fn exclude_globs(&self) -> Vec<String> {
exclude_globs(&self.settings.effective(), &self.detected_roots.read())
+1 -1
Переглянути файл
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenIDEA",
"version": "0.1.16",
"version": "0.1.15",
"identifier": "ai.l0ng.openidea",
"build": {
"beforeDevCommand": "pnpm dev",
+1 -22
Переглянути файл
@@ -287,12 +287,7 @@ export const commands = {
* language server returned a non-`file:` URI for. Cached per project.
*/
lspVirtualDocument: (uri: string) => typedError<VirtualDocument, IdeError>(__TAURI_INVOKE("lsp_virtual_document", { uri })),
/**
* References of the symbol at `pos`. `project_wide` also searches project files
* outside the language server's analysis scope; bulk scans over many symbols
* leave it off. Cancel with `cancel_request(request)`.
*/
lspReferences: (request: RequestId, doc: DocId, pos: Pos, includeDeclaration: boolean, projectWide: boolean) => typedError<References, IdeError>(__TAURI_INVOKE("lsp_references", { request, doc, pos, includeDeclaration, projectWide })),
lspReferences: (doc: DocId, pos: Pos, includeDeclaration: boolean) => typedError<Location[], IdeError>(__TAURI_INVOKE("lsp_references", { doc, pos, includeDeclaration })),
lspDocumentHighlights: (doc: DocId, pos: Pos) => typedError<Highlight[], IdeError>(__TAURI_INVOKE("lsp_document_highlights", { doc, pos })),
lspWorkspaceSymbols: (request: RequestId, query: string) => typedError<WorkspaceSymbol[], IdeError>(__TAURI_INVOKE("lsp_workspace_symbols", { request, query })),
lspCodeActions: (doc: DocId, range: Range, only: string[]) => typedError<CodeAction[], IdeError>(__TAURI_INVOKE("lsp_code_actions", { doc, range, only })),
@@ -4180,18 +4175,6 @@ export type RecentProject = {
branch: string | null,
};
export type References = {
locations: Location[],
incomplete: ReferencesIncomplete | null,
};
/** Why a references search may have missed usages. */
export type ReferencesIncomplete =
/** A language server was still indexing. */
"indexing" |
/** More project files mention the name than were checked. */
"tooManyFiles";
export type Remote = {
name: string,
/** Fetch URL. */
@@ -5167,10 +5150,6 @@ export type VcsRoot = {
root: IpcPath,
/** Merge / rebase / cherry-pick / revert in progress. */
operation: string | null,
/** Current branch; `None` when HEAD is detached (or unreadable). */
head: string | null,
/** HEAD commit; `None` before the first commit. */
headCommit: string | null,
};
/** Version Control (main page) and its sub-pages. */
+1 -17
Переглянути файл
@@ -37,7 +37,7 @@ import { qualifiedReference } from "./copyReference";
import { symbolChain } from "./view/outline";
import { recordClipboard } from "./clipboardHistory";
import { useDocMeta, useOutline } from "./model/document";
import { fontZoom, setFontZoom, stepFontZoom } from "./cm/prefs";
import { fontZoom, setFontZoom } from "./cm/prefs";
import { useEditorRegistry } from "@/editor/api";
import { useProject } from "@/platform/project";
import { call, commands } from "@/platform/ipc";
@@ -471,22 +471,6 @@ export function registerEditorActions(): () => void {
if (ed.view.state.field(fontZoom, false)) ed.view.dispatch({ effects: setFontZoom.of(0) });
},
},
{
id: "editor.increaseFontSize",
title: "Increase Font Size",
category: "View",
keywords: ["zoom", "font size"],
when: EDITOR_WHEN,
run: withView((view) => stepFontZoom(view, 1)),
},
{
id: "editor.decreaseFontSize",
title: "Decrease Font Size",
category: "View",
keywords: ["zoom", "font size"],
when: EDITOR_WHEN,
run: withView((view) => stepFontZoom(view, -1)),
},
{
id: "file.toggleReadOnly",
title: "Toggle Read-only Attribute",
+4 -11
Переглянути файл
@@ -343,9 +343,8 @@ export const setFontZoom = StateEffect.define<number>();
export const fontZoom = StateField.define<number>({
create: () => 0,
update: (v, tr) => tr.effects.reduce((acc, e) => (e.is(setFontZoom) ? e.value : acc), v),
// Highest precedence: its style comes after the configured font size, which it scales.
provide: (f) =>
Prec.highest(
Prec.lowest(
EditorView.editorAttributes.compute([f], (s) => {
const z = s.field(f);
const attrs: Record<string, string> = {};
@@ -356,19 +355,13 @@ export const fontZoom = StateField.define<number>({
),
});
/** Steps an editor's font zoom by `delta` px, kept within -6..36. */
export function stepFontZoom(view: EditorView, delta: number): void {
const z = view.state.field(fontZoom, false);
if (z === undefined) return;
const next = Math.max(-6, Math.min(36, z + delta));
if (next !== z) view.dispatch({ effects: setFontZoom.of(next) });
}
const wheelZoom = EditorView.domEventHandlers({
wheel(e, view) {
if (!e.metaKey && !e.ctrlKey) return false;
e.preventDefault();
stepFontZoom(view, e.deltaY < 0 ? 1 : -1);
const z = view.state.field(fontZoom, false) ?? 0;
const next = Math.max(-6, Math.min(36, z + (e.deltaY < 0 ? 1 : -1)));
if (next !== z) view.dispatch({ effects: setFontZoom.of(next) });
return true;
},
});
+2 -4
Переглянути файл
@@ -9,7 +9,7 @@ import { EditorSelection, MapMode, StateEffect, StateField, type Extension, type
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { codeLenses, type CodeLens } from "@/editor/api";
import { executeAction } from "@/platform/actions";
import { commands, nextRequestId, type OutlineItem, type SymbolKind } from "@/platform/ipc";
import { commands, type OutlineItem, type SymbolKind } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { debounce, docOf, isUnavailable, lspRequest } from "./lsp";
import { posToOffset } from "./positions";
@@ -166,9 +166,7 @@ class UsagesLensPlugin {
await Promise.all(
todo.slice(i, i + CONCURRENCY).map(async (t) => {
try {
const { locations: refs } = await lspRequest(() =>
commands.lspReferences(nextRequestId(), doc.doc, { line: t.line, col: t.col }, false, true),
);
const refs = await lspRequest(() => commands.lspReferences(doc.doc, { line: t.line, col: t.col }, false));
this.cache.set(key(t), refs.length);
} catch (e) {
if (isUnavailable(e)) unavailable = true;
+1 -41
Переглянути файл
@@ -4,16 +4,13 @@ import { EditorView } from "@codemirror/view";
import type { InlayHint } from "@/bindings";
const openFile = vi.fn(async () => undefined);
const gotoTargets = vi.fn(async () => undefined);
vi.mock("./navigation", () => ({ gotoTargets }));
vi.mock("@/workbench/contributions", async (orig) => {
const actual = await orig<typeof import("@/workbench/contributions")>();
return { ...actual, maybeEditorService: () => ({ openFile }) };
});
const { inlayDecorations, inlayExtension, inlayMenuItems } = await import("./inlay");
const { inlayDecorations, inlayMenuItems } = await import("./inlay");
const { usePlatform } = await import("@/platform/platformInfo");
const { resetNavigationModifier } = await import("@/platform/navigationModifier");
const { useContextMenuStore } = await import("@/ui");
const hint: InlayHint = {
@@ -36,7 +33,6 @@ const hint: InlayHint = {
const views: EditorView[] = [];
afterEach(() => {
views.splice(0).forEach((v) => v.destroy());
resetNavigationModifier();
vi.clearAllMocks();
});
@@ -75,40 +71,4 @@ describe("inlay hints", () => {
]);
expect((inlayMenuItems("parameter")[0] as { label: string }).label).toBe("Disable Parameter name hints");
});
it("uses type declaration navigation for a plain type hint after an identifier", () => {
usePlatform.setState({ os: "macos" });
const view = editorWith([{ ...hint, label: ": Foo", parts: [] }]);
const el = view.dom.querySelector<HTMLElement>(".cm-lsp-inlay")!;
el.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }));
expect(gotoTargets).not.toHaveBeenCalled();
el.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0, metaKey: true }));
expect(gotoTargets).toHaveBeenCalledWith(view, "typeDefinition", 4);
expect(openFile).not.toHaveBeenCalled();
});
it("does not treat parameter hints or type hints away from an identifier as type links", () => {
const view = editorWith([
{ ...hint, kind: "parameter", parts: [] },
{ ...hint, position: { line: 0, col: 6 }, parts: [] },
]);
expect(view.dom.querySelectorAll(".cm-lsp-inlay-part")).toHaveLength(0);
});
it.each([
{ os: "macos", key: "Meta", modifier: "metaKey" },
{ os: "windows", key: "Control", modifier: "ctrlKey" },
] as const)("tracks the navigation modifier for inlay cursors on $os", ({ os, key, modifier }) => {
usePlatform.setState({ os });
const view = new EditorView({
state: EditorState.create({ doc: "let x = foo();", extensions: [inlayExtension()] }),
parent: document.body,
});
views.push(view);
expect(view.contentDOM.classList.contains("cm-lsp-navigation-modifier")).toBe(false);
window.dispatchEvent(new KeyboardEvent("keydown", { key, [modifier]: true }));
expect(view.contentDOM.classList.contains("cm-lsp-navigation-modifier")).toBe(true);
window.dispatchEvent(new KeyboardEvent("keyup", { key }));
expect(view.contentDOM.classList.contains("cm-lsp-navigation-modifier")).toBe(false);
});
});
+1 -30
Переглянути файл
@@ -8,7 +8,7 @@ import { StateEffect, StateField, type Extension } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { call, commands, isTauri, type InlayHint } from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { isNavigationGesture, navigationModifierHeld, onNavigationModifier } from "@/platform/navigationModifier";
import { isNavigationGesture } from "@/platform/navigationModifier";
import { maybeEditorService } from "@/workbench/contributions";
import { showContextMenu, type MenuItem } from "@/ui";
import { useProject } from "@/platform/project";
@@ -16,7 +16,6 @@ import { editorPrefs } from "@/platform/editorSettings";
import { debounce, docOf, isUnavailable, lspRequest } from "./lsp";
import { offsetsToRange, posToOffset } from "./positions";
import { onLspRefresh, serverBackoff } from "./availability";
import { gotoTargets } from "./navigation";
const KIND_LABEL: Record<InlayHint["kind"], string> = {
type: "Type hints",
@@ -29,13 +28,6 @@ async function setEditorSetting(key: string, value: unknown) {
useProject.setState({ settings: await call(commands.settingsSet("global", `editor.${key}`, JSON.stringify(value))) });
}
/** A type hint after an identifier can resolve that identifier's inferred type. */
function typeHintOffset(view: EditorView, at: number): number | null {
if (at <= 0 || at > view.state.doc.length) return null;
const word = view.state.wordAt(at - 1);
return word?.to === at ? word.from : null;
}
/** Right-click on a hint: turn its kind off (IDEA's "Disable '…' hints"), or open the settings. */
export function inlayMenuItems(kind: InlayHint["kind"]): MenuItem[] {
return [
@@ -89,22 +81,6 @@ class InlayWidget extends WidgetType {
el.appendChild(span);
}
} else el.textContent = this.hint.label;
// A plain type hint (basedpyright's `: Series`) names no location: ⌘-click opens the preceding identifier's type.
if (
this.hint.kind === "type" &&
!parts.some((p) => p.location) &&
typeHintOffset(view, posToOffset(view.state.doc, this.hint.position)) !== null
) {
el.classList.add("cm-lsp-inlay-part");
el.addEventListener("mousedown", (e) => {
if (e.button !== 0 || !isNavigationGesture(e)) return;
const offset = typeHintOffset(view, view.posAtDOM(el));
if (offset === null) return;
e.preventDefault();
e.stopPropagation();
void gotoTargets(view, "typeDefinition", offset);
});
}
if (this.hint.tooltip) el.title = this.hint.tooltip;
el.setAttribute("aria-hidden", "true");
el.addEventListener("contextmenu", (e) => {
@@ -155,11 +131,8 @@ const inlayPlugin = ViewPlugin.fromClass(
private refresh = debounce(() => void this.run(), 400);
private unsubscribe: () => void;
private offReady: () => void;
private offModifier: () => void;
constructor(private view: EditorView) {
this.refresh();
view.contentDOM.classList.toggle("cm-lsp-navigation-modifier", navigationModifierHeld());
this.offModifier = onNavigationModifier((held) => view.contentDOM.classList.toggle("cm-lsp-navigation-modifier", held));
this.unsubscribe = useProject.subscribe((s, prev) => {
if (s.settings?.editor?.inlayHints !== prev.settings?.editor?.inlayHints || s.settings?.editor?.inlay !== prev.settings?.editor?.inlay)
this.refresh();
@@ -194,8 +167,6 @@ const inlayPlugin = ViewPlugin.fromClass(
this.refresh.cancel();
this.unsubscribe();
this.offReady();
this.offModifier();
this.view.contentDOM.classList.remove("cm-lsp-navigation-modifier");
}
},
);
+1 -5
Переглянути файл
@@ -328,11 +328,7 @@ export const lspTheme = EditorView.theme({
userSelect: "none",
},
// A part naming a declaration (⌘-click navigates there).
".cm-lsp-navigation-modifier .cm-lsp-inlay-part:hover": {
textDecoration: "underline",
textUnderlineOffset: "2px",
cursor: "pointer",
},
".cm-lsp-inlay-part:hover": { textDecoration: "underline", textUnderlineOffset: "2px" },
// Inline completion: the suggestion as gray text at the caret.
".cm-inline-ghost": { color: "var(--fg-subtle)", whiteSpace: "pre" },
".cm-lsp-inlay-pl": { marginLeft: "4px" },
+1 -4
Переглянути файл
@@ -16,10 +16,7 @@ let outline: Answer<OutlineItem[]> = ok([]);
let references: Answer<Location[]> = ok([]);
const lspGoto = vi.fn(async () => goto());
const docOutline = vi.fn(async () => outline());
const lspReferences = vi.fn(async () => {
const r = references();
return r.status === "ok" ? { status: "ok" as const, data: { locations: r.data, incomplete: null } } : r;
});
const lspReferences = vi.fn(async () => references());
const lspCodeActions = vi.fn(async () => ({ status: "ok", data: [] }));
const lspApplyCodeAction = vi.fn(async () => ({ status: "ok", data: null }));
const docOpen = vi.fn(async (path: string) => ({ status: "ok", data: { id: 99, path } }));
+3 -4
Переглянути файл
@@ -13,7 +13,7 @@
import type { EditorView } from "@codemirror/view";
import type { Text } from "@codemirror/state";
import type { LocalSymbol, Location, OutlineItem, Pos, Range, SyntaxNode } from "@/bindings";
import { call, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
import { call, commands, isCancelled, isTauri } from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { basename } from "@/platform/project";
import { editorsFor, whenSynced, type EditorDocContext } from "@/editor/api";
@@ -252,7 +252,7 @@ async function findUsages(ctx: EditorDocContext, target: SafeDeleteTarget): Prom
comparePos(range.start, target.range.end) > 0;
if (target.local)
return target.local.references.filter((r) => outside(ctx.path, r)).map((range) => ({ path: ctx.path, range }));
const { locations: refs } = await lspRequest(() => commands.lspReferences(nextRequestId(), ctx.doc, target.at, false, true));
const refs = await lspRequest(() => commands.lspReferences(ctx.doc, target.at, false));
return refs.filter((l) => outside(l.path, l.range));
}
@@ -517,8 +517,7 @@ export async function fileUsages(paths: readonly string[], signal?: AbortSignal)
if (signal?.aborted) return;
let refs: Location[];
try {
// Every symbol of every file: the server's own scope (a project search each would be too slow).
refs = (await lspRequest(() => commands.lspReferences(nextRequestId(), doc, item.selection_range.start, false, false))).locations;
refs = await lspRequest(() => commands.lspReferences(doc, item.selection_range.start, false));
} catch (e) {
if (isUnavailable(e)) {
reason = errorText(e);
+1 -5
Переглянути файл
@@ -28,7 +28,6 @@ import {
} from "./composerModel";
import { composerDraft, updateComposer, useAgents } from "./store";
import styles from "./Composer.module.css";
import { isImeKey } from "@/platform/ime";
const MAX_PROMPT_HEIGHT = 280;
const MAX_ITEMS = 12;
@@ -214,7 +213,7 @@ export function Composer(props: ComposerProps) {
}, [id, root]);
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (isImeKey(e.nativeEvent)) return;
if (e.nativeEvent.isComposing) return;
if (open) {
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
@@ -321,9 +320,6 @@ export function Composer(props: ComposerProps) {
ref={ref}
className={styles.textarea}
rows={2}
spellCheck={false}
autoCorrect="off"
autoCapitalize="off"
value={text}
aria-label={tx("Message")}
placeholder={tx(props.placeholder)}
+2 -6
Переглянути файл
@@ -38,18 +38,14 @@
.headerDetail {
flex: 1 1 0;
min-width: 0;
display: flex;
align-items: center;
gap: 4px;
color: var(--fg-subtle);
}
.headerText {
min-width: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.providerIcon {
vertical-align: -2px;
margin-right: 4px;
color: var(--fg-muted);
}
.muted {
+6 -8
Переглянути файл
@@ -68,14 +68,12 @@ function Header({ task }: { task: AgentTask }) {
</span>
<span className={styles.headerDetail} title={task.cwd}>
<Icon name={providerIcon(task.provider)} size={13} className={styles.providerIcon} />
<span className={styles.headerText}>
{providerName(task.provider)}
{task.model ? ` · ${task.model}` : ""}
{" · "}
{where ?? <T>Local checkout</T>}
{" · "}
<T>{statusLabel(task.status)}</T>
</span>
{providerName(task.provider)}
{task.model ? ` · ${task.model}` : ""}
{" · "}
{where ?? <T>Local checkout</T>}
{" · "}
<T>{statusLabel(task.status)}</T>
</span>
{task.usage && <Usage task={task} />}
{busy && <IconButton icon="stop" title="Stop" size="small" onClick={() => void cancelTask(task.id)} />}
+2 -12
Переглянути файл
@@ -24,7 +24,7 @@ vi.mock("@/platform/ipc", async (orig) => {
vi.mock("./candidates", () => ({ filesMentioning: () => filesMentioning() }));
const { _addEditor } = await import("@/editor/api");
const { fetchUsages, incompleteNote } = await import("./usages");
const { fetchUsages } = await import("./usages");
const { LOCAL_NOTE, TEXT_NOTE } = await import("./syntaxUsages");
const r = (line: number, col: number, endCol: number): Range => ({ start: { line, col }, end: { line, col: endCol } });
@@ -39,21 +39,11 @@ beforeEach(() => {
describe("Find Usages fallback", () => {
it("uses the server when it answers, even with nothing", async () => {
cmd.lspReferences.mockReturnValueOnce(ok({ locations: [], incomplete: null }));
cmd.lspReferences.mockReturnValueOnce(ok([]));
expect(await fetchUsages(caret)).toEqual({ groups: [], note: null });
expect(cmd.syntaxLocals).not.toHaveBeenCalled();
});
it("searches project-wide under the given request and says when results may be incomplete", async () => {
const usage = { path: "/p/a.ts", range: r(1, 0, 1) };
cmd.lspReferences.mockReturnValueOnce(ok({ locations: [usage], incomplete: "indexing" }));
const res = await fetchUsages(caret, 42 as never);
expect(cmd.lspReferences).toHaveBeenCalledWith(42, 3, { line: 1, col: 0 }, false, true);
expect(res.groups[0]!.usages.length).toBe(1);
expect(res.note).toBe(incompleteNote("indexing", "x"));
expect(incompleteNote("tooManyFiles", "x")).toBe("May be incomplete: too many files mention 'x' to search them all");
});
it("lists a certain local's references when the server is not ready", async () => {
cmd.syntaxLocals.mockReturnValueOnce(
ok({
+9 -47
Переглянути файл
@@ -1,7 +1,7 @@
/** Find Usages (⌥F7 → "usages" tool window) and Show Usages (⌥⌘F7 → popup). */
import { create } from "zustand";
import type { Location, ReferencesIncomplete, RequestId } from "@/bindings";
import { commands, isCancelled, nextRequestId } from "@/platform/ipc";
import type { Location } from "@/bindings";
import { commands, isCancelled } from "@/platform/ipc";
import { toolWindowService } from "@/workbench/contributions";
import {
caretContext,
@@ -119,7 +119,6 @@ export function pinUsageTab(id: number, pinned: boolean) {
}
export function closeUsageTab(id: number) {
cancelSearch(id);
useUsages.setState((s) => {
const i = s.tabs.findIndex((t) => t.id === id);
const tabs = s.tabs.filter((t) => t.id !== id);
@@ -154,25 +153,15 @@ interface FetchedUsages {
note: string | null;
}
/** Why the server's answer may miss usages, for the results' note. */
export function incompleteNote(reason: ReferencesIncomplete, word: string | null): string {
if (reason === "indexing") return "May be incomplete: the language server is still indexing";
return `May be incomplete: too many files mention ${word ? `'${word}'` : "the name"} to search them all`;
}
/**
* The server's references across the project (files outside its analysis scope
* included); when it is not ready or fails, the syntax fallback (an empty server
* answer is respected). Without a fallback the server error stands.
* Cancel with `commands.cancelRequest(request)`.
* The server's references; when it is not ready or fails, the syntax fallback
* (an empty server answer is respected). Without a fallback the server error stands.
*/
export async function fetchUsages(c: CaretContext, request: RequestId = nextRequestId()): Promise<FetchedUsages> {
export async function fetchUsages(c: CaretContext): Promise<FetchedUsages> {
let locs: Location[];
let note: string | null = null;
try {
const refs = await lspRequest(() => commands.lspReferences(request, c.doc, { line: c.line, col: c.col }, false, true));
locs = refs.locations;
if (refs.incomplete) note = incompleteNote(refs.incomplete, c.word);
locs = await lspRequest(() => commands.lspReferences(c.doc, { line: c.line, col: c.col }, false));
} catch (e) {
if (isCancelled(e)) throw e;
let fb = null;
@@ -190,22 +179,8 @@ export async function fetchUsages(c: CaretContext, request: RequestId = nextRequ
return { groups: groupUsages(locs, files), note };
}
/** In-flight server requests: of tool window searches by search id, and of the popup. */
const inflight = new Map<number, RequestId>();
let popupRequest: RequestId | null = null;
function cancelSearch(id: number) {
const request = inflight.get(id);
if (request === undefined) return;
inflight.delete(id);
void commands.cancelRequest(request).catch(() => {});
}
/** The window switched projects: results (and in-flight searches) of the previous one are dropped. */
export function resetUsages() {
for (const id of [...inflight.keys()]) cancelSearch(id);
if (popupRequest !== null) void commands.cancelRequest(popupRequest).catch(() => {});
popupRequest = null;
useUsages.setState({ tabs: [], active: null });
useUsagesPopup.setState({ open: false, symbol: null, groups: [], note: null });
}
@@ -220,22 +195,15 @@ export async function findUsages() {
const id = ++searchSeq;
const base = { id, symbol: c.word, rerun: () => void run(id) };
const loading = { ...base, loading: true, groups: [], error: null, note: null };
if (prev !== null) cancelSearch(prev);
if (prev === null || !replaceUsageTab(prev, loading)) openUsageTab(loading);
toolWindowService().show("usages");
const request = nextRequestId();
inflight.set(id, request);
try {
const { groups, note } = await fetchUsages(c, request);
const { groups, note } = await fetchUsages(c);
replaceUsageTab(id, { ...base, loading: false, groups, error: null, note });
} catch (e) {
// Cancelled here (closed tab, rerun): a newer state already replaced it.
if (isCancelled(e) && !inflight.has(id)) return;
const message = e instanceof Error ? e.message : String(e);
if (!replaceUsageTab(id, { ...base, loading: false, groups: [], error: message, note: null })) return;
reportError(e);
} finally {
if (inflight.get(id) === request) inflight.delete(id);
}
};
await run(null);
@@ -264,15 +232,11 @@ export async function showUsagesPopup() {
hint("Open a file to show usages");
return;
}
if (popupRequest !== null) void commands.cancelRequest(popupRequest).catch(() => {});
const request = nextRequestId();
popupRequest = request;
try {
const { groups, note } = await fetchUsages(c, request);
const { groups, note } = await fetchUsages(c);
const total = usageCount(groups);
if (!total) {
const none = c.word ? `No usages of '${c.word}' found` : "No usages found";
hint(note ? `${none}. ${note}` : none);
hint(c.word ? `No usages of '${c.word}' found` : "No usages found");
return;
}
if (total === 1) {
@@ -285,7 +249,5 @@ export async function showUsagesPopup() {
useUsagesPopup.setState({ open: true, anchor: caretPoint(), symbol: c.word, groups, note });
} catch (e) {
reportError(e);
} finally {
if (popupRequest === request) popupRequest = null;
}
}
+1 -1
Переглянути файл
@@ -6,7 +6,7 @@ const loc = { path: "/p/b.ts", range: { start: { line: 1, col: 4 }, end: { line:
vi.mock("./ipc", async (orig) => ({
...(await orig<typeof import("./ipc")>()),
caretContext: () => ({ doc: 1, path: "/p/a.ts", line: 0, col: 0, word: "used", view: null }),
lspRequest: async () => ({ locations: [loc], incomplete: null }),
lspRequest: async () => [loc],
readManyFileLines: async () => new Map([["/p/b.ts", ["", " used();"]]]),
openLocation: async (path: string, line: number) => void calls.push(`open ${path}:${line}`),
hint: (text: string) => void calls.push(`hint ${text}`),
+1 -2
Переглянути файл
@@ -6,7 +6,6 @@ import { sshLabel } from "./model";
import { SourceDialog } from "./SourceDialog";
import { closeDialog, useDatabase } from "./store";
import styles from "./Database.module.css";
import { isImeKey } from "@/platform/ime";
const ObjectDialogs = lazyComponent(() => import("./ObjectDialogs").then((m) => m.ObjectDialogs));
const ExportDialog = lazyComponent(() => import("./ExportDialog").then((m) => m.ExportDialog));
@@ -139,7 +138,7 @@ function ParamsDialog({
<div
className={styles.form}
onKeyDown={(e) => {
if (e.key !== "Enter" || isImeKey(e.nativeEvent)) return;
if (e.key !== "Enter" || e.nativeEvent.isComposing) return;
e.preventDefault();
done(values);
}}
+1 -2
Переглянути файл
@@ -23,7 +23,6 @@ import { colorVar, connectRemedy, fileSourceName, newSourceId, parseSourceUrl, s
import { closeDialog, loadDatabases, loadSchemas, saveSource, useDatabase } from "./store";
import { VENDORS, sourceUrl, vendorById, vendorOf } from "./vendors";
import styles from "./Database.module.css";
import { isImeKey } from "@/platform/ime";
type Tab = "general" | "options" | "ssh" | "schemas" | "advanced";
@@ -285,7 +284,7 @@ function NamePicker({
aria-label={`Add ${title} pattern`}
onChange={(e) => setPattern(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !isImeKey(e.nativeEvent)) {
if (e.key === "Enter" && !e.nativeEvent.isComposing) {
e.preventDefault();
add();
}
-11
Переглянути файл
@@ -197,15 +197,4 @@ describe("run config → launch config", () => {
// lldb-dap takes `KEY=VALUE` strings.
expect(extra(dap)).toEqual({ env: ["K=v"] });
});
it("Godot: the editor's adapter plays the main scene or the chosen one of the project", () => {
const project = rc({ kind: "godot", command: "/Apps/Godot", args: ["--path", "."], cwd: "game", debugAdapter: "godot" });
const main = launchConfigFor(project, "/p")!;
expect(main).toMatchObject({ adapter: "godot", request: "launch", cwd: "/p/game", program: null });
expect(extra(main)).toEqual({ project: "/p/game", scene: "main" });
const scene = launchConfigFor({ ...project, args: ["--path", ".", "res://levels/one.tscn"] }, "/p")!;
expect(extra(scene)).toEqual({ project: "/p/game", scene: "res://levels/one.tscn" });
const relative = launchConfigFor({ ...project, cwd: null, args: ["--path", "game", "menu.tscn"] }, "/p")!;
expect(extra(relative)).toEqual({ project: "/p/game", scene: "res://menu.tscn" });
});
});
-8
Переглянути файл
@@ -137,14 +137,6 @@ describe("remote attach requests", () => {
});
});
it("Attach to Godot connects to the editor's debug adapter for the project", () => {
const l = remoteAttachConfig(configOf(remote.godotAttachType), "/p/game")!;
expect(l).toMatchObject({ adapter: "godot", request: "attach", cwd: "/p/game" });
expect(JSON.parse(l.extraJson!)).toEqual({ debugServer: "localhost:6006", project: "/p/game" });
const custom = remoteAttachConfig(configOf(remote.godotAttachType, { port: "6010" }), "/p")!;
expect(JSON.parse(custom.extraJson!).debugServer).toBe("localhost:6010");
});
it("Attach to Node.js attaches js-debug to the inspector with local/remote roots", () => {
const l = remoteAttachConfig(configOf(nodeRemoteType, { host: "web", remoteRoot: "/usr/src/app" }), "/p")!;
expect(l.adapter).toBe("js-debug");
-19
Переглянути файл
@@ -196,24 +196,6 @@ function delveLaunch(rc: RunConfig, cwd: string): LaunchConfig {
return out;
}
/** The scene a `godot --path <dir> [scene]` command line plays: `main`, or a `res://` path. */
export function godotScene(args: readonly string[]): string {
const scene = args.find((a, i) => args[i - 1] !== "--path" && /\.t?scn$/i.test(a));
if (!scene) return "main";
return scene.startsWith("res://") ? scene : `res://${scene.replace(/^\.\//, "")}`;
}
/**
* Godot: the adapter inside the editor plays the scene itself (with the editor's run
* settings), so the launch names the project (checked against the editor's) and the scene.
*/
function godotLaunch(rc: RunConfig, cwd: string): LaunchConfig {
const i = rc.args.indexOf("--path");
const dir = i >= 0 ? rc.args[i + 1] : undefined;
const project = dir ? join(cwd, dir) : cwd;
return { ...base(rc, "godot", project), extraJson: JSON.stringify({ project, scene: godotScene(rc.args) }) };
}
/** A native program under CodeLLDB or lldb-dap: program, args, cwd, env. */
function nativeLaunch(rc: RunConfig, cwd: string, adapter: string): LaunchConfig {
const out: LaunchConfig = { ...base(rc, adapter, cwd), program: resolveCommand(rc.command, cwd), args: [...rc.args] };
@@ -237,7 +219,6 @@ export function launchConfigFor(rc: RunConfig, root: string): LaunchConfig | nul
if (adapter === "debugpy") return debugpyLaunch(rc, cwd);
if (adapter === "js-debug") return jsDebugLaunch(rc, cwd);
if (adapter === "delve") return delveLaunch(rc, cwd);
if (adapter === "godot") return godotLaunch(rc, cwd);
// Adapters without a template (hidden in Edit Configurations): generic arguments.
return {
...base(rc, adapter, cwd),
-28
Переглянути файл
@@ -12,7 +12,6 @@ export const REMOTE_JVM = "remote-jvm";
export const GO_REMOTE = "go-remote";
export const PYTHON_REMOTE = "python-remote";
export const NODE_REMOTE = "node-remote";
export const GODOT_ATTACH = "godot-attach";
type Params = Readonly<Record<string, string>>;
@@ -221,36 +220,11 @@ export const nodeRemoteType: RunConfigTypeContribution = {
commandLine: () => null,
};
// ---------------------------------------------------------------------------
// Attach to Godot (the editor's debug adapter, Editor Settings › Network › Debug Adapter)
export const godotAttachType: RunConfigTypeContribution = {
id: GODOT_ATTACH,
label: "Attach to Godot",
icon: "file-gdscript",
description: "Debug the game the Godot editor is running, through the editor's debug adapter",
defaults: { host: "localhost", port: "6006" },
debugOnly: true,
debugAdapter: "godot",
fields: [
hostField,
portField,
{
key: "hint",
label: "Before attaching",
control: "output",
value: () => "Open the project in the Godot editor and run a scene (F5 / F6)",
},
],
commandLine: () => null,
};
export const REMOTE_TYPES: readonly RunConfigTypeContribution[] = [
remoteJvmType,
goRemoteType,
pythonRemoteType,
nodeRemoteType,
godotAttachType,
];
export const isRemoteConfig = (c: Pick<RunConfig, "kind">) => REMOTE_TYPES.some((t) => t.id === c.kind);
@@ -317,8 +291,6 @@ export function remoteAttachConfig(rc: RunConfig, root: string): LaunchConfig |
justMyCode: skip,
...(map ? { pathMappings: [{ localRoot: map.local, remoteRoot: map.remote }] } : {}),
});
case GODOT_ATTACH:
return attachBase(rc, "godot", root, { debugServer: serverAddress(host, portOf(p, 6006)), project: root });
case NODE_REMOTE:
return attachBase(rc, "js-debug", root, {
type: "pwa-node",
+1 -2
Переглянути файл
@@ -33,7 +33,6 @@ import { closeBreakpointPopover, useOverlays } from "./popoverStore";
import { VariablesView, type VarRoot } from "./VariablesView";
import { pushHistory, readHistory } from "./expressionHistory";
import styles from "./Overlays.module.css";
import { isImeKey } from "@/platform/ime";
export function DebuggerOverlays() {
return (
@@ -711,7 +710,7 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
});
};
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (isImeKey(e.nativeEvent)) return;
if (e.nativeEvent.isComposing) return;
const el = e.currentTarget;
if (e.key === "Enter" && e.shiftKey && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
+1 -2
Переглянути файл
@@ -21,7 +21,6 @@ import {
useMacros,
type MacroStep,
} from "./model";
import { isImeKey } from "@/platform/ime";
/** Records typing and editor keys of every text editor while a macro records. */
const recorder = [
@@ -32,7 +31,7 @@ const recorder = [
EditorView.domEventHandlers({
keydown(e) {
// Keys the IDE keymap ran as actions were recorded as those actions.
if (e.defaultPrevented || isImeKey(e) || !useMacros.getState().recording) return false;
if (e.defaultPrevented || e.isComposing || !useMacros.getState().recording) return false;
const key = editorKeyName(e);
if (key) recordStep({ kind: "key", key });
return false;
+1 -1
Переглянути файл
@@ -245,7 +245,7 @@ export async function runFileRefactoring(
} catch (e) {
notifications().notify({
level: "error",
title: `${label === "Move" ? "Cannot move" : "Cannot rename"} ${moves.length === 1 ? nameOf(moves[0]!.from) : `${moves.length} items`}`,
title: `Cannot ${label.toLowerCase()} ${moves.length === 1 ? nameOf(moves[0]!.from) : `${moves.length} items`}`,
body: e instanceof Error ? e.message : String(e),
});
return "failed";
-20
Переглянути файл
@@ -262,26 +262,6 @@ describe("project producers", () => {
cfg({ id: "pytest", kind: "pytest", command: ".venv/bin/pytest", args: [], isTest: true }),
];
it("Godot scenes run with godot --path in the project holding them (Current Scene)", () => {
const godot = [
cfg({ id: "godot:project", kind: "godot", command: "godot", args: ["--path", "."], debugAdapter: "godot" }),
cfg({ id: "godot:project:demo", kind: "godot", command: "godot", args: ["--path", "."], cwd: "demo" }),
];
const root = produceContext({ path: `${ROOT}/levels/one.tscn`, root: ROOT, configs: godot }, OPTIMISTIC)!;
expect(root).toMatchObject({ name: "one.tscn", scope: "file" });
expect(root.config).toMatchObject({
kind: "godot",
command: "godot",
args: ["--path", ".", "res://levels/one.tscn"],
cwd: null,
debugAdapter: "godot",
});
const nested = produceContext({ path: `${ROOT}/demo/main.tscn`, root: ROOT, configs: godot }, OPTIMISTIC)!;
expect(nested.config).toMatchObject({ args: ["--path", ".", "res://main.tscn"], cwd: "demo" });
// Outside a Godot project there is nothing to run.
expect(produceContext({ path: `${ROOT}/a.tscn`, root: ROOT, configs: [] }, OPTIMISTIC)).toBeNull();
});
it("keeps package.json test files on the project's runner", () => {
const p = produceContext({ path: `${ROOT}/src/a.test.ts`, root: ROOT, configs, content: "test('x', () => {})" }, ALL)!;
expect(p).toMatchObject({ name: "a.test.ts", scope: "file" });
-28
Переглянути файл
@@ -511,33 +511,6 @@ function cargoOwner(rel: string, configs: readonly RunConfig[]): RunConfig[] {
const hasBuildTool = (configs: readonly RunConfig[], kinds: string[]) => configs.some((c) => kinds.includes(c.kind));
/**
* A Godot scene: `godot --path <project> res://<scene>` in the Godot project holding it
* (a detected "Godot Project" configuration), debuggable through the editor's adapter.
*/
function godotScene(rel: string, configs: readonly RunConfig[]): Produced | null {
const dirs = configs
.filter((c) => c.kind === "godot" && c.detected && c.id.startsWith("godot:project"))
.map((c) => (c.cwd ?? "").replace(/^\.\/?/, "").replace(/\/+$/, ""));
const dir = dirs.filter((d) => !d || rel.startsWith(d + "/")).sort((a, b) => b.length - a.length)[0];
if (dir === undefined) return null;
const name = baseName(rel);
const scene = `res://${dir ? rel.slice(dir.length + 1) : rel}`;
const config: RunConfig = {
id: `context:file:${rel}`,
name,
kind: "godot",
command: "godot",
args: ["--path", ".", scene],
cwd: dir || null,
env: {},
detected: true,
isTest: false,
debugAdapter: "godot",
};
return { name, scope: "file", config };
}
/** The file as a whole: tests of a test file, the project's run target, or the runtime for its language. */
export function produceFile(input: ContextInput, env: ToolEnv): Produced | null {
const s = site(input);
@@ -546,7 +519,6 @@ export function produceFile(input: ContextInput, env: ToolEnv): Produced | null
const rel = s.idPath;
if (s.inProject) {
if (/\.t?scn$/i.test(rel)) return godotScene(rel, configs);
// Project-aware: test files through the project's test runner, Cargo / Go / Gradle / Maven mains.
const role = fileRole(rel, input.content);
if (role === "test") {
-20
Переглянути файл
@@ -77,26 +77,6 @@ describe("configuration types", () => {
expect(withParams(old, params)).toMatchObject({ command: "cargo", args: ["run", "--bin", "my app"] });
});
it("Godot runs the main scene or a chosen one, and reads detected configurations back", () => {
const godot = typeFor("godot")!;
expect(godot.debugAdapter).toBe("godot");
const c = cfg("g", { kind: "godot" });
expect(withParams(c, { projectDir: "game", scene: "", arguments: "" })).toMatchObject({
command: "godot",
args: ["--path", "."],
cwd: "game",
});
expect(withParams(c, { scene: "res://one.tscn", arguments: "--debug-collisions" })).toMatchObject({
args: ["--path", ".", "res://one.tscn", "--debug-collisions"],
cwd: null,
});
const detected = cfg("godot:project", { kind: "godot", command: "/Apps/Godot.app/Contents/MacOS/Godot", args: ["--path", "."] });
expect(godot.paramsFrom!(detected)).toEqual({ projectDir: "", scene: "", arguments: "" });
const scene = { ...detected, cwd: "demo", args: ["--path", ".", "res://a.tscn", "--verbose"] };
expect(godot.paramsFrom!(scene)).toEqual({ projectDir: "demo", scene: "res://a.tscn", arguments: "--verbose" });
expect(godot.paramsFrom!(cfg("x", { command: "cargo" }))).toBeNull();
});
it("shell script files and text derive the command line", () => {
const c = cfg("s");
expect(
+1 -42
Переглянути файл
@@ -111,47 +111,6 @@ const program: RunConfigTypeContribution = {
c.args.length || !/\s/.test(c.command) ? { program: c.command, arguments: formatArgs(c.args) } : null,
};
const isScene = (a: string) => /\.t?scn$/i.test(a);
const isGodot = (cmd: string) => /^godot([-.\w]*)$/i.test(baseName(cmd).replace(/\.exe$/i, ""));
/**
* Godot: `godot --path <project>` runs the main scene, `… <scene>` one scene. The
* executable is the one from Settings › Language Servers › godot (else detected).
*/
const godot: RunConfigTypeContribution = {
id: "godot",
label: "Godot",
icon: "file-gdscript",
description: "Run a Godot project's main scene or a chosen scene",
ownsWorkingDirectory: true,
debugAdapter: "godot",
fields: [
{ key: "projectDir", label: "Project directory", mono: true, placeholder: "Project root (holds project.godot)" },
{
key: "scene",
label: "Scene",
mono: true,
placeholder: "Main scene",
hint: "e.g. res://levels/level_1.tscn; empty runs the project's main scene",
suggestions: (configs) => [...new Set(configs.filter((c) => c.kind === "godot").flatMap((c) => c.args.filter(isScene)))],
},
{ key: "arguments", label: "Arguments", mono: true, placeholder: "Godot command line options, e.g. --debug-collisions" },
],
commandLine: (p) => ({
command: "godot",
args: ["--path", ".", ...(p.scene?.trim() ? [p.scene.trim()] : []), ...parseArgs(p.arguments ?? "")],
cwd: p.projectDir?.trim() || null,
}),
paramsFrom(c) {
if (!isGodot(c.command)) return null;
const rest = [...c.args];
const path = rest.indexOf("--path");
if (path >= 0) rest.splice(path, 2);
const scene = rest.find(isScene) ?? "";
return { projectDir: dirOf(c.cwd), scene, arguments: formatArgs(rest.filter((a) => a !== scene)) };
},
};
const PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
const NPM_COMMANDS = ["run", "test", "start", "install", "ci", "publish", "pack"];
@@ -269,7 +228,7 @@ const compound: RunConfigTypeContribution = {
commandLine: () => null,
};
export const BUILTIN_TYPES: readonly RunConfigTypeContribution[] = [shell, program, npm, gradle, maven, godot, compound];
export const BUILTIN_TYPES: readonly RunConfigTypeContribution[] = [shell, program, npm, gradle, maven, compound];
export function registerBuiltinTypes(): () => void {
const disposers = BUILTIN_TYPES.map(registerRunConfigType);
+1 -2
Переглянути файл
@@ -57,7 +57,6 @@ import {
widenSearchEverywhere,
} from "./store";
import styles from "./SearchEverywhere.module.css";
import { isImeKey } from "@/platform/ime";
type SeScope = "allPlaces" | ProjectFileSet;
@@ -316,7 +315,7 @@ function SearchEverywhereDialog() {
};
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (isImeKey(e.nativeEvent)) return;
if (e.nativeEvent.isComposing) return;
if (e.key === "Tab") {
e.preventDefault();
e.stopPropagation();
+1 -2
Переглянути файл
@@ -33,7 +33,6 @@ import { trackRuntimeSettings } from "./runtime";
import { installActionProxies, installSettingsHost } from "./window/bridge";
import { AssignShortcutOverlay, showAssignShortcut } from "./keymap/AssignShortcut";
import { settingsSearchEntries } from "./searchIndex";
import { isImeKey } from "@/platform/ime";
export { settingsWindowParent } from "./window/bridge";
export const SettingsWindow = lazyComponent(() => import("./window/SettingsWindow").then((m) => m.SettingsWindow));
@@ -166,7 +165,7 @@ function listenLaunch(): () => void {
/** Esc and ⌘W cancel, like closing the window; ⌘, stays here. */
function installWindowKeys(): () => void {
const onKey = (e: KeyboardEvent) => {
if (e.defaultPrevented || isImeKey(e)) return;
if (e.defaultPrevented || e.isComposing) return;
const mod = e.metaKey || e.ctrlKey;
if ((e.key === "Escape" && !isPopupOpen()) || (mod && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "w")) {
e.preventDefault();
+1 -2
Переглянути файл
@@ -18,7 +18,6 @@ import { executeAction } from "@/platform/actions";
import { effectiveBindings, strokeOf } from "@/platform/keymap";
import { workflowSettings } from "@/platform/workflowSettings";
import { terminalRuntime } from "./loader";
import { isImeKey } from "@/platform/ime";
export type TerminalKeyResult =
| { kind: "send"; data: string }
@@ -129,7 +128,7 @@ export function isAllowedIdeShortcut(stroke: string, bindings: ReadonlyArray<rea
export function installTerminalKeys(target: Window = window): () => void {
const onKeyDown = (e: KeyboardEvent) => {
const rt = terminalRuntime();
if (isImeKey(e) || !rt) return;
if (e.isComposing || !rt) return;
// The terminal find bar: Escape closes it (instead of "focus editor"), ⌘F reselects the query.
if ((e.target as Element | null)?.closest?.("[data-terminal-find]")) {
const plain = !e.ctrlKey && !e.altKey && !e.shiftKey;
+31 -36
Переглянути файл
@@ -29,6 +29,37 @@
content: " /";
color: var(--fg-subtle);
}
.repos {
flex: none;
display: flex;
flex-wrap: wrap;
gap: 4px;
padding: 6px 8px;
border-bottom: 1px solid var(--border-popup);
}
.repoButton {
max-width: 160px;
height: 22px;
padding: 0 8px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
border: none;
border-radius: var(--radius-small);
background: transparent;
color: var(--fg-secondary);
font: inherit;
font-size: var(--fs-small);
cursor: pointer;
}
.repoButton:hover {
background: var(--bg-hover);
}
.repoSelected,
.repoSelected:hover {
background: var(--bg-selected);
color: var(--fg);
}
.operation {
color: var(--warning);
font-size: var(--fs-tiny);
@@ -44,9 +75,6 @@
flex-direction: column;
overflow: hidden;
}
.popup.wide {
width: 440px;
}
.search {
flex: none;
display: flex;
@@ -55,9 +83,6 @@
padding: 6px 6px 6px 4px;
border-bottom: 1px solid var(--border-popup);
}
.searchGrow {
flex: 1;
}
.listWrap {
display: flex;
flex-direction: column;
@@ -169,33 +194,3 @@
[role="option"]:hover .star:not(.starOn) .branchIcon {
visibility: hidden;
}
.separator {
flex: 1;
height: 1px;
margin: 0 4px;
background: var(--border-popup);
}
.repoColor {
flex: none;
width: 10px;
height: 10px;
margin: 0 2px;
border-radius: 2px;
}
.repoHead {
flex: 0 4 auto;
margin-left: auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-muted);
font-family: var(--font-mono);
font-size: var(--fs-small);
}
.subChevron {
flex: none;
color: var(--fg-faint);
}
.groupRow {
color: var(--fg-secondary);
}
+79 -482
Переглянути файл
@@ -2,11 +2,9 @@
import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type RefObject } from "react";
import clsx from "clsx";
import { create } from "zustand";
import type { Branch, BranchInfo } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { useEditorRegistry } from "@/editor/api";
import {
BarButton,
HighlightedText,
@@ -21,20 +19,10 @@ import {
type MenuItem,
} from "@/ui";
import { buildBranchRows, type BranchRow, type PopupAction } from "./branches";
import { branchMenu, commonBranchMenu, inRepo, tagMenu } from "./branchMenu";
import { branchMenu, tagMenu } from "./branchMenu";
import { loadFavoriteBranches, recentBranches, toggleFavoriteBranch, useFavoriteBranches } from "./branchOps";
import { inProgress, operationTitle, type InProgress } from "./operations";
import {
buildMultiRepoRows,
currentRepoFor,
DEFAULT_EXPANDED,
repoHeadLabel,
toggleExpanded,
widgetShowsRepo,
type RepoEntry,
type RepoRow,
} from "./repoBranches";
import { currentRepo, focusRepo, loadBranches, repoName, useVcs } from "./store";
import { currentRepo, loadBranches, repoName, selectRepo, useVcs } from "./store";
import styles from "./BranchWidget.module.css";
export const useBranchesPopup = create<{ open: boolean }>(() => ({ open: false }));
@@ -46,29 +34,14 @@ export function headLabel(branch: { head: string | null; headCommit: string | nu
return branch.headCommit ? branch.headCommit.slice(0, 8) : "No commits";
}
/** The current repository (see `currentRepoFor`): the widget and the popup show the same one. */
function useCurrentRepo(): string | null {
const path = useEditorRegistry((s) => s.active?.ctx.path ?? null);
return useVcs((s) => currentRepoFor(path, s.roots, s.repo));
}
export function BranchWidget() {
const available = useVcs((s) => s.available);
const selected = useVcs((s) => s.branch);
const count = useVcs((s) => s.roots.length);
const current = useCurrentRepo();
// Several repositories on different branches: the widget names the current one.
const diverged = useVcs((s) => widgetShowsRepo(s.roots.map((r) => ({ head: s.heads[r]?.head ?? null }))));
// The current repository is not the selected one: its HEAD from the last scan (no upstream).
const other = useVcs((s) => (diverged && current && current !== s.repo ? (s.heads[current] ?? null) : null));
const otherOp = useVcs((s) => (current ? (s.operations[current] ?? null) : null));
const branch = useVcs((s) => s.branch);
// With several repositories the widget names the selected one, like IDEA's.
const repo = useVcs((s) => (s.roots.length > 1 && s.repo ? repoName(s.repo) : null));
const open = useBranchesPopup((s) => s.open);
const ref = useRef<HTMLButtonElement>(null);
if (!available || !selected) return null;
const repo = diverged && current ? repoName(current) : null;
const branch: BranchInfo = other
? { head: other.head, headCommit: other.headCommit, upstream: null, ahead: 0, behind: 0, operation: otherOp }
: selected;
if (!available || !branch) return null;
const op = branch.operation ? ` (${branch.operation})` : "";
const sync = [
branch.behind > 0 ? `${branch.behind} incoming` : "",
@@ -79,7 +52,6 @@ export function BranchWidget() {
(branch.upstream
? `Git branch: ${headLabel(branch)}${op}\nTracking ${branch.upstream}`
: `Git branch: ${headLabel(branch)}${op}`) +
(count > 1 && !repo ? `\nIn all ${count} repositories` : "") +
(sync.length ? `\n${sync.join(", ")} commits` : "");
return (
<>
@@ -120,12 +92,6 @@ const POPUP_ACTIONS: PopupAction[] = [
{ id: "vcs.checkoutRevision", label: "Checkout Tag or Revision…", icon: "branch" },
];
/** A single repository's own entries (its submenu in the popup with several repositories). */
const REPO_ACTIONS: PopupAction[] = [
{ id: "vcs.newBranch", label: "New Branch…", icon: "plus" },
{ id: "vcs.checkoutRevision", label: "Checkout Tag or Revision…", icon: "branch" },
];
/** Entries IDEA puts at the top of the Branches popup while an operation is stopped. */
export function operationActions(op: InProgress | null, conflicts: number): PopupAction[] {
if (!op) return [];
@@ -152,105 +118,42 @@ export function operationActions(op: InProgress | null, conflicts: number): Popu
return out;
}
const NO_BRANCHES: readonly Branch[] = [];
const INDENT = 16;
const ROW_HEIGHT = 24;
const SEPARATOR_HEIGHT = 9;
const listHeight = (rows: readonly { type: string; key: string }[]) =>
Math.min(
440,
Math.max(
ROW_HEIGHT * 3,
rows.reduce(
(h, r) => h + (r.type === "section" && r.key.startsWith("separator:") ? SEPARATOR_HEIGHT : ROW_HEIGHT),
0,
),
),
);
/** The option element of the row with `key`, to anchor a submenu on. */
function rowElement(list: HTMLElement | null, key: string): HTMLElement | null {
const el = list?.querySelector<HTMLElement>(`[data-row-key="${CSS.escape(key)}"]`);
return el ? ((el.closest('[role="option"]') as HTMLElement | null) ?? el) : null;
}
/** Caret at the end (→ opens) / start (← closes) of the search field. */
const caretAt = (e: KeyboardEvent, where: "start" | "end") => {
const input = e.target as HTMLInputElement;
if (input.selectionStart !== input.selectionEnd) return false;
return where === "end" ? input.selectionStart === input.value.length : input.selectionStart === 0;
};
function BranchesPopup({ anchor, onClose }: { anchor: RefObject<HTMLElement | null>; onClose: () => void }) {
const multi = useVcs((s) => s.roots.length > 1);
return (
<Popup
open
anchor={anchor}
onClose={onClose}
placement="bottom-start"
aria-label="Git Branches"
className={clsx(styles.popup, multi && styles.wide)}
>
{multi ? <MultiRepoPanel onClose={onClose} /> : <BranchesPanel onClose={onClose} actions={POPUP_ACTIONS} />}
</Popup>
);
}
interface BranchesPanelProps {
onClose: () => void;
actions: readonly PopupAction[];
/** A repository other than the selected one (the submenu of a repository): it is selected before acting. */
root?: string;
/** Its branches until the selected repository's are loaded. */
fallback?: readonly Branch[];
/** ← at the start of the search field (back to the repositories). */
onBack?: () => void;
}
/** Search, actions and the branches of one repository (the selected one, or `root`). */
function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack }: BranchesPanelProps) {
const selected = useVcs((s) => s.repo);
const live = root === undefined || selected === root;
const storeBranches = useVcs((s) => s.branches);
const storeLoaded = useVcs((s) => s.branchesLoaded);
const branches = live && (storeLoaded || !fallback) ? storeBranches : (fallback ?? NO_BRANCHES);
const loaded = (live && storeLoaded) || !!fallback;
const current = useVcs((s) =>
live ? (s.branch?.head ?? null) : root ? (s.heads[root]?.head ?? null) : (s.branch?.head ?? null),
);
const branches = useVcs((s) => s.branches);
const loaded = useVcs((s) => s.branchesLoaded);
const current = useVcs((s) => s.branch?.head ?? null);
const [query, setQuery] = useState("");
const [recent] = useState(recentBranches);
const [active, setActive] = useState(0);
const [menuFor, setMenuFor] = useState<{ items: MenuItem[]; label: string; el: HTMLElement } | null>(null);
const listRef = useRef<HTMLDivElement>(null);
const repo = useVcs((s) => s.repo);
const favorites = useFavoriteBranches((s) => s.names);
const [tags, setTags] = useState<string[]>([]);
useEffect(() => {
if (root === undefined) void loadBranches().catch(() => undefined);
void loadBranches().catch(() => undefined);
loadFavoriteBranches();
}, [root]);
}, []);
useEffect(() => {
let live = true;
call(commands.vcsTags(root ?? currentRepo())).then(
call(commands.vcsTags(currentRepo())).then(
(t) => live && setTags(t),
() => live && setTags([]),
);
return () => {
live = false;
};
}, [root, selected, branches]);
}, [repo, branches]);
const op = useVcs((s) => inProgress(root ? s.operations[root] : s.branch?.operation));
const op = useVcs((s) => inProgress(s.branch?.operation));
const conflicts = useVcs((s) => s.status.filter((f) => f.unstaged === "conflicted").length);
const actions = useMemo(() => [...operationActions(op, conflicts), ...baseActions], [op, conflicts, baseActions]);
const actions = useMemo(() => [...operationActions(op, conflicts), ...POPUP_ACTIONS], [op, conflicts]);
const rows = useMemo(
() => buildBranchRows(branches, recent, query, actions, favorites, tags),
[branches, recent, query, actions, favorites, tags],
);
const isSection = (r: BranchRow) => r.type === "section";
const activeIndex = rows[active] && !isSection(rows[active]!) ? active : firstSelectable(rows, isSection);
const scoped = (items: MenuItem[]) => (root ? inRepo(root, items) : items);
const closeAll = () => {
setMenuFor(null);
@@ -259,12 +162,13 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack }
const openMenu = (i: number) => {
const row = rows[i];
if (row?.type !== "branch" && row?.type !== "tag") return;
const el = rowElement(listRef.current, row.key);
const el = listRef.current?.querySelector<HTMLElement>(`[data-row-key="${CSS.escape(row.key)}"]`);
if (!el) return;
const anchorEl = (el.closest('[role="option"]') as HTMLElement | null) ?? el;
setMenuFor(
row.type === "branch"
? { items: scoped(branchMenu(row.branch, current, closeAll)), label: `Branch ${row.branch.name}`, el }
: { items: scoped(tagMenu(row.tag, closeAll)), label: `Tag ${row.tag}`, el },
? { items: branchMenu(row.branch, current, closeAll), label: `Branch ${row.branch.name}`, el: anchorEl }
: { items: tagMenu(row.tag, closeAll), label: `Tag ${row.tag}`, el: anchorEl },
);
};
@@ -273,8 +177,7 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack }
if (!row) return;
if (row.type === "action") {
onClose();
const { id, arg } = row.action;
void (root ? focusRepo(root) : Promise.resolve()).then(() => executeAction(id, arg));
void executeAction(row.action.id, row.action.arg);
} else if (row.type === "branch" || row.type === "tag") {
openMenu(i);
}
@@ -288,17 +191,13 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack }
}
const type = rows[activeIndex]?.type;
if (e.key === "ArrowRight" && (type === "branch" || type === "tag")) {
if (caretAt(e, "end")) {
const input = e.target as HTMLInputElement;
if (input.selectionStart === input.value.length) {
e.preventDefault();
openMenu(activeIndex);
}
return;
}
if (e.key === "ArrowLeft" && onBack && caretAt(e, "start")) {
e.preventDefault();
onBack();
return;
}
const next = listNavigate(e.key, { items: rows, active: activeIndex, isSection, wrap: true });
if (next !== null) {
e.preventDefault();
@@ -306,26 +205,35 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack }
}
};
const label = root ? `Search branches of ${repoName(root)}` : "Search branches and actions";
const rowHeight = 24;
const height = Math.min(440, Math.max(rowHeight * 3, rows.length * rowHeight));
return (
<>
<Popup
open
anchor={anchor}
onClose={onClose}
placement="bottom-start"
aria-label="Git Branches"
className={styles.popup}
>
<RepositoryBar />
<div className={styles.search}>
<SearchField
className={root ? styles.searchGrow : undefined}
data-autofocus
value={query}
onChange={(v) => {
setQuery(v);
setActive(0);
}}
placeholder={label}
aria-label={label}
placeholder="Search branches and actions"
aria-label="Search branches and actions"
variant="bare"
onKeyDown={onKeyDown}
/>
{!root && <IconButton icon="git-fetch" title="Fetch" size="small" action="vcs.fetch" />}
<IconButton icon="git-fetch" title="Fetch" size="small" action="vcs.fetch" />
</div>
<div ref={listRef} style={{ height: listHeight(rows) }} className={styles.listWrap}>
<div ref={listRef} style={{ height }} className={styles.listWrap}>
<List
items={rows}
getKey={(r) => r.key}
@@ -336,371 +244,60 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack }
onActivate={(_r, i) => activate(i)}
focusable={false}
hoverSelects
rowHeight={ROW_HEIGHT}
rowHeight={rowHeight}
aria-label="Branches"
className={styles.list}
empty={<span className={styles.empty}>{loaded ? "No matching branches" : "Loading…"}</span>}
renderItem={(r) => <BranchRowView row={r} />}
/>
</div>
{menuFor && <SubMenu {...menuFor} onClose={() => setMenuFor(null)} />}
</>
);
}
function SubMenu({
items,
label,
el,
onClose,
}: {
items: MenuItem[];
label: string;
el: HTMLElement;
onClose: () => void;
}) {
return (
<Popup
open
anchor={el}
placement="right-start"
offset={2}
role="presentation"
autoFocus={false}
onClose={onClose}
className={styles.menuPopup}
>
<MenuList items={items} onDone={onClose} onCloseLevel={onClose} aria-label={label} />
{menuFor && (
<Popup
open
anchor={menuFor.el}
placement="right-start"
offset={2}
role="presentation"
autoFocus={false}
onClose={() => setMenuFor(null)}
className={styles.menuPopup}
>
<MenuList
items={menuFor.items}
onDone={() => setMenuFor(null)}
onCloseLevel={() => setMenuFor(null)}
aria-label={menuFor.label}
/>
</Popup>
)}
</Popup>
);
}
const EXPANDED_KEY = "openidea.vcs.branchesPopup.expanded";
function loadExpanded(): Set<string> {
try {
const v: unknown = JSON.parse(localStorage.getItem(EXPANDED_KEY) ?? "null");
if (Array.isArray(v)) return new Set(v.filter((x): x is string => typeof x === "string"));
} catch {
// Storage unavailable: defaults.
}
return new Set(DEFAULT_EXPANDED);
}
function saveExpanded(expanded: ReadonlySet<string>) {
try {
localStorage.setItem(EXPANDED_KEY, JSON.stringify([...expanded]));
} catch {
// Expansion is remembered for the session only.
}
}
/**
* Branches popup of a project with several repositories: actions; the repositories,
* each opening its own branches (on hover or →); then the branches they all have
* (acting on all of them) or, when their branches differ, the current repository's.
*/
function MultiRepoPanel({ onClose }: { onClose: () => void }) {
/** Repository switcher (several repositories): branches, log and push act on the selected one. */
function RepositoryBar() {
const roots = useVcs((s) => s.roots);
const heads = useVcs((s) => s.heads);
const operations = useVcs((s) => s.operations);
const version = useVcs((s) => s.version);
const favorites = useFavoriteBranches((s) => s.names);
const current = useCurrentRepo();
const [recent] = useState(recentBranches);
const [tags, setTags] = useState<string[]>([]);
const [query, setQuery] = useState("");
const [active, setActive] = useState(0);
const [expanded, setExpanded] = useState<ReadonlySet<string>>(loadExpanded);
const [all, setAll] = useState<Record<string, Branch[]>>({});
const [menuFor, setMenuFor] = useState<{ items: MenuItem[]; label: string; el: HTMLElement } | null>(null);
const [repoMenu, setRepoMenu] = useState<{ root: string; el: HTMLElement; focus: boolean } | null>(null);
const listRef = useRef<HTMLDivElement>(null);
const searchRef = useRef<HTMLInputElement>(null);
/** Back from a repository's submenu to the search field. */
const closeRepoMenu = () => {
setRepoMenu(null);
searchRef.current?.focus();
};
useEffect(() => loadFavoriteBranches(), []);
// Every repository's branches (common ones, submenus, search); refreshed after operations.
useEffect(() => {
let live = true;
void Promise.all(
roots.map((r) =>
call(commands.vcsBranches(r)).then(
(list) => [r, list] as const,
() => [r, [] as Branch[]] as const,
),
),
).then((entries) => live && setAll(Object.fromEntries(entries)));
return () => {
live = false;
};
}, [roots, version]);
useEffect(() => {
let live = true;
if (current)
call(commands.vcsTags(current)).then(
(t) => live && setTags(t),
() => live && setTags([]),
);
return () => {
live = false;
};
}, [current, version]);
const repos = useMemo<RepoEntry[]>(
() =>
roots.map((root) => ({
root,
name: repoName(root),
head: heads[root]?.head ?? null,
headCommit: heads[root]?.headCommit ?? null,
})),
[roots, heads],
);
const op = useVcs((s) => inProgress(s.branch?.operation));
const conflicts = useVcs((s) => s.status.filter((f) => f.unstaged === "conflicted").length);
const actions = useMemo(
() => [
...operationActions(op, conflicts),
...POPUP_ACTIONS.map((a) => (a.id === "vcs.newBranch" ? { ...a, arg: { repos: roots } } : a)),
],
[op, conflicts, roots],
);
const rows = useMemo(
() => buildMultiRepoRows({ repos, branches: all, query, actions, expanded, favorites, current, recent, tags }),
[repos, all, query, actions, expanded, favorites, current, recent, tags],
);
const isSection = (r: RepoRow) => r.type === "section";
const activeIndex = rows[active] && !isSection(rows[active]!) ? active : firstSelectable(rows, isSection);
const closeAll = () => {
setMenuFor(null);
setRepoMenu(null);
onClose();
};
/** Opens the submenu of row `i`; `focus` moves the keyboard into a repository's submenu. */
const openSub = (i: number, focus: boolean) => {
const row = rows[i];
if (!row) return;
const el = rowElement(listRef.current, row.key);
if (!el) return;
if (row.type === "repo") {
setMenuFor(null);
setRepoMenu((prev) =>
prev?.root === row.repo.root && prev.el === el && prev.focus === focus
? prev
: { root: row.repo.root, el, focus },
);
return;
}
setRepoMenu(null);
if (row.type === "common") {
setMenuFor({ items: commonBranchMenu(row.branch, roots, closeAll), label: `Branch ${row.branch.name}`, el });
} else if (row.type === "branch") {
const items = inRepo(row.repo.root, branchMenu(row.branch, row.repo.head, closeAll));
setMenuFor({ items, label: `Branch ${row.branch.name} of ${row.repo.name}`, el });
} else if (row.type === "tag") {
setMenuFor({ items: inRepo(row.repo.root, tagMenu(row.tag, closeAll)), label: `Tag ${row.tag}`, el });
}
};
const setOpen = (key: string, open: boolean) =>
setExpanded((prev) => {
if (prev.has(key) === open) return prev;
const next = toggleExpanded(prev, key);
saveExpanded(next);
return next;
});
const activate = (i: number) => {
const row = rows[i];
if (!row) return;
if (row.type === "action") {
onClose();
void executeAction(row.action.id, row.action.arg);
} else if (row.type === "group") {
if (!query.trim()) setOpen(row.key, !row.expanded);
} else {
openSub(i, true);
}
};
// The pointer on a repository opens its branches right away; elsewhere it closes them.
const hover = (i: number) => {
setActive(i);
if (rows[i]?.type === "repo") openSub(i, false);
else setRepoMenu(null);
};
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === "Enter") {
e.preventDefault();
activate(activeIndex);
return;
}
const row = rows[activeIndex];
if (e.key === "ArrowRight" && row && row.type !== "action" && row.type !== "section") {
if (!caretAt(e, "end")) return;
e.preventDefault();
if (row.type === "group") {
if (!query.trim()) setOpen(row.key, true);
} else openSub(activeIndex, true);
return;
}
if (e.key === "ArrowLeft" && row?.type === "group" && row.expanded) {
if (!caretAt(e, "start") || query.trim()) return;
e.preventDefault();
setOpen(row.key, false);
return;
}
const next = listNavigate(e.key, { items: rows, active: activeIndex, isSection, wrap: true });
if (next !== null) {
e.preventDefault();
setActive(next);
}
};
const repo = useVcs((s) => s.repo);
if (roots.length < 2) return null;
return (
<>
<div className={styles.search}>
<SearchField
ref={searchRef}
className={styles.searchGrow}
data-autofocus
value={query}
onChange={(v) => {
setQuery(v);
setActive(0);
}}
placeholder="Search for branches, actions, repositories"
aria-label="Search for branches, actions, repositories"
variant="bare"
onKeyDown={onKeyDown}
/>
<IconButton icon="git-fetch" title="Fetch" size="small" action="vcs.fetch" />
<IconButton
icon="settings"
title="Git Settings"
size="small"
onClick={() => {
closeAll();
void executeAction("file.settings", "vcs.git");
}}
/>
</div>
<div ref={listRef} style={{ height: listHeight(rows) }} className={styles.listWrap}>
<List
items={rows}
getKey={(r) => r.key}
isSection={isSection}
sectionHeightOf={(r) => (r.type === "section" && !r.label ? SEPARATOR_HEIGHT : undefined)}
renderSection={(r) =>
r.type === "section" && r.label ? (
<span className={styles.section}>{r.label}</span>
) : (
<span className={styles.separator} role="separator" />
)
}
activeIndex={activeIndex}
onActiveChange={hover}
onActivate={(_r, i) => activate(i)}
focusable={false}
hoverSelects
rowHeight={ROW_HEIGHT}
aria-label="Repositories and branches"
className={styles.list}
empty={<span className={styles.empty}>No matching repositories or branches</span>}
renderItem={(r) => (
<RepoRowView row={r} operation={r.type === "repo" ? operations[r.repo.root] : undefined} />
)}
/>
</div>
{menuFor && <SubMenu {...menuFor} onClose={() => setMenuFor(null)} />}
{repoMenu && (
<Popup
open
anchor={repoMenu.el}
placement="right-start"
offset={2}
autoFocus={repoMenu.focus}
aria-label={`Branches of ${repoName(repoMenu.root)}`}
onClose={closeRepoMenu}
className={styles.popup}
<div className={styles.repos} role="group" aria-label="Repository">
{roots.map((r) => (
<button
key={r}
type="button"
className={clsx(styles.repoButton, r === repo && styles.repoSelected)}
aria-pressed={r === repo}
title={r}
onClick={() => void selectRepo(r).then(() => loadBranches().catch(() => undefined))}
>
<BranchesPanel
key={repoMenu.root}
root={repoMenu.root}
fallback={all[repoMenu.root]}
actions={REPO_ACTIONS}
onClose={closeAll}
onBack={closeRepoMenu}
/>
</Popup>
)}
</>
{repoName(r)}
</button>
))}
</div>
);
}
function RepoRowView({ row, operation }: { row: RepoRow; operation?: string }) {
switch (row.type) {
case "action":
case "branch":
case "tag":
return <BranchRowView row={row} />;
case "repo":
return (
<span className={styles.row} data-row-key={row.key}>
<span
className={styles.repoColor}
style={{ background: `var(--project-color-${row.color})` }}
aria-hidden="true"
/>
<HighlightedText className={styles.label} text={row.repo.name} indices={row.matches} tone="accent" />
{operation && <span className={styles.operation}>{operation}</span>}
<span className={styles.repoHead}>{repoHeadLabel(row.repo)}</span>
<Icon name="chevron-right" size={10} className={styles.subChevron} />
</span>
);
case "group":
return (
<span
className={clsx(styles.row, row.depth === 0 && styles.groupRow)}
data-row-key={row.key}
style={row.depth ? { paddingLeft: row.depth * INDENT } : undefined}
aria-expanded={row.expanded}
>
<Icon name={row.expanded ? "chevron-down" : "chevron-right"} size={12} className={styles.rowIcon} />
{row.depth > 0 && <Icon name="folder" size={14} className={styles.rowIcon} />}
<span className={styles.label}>{row.label}</span>
</span>
);
case "common":
return (
<span className={styles.row} data-row-key={row.key} style={{ paddingLeft: row.depth * INDENT }}>
<Icon
name={row.branch.current ? "current-branch" : row.branch.favorite ? "star" : "branch"}
size={14}
className={clsx(styles.rowIcon, row.branch.current && styles.currentIcon)}
/>
<HighlightedText
className={clsx(styles.label, styles.branchName, row.branch.current && styles.current)}
text={row.label}
indices={row.matches}
tone="accent"
/>
{row.branch.current && <span className={styles.tag}>current</span>}
<Icon name="chevron-right" size={10} className={styles.chevron} />
</span>
);
default:
return null;
}
}
function BranchRowView({ row }: { row: BranchRow | Extract<RepoRow, { type: "action" | "branch" | "tag" }> }) {
const indent = "depth" in row && row.depth ? { paddingLeft: row.depth * INDENT } : undefined;
function BranchRowView({ row }: { row: BranchRow }) {
if (row.type === "action") {
const keys = shortcutLabel(row.action.id);
return (
@@ -713,7 +310,7 @@ function BranchRowView({ row }: { row: BranchRow | Extract<RepoRow, { type: "act
}
if (row.type === "tag") {
return (
<span className={styles.row} data-row-key={row.key} style={indent}>
<span className={styles.row} data-row-key={row.key}>
<Icon name="tag" size={14} className={styles.rowIcon} />
<HighlightedText
className={clsx(styles.label, styles.branchName)}
@@ -728,7 +325,7 @@ function BranchRowView({ row }: { row: BranchRow | Extract<RepoRow, { type: "act
if (row.type !== "branch") return null;
const b = row.branch;
return (
<span className={styles.row} data-row-key={row.key} style={indent}>
<span className={styles.row} data-row-key={row.key}>
{b.current ? (
<Icon name="current-branch" size={14} className={clsx(styles.rowIcon, styles.currentIcon)} />
) : (
-270
Переглянути файл
@@ -1,270 +0,0 @@
import { describe, expect, it } from "vitest";
import type { Branch } from "@/bindings";
import {
buildMultiRepoRows,
commonBranches,
currentRepoFor,
DEFAULT_EXPANDED,
repoColorIndex,
repoHeadLabel,
toggleExpanded,
widgetShowsRepo,
type RepoEntry,
type RepoRow,
} from "../repoBranches";
const b = (name: string, opts: Partial<Branch> = {}): Branch => ({
name,
remote: name.startsWith("origin/") || name.startsWith("upstream/"),
current: false,
upstream: null,
ahead: 0,
behind: 0,
lastCommitMs: 0,
commit: "",
...opts,
});
const repo = (name: string, head: string | null = "dev"): RepoEntry => ({
root: `/p/${name}`,
name,
head,
headCommit: "0123456789abcdef",
});
// The reported layout: several repositories, all on `dev`.
const repos = [repo("ology-collect"), repo("ology-dependencies"), repo("ology-gateway")];
const branches: Record<string, Branch[]> = {
"/p/ology-collect": [
b("dev", { current: true }),
b("main"),
b("collect-only"),
b("origin/HEAD"),
b("origin/dev"),
b("origin/main"),
b("origin/feature/x"),
],
"/p/ology-dependencies": [b("dev", { current: true }), b("main"), b("origin/dev"), b("origin/main")],
"/p/ology-gateway": [b("dev", { current: true }), b("main"), b("origin/dev"), b("origin/main"), b("gw-fix")],
};
const actions = [
{ id: "vcs.update", label: "Update Project…" },
{ id: "vcs.newBranch", label: "New Branch…" },
];
const summary = (rows: RepoRow[]) =>
rows.map((r) => {
switch (r.type) {
case "section":
return r.label ? `# ${r.label}` : "---";
case "action":
return `> ${r.action.label}`;
case "repo":
return `repo ${r.repo.name} [${r.repo.head}] c${r.color}`;
case "group":
return `${" ".repeat(r.depth)}${r.expanded ? "v" : ">"} ${r.label}`;
case "common":
return `${" ".repeat(r.depth)}${r.label}${r.branch.current ? " (current)" : ""}`;
case "branch":
return `${" ".repeat(r.depth)}${r.repo.name}:${r.branch.name}`;
case "tag":
return `${" ".repeat(r.depth)}tag ${r.tag}`;
}
});
describe("currentRepoFor (shared by the widget and the popup)", () => {
const roots = ["/p", "/p/ology-collect", "/p/ology-collect/sub", "/p/ology-gateway"];
it.each([
[
"the innermost repository of the active file",
"/p/ology-collect/src/A.java",
"/p/ology-gateway",
"/p/ology-collect",
],
["a nested repository's file", "/p/ology-collect/sub/x.ts", null, "/p/ology-collect/sub"],
["the project's own repository", "/p/README.md", "/p/ology-gateway", "/p"],
["no active file: the selected repository", null, "/p/ology-gateway", "/p/ology-gateway"],
["a file outside every repository: the selected one", "/elsewhere/a.txt", "/p/ology-gateway", "/p/ology-gateway"],
["a selected repository that is gone: the first", null, "/gone", "/p"],
["nothing selected: the first", null, null, "/p"],
])("%s", (_name, active, selected, expected) => {
expect(currentRepoFor(active, roots, selected)).toBe(expected);
});
it("is null without repositories", () => {
expect(currentRepoFor("/p/a", [], null)).toBeNull();
});
});
describe("widgetShowsRepo", () => {
it.each([
["one repository", [{ head: "main" }], false],
["all on the same branch", [{ head: "dev" }, { head: "dev" }, { head: "dev" }], false],
["one on another branch", [{ head: "dev" }, { head: "feature" }, { head: "dev" }], true],
["one detached", [{ head: "dev" }, { head: null }], true],
["all detached", [{ head: null }, { head: null }], true],
["no repositories", [], false],
])("%s", (_name, heads, shows) => {
expect(widgetShowsRepo(heads)).toBe(shows);
});
});
describe("commonBranches", () => {
it("keeps the branches every repository has, current in all first, then favourites", () => {
const common = commonBranches(Object.values(branches));
expect(common.local.map((x) => [x.name, x.current, x.favorite])).toEqual([
["dev", true, false],
["main", false, true],
]);
expect(common.remote.map((x) => x.name)).toEqual(["origin/main", "origin/dev"]);
});
it("is current only when checked out everywhere", () => {
const common = commonBranches([[b("dev", { current: true })], [b("dev")]]);
expect(common.local).toEqual([{ name: "dev", remote: false, current: false, favorite: false }]);
});
it("does not match a local branch with a remote one of the same name", () => {
expect(commonBranches([[b("origin/x", { remote: false })], [b("origin/x")]])).toEqual({ local: [], remote: [] });
expect(commonBranches([])).toEqual({ local: [], remote: [] });
});
});
describe("buildMultiRepoRows", () => {
const input = { repos, branches, actions, expanded: new Set(DEFAULT_EXPANDED) };
it("lists actions, repositories with their branch, then the common groups", () => {
expect(summary(buildMultiRepoRows({ ...input, query: "" }))).toEqual([
"> Update Project…",
"> New Branch…",
"---",
"repo ology-collect [dev] c1",
"repo ology-dependencies [dev] c2",
"repo ology-gateway [dev] c3",
"---",
"v Common Local Branches",
" dev (current)",
" main",
"> Common Remote Branches",
]);
});
it("groups common remote branches by remote when expanded", () => {
const expanded = toggleExpanded(toggleExpanded(new Set(), "common:remote"), "common:folder:origin");
expect(summary(buildMultiRepoRows({ ...input, expanded, query: "" })).slice(-6)).toEqual([
"---",
"> Common Local Branches",
"v Common Remote Branches",
" v origin",
" main",
" dev",
]);
});
it("filters repositories and branches, expands every group and lists each repository's own matches", () => {
expect(summary(buildMultiRepoRows({ ...input, expanded: new Set(), query: "dev" }))).toEqual([
"v Common Local Branches",
" dev (current)",
"v Common Remote Branches",
" v origin",
" dev",
]);
expect(summary(buildMultiRepoRows({ ...input, query: "deps" }))).toEqual(["repo ology-dependencies [dev] c2"]);
expect(summary(buildMultiRepoRows({ ...input, query: "fix" }))).toEqual([
"# ology-gateway",
"ology-gateway:gw-fix",
]);
expect(summary(buildMultiRepoRows({ ...input, query: "collect" }))).toEqual([
"repo ology-collect [dev] c1",
"# ology-collect",
"ology-collect:collect-only",
]);
});
it("highlights the shown part of a remote branch name", () => {
const rows = buildMultiRepoRows({ ...input, query: "origin/dev" });
const dev = rows.find((r) => r.type === "common" && r.branch.name === "origin/dev");
expect(dev?.type === "common" && [dev.label, dev.matches]).toEqual(["dev", [0, 1, 2]]);
});
it("shows no common branches until every repository's branches are loaded", () => {
const partial = { "/p/ology-collect": branches["/p/ology-collect"]! };
expect(summary(buildMultiRepoRows({ ...input, branches: partial, query: "" })).at(-1)).toBe(
"repo ology-gateway [dev] c3",
);
});
});
describe("buildMultiRepoRows with repositories on different branches", () => {
const diverged = [repo("ology-collect", "release/1.0"), repo("ology-dependencies"), repo("ology-gateway")];
const own: Record<string, Branch[]> = {
...branches,
"/p/ology-collect": [
b("release/1.0", { current: true }),
b("dev"),
b("main"),
b("origin/dev"),
b("origin/release/1.0"),
],
};
const input = {
repos: diverged,
branches: own,
actions: [],
expanded: new Set(DEFAULT_EXPANDED),
recent: ["dev", "release/1.0", "gone"],
tags: ["v1.2", "v1.10"],
};
it("lists the current repository's recent, local, remote branches and tags instead of the common ones", () => {
expect(summary(buildMultiRepoRows({ ...input, current: "/p/ology-collect", query: "" }))).toEqual([
"repo ology-collect [release/1.0] c1",
"repo ology-dependencies [dev] c2",
"repo ology-gateway [dev] c3",
"---",
"> Recent Branches in ology-collect",
"v Local Branches in ology-collect",
" ology-collect:release/1.0",
" ology-collect:main",
" ology-collect:dev",
"> Remote Branches in ology-collect",
"> Tags in ology-collect",
]);
});
it("falls back to the first repository and expands the matching lists on search", () => {
const expanded = new Set(["repo:tags", "repo:recent"]);
const rows = summary(buildMultiRepoRows({ ...input, expanded, current: "/elsewhere", query: "" }));
expect(rows.slice(4)).toEqual([
"v Recent Branches in ology-collect",
" ology-collect:dev",
"> Local Branches in ology-collect",
"> Remote Branches in ology-collect",
"v Tags in ology-collect",
" tag v1.10",
" tag v1.2",
]);
// Search: the current repository's lists, then the other repositories' branches.
expect(summary(buildMultiRepoRows({ ...input, current: "/p/ology-gateway", query: "fix" }))).toEqual([
"v Local Branches in ology-gateway",
" ology-gateway:gw-fix",
]);
expect(summary(buildMultiRepoRows({ ...input, current: "/p/ology-gateway", query: "rel" }))).toEqual([
"# ology-collect",
"ology-collect:release/1.0",
"ology-collect:origin/release/1.0",
]);
});
});
describe("repository colours and heads", () => {
it("gives up to nine repositories distinct colours, then cycles", () => {
expect(Array.from({ length: 10 }, (_, i) => repoColorIndex(i))).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 1]);
});
it("names a detached HEAD by its short commit", () => {
expect(repoHeadLabel({ head: "dev", headCommit: "0123456789" })).toBe("dev");
expect(repoHeadLabel({ head: null, headCommit: "0123456789" })).toBe("01234567");
expect(repoHeadLabel({ head: null, headCommit: null })).toBe("No commits");
});
});
+2 -6
Переглянути файл
@@ -6,7 +6,7 @@ import { Menu, type MenuItem } from "@/ui";
import { editorService, maybeEditorService, notifications, toolWindowService } from "@/workbench/contributions";
import { annotationsShown, toggleAnnotations } from "./blame";
import { showBranchesPopup } from "./BranchWidget";
import { checkoutRevision, newBranch, newBranchInRepos } from "./branchOps";
import { checkoutRevision, newBranch } from "./branchOps";
import {
addToVcs,
commitChanges,
@@ -401,11 +401,7 @@ export function registerVcsActions(): () => void {
category: "Git",
icon: "plus",
when: VCS,
// `{ repos }` (Branches popup with several repositories): in each of them.
run: ({ arg }) => {
const repos = (arg as { repos?: unknown } | undefined)?.repos;
void (Array.isArray(repos) && repos.length ? newBranchInRepos(repos as string[]) : newBranch());
},
run: () => void newBranch(),
},
{
id: "vcs.checkoutRevision",
-60
Переглянути файл
@@ -7,13 +7,8 @@ import {
checkoutAndRebase,
checkoutBranch,
checkoutDetached,
checkoutInRepos,
deleteBranch,
deleteInRepos,
deleteRemoteBranch,
mergeInRepos,
newBranchInRepos,
rebaseInRepos,
loadFavoriteBranches,
mergeIntoCurrent,
newBranch,
@@ -25,8 +20,6 @@ import {
} from "./branchOps";
import { showCompareBranches } from "./CompareBranches";
import { showDiffWithWorkingTree } from "./operations";
import type { CommonBranch } from "./repoBranches";
import { focusRepo } from "./store";
export function branchMenu(b: Branch, current: string | null, done: () => void = () => {}): MenuItem[] {
const run = (fn: () => unknown) => () => {
@@ -105,56 +98,3 @@ export function tagMenu(tag: string, done: () => void = () => {}): MenuItem[] {
{ label: "Show History", icon: "history", run: run(() => executeAction("vcs.showLog", { branch: tag })) },
];
}
/** Entries for a branch common to all repositories: each acts in every one of `roots`. */
export function commonBranchMenu(b: CommonBranch, roots: readonly string[], done: () => void = () => {}): MenuItem[] {
const run = (fn: () => unknown) => () => {
done();
void fn();
};
const newFrom: MenuItem = {
label: `New Branch from '${b.name}'…`,
icon: "branch",
run: run(() => newBranchInRepos(roots, b.name)),
};
if (b.current)
return [
newFrom,
{ kind: "separator" },
{ label: "Update", icon: "git-pull", run: run(() => executeAction("vcs.update")) },
{ label: "Push…", icon: "git-push", run: run(() => executeAction("vcs.push")) },
];
const items: MenuItem[] = [
{ label: "Checkout", run: run(() => checkoutInRepos(b.name, roots)) },
newFrom,
{ kind: "separator" },
{ label: `Rebase Current onto '${b.name}'`, run: run(() => rebaseInRepos(b.name, roots)) },
{ label: `Merge '${b.name}' into Current`, run: run(() => mergeInRepos(b.name, roots)) },
];
if (!b.remote)
items.push(
{ kind: "separator" },
{ label: "Delete", danger: true, icon: "trash", run: run(() => deleteInRepos(b.name, roots)) },
);
return items;
}
/** `items` acting on repository `root`: it is selected (with its branches loaded) before each entry runs. */
export function inRepo(root: string, items: MenuItem[]): MenuItem[] {
return items.map((item): MenuItem => {
if (item.kind === "separator" || item.kind === "header") return item;
if (item.kind === "action")
return {
label: item.label ?? item.action,
icon: item.icon,
disabled: item.disabled,
run: () => void focusRepo(root).then(() => executeAction(item.action, item.arg)),
};
const run = item.run;
return {
...item,
run: run && (() => void focusRepo(root).then(run)),
submenu: item.submenu && inRepo(root, item.submenu),
};
});
}
+5 -118
Переглянути файл
@@ -9,7 +9,7 @@ import { isFavoriteBranch, pushRecent, shortRemoteName } from "./branches";
import { showCommitRange } from "./CompareBranches";
import { confirmDialog, promptText } from "./dialogs";
import { runOp, runRemote, saveAll } from "./ops";
import { conflictedFiles, currentRepo, refreshNow, repoName, useVcs } from "./store";
import { conflictedFiles, currentRepo, refreshNow, useVcs } from "./store";
const recentKey = () => `openidea.vcs.recentBranches:${useVcs.getState().root ?? ""}`;
@@ -68,23 +68,18 @@ async function askSmartCheckout(files: readonly string[]): Promise<CheckoutOptio
* to rebase that branch onto the remote or drop its commits (one that is only behind is
* fast-forwarded). Resolves true once switched.
*/
async function performCheckout(
rev: string,
success: () => string,
repo: string | null = currentRepo(),
quiet = false,
): Promise<boolean> {
async function performCheckout(rev: string, success: () => string): Promise<boolean> {
await saveAll();
let options: CheckoutOptions = { mode: "normal", diverged: null };
for (;;) {
const opts = options;
const outcome = await runOp(`Checkout ${rev}`, () => call(commands.vcsCheckout(repo, rev, false, opts)));
const outcome = await runOp(`Checkout ${rev}`, () => call(commands.vcsCheckout(currentRepo(), rev, false, opts)));
if (!outcome) return false;
// `success` may name the branch now checked out.
if (outcome.kind === "done" || outcome.kind === "conflicts") await refreshNow();
switch (outcome.kind) {
case "done":
if (!quiet) notifications().notify({ group: "vcs", level: "info", title: success() });
notifications().notify({ group: "vcs", level: "info", title: success() });
return true;
case "conflicts":
notifications().notify({
@@ -321,109 +316,6 @@ export async function updateBranch(name: string) {
await runRemote({ op: "updateBranch", branch: name }, `${name} ← ${b.upstream}`);
}
// --- several repositories ----------------------------------------------------
/** "in 3 repositories", or "in 2 of 3 repositories" when some were left out. */
function inRepos(done: number, total: number): string {
return done === total ? `in ${total} repositories` : `in ${done} of ${total} repositories`;
}
/**
* Runs `step` in each repository in turn, stopping at the first one that fails (its
* error is reported by `step`), then reports how many repositories it was done in.
*/
async function eachRepo(roots: readonly string[], step: (root: string) => Promise<boolean>, title: string) {
let done = 0;
for (const root of roots) {
if (!(await step(root))) break;
done++;
}
await refreshNow();
if (done) notifications().notify({ group: "vcs", level: "info", title: `${title} ${inRepos(done, roots.length)}` });
}
/** Checks out `name` (local, or remote: its local namesake) in every repository of `roots`. */
export async function checkoutInRepos(name: string, roots: readonly string[]) {
const label = useVcs.getState().branches.some((b) => b.remote && b.name === name) ? shortRemoteName(name) : name;
const previous = useVcs.getState().branch?.head;
await eachRepo(roots, (root) => performCheckout(name, () => "", root, true), `Checked out ${label}`);
rememberBranch(previous);
rememberBranch(useVcs.getState().branch?.head);
}
/** New Branch in every repository of `roots` (from HEAD or `from`), checked out by default. */
export async function newBranchInRepos(roots: readonly string[], from?: string) {
const r = await promptText({
title: from ? `Create New Branch from ${from}` : "Create New Branch",
label: `New branch name (in ${roots.length} repositories):`,
initial: from?.includes("/") ? shortRemoteName(from) : "",
mono: true,
okLabel: "Create",
validate: validateBranchName,
checkbox: { label: "Checkout branch", initial: true },
});
if (!r) return;
const name = r.value.trim();
if (r.checked) await saveAll();
await eachRepo(
roots,
async (root) =>
(await runOp(`Create branch ${name}`, () => call(commands.vcsCreateBranch(root, name, from ?? null, r.checked)), {
refresh: false,
})) !== undefined,
r.checked ? `Created and checked out ${name}` : `Created branch ${name}`,
);
}
/** Merges `branch` into the current branch of every repository of `roots`; stops on conflicts. */
export async function mergeInRepos(branch: string, roots: readonly string[]) {
await saveAll();
await eachRepo(
roots,
async (root) =>
(await runOp(`Merge ${branch} (${repoName(root)})`, () => call(commands.vcsMerge(root, branch)), {
refresh: false,
errorActions: conflictActions,
onError: openConflictsInstead,
})) !== undefined,
`Merged ${branch}`,
);
}
/** Rebases the current branch of every repository of `roots` onto `branch`; stops on conflicts. */
export async function rebaseInRepos(branch: string, roots: readonly string[]) {
await saveAll();
await eachRepo(
roots,
async (root) =>
(await runOp(`Rebase onto ${branch} (${repoName(root)})`, () => call(commands.vcsRebase(root, branch)), {
refresh: false,
errorActions: conflictActions,
onError: openConflictsInstead,
})) !== undefined,
`Rebased onto ${branch}`,
);
}
/** Deletes local branch `name` in every repository of `roots`. */
export async function deleteInRepos(name: string, roots: readonly string[]) {
const ok = await confirmDialog({
title: "Delete Branch",
message: `Delete branch '${name}' in ${roots.length} repositories? Unmerged commits are discarded.`,
okLabel: "Delete",
danger: true,
});
if (!ok) return;
await eachRepo(
roots,
async (root) =>
(await runOp(`Delete branch ${name} (${repoName(root)})`, () => call(commands.vcsDeleteBranch(root, name)), {
refresh: false,
})) !== undefined,
`Deleted branch ${name}`,
);
}
// --- favorites ---------------------------------------------------------------
const favoritesKey = () => `openidea.vcs.favoriteBranches:${useVcs.getState().root ?? ""}`;
@@ -449,12 +341,7 @@ export function toggleFavoriteBranch(b: Branch) {
loadFavoriteBranches();
const stored = useFavoriteBranches.getState().names;
// First edit: start from the defaults that are currently shown.
const base =
stored ??
useVcs
.getState()
.branches.filter((x) => isFavoriteBranch(x, null))
.map((x) => x.name);
const base = stored ?? useVcs.getState().branches.filter((x) => isFavoriteBranch(x, null)).map((x) => x.name);
const names = base.includes(b.name) ? base.filter((n) => n !== b.name) : [...base, b.name];
useFavoriteBranches.setState({ names });
try {
-307
Переглянути файл
@@ -1,307 +0,0 @@
/** Branches popup model for a project with several repositories (pure). */
import type { Branch } from "@/bindings";
import { fuzzyMatch } from "@/ui/match";
import { rootOf } from "./model";
import { isFavoriteBranch, MAX_RECENT, sortLocal, sortRemote, type PopupAction } from "./branches";
export interface RepoEntry {
root: string;
name: string;
/** Current branch; `null` when HEAD is detached. */
head: string | null;
headCommit: string | null;
}
/** Number of `--project-color-N` tokens repositories are coloured with. */
export const REPO_COLORS = 9;
/** Colour slot (1-based) of the repository at `index`: distinct for up to `REPO_COLORS` repositories. */
export function repoColorIndex(index: number): number {
return (index % REPO_COLORS) + 1;
}
/** Display name of a repository's HEAD: its branch, else the short commit. */
export function repoHeadLabel(r: Pick<RepoEntry, "head" | "headCommit">): string {
if (r.head) return r.head;
return r.headCommit ? r.headCommit.slice(0, 8) : "No commits";
}
/**
* The current repository, shown by the branch widget and the lower part of the Branches
* popup: the one holding the active editor's file, else the selected one, else the first.
*/
export function currentRepoFor(
activePath: string | null,
roots: readonly string[],
selected: string | null,
): string | null {
const ofFile = activePath ? rootOf(activePath, roots) : null;
return ofFile ?? (selected && roots.includes(selected) ? selected : null) ?? roots[0] ?? null;
}
/**
* Whether the branch widget names the repository besides the branch: only with several
* repositories that are not all on the same branch.
*/
export function widgetShowsRepo(repos: readonly Pick<RepoEntry, "head">[]): boolean {
if (repos.length < 2) return false;
const first = repos[0]!.head;
return !first || repos.some((r) => r.head !== first);
}
export interface CommonBranch {
name: string;
remote: boolean;
/** Checked out in every repository. */
current: boolean;
favorite: boolean;
}
/** Branches present in every repository (by name), local and remote, sorted like the single-repository lists. */
export function commonBranches(
branchesByRepo: readonly (readonly Branch[])[],
favorites: readonly string[] | null = null,
): { local: CommonBranch[]; remote: CommonBranch[] } {
if (!branchesByRepo.length) return { local: [], remote: [] };
const pick = (sorted: (list: readonly Branch[]) => Branch[]): CommonBranch[] => {
const [first, ...rest] = branchesByRepo;
const others = rest.map((list) => new Map(list.map((b) => [`${b.remote}:${b.name}`, b])));
return sorted(first!).flatMap((b) => {
const all = others.map((m) => m.get(`${b.remote}:${b.name}`));
if (all.some((x) => !x)) return [];
return [
{
name: b.name,
remote: b.remote,
current: b.current && all.every((x) => x!.current),
favorite: isFavoriteBranch(b, favorites),
},
];
});
};
const byRank = (a: CommonBranch, b: CommonBranch) =>
Number(b.current) - Number(a.current) || Number(b.favorite) - Number(a.favorite);
return {
local: pick((l) => sortLocal(l, favorites)).sort(byRank),
remote: pick((l) => sortRemote(l, favorites)).sort(byRank),
};
}
export type BranchGroupKind = "recent" | "local" | "remote";
export type RepoRow =
/** Section header; an empty label draws a separator. */
| { type: "section"; key: string; label: string }
| { type: "action"; key: string; action: PopupAction; matches: number[] | null }
| { type: "repo"; key: string; repo: RepoEntry; color: number; matches: number[] | null }
/** Collapsible group (common branches, or one of the current repository's lists) or remote folder. */
| { type: "group"; key: string; label: string; expanded: boolean; depth: number }
| {
type: "common";
key: string;
branch: CommonBranch;
/** Shown name: remote branches without their remote (it is the folder). */
label: string;
depth: number;
matches: number[] | null;
}
/** A branch of one repository. */
| {
type: "branch";
key: string;
repo: RepoEntry;
branch: Branch;
group: BranchGroupKind;
depth: number;
matches: number[] | null;
favorite: boolean;
}
| { type: "tag"; key: string; repo: RepoEntry; tag: string; depth: number; matches: number[] | null };
/**
* Initially expanded groups: the common local branches, and the current repository's
* local branches (switching a repository's branch stays one click away).
*/
export const DEFAULT_EXPANDED: readonly string[] = ["common:local", "repo:local"];
export interface MultiRepoInput {
repos: readonly RepoEntry[];
/** Root → its branches (missing while loading). */
branches: Readonly<Record<string, readonly Branch[]>>;
query: string;
actions: readonly PopupAction[];
/** Expanded group / folder keys (`common:local`, `repo:remote`, `common:folder:origin`…). */
expanded: ReadonlySet<string>;
favorites?: readonly string[] | null;
/** The current repository (of the active file), whose lists are shown when the repositories' branches differ. */
current?: string | null;
/** Recently checked-out branches (newest first). */
recent?: readonly string[];
/** Tags of the current repository. */
tags?: readonly string[];
}
/**
* Rows of the Branches popup with several repositories: actions; the repositories,
* each with its current branch and opening its own branches; then, when they are all
* on the same branch, the branches common to all of them (acting on all of them),
* otherwise the current repository's recent, local and remote branches and tags, in
* collapsible groups. A query filters actions, repositories (by name) and branches,
* expands every group, and adds the other repositories' matching branches.
*/
export function buildMultiRepoRows({
repos,
branches,
query,
actions,
expanded,
favorites = null,
current = null,
recent = [],
tags = [],
}: MultiRepoInput): RepoRow[] {
const q = query.trim();
const match = (text: string): number[] | null | false => (q ? (fuzzyMatch(text, q) ?? false) : null);
const open = (key: string) => !!q || expanded.has(key);
const blocks: RepoRow[][] = [];
const actionRows: RepoRow[] = [];
for (const a of actions) {
const m = match(a.label);
if (m !== false) actionRows.push({ type: "action", key: `action:${a.id}`, action: a, matches: m });
}
blocks.push(actionRows);
const repoRows: RepoRow[] = [];
repos.forEach((repo, i) => {
const m = match(repo.name);
if (m !== false)
repoRows.push({ type: "repo", key: `repo:${repo.root}`, repo, color: repoColorIndex(i), matches: m });
});
blocks.push(repoRows);
/** A group row followed (when expanded) by its children; nothing when it has none. */
const group = (out: RepoRow[], key: string, label: string, depth: number, children: RepoRow[]) => {
if (!children.length) return;
const expandedNow = open(key);
out.push({ type: "group", key, label, expanded: expandedNow, depth });
if (expandedNow) out.push(...children);
};
const branchRows = (repo: RepoEntry, list: readonly Branch[], kind: BranchGroupKind, depth: number) =>
list.flatMap((b): RepoRow[] => {
const m = match(b.name);
if (m === false) return [];
const key = `branch:${repo.root}:${kind}:${b.name}`;
return [
{
type: "branch",
key,
repo,
branch: b,
group: kind,
depth,
matches: m,
favorite: isFavoriteBranch(b, favorites),
},
];
});
const shared = !widgetShowsRepo(repos);
const groups: RepoRow[] = [];
let shown = new Set<string>();
const currentRepo = repos.find((r) => r.root === current) ?? repos[0];
if (shared) {
const loaded = repos.every((r) => branches[r.root]);
const common = loaded
? commonBranches(
repos.map((r) => branches[r.root]!),
favorites,
)
: { local: [], remote: [] };
shown = new Set([...common.local, ...common.remote].map((b) => `${b.remote}:${b.name}`));
const local = common.local.flatMap((b): RepoRow[] => {
const m = match(b.name);
return m === false
? []
: [{ type: "common", key: `common:${b.name}`, branch: b, label: b.name, depth: 1, matches: m }];
});
group(groups, "common:local", "Common Local Branches", 0, local);
const byRemote = new Map<string, CommonBranch[]>();
for (const b of common.remote) {
const remote = b.name.slice(0, Math.max(0, b.name.indexOf("/")));
byRemote.set(remote, [...(byRemote.get(remote) ?? []), b]);
}
const remote: RepoRow[] = [];
for (const [name, items] of byRemote) {
const leaves = items.flatMap((b): RepoRow[] => {
const m = match(b.name);
if (m === false) return [];
// Highlights are of the full name: shift them onto the shown part.
const part = m && m.map((i) => i - name.length - 1).filter((i) => i >= 0);
const label = b.name.slice(name.length + 1);
return [{ type: "common", key: `common:${b.name}`, branch: b, label, depth: 2, matches: part }];
});
group(remote, `common:folder:${name}`, name, 1, leaves);
}
group(groups, "common:remote", "Common Remote Branches", 0, remote);
} else if (currentRepo) {
const list = branches[currentRepo.root] ?? [];
const local = sortLocal(list, favorites);
const byName = new Map(local.map((b) => [b.name, b]));
const recentList = q
? []
: recent
.map((n) => byName.get(n))
.filter((b): b is Branch => !!b && !b.current)
.slice(0, MAX_RECENT);
const name = currentRepo.name;
group(groups, "repo:recent", `Recent Branches in ${name}`, 0, branchRows(currentRepo, recentList, "recent", 1));
group(groups, "repo:local", `Local Branches in ${name}`, 0, branchRows(currentRepo, local, "local", 1));
group(
groups,
"repo:remote",
`Remote Branches in ${name}`,
0,
branchRows(currentRepo, sortRemote(list, favorites), "remote", 1),
);
const tagRows = [...tags]
.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }))
.flatMap((t): RepoRow[] => {
const m = match(t);
return m === false
? []
: [{ type: "tag", key: `tag:${currentRepo.root}:${t}`, repo: currentRepo, tag: t, depth: 1, matches: m }];
});
group(groups, "repo:tags", `Tags in ${name}`, 0, tagRows);
}
blocks.push(groups);
if (q) {
for (const repo of repos) {
if (!shared && repo === currentRepo) continue;
const list = branches[repo.root] ?? [];
const own = (l: Branch[]) => l.filter((b) => !shown.has(`${b.remote}:${b.name}`));
const rows = [
...branchRows(repo, own(sortLocal(list, favorites)), "local", 0),
...branchRows(repo, own(sortRemote(list, favorites)), "remote", 0),
];
if (rows.length) blocks.push([{ type: "section", key: `section:${repo.root}`, label: repo.name }, ...rows]);
}
}
const rows: RepoRow[] = [];
for (const block of blocks) {
if (!block.length) continue;
if (rows.length && block[0]!.type !== "section")
rows.push({ type: "section", key: `separator:${rows.length}`, label: "" });
rows.push(...block);
}
return rows;
}
/** Toggles a group / folder key. */
export function toggleExpanded(expanded: ReadonlySet<string>, key: string): Set<string> {
const next = new Set(expanded);
if (!next.delete(key)) next.add(key);
return next;
}
+1 -16
Переглянути файл
@@ -17,11 +17,6 @@ import { useProject } from "@/platform/project";
import { setFileDecorations } from "@/workbench/contributions";
import { effectiveKind, repoLabel, rootOf, statusDecorations, stripSlash } from "./model";
export interface RepoHead {
head: string | null;
headCommit: string | null;
}
export interface VcsState {
/** The open project is a git repository. */
available: boolean;
@@ -30,8 +25,6 @@ export interface VcsState {
roots: string[];
/** Root → merge / rebase / cherry-pick / revert in progress there. */
operations: Record<string, string>;
/** Root → its current branch (`head` null when detached) and HEAD commit. */
heads: Record<string, RepoHead>;
/** The selected repository's root (branch widget, log, push…). */
repo: string | null;
status: FileStatus[];
@@ -57,7 +50,6 @@ const initial: VcsState = {
root: null,
roots: [],
operations: {},
heads: {},
repo: null,
status: [],
statusLoaded: false,
@@ -117,12 +109,6 @@ export function selectRepo(root: string): Promise<void> {
return refreshNow();
}
/** Selects `root` and loads its branches, so branch operations act on it. */
export async function focusRepo(root: string): Promise<void> {
await selectRepo(root);
if (!useVcs.getState().branchesLoaded) await loadBranches();
}
export function conflictedFiles(status: readonly FileStatus[] = useVcs.getState().status): FileStatus[] {
return status.filter((f) => effectiveKind(f) === "conflicted");
}
@@ -194,8 +180,7 @@ export function refreshNow(): Promise<void> {
// `null` (before the first refresh) is the primary repository, listed first.
const shown = s.repo && roots.includes(s.repo) ? s.repo : (roots[0] ?? null);
const repo = attentionRepo(shown, s.operations, operations) ?? shown;
const heads = Object.fromEntries(vcsRoots.map((r) => [r.root, { head: r.head, headCommit: r.headCommit }]));
useVcs.setState({ operations, heads });
useVcs.setState({ operations });
if (repo !== s.repo || roots.join("\n") !== s.roots.join("\n")) useVcs.setState({ roots, repo });
applyStatus(status, branch);
useVcs.setState({ branches, stashes, error: null });
+2 -29
Переглянути файл
@@ -47,7 +47,7 @@
background: var(--bg-editor, var(--bg-app));
color: var(--fg);
font-family: var(--font-ui);
font-size: calc(14px + var(--markdown-font-zoom, 0px));
font-size: 14px;
line-height: 1.6;
overflow-wrap: break-word;
}
@@ -112,7 +112,7 @@
.preview :global(pre code) {
padding: 0;
background: none;
font-size: calc(var(--fs-code) + var(--markdown-font-zoom, 0px));
font-size: var(--fs-code);
}
.preview :global(blockquote) {
padding: 0 1em;
@@ -188,30 +188,3 @@
.preview :global(.tok-operator) {
color: var(--syn-punct);
}
/* Mermaid diagrams: the source stays until the diagram is drawn, and next to an error. */
.preview :global([data-mermaid]) {
margin: 0 0 1em;
}
.preview :global([data-mermaid] > pre) {
margin: 0;
}
.preview :global([data-mermaid-state="ok"] > pre) {
display: none;
}
.preview :global(.mermaid-output) {
overflow-x: auto;
text-align: center;
}
.preview :global([data-mermaid-state="error"] > .mermaid-output) {
margin-top: 6px;
padding: 6px 10px;
border-left: 3px solid var(--danger);
border-radius: var(--radius-small);
background: var(--bg-elev);
color: var(--danger);
font-family: var(--font-mono);
font-size: var(--fs-code);
text-align: left;
white-space: pre-wrap;
}
+2 -33
Переглянути файл
@@ -3,25 +3,13 @@
* side by side, switched from the floating toolbar at the top right. The
* preview follows the editor's scroll position in the split layout.
*/
import {
useDeferredValue,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
type CSSProperties,
type MouseEvent,
type ReactNode,
} from "react";
import { useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, type MouseEvent, type ReactNode } from "react";
import clsx from "clsx";
import { call, commands, isTauri } from "@/platform/ipc";
import { maybeEditorService } from "@/workbench/contributions";
import { highlightInto } from "@/editor/lsp/markdown";
import { IconButton, selectableText } from "@/ui";
import { useLiveMarkdown } from "./live";
import { hasMermaid, MERMAID_SELECTOR, renderMermaidIn, subscribeTheme, themeKey } from "./mermaid";
import { modeOf, useMarkdownModes } from "./modes";
import { ANCHOR_PREFIX, previewOffsetForLine, renderMarkdown, resolveLink, slugify } from "./render";
import styles from "./Markdown.module.css";
@@ -81,28 +69,11 @@ export function MarkdownEditor({ path, children }: { path: string; tabId: string
function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
const text = useLiveMarkdown((s) => s[path]?.text);
const fontZoom = useLiveMarkdown((s) => s[path]?.fontZoom ?? 0);
const topLine = useLiveMarkdown((s) => s[path]?.topLine ?? 0);
const scrollSeq = useLiveMarkdown((s) => s[path]?.scrollSeq ?? 0);
const deferred = useDeferredValue(text ?? "");
const html = useMemo(() => renderMarkdown(deferred), [deferred]);
const ref = useRef<HTMLDivElement>(null);
const theme = useSyncExternalStore(subscribeTheme, themeKey, () => "");
const diagrams = useRef<Node[]>([]);
const [diagramsDrawn, setDiagramsDrawn] = useState(0);
// Mermaid diagrams: before paint, so cached ones don't flash their source.
useLayoutEffect(() => {
const root = ref.current;
if (!root || !hasMermaid(root)) return;
const pass = renderMermaidIn(root, diagrams.current);
let live = true;
if (pass.async) void pass.done.then(() => live && setDiagramsDrawn((n) => n + 1));
return () => {
live = false;
pass.cancel();
};
}, [html, theme]);
// Images and code highlighting after each render.
useEffect(() => {
@@ -127,7 +98,6 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
);
});
root.querySelectorAll<HTMLElement>("pre > code").forEach((code) => {
if (code.closest(MERMAID_SELECTOR)) return;
const lang = [...code.classList].find((c) => c.startsWith("language-"))?.slice("language-".length) ?? null;
const src = (code.textContent ?? "").replace(/\n+$/, "");
code.textContent = src;
@@ -147,7 +117,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
top: el.offsetTop,
}));
root.scrollTop = topLine <= 0 ? 0 : previewOffsetForLine(blocks, topLine, root.scrollHeight);
}, [html, topLine, scrollSeq, sync, diagramsDrawn]);
}, [html, topLine, scrollSeq, sync]);
const onClick = (e: MouseEvent) => {
const a = (e.target as Element).closest("a");
@@ -171,7 +141,6 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
<div
ref={ref}
className={clsx(styles.preview, selectableText)}
style={{ "--markdown-font-zoom": `${fontZoom}px` } as CSSProperties}
tabIndex={-1}
role="document"
aria-label="Markdown preview"
+2 -7
Переглянути файл
@@ -6,7 +6,6 @@
import { ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
import { create } from "zustand";
import { registerEditorContribution } from "@/editor/api";
import { fontZoom } from "@/editor/core/cm/prefs";
import { isMarkdownPath } from "../fileKinds";
export interface LiveMarkdown {
@@ -15,8 +14,6 @@ export interface LiveMarkdown {
topLine: number;
/** Bumped when the editor scrolls, so equal lines still resync. */
scrollSeq: number;
/** The editor's font zoom in px; the preview scales its text by the same amount. */
fontZoom: number;
}
export const useLiveMarkdown = create<Record<string, LiveMarkdown | undefined>>(() => ({}));
@@ -25,7 +22,7 @@ const TEXT_DELAY = 120;
function publish(path: string, patch: Partial<LiveMarkdown>) {
useLiveMarkdown.setState((s) => {
const prev = s[path] ?? { text: "", topLine: 0, scrollSeq: 0, fontZoom: 0 };
const prev = s[path] ?? { text: "", topLine: 0, scrollSeq: 0 };
return { [path]: { ...prev, ...patch } };
});
}
@@ -50,13 +47,11 @@ function livePlugin(path: string) {
};
constructor(private view: EditorView) {
publish(path, { text: view.state.doc.toString(), fontZoom: view.state.field(fontZoom, false) ?? 0 });
publish(path, { text: view.state.doc.toString() });
view.scrollDOM.addEventListener("scroll", this.onScroll, { passive: true });
}
update(u: ViewUpdate) {
const zoom = u.state.field(fontZoom, false) ?? 0;
if (zoom !== (u.startState.field(fontZoom, false) ?? 0)) publish(path, { fontZoom: zoom });
if (!u.docChanged) return;
clearTimeout(this.timer);
this.timer = setTimeout(() => publish(path, { text: this.view.state.doc.toString() }), TEXT_DELAY);
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more