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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 2bf57a8297 fix(editor): Keep the internal cancellation message out of the UI text catalog 2026-10-28 09:01:45 +08:00
l0ng-ai 7c09a13afc fix(editor): List identical completion items once
kotlin-language-server repeats a class once per classpath entry declaring
it, so `String()` and `String` were listed three times each.
2026-10-28 08:58:41 +08:00
l0ng-ai b9f8a0b4bd fix(editor): Rank the exact type first in Java constructor completion
jdtls appends the call or body to filterText (`String(${0})`); matching
on the label instead lets typing `String` rank `String` above
`StringBuilder` and the other types sharing its sort text.
2026-10-28 08:51:15 +08:00
l0ng-ai aaf4d12ba6 fix(editor): Skip cancelled LSP requests and limit generated-code reformat
- Requests cancelled while waiting for pending edits are not sent.
- Code generated by an action is reformatted per changed hunk, so an added
  import doesn't reformat the code between it and the generated lines.
- A long busy spell caused by a settle refresh re-runs it only once.
- Files dropped on a file row of another changelist move to that changelist.
- Python Implement methods: a nested class without bases ends the lookup,
  class bodies continue through unindented string lines, and
  `@abstractproperty` stubs become `@property`.
- Resend diagnostics goes through the host ops, and custom servers get
  `max_java`.
2026-10-28 08:45:21 +08:00
l0ng-ai a645632b23 chore(lint): Skip agent worktrees under .claude 2026-10-28 08:28:00 +08:00
l0ng-ai 69fa7f7387 feat(editor): Quick fixes, completion and navigation while typing
Quick fixes
- Errors get a red quick-fix bulb; Apply Quick Fix (⌥⇧↵) fixes the most
  severe problem at the caret, and the error hover offers the fix directly.
- Code generated by a code action is re-indented to the file's style.
- Python: Implement abstract methods (⌃I or the bulb) from the bases.
- Duplicate code actions are listed once.

Completion
- Overloads sharing a name, and a name importable from several modules,
  are no longer merged into one entry.
- Auto-import entries show the module they import from.
- Call snippets without a stop (`new ArrayList<>()`) leave the caret inside
  the parentheses with parameter info, or past them when nothing takes
  arguments; parameter info also opens after server call snippets.
- The selected item is resolved ahead of acceptance, so its auto-import
  is applied (rust-analyzer).

Navigation and diagnostics
- Language server requests wait for pending edits, so Go to Declaration
  right after typing answers for the current text; an empty answer right
  after an edit is retried while the server catches up.
- Diagnostics come back after a window reload; error underlines stay
  visible under typo / unused highlighting.
- Implementation gutter markers no longer refresh in a loop while the
  server reports progress.
- A missing alternative server no longer shows as a server error.
2026-10-28 08:28:00 +08:00
l0ng-ai 1122d67f7d fix(lsp): Deliver server settings and start servers on a supported JDK
- workspace/configuration answers a server's own section (basedpyright)
  from its settings block; basedpyright runs in "standard" mode and keeps
  auto search paths on, so `src/` layouts resolve from `tests/`.
- jdtls: formatting follows the editor indent, calls complete without
  guessed arguments, and JDK internals stay out of completion.
- `max-java` in a language server config picks an installed JDK no newer
  than that (kotlin-language-server fails on JDK 25).
- Server initialization may take up to 5 minutes (first Gradle import).
- `lsp_resend_diagnostics` re-emits stored diagnostics after a reload.
- Spelling only checks declared names (not called methods like
  `substring`) and accepts plurals of known software terms.
2026-10-28 08:28:00 +08:00
l0ng-ai 60722e0cc5 feat(editor): Drag tabs and files between split panes
HTML5 drag and drop never reaches the webview while native file drop is
enabled, so tab, project-file and changelist drags did nothing. They now
run on pointer events:

- Drag an editor tab onto another pane, or onto a pane's edge to split it.
- Drag files from the Project view into an editor pane (center opens them
  there, an edge opens them in a new split).
- Drag files between changelists in the Commit view.
- "Drag-and-drop with Alt pressed only" applies to tabs and stripe buttons.
2026-10-28 08:27:20 +08:00
l0ng-ai 48ac2094fc feat(lsp): Configure language servers and add servers of one's own (#108)
Language servers can be configured from settings.toml (global or project) and Settings › Language Servers: arguments, environment, initialization options and workspace settings per server, enable/disable, and any stdio LSP server can be added for a language. Settings-only changes are pushed with workspace/didChangeConfiguration; launch changes restart the server.

Also: re-enabling a server now detaches and stops the fallback that stood in for it, and a server added from the dialog is written as its own [languageServers.<name>] table.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-28 03:40:18 +08:00
l0ng-ai 025e0019d2 feat(remote): SSH configurations, SFTP deployment, run targets and remote development (#91) 2026-10-27 23:12:19 +08:00
99 змінених файлів з 3866 додано та 550 видалено

No files matched your search

Створено
+2
Переглянути файл
@@ -4031,6 +4031,7 @@ dependencies = [
"serde",
"serde_json",
"specta",
"specta-typescript",
"thiserror 2.0.21",
"tokio-util",
]
@@ -4221,6 +4222,7 @@ dependencies = [
"parking_lot",
"regex-lite",
"serde",
"serde_json",
"specta",
"toml 0.9.12+spec-1.1.0",
"tracing",
+1
Переглянути файл
@@ -46,6 +46,7 @@ serde_json = "1"
toml = "0.9"
toml_edit = "0.25"
specta = { version = "=2.0.0-rc.25", features = ["derive"] }
specta-typescript = "0.0.12"
# async & concurrency
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "process", "io-util", "fs"] }
+1
Переглянути файл
@@ -10,5 +10,6 @@ dunce.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
specta-typescript.workspace = true
thiserror.workspace = true
tokio-util.workspace = true
+56
Переглянути файл
@@ -42,6 +42,9 @@ pub struct Settings {
/// Language servers / debug adapters at a user-chosen location, by the
/// command the language definition launches (`elixir-ls`, `codelldb`).
pub tools: BTreeMap<String, ToolSettings>,
/// Per language server, by name (`rust-analyzer`): launch and protocol
/// options on top of the language definition, or a server defined here.
pub language_servers: BTreeMap<String, LanguageServerSettings>,
/// Editor › Inspections profiles.
pub inspections: InspectionSettings,
/// Editor › Natural Languages › Spelling.
@@ -61,6 +64,58 @@ pub struct ToolSettings {
pub path: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct LanguageServerSettings {
/// `false` keeps the server from starting for any language.
pub enabled: bool,
/// Executable to launch instead of the definition's; required for a server
/// defined here (one with `languages`).
pub command: String,
/// Replaces the definition's arguments.
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub args: Option<Vec<String>>,
/// Added to the server's environment.
pub env: BTreeMap<String, String>,
/// Merged over the definition's `initializationOptions` (sent once at startup).
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional, type = Option<specta_typescript::Unknown>)]
pub initialization_options: Option<serde_json::Value>,
/// Answers the server's `workspace/configuration` requests; changes are pushed
/// with `workspace/didChangeConfiguration` without a restart.
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional, type = Option<specta_typescript::Unknown>)]
pub settings: Option<serde_json::Value>,
/// Language ids a server defined here serves (`python`); empty for the servers
/// of the language definitions.
pub languages: Vec<String>,
/// Files marking a workspace root for a server defined here (`pyproject.toml`).
pub root_markers: Vec<String>,
}
impl Default for LanguageServerSettings {
fn default() -> Self {
Self {
enabled: true,
command: String::new(),
args: None,
env: BTreeMap::new(),
initialization_options: None,
settings: None,
languages: Vec::new(),
root_markers: Vec::new(),
}
}
}
impl LanguageServerSettings {
/// A server defined in settings rather than by a language definition.
pub fn is_custom(&self) -> bool {
!self.languages.is_empty()
}
}
impl Settings {
/// The configured executable for `command`, if any (`~/` not yet expanded).
pub fn tool_path(&self, command: &str) -> Option<&str> {
@@ -89,6 +144,7 @@ impl Default for Settings {
actions_on_save: ActionsOnSaveSettings::default(),
external_tools: Vec::new(),
tools: BTreeMap::new(),
language_servers: BTreeMap::new(),
inspections: InspectionSettings::default(),
spelling: SpellingSettings::default(),
ssh: SshSettings::default(),
+6
Переглянути файл
@@ -241,6 +241,11 @@ pub fn lsp_servers(host: &Host, window: &str) -> IdeResult<Vec<ServerInfo>> {
Ok(host.project(window)?.lsp.servers())
}
pub fn lsp_resend_diagnostics(host: &Host, window: &str) -> IdeResult<()> {
host.project(window)?.lsp.resend_diagnostics();
Ok(())
}
pub async fn lsp_restart(host: &Host, window: &str, server: ServerId) -> IdeResult<()> {
host.project(window)?.lsp.restart(server).await
}
@@ -349,6 +354,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
lsp_type_hierarchy(&c.host, &c.window, c.arg("doc")?, c.arg("pos")?, c.arg("direction")?).await
});
d.add("lsp_servers", |c| async move { lsp_servers(&c.host, &c.window) });
d.add("lsp_resend_diagnostics", |c| async move { lsp_resend_diagnostics(&c.host, &c.window) });
d.add("lsp_restart", |c| async move { lsp_restart(&c.host, &c.window, c.arg("server")?).await });
d.add("apply_workspace_edit", |c| async move { apply_workspace_edit(&c.host, &c.window, c.arg("edit")?) });
d.add("lsp_execute_command", |c| async move {
+1 -1
Переглянути файл
@@ -113,7 +113,7 @@ pub fn set_settings(
host.ssh.set_configs(host.global_settings.effective().ssh.configs);
}
// A new interpreter / toolchain / server executable restarts the language servers it affects.
if ["languages", "tools"].iter().any(|k| key == *k || key.starts_with(&format!("{k}."))) {
if ["languages", "tools", "languageServers"].iter().any(|k| key == *k || key.starts_with(&format!("{k}."))) {
for project in affected() {
let lsp = project.lsp.clone();
host.runtime.spawn(async move { lsp.reconfigure().await });
+14 -3
Переглянути файл
@@ -26,6 +26,17 @@ fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
Ok(Tools::new(&data).with_custom_paths(custom).with_found_paths(found.into_iter().collect()))
}
/// The language definitions plus the servers defined in the window's settings.
fn languages(host: &Host, window: &str) -> Vec<ide_language::LanguageConfig> {
let settings = match host.project(window) {
Ok(project) => project.settings.effective(),
Err(_) => host.global_settings.effective(),
};
let mut langs = host.languages.all();
ide_sdk::apply::with_custom_servers(&mut langs, &settings);
langs
}
fn join_err(e: impl std::fmt::Display) -> IdeError {
IdeError::internal(e.to_string())
}
@@ -40,7 +51,7 @@ fn reconfigure_servers(host: &Host) {
/// Status of every known language server / debug adapter and the languages using it.
pub async fn tools_list(host: &Host, window: &str) -> IdeResult<Vec<ToolInfo>> {
let tools = tools(host, window)?;
let langs = host.languages.all();
let langs = languages(host, window);
tokio::task::spawn_blocking(move || tools.list(&langs)).await.map_err(join_err)
}
@@ -54,7 +65,7 @@ pub async fn tools_install(
on_event: Channel<InstallEvent>,
) -> IdeResult<ToolInfo> {
let tools = tools(host, window)?;
let langs = host.languages.all();
let langs = languages(host, window);
let cancel = host.begin_request(request);
let result = tokio::task::spawn_blocking(move || {
tools.install(&name, &langs, &cancel, &|e| {
@@ -74,7 +85,7 @@ pub async fn tools_install(
/// Removes a tool the IDE installed.
pub async fn tools_uninstall(host: &Host, window: &str, name: String) -> IdeResult<ToolInfo> {
let tools = tools(host, window)?;
let langs = host.languages.all();
let langs = languages(host, window);
let info = tokio::task::spawn_blocking(move || tools.uninstall(&name, &langs)).await.map_err(join_err)??;
reconfigure_servers(host);
Ok(info)
+9
Переглянути файл
@@ -117,7 +117,9 @@ impl Host {
let data_dir = self.data_dir.clone();
lsp.set_config_hook(Box::new(move |cfg, server_root| {
let effective = settings.effective();
ide_sdk::apply::server_launch_overrides(cfg, &effective);
ide_sdk::apply::configure_server(cfg, &root, server_root, &effective);
ide_sdk::java::cap_java_home(cfg, &ide_sdk::java::installed_jdks());
if cfg.name == "jdtls" {
let bundles: Vec<PathBuf> =
ide_tools::managed_bundle(&data_dir, "java-debug").into_iter().collect();
@@ -149,6 +151,13 @@ impl Host {
);
ide_sdk::jdtls::launch_directly(cfg);
}
ide_sdk::apply::server_protocol_overrides(cfg, &effective);
}));
}
{
let settings = settings.clone();
lsp.set_servers_hook(Box::new(move |language, defined| {
ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective())
}));
}
{
+1
Переглянути файл
@@ -9,6 +9,7 @@ license.workspace = true
ide-core.workspace = true
ide-text.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
toml.workspace = true
tree-sitter.workspace = true
+8
Переглянути файл
@@ -72,6 +72,10 @@ pub struct LanguageServerConfig {
/// JSON passed as `initializationOptions`.
#[serde(default)]
pub initialization_options: Option<toml::Value>,
/// Answers `workspace/configuration`; without it the sections are looked up
/// in `initialization_options`.
#[serde(default)]
pub settings: Option<serde_json::Value>,
/// Human hint shown when the binary is missing.
#[serde(default)]
pub install_hint: Option<String>,
@@ -87,6 +91,10 @@ pub struct LanguageServerConfig {
/// basedpyright): only used while none of those is installed.
#[serde(default)]
pub fallback: bool,
/// Newest Java release the server runs on (kotlin-language-server: 21). A
/// newer `JAVA_HOME` is replaced by the newest installed JDK that fits.
#[serde(default)]
pub max_java: Option<u32>,
/// Set by the settings hook when the server can't run here (jdtls without
/// a JDK 21+); reported as the failure instead of launching it.
#[serde(skip)]
+10 -6
Переглянути файл
@@ -79,20 +79,24 @@ fn is_name_leaf(kind: &str) -> bool {
kind.contains("identifier") || kind == "name"
}
/// Node kinds whose `name` field is a use, not a declaration.
const USE_PARENTS: &[&str] =
&["invocation", "call", "access", "scoped", "reference", "expression", "selector", "qualified", "use_", "import"];
/// Whether the identifier leaf under `cursor` is the name a declaration
/// introduces (`fn name`, `let pattern`, `int *declarator`, parameters,
/// `name = …` assignments) rather than a use of one.
fn declares(cursor: &TreeCursor<'_>, node: &Node<'_>) -> bool {
let parent = node.parent().map(|p| p.kind()).unwrap_or_default();
// Paths and calls name what is declared elsewhere (`use a::b::name`, `a.name()`).
let reference = ["scoped", "qualified", "invocation", "member_access", "use_", "import", "call"]
.iter()
.any(|k| parent.contains(k));
match cursor.field_name() {
Some("name") => !reference,
// Uses name their target with a `name` field too: Java `s.substring()`,
// C# `a.Name`, Rust `use a::b::name`.
Some("name") => !USE_PARENTS.iter().any(|p| parent.contains(p)),
Some("pattern" | "declarator") => true,
Some("left") => parent.contains("assignment") || parent.contains("declarator"),
_ => parent.contains("parameter"),
// A parameter's name, not its type (`String text`).
Some("type") => false,
_ => parent.contains("parameter") && !node.kind().contains("type"),
}
}
+9
Переглянути файл
@@ -1320,4 +1320,13 @@ fn spelling_regions_cover_declared_names_only() {
.map(|r| &rs[r.start..r.end])
.collect();
assert_eq!(names, ["run", "n"]);
let java = "class Bird { String fly(String text) { return text.substring(1); } }\n";
let names: Vec<&str> = syntax()
.spelling_regions(&lang("java"), java)
.unwrap()
.iter()
.filter(|r| r.kind == SpellingKind::Name)
.map(|r| &java[r.start..r.end])
.collect();
assert_eq!(names, ["Bird", "fly", "text"]);
}
+32 -8
Переглянути файл
@@ -125,20 +125,18 @@ impl ClientHandler {
}
fn configuration(&self, params: &Value) -> Value {
let options = self
.server
.effective_config()
.initialization_options
.as_ref()
.and_then(|v| serde_json::to_value(v).ok())
.unwrap_or(Value::Null);
let options = all_settings(&self.server.effective_config());
let items = params.get("items").and_then(Value::as_array).cloned().unwrap_or_default();
Value::Array(
items
.iter()
// vtsls asks for the whole configuration as section `""`.
.map(|item| match item.get("section").and_then(Value::as_str).filter(|s| !s.is_empty()) {
Some(section) if section == self.server.name => options.clone(),
// The server's own section: its block under `settings` (basedpyright asks
// `basedpyright` and `basedpyright.analysis`), else the options themselves.
Some(section) if section == self.server.name => {
options.get("settings").and_then(|s| s.get(section)).unwrap_or(&options).clone()
}
// Servers that take settings under `initializationOptions.settings`
// (jdtls) ask for the same sections later.
Some(section) => [&options, options.get("settings").unwrap_or(&Value::Null)]
@@ -244,3 +242,29 @@ impl Handler for ClientHandler {
}
}
}
/// What `workspace/configuration` sections are looked up in: the server's
/// `initializationOptions` with its `settings` merged over them.
pub(crate) fn all_settings(cfg: &ide_language::LanguageServerConfig) -> Value {
let mut out = cfg.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok()).unwrap_or(Value::Null);
if let Some(settings) = &cfg.settings {
merge(&mut out, settings.clone());
}
out
}
fn merge(base: &mut Value, layer: Value) {
match (base, layer) {
(Value::Object(base), Value::Object(layer)) => {
for (k, v) in layer {
match base.get_mut(&k) {
Some(existing) => merge(existing, v),
None => {
base.insert(k, v);
}
}
}
}
(base, layer) => *base = layer,
}
}
+1 -2
Переглянути файл
@@ -65,8 +65,7 @@ impl LspManager {
/// run doesn't prompt to install every language it meets.
pub fn serves_path(&self, path: &Path) -> bool {
let lang = self.languages.detect(path, None);
let Some(config) = self.languages.get(&lang) else { return false };
config.language_servers.iter().any(|ls| {
self.language_servers(&lang).iter().any(|ls| {
let mut cfg = ls.clone();
if let Some(hook) = self.config_hook.read().clone() {
hook(&mut cfg, &self.project_root);
+161 -5
Переглянути файл
@@ -56,6 +56,12 @@ use types::*;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
const COMPLETION_TIMEOUT: Duration = Duration::from_secs(5);
const LONG_TIMEOUT: Duration = Duration::from_secs(30);
/// How long a server may take to answer `initialize`. Some import the whole
/// build there (kotlin-lsp, jdtls on a large Gradle project) and need minutes
/// on a cold start; the status shows "starting" meanwhile, and a crash still
/// ends the wait at once.
const INITIALIZE_TIMEOUT: Duration = Duration::from_secs(300);
/// How long a request waits for a server that is still initializing.
const START_WAIT: Duration = Duration::from_secs(10);
/// File moves may start a server (jdtls takes a while to import).
@@ -68,6 +74,9 @@ pub type ApplyEditHook = Arc<dyn Fn(WorkspaceEdit) -> bool + Send + Sync>;
/// settings before each launch; receives the server's workspace root.
pub type ConfigFn = dyn Fn(&mut LanguageServerConfig, &Path) + Send + Sync;
pub type ConfigHook = Arc<ConfigFn>;
/// The servers a language uses, from its definition's list (user settings
/// disable some and add others).
pub type ServersFn = dyn Fn(&LanguageId, &[LanguageServerConfig]) -> Vec<LanguageServerConfig> + Send + Sync;
struct Attached {
server: Arc<Server>,
@@ -146,6 +155,7 @@ pub struct LspManager {
docs: Mutex<HashMap<DocId, DocState>>,
apply_edit_hook: RwLock<Option<ApplyEditHook>>,
config_hook: RwLock<Option<ConfigHook>>,
servers_hook: RwLock<Option<Arc<ServersFn>>>,
candidates_hook: RwLock<Option<Arc<CandidateFn>>>,
shutting_down: AtomicBool,
/// `window/showMessage` texts already surfaced; servers repeat them on every restart/reconfigure.
@@ -264,6 +274,7 @@ impl LspManager {
docs: Mutex::new(HashMap::new()),
apply_edit_hook: RwLock::new(None),
config_hook: RwLock::new(None),
servers_hook: RwLock::new(None),
candidates_hook: RwLock::new(None),
shutting_down: AtomicBool::new(false),
shown_messages: Mutex::new(HashSet::new()),
@@ -297,10 +308,9 @@ impl LspManager {
/// The servers serving `path`: every regular one, and each `fallback` one
/// only while all servers listed before it are missing.
fn servers_for(&self, language: &LanguageId, path: &Path) -> Vec<Arc<Server>> {
let Some(cfg) = self.languages.get(language) else { return Vec::new() };
let mut out = Vec::new();
let mut available_before = false;
for sc in &cfg.language_servers {
for sc in &self.language_servers(language) {
if sc.fallback && available_before {
continue;
}
@@ -311,8 +321,18 @@ impl LspManager {
out
}
/// The definitions of the servers `language` uses.
fn language_servers(&self, language: &LanguageId) -> Vec<LanguageServerConfig> {
let Some(cfg) = self.languages.get(language) else { return Vec::new() };
match self.servers_hook.read().clone() {
Some(hook) => hook(language, &cfg.language_servers),
None => cfg.language_servers,
}
}
/// A server turned out to be missing: attach the fallbacks it was hiding
/// to the open documents (and start them).
/// to the open documents (and start them). Also attaches servers newly
/// enabled in settings.
fn attach_fallbacks(&self) {
let open: Vec<(DocId, LanguageId, PathBuf)> =
self.docs.lock().iter().map(|(id, d)| (*id, d.language.clone(), d.path.clone())).collect();
@@ -407,7 +427,7 @@ impl LspManager {
};
let init = self.initialize_params(&server);
let result = tokio::time::timeout(Duration::from_secs(60), peer.request::<_, Value>("initialize", init, None))
let result = tokio::time::timeout(INITIALIZE_TIMEOUT, peer.request::<_, Value>("initialize", init, None))
.await
.unwrap_or(Err(RpcError::Timeout));
let caps = match result {
@@ -432,6 +452,14 @@ impl LspManager {
if let Err(e) = peer.notify("initialized", json!({})) {
tracing::warn!("{}: {e}", server.name);
}
// Servers that don't ask with `workspace/configuration` only learn settings this way.
let cfg = server.effective_config();
if cfg.settings.is_some()
&& let Err(e) =
peer.notify("workspace/didChangeConfiguration", json!({ "settings": handler::all_settings(&cfg) }))
{
tracing::debug!("{}: didChangeConfiguration: {e}", server.name);
}
let run = Running { generation, peer: peer.clone(), caps: Arc::new(RwLock::new(caps)) };
// Publish readiness and (re)open attached documents atomically w.r.t. did_change.
@@ -1778,6 +1806,11 @@ impl LspManager {
*self.config_hook.write() = Some(Arc::from(hook));
}
/// Installed by `src-tauri` to apply the servers enabled / defined in settings.
pub fn set_servers_hook(&self, hook: Box<ServersFn>) {
*self.servers_hook.write() = Some(Arc::from(hook));
}
/// The server's base configuration with the settings hook applied.
fn configured(&self, server: &Server) -> LanguageServerConfig {
let mut cfg = server.config.clone();
@@ -1789,11 +1822,26 @@ impl LspManager {
/// Restarts running servers whose settings-derived configuration changed
/// (e.g. a new project interpreter); stopped ones pick it up on their next start.
/// A change of `settings` alone reaches a running server without a restart.
/// Servers no longer enabled stop; newly enabled ones attach to open documents.
pub async fn reconfigure(&self) {
self.stop_unlisted().await;
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
for s in servers {
let next = self.configured(&s);
if next == s.effective_config() {
let current = s.effective_config();
if next == current {
continue;
}
let without_settings = |c: &LanguageServerConfig| LanguageServerConfig { settings: None, ..c.clone() };
if let Some(run) = s.running()
&& without_settings(&next) == without_settings(&current)
{
s.set_effective_config(next);
let params = json!({ "settings": handler::all_settings(&s.effective_config()) });
if let Err(e) = run.peer.notify("workspace/didChangeConfiguration", params) {
tracing::debug!("{}: didChangeConfiguration: {e}", s.name);
}
continue;
}
match s.status() {
@@ -1815,12 +1863,120 @@ impl LspManager {
ide_core::event::ServerStatus::Stopped => {}
}
}
self.attach_fallbacks();
self.detach_shadowed_fallbacks().await;
}
/// A server enabled again shadows the fallbacks attached in its place: they
/// leave the open documents, and stop once no document uses them.
async fn detach_shadowed_fallbacks(&self) {
let open: Vec<(DocId, LanguageId, PathBuf)> =
self.docs.lock().iter().map(|(id, d)| (*id, d.language.clone(), d.path.clone())).collect();
let mut shadowed: Vec<(DocId, Vec<ide_core::ServerId>)> = Vec::new();
for (id, language, path) in open {
let configs = self.language_servers(&language);
let wanted = self.servers_for(&language, &path);
let docs = self.docs.lock();
let Some(d) = docs.get(&id) else { continue };
let gone: Vec<ide_core::ServerId> = d
.servers
.iter()
.filter(|a| {
!wanted.iter().any(|w| w.id == a.server.id)
&& configs.iter().any(|c| c.fallback && c.name == a.server.name)
})
.map(|a| a.server.id)
.collect();
if !gone.is_empty() {
shadowed.push((id, gone));
}
}
if shadowed.is_empty() {
return;
}
let mut detached: Vec<Arc<Server>> = Vec::new();
{
let mut docs = self.docs.lock();
for (id, gone) in shadowed {
let Some(d) = docs.get_mut(&id) else { continue };
let (leaving, staying): (Vec<Attached>, Vec<Attached>) =
d.servers.drain(..).partition(|a| gone.contains(&a.server.id));
d.servers = staying;
for a in leaving {
if let Some(run) = a.server.running()
&& a.opened_gen == Some(run.generation)
&& run.caps.read().open_close
&& let Err(e) =
run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": d.uri } }))
{
tracing::debug!("{}: didClose: {e}", a.server.name);
}
self.sink.emit(ide_core::IdeEvent::Diagnostics {
path: d.path.clone().into(),
source: a.server.name.clone(),
items: Vec::new(),
});
if !detached.iter().any(|s| s.id == a.server.id) {
detached.push(a.server);
}
}
}
let in_use = |s: &Arc<Server>| docs.values().any(|d| d.servers.iter().any(|a| a.server.id == s.id));
detached.retain(|s| !in_use(s));
}
if detached.is_empty() {
return;
}
for s in &detached {
tracing::info!("{}: shadowed by an enabled server, stopping", s.name);
self.stop_instance(s, true).await;
}
self.servers.lock().retain(|s| !detached.iter().any(|d| d.id == s.id));
}
/// Stops and forgets the servers that none of their languages uses any more.
async fn stop_unlisted(&self) {
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
let unlisted: Vec<Arc<Server>> = servers
.into_iter()
.filter(|s| !s.languages().iter().any(|l| self.language_servers(l).iter().any(|c| c.name == s.name)))
.collect();
if unlisted.is_empty() {
return;
}
for s in &unlisted {
tracing::info!("{}: no longer enabled, stopping", s.name);
self.stop_instance(s, true).await;
}
let gone = |s: &Arc<Server>| unlisted.iter().any(|u| u.id == s.id);
self.servers.lock().retain(|s| !gone(s));
for d in self.docs.lock().values_mut() {
d.servers.retain(|a| !gone(&a.server));
}
}
pub fn set_apply_edit_hook(&self, hook: Box<dyn Fn(WorkspaceEdit) -> bool + Send + Sync>) {
*self.apply_edit_hook.write() = Some(Arc::from(hook));
}
/// Emits every server's current diagnostics again: a UI that (re)loaded
/// after they were published has missed those events.
pub fn resend_diagnostics(&self) {
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
for server in servers {
let encoding = server.running().map(|r| r.caps.read().encoding).unwrap_or_default();
let conv = self.conv(encoding);
for (path, items) in server.diagnostics_by_path() {
let items = items.into_iter().map(|d| convert::diagnostic(&conv, &path, d, &server.name)).collect();
self.sink.emit(ide_core::IdeEvent::Diagnostics {
path: path.into(),
source: server.name.clone(),
items,
});
}
}
}
pub fn servers(&self) -> Vec<ServerInfo> {
self.servers
.lock()
+5
Переглянути файл
@@ -461,6 +461,11 @@ impl Server {
d.iter().flat_map(|(p, items)| items.iter().map(move |i| (p.clone(), i.clone()))).collect()
}
/// The current diagnostics of each file that has some.
pub fn diagnostics_by_path(&self) -> Vec<(PathBuf, Vec<lsp::Diagnostic>)> {
self.diagnostics.lock().iter().map(|(p, d)| (p.clone(), d.clone())).collect()
}
pub fn take_diagnostic_paths(&self) -> Vec<PathBuf> {
self.published.lock().clear();
self.diagnostics.lock().drain().map(|(p, _)| p).collect()
+93
Переглянути файл
@@ -203,9 +203,11 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
env: Default::default(),
root_markers: vec!["mock.toml".into()],
initialization_options: Some(toml::Value::Table(toml::toml! { flag = true nested = { deep = 1 } })),
settings: None,
install_hint: Some(format!("install {name}")),
connect: None,
fallback: false,
max_java: None,
launch_error: None,
}
}
@@ -521,6 +523,15 @@ async fn diagnostics_become_events_and_feed_code_actions() {
assert_eq!(items[0].range, rng(0, 4, 0, 10));
}
// A reloaded UI asks for them again.
h.events.lock().clear();
h.mgr.resend_diagnostics();
let again = h.events.lock().iter().find_map(|e| match e {
IdeEvent::Diagnostics { path, items, .. } => Some((path.clone(), items.len())),
_ => None,
});
assert_eq!(again, Some((path.clone().into(), 2)));
s.respond(
"textDocument/codeAction",
json!([
@@ -795,6 +806,54 @@ async fn launch_error_fails_without_starting_the_server() {
assert!(!h.statuses("mock").contains(&ServerStatus::Crashed));
}
#[tokio::test(flavor = "multi_thread")]
async fn settings_changes_reach_servers_without_restarts() {
let h = harness(&[("mock", incremental_caps()), ("extra", incremental_caps())]);
let settings: Arc<Mutex<Option<Value>>> = Default::default();
let disabled: Arc<Mutex<Vec<String>>> = Default::default();
{
let settings = settings.clone();
h.mgr.set_config_hook(Box::new(move |cfg, _| cfg.settings = settings.lock().clone()));
}
{
let disabled = disabled.clone();
h.mgr.set_servers_hook(Box::new(move |_, defined| {
defined.iter().filter(|c| !disabled.lock().contains(&c.name)).cloned().collect()
}));
}
h.open("a.mk", "x");
h.wait_status("mock", ServerStatus::Ready).await;
h.wait_status("extra", ServerStatus::Ready).await;
// Only `settings` changed: pushed to the running server, which keeps running.
let s = h.launcher.state("mock");
*settings.lock() = Some(json!({ "nested": { "other": 2 } }));
h.mgr.reconfigure().await;
eventually(|| !s.notified("workspace/didChangeConfiguration").is_empty()).await;
assert_eq!(
s.notified("workspace/didChangeConfiguration")[0],
json!({ "settings": { "flag": true, "nested": { "deep": 1, "other": 2 } } })
);
assert_eq!(s.launches.load(Ordering::SeqCst), 1);
let cfg: Value = s
.peer()
.request("workspace/configuration", json!({ "items": [{ "section": "nested.other" }] }), None)
.await
.unwrap();
assert_eq!(cfg, json!([2]));
// Disabled: stopped and forgotten; enabled again: attached to the open document.
disabled.lock().push("extra".into());
h.mgr.reconfigure().await;
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["mock"]);
assert_eq!(h.statuses("extra").last(), Some(&ServerStatus::Stopped));
disabled.lock().clear();
h.mgr.reconfigure().await;
h.wait_status("extra", ServerStatus::Ready).await;
eventually(|| h.launcher.state("extra").notified("textDocument/didOpen").len() == 2).await;
assert_eq!(s.launches.load(Ordering::SeqCst), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn fallback_servers_only_run_when_the_preferred_one_is_missing() {
// Preferred installed: the alternative is never started.
@@ -819,6 +878,40 @@ async fn fallback_servers_only_run_when_the_preferred_one_is_missing() {
assert!(h.mgr.hover(doc, Pos::new(0, 0), Default::default()).await.is_ok());
}
#[tokio::test(flavor = "multi_thread")]
async fn a_fallback_leaves_when_the_preferred_server_is_enabled_again() {
let h = harness_with_fallbacks(&[("main", incremental_caps()), ("alt", incremental_caps())], &["alt"]);
let disabled: Arc<Mutex<Vec<String>>> = Default::default();
{
let disabled = disabled.clone();
h.mgr.set_servers_hook(Box::new(move |_, defined| {
defined.iter().filter(|c| !disabled.lock().contains(&c.name)).cloned().collect()
}));
}
let (doc, path) = h.open("a.mk", "x");
let uri = uri_of(&path);
h.wait_status("main", ServerStatus::Ready).await;
assert!(h.statuses("alt").is_empty());
// Preferred disabled: the fallback takes over the open document.
disabled.lock().push("main".into());
h.mgr.reconfigure().await;
h.wait_status("alt", ServerStatus::Ready).await;
eventually(|| h.launcher.state("alt").docs.lock().contains_key(&uri)).await;
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["alt"]);
// Enabled again: the fallback closes the document and stops.
disabled.lock().clear();
h.mgr.reconfigure().await;
h.wait_status("main", ServerStatus::Ready).await;
eventually(|| h.launcher.state("main").docs.lock().contains_key(&uri)).await;
assert!(!h.launcher.state("alt").notified("textDocument/didClose").is_empty());
assert_eq!(h.statuses("alt").last(), Some(&ServerStatus::Stopped));
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["main"]);
assert!(h.mgr.hover(doc, Pos::new(0, 0), Default::default()).await.is_ok());
assert_eq!(h.launcher.state("alt").requested("textDocument/hover").len(), 0);
}
#[tokio::test(flavor = "multi_thread")]
async fn implementations_per_position() {
let caps = json!({ "textDocumentSync": 1, "implementationProvider": true });
+6
Переглянути файл
@@ -70,9 +70,11 @@ async fn missing_binary_is_reported_with_install_hint() {
env: Default::default(),
root_markers: vec![],
initialization_options: None,
settings: None,
install_hint: Some("npm i -g nope-ls".into()),
connect: None,
fallback: false,
max_java: None,
launch_error: None,
};
let (mgr, events) = manager(dir.path(), LanguageRegistry::from_configs(vec![lang("nope", "nope", server)]));
@@ -198,9 +200,11 @@ async fn typescript_language_server_end_to_end() {
env: Default::default(),
root_markers: vec!["tsconfig.json".into()],
initialization_options: None,
settings: None,
install_hint: None,
connect: None,
fallback: false,
max_java: None,
launch_error: None,
};
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![lang("typescript", "ts", server)]));
@@ -240,9 +244,11 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
env: Default::default(),
root_markers: vec!["package.json".into()],
initialization_options: init.map(|v| toml::Value::try_from(v).unwrap()),
settings: None,
install_hint: None,
connect: None,
fallback: false,
max_java: None,
launch_error: None,
}
}
+74 -2
Переглянути файл
@@ -5,8 +5,8 @@ use crate::discover::{project_venv_python, workspace_tsdk};
use crate::exec::{path_with, search_path};
use crate::{bin_dir, exe, venv_of};
use crate::{godot, vue};
use ide_core::settings::Settings;
use ide_language::LanguageServerConfig;
use ide_core::settings::{LanguageServerSettings, Settings};
use ide_language::{LanguageConfig, LanguageServerConfig};
use ide_run::RunConfig;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
@@ -302,6 +302,78 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
}
}
/// The servers `language` uses after Settings › Language Servers: the
/// definition's ones that aren't disabled, then the ones defined in settings for it.
pub fn language_servers(language: &str, defined: &[LanguageServerConfig], s: &Settings) -> Vec<LanguageServerConfig> {
let enabled = |name: &str| s.language_servers.get(name).is_none_or(|ls| ls.enabled);
let mut out: Vec<LanguageServerConfig> = defined.iter().filter(|c| enabled(&c.name)).cloned().collect();
for (name, ls) in &s.language_servers {
if ls.enabled && ls.languages.iter().any(|l| l == language) && !out.iter().any(|c| &c.name == name) {
out.push(custom_server(name, ls));
}
}
out
}
/// Adds the servers defined in settings to the languages they serve (to list
/// them with the tools); disabled ones stay so they can be turned back on.
pub fn with_custom_servers(langs: &mut [LanguageConfig], s: &Settings) {
for (name, ls) in s.language_servers.iter().filter(|(_, ls)| ls.is_custom()) {
for lang in langs.iter_mut().filter(|l| ls.languages.iter().any(|id| id == l.id.as_str())) {
if !lang.language_servers.iter().any(|c| &c.name == name) {
lang.language_servers.push(custom_server(name, ls));
}
}
}
}
fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfig {
LanguageServerConfig {
name: name.to_owned(),
command: ls.command.trim().to_owned(),
args: Vec::new(),
env: Default::default(),
root_markers: ls.root_markers.clone(),
initialization_options: None,
settings: None,
install_hint: Some(match ls.command.trim() {
"" => format!("Set the command of `{name}` in Settings › Language Servers"),
command => format!("`{command}` was not found: install it, or set its path in Settings › Language Servers"),
}),
connect: None,
fallback: false,
max_java: None,
launch_error: None,
}
}
/// Command and arguments from Settings › Language Servers; applied before
/// [`configure_server`] so toolchain adjustments (a custom path, JVM args) still follow.
pub fn server_launch_overrides(cfg: &mut LanguageServerConfig, s: &Settings) {
let Some(ls) = s.language_servers.get(&cfg.name) else { return };
if let Some(command) = non_empty(ls.command.trim()) {
cfg.command = command.to_owned();
}
if let Some(args) = &ls.args {
cfg.args = args.clone();
}
}
/// Environment, `initializationOptions` and `workspace/configuration` settings
/// from Settings › Language Servers; applied last so they win over derived values.
pub fn server_protocol_overrides(cfg: &mut LanguageServerConfig, s: &Settings) {
let Some(ls) = s.language_servers.get(&cfg.name) else { return };
cfg.env.extend(ls.env.iter().map(|(k, v)| (k.clone(), v.clone())));
if let Some(options) = &ls.initialization_options {
merge_init_options(cfg, options.clone());
}
if let Some(settings) = &ls.settings {
let mut current = cfg.settings.take().filter(Value::is_object).unwrap_or_else(|| json!({}));
merge(&mut current, settings.clone());
cfg.settings = Some(current);
}
}
/// vue-language-server loads TypeScript as a library (`--tsdk`, else its own
/// `require('typescript')`): the selected version, else its own, else the
/// project's — whichever still has the language-service API.
+13
Переглянути файл
@@ -161,6 +161,19 @@ pub fn jdtls_jdks(min_java: u32) -> Arc<[Jdk]> {
}
}
/// For a server with `max-java`: when the `JAVA_HOME` it would get (its env,
/// else the IDE's) is a newer JDK, points it at the newest of `jdks` that fits.
pub fn cap_java_home(cfg: &mut LanguageServerConfig, jdks: &[Jdk]) {
let Some(max) = cfg.max_java else { return };
let current = cfg.env.get("JAVA_HOME").cloned().or_else(|| std::env::var("JAVA_HOME").ok());
if current.as_deref().and_then(|h| jdk_at(Path::new(h))).is_some_and(|j| j.major <= max) {
return;
}
if let Some(jdk) = jdks.iter().filter(|j| j.major <= max).max_by_key(|j| j.major) {
cfg.env.insert("JAVA_HOME".into(), jdk.home.to_string_lossy().into_owned());
}
}
/// Oldest Java version jdtls runs on when its install can't tell (its launcher's check).
pub const JDTLS_MIN_JAVA: u32 = 21;
+81
Переглянути файл
@@ -28,9 +28,11 @@ fn server(name: &str) -> LanguageServerConfig {
env: BTreeMap::new(),
root_markers: vec![],
initialization_options: None,
settings: None,
install_hint: None,
connect: None,
fallback: false,
max_java: None,
launch_error: None,
}
}
@@ -205,6 +207,59 @@ fn project_jdk_and_maven_settings() {
assert_eq!(project_jdk(tmp.path(), &s), None);
}
#[test]
fn language_server_settings_disable_add_and_override() {
use crate::apply::{language_servers, server_launch_overrides, server_protocol_overrides, with_custom_servers};
use ide_core::settings::LanguageServerSettings;
use serde_json::json;
let mut s = Settings::default();
s.language_servers.insert("pylsp".into(), LanguageServerSettings { enabled: false, ..Default::default() });
s.language_servers.insert(
"ruff".into(),
LanguageServerSettings {
command: "ruff".into(),
args: Some(vec!["server".into()]),
languages: vec!["python".into()],
root_markers: vec!["pyproject.toml".into()],
..Default::default()
},
);
let defined = [server("basedpyright"), server("pylsp")];
let names = |v: Vec<LanguageServerConfig>| v.into_iter().map(|c| c.name).collect::<Vec<_>>();
assert_eq!(names(language_servers("python", &defined, &s)), ["basedpyright", "ruff"]);
assert_eq!(names(language_servers("rust", &[server("rust-analyzer")], &s)), ["rust-analyzer"]);
// Listed with the tools even while disabled.
let mut langs = ide_language::LanguageRegistry::load(None).unwrap().all();
with_custom_servers(&mut langs, &s);
let python = langs.iter().find(|l| l.id.as_str() == "python").unwrap();
let mut ruff = python.language_servers.iter().find(|c| c.name == "ruff").unwrap().clone();
assert_eq!(ruff.root_markers, ["pyproject.toml"]);
server_launch_overrides(&mut ruff, &s);
assert_eq!((ruff.command.as_str(), ruff.args.as_slice()), ("ruff", &["server".to_string()][..]));
s.language_servers.insert(
"rust-analyzer".into(),
LanguageServerSettings {
env: BTreeMap::from([("RA_LOG".into(), "info".into())]),
initialization_options: Some(json!({ "check": { "command": "clippy" } })),
settings: Some(json!({ "rust-analyzer": { "cargo": { "features": "all" } } })),
..Default::default()
},
);
let mut ra = server("rust-analyzer");
ra.args = vec!["--stdio".into()];
ra.initialization_options = Some(toml::Value::Table(toml::toml! { checkOnSave = false }));
server_launch_overrides(&mut ra, &s);
assert_eq!(ra.args, ["--stdio"], "no args setting keeps the definition's");
server_protocol_overrides(&mut ra, &s);
assert_eq!(ra.env["RA_LOG"], "info");
let init = serde_json::to_value(ra.initialization_options.unwrap()).unwrap();
assert_eq!(init, json!({ "checkOnSave": false, "check": { "command": "clippy" } }));
assert_eq!(ra.settings, Some(json!({ "rust-analyzer": { "cargo": { "features": "all" } } })));
}
#[test]
fn jdtls_jdk_setting() {
if cfg!(windows) {
@@ -544,3 +599,29 @@ fn vue_language_server_gets_a_typescript_with_the_language_service_api() {
let lib = project.join("node_modules/typescript/lib");
assert_eq!(cfg.args, [format!("--tsdk={}", lib.to_string_lossy())]);
}
#[test]
fn max_java_picks_an_older_jdk() {
let dir = tempfile::tempdir().unwrap();
let jdk = |major: u32| {
let home = dir.path().join(format!("jdk-{major}"));
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::write(home.join("release"), format!("JAVA_VERSION=\"{major}.0.1\"\n")).unwrap();
std::fs::write(home.join("bin").join(exe("java")), "").unwrap();
crate::java::jdk_at(&home).unwrap()
};
let (j17, j21, j25) = (jdk(17), jdk(21), jdk(25));
let jdks = [j25.clone(), j21.clone(), j17];
let mut cfg = LanguageServerConfig { max_java: Some(21), ..server("kotlin-language-server") };
cfg.env.insert("JAVA_HOME".into(), j25.home.to_string_lossy().into_owned());
crate::java::cap_java_home(&mut cfg, &jdks);
assert_eq!(cfg.env["JAVA_HOME"], j21.home.to_string_lossy());
// A JAVA_HOME that fits, or no limit: left alone.
crate::java::cap_java_home(&mut cfg, &[]);
assert_eq!(cfg.env["JAVA_HOME"], j21.home.to_string_lossy());
let mut free = server("other");
free.env.insert("JAVA_HOME".into(), j25.home.to_string_lossy().into_owned());
crate::java::cap_java_home(&mut free, &jdks);
assert_eq!(free.env["JAVA_HOME"], j25.home.to_string_lossy());
}
+12
Переглянути файл
@@ -551,3 +551,15 @@ vulkan
wgpu
woff
woff2
breakpoint
sku
dropdown
navbar
superclass
typedef
eslint
unittest
jvm
jdk
ux
endpoint
+17 -3
Переглянути файл
@@ -162,6 +162,14 @@ fn software_terms() -> &'static HashSet<&'static str> {
})
}
/// A software term, or its plural (`endpoints`, `regexes`).
fn software_term(lower: &str) -> bool {
let terms = software_terms();
terms.contains(lower)
|| lower.strip_suffix('s').is_some_and(|w| terms.contains(w))
|| lower.strip_suffix("es").is_some_and(|w| terms.contains(w))
}
/// Words of a custom dictionary file: a plain word list or a Hunspell `.dic`
/// (leading count line and `/FLAGS` ignored). Cached by modification time.
fn dictionary_file(path: &Path) -> Arc<HashSet<String>> {
@@ -230,9 +238,7 @@ impl Speller {
}
fn user_word(&self, lower: &str) -> bool {
self.accepted.contains(lower)
|| software_terms().contains(lower)
|| self.custom.iter().any(|d| d.contains(lower))
self.accepted.contains(lower) || software_term(lower) || self.custom.iter().any(|d| d.contains(lower))
}
/// In a dictionary, in any case style.
@@ -439,6 +445,14 @@ mod tests {
assert!(!s.is_correct("lenght"));
}
#[test]
fn software_terms_and_their_plurals() {
let s = Speller::default();
for ok in ["breakpoint", "breakpoints", "endpoints", "datasets", "regexes"] {
assert!(s.is_correct(ok), "{ok}");
}
}
#[test]
fn agent_nouns_of_known_words() {
let s = Speller::default();
+18
Переглянути файл
@@ -72,6 +72,10 @@ pub struct ToolInfo {
pub homepage: Option<String>,
/// Why the executable chosen in settings cannot be used (status is then `Missing`).
pub custom_error: Option<String>,
/// A language server's arguments from its language definition.
pub default_args: Vec<String>,
/// A language server's `initializationOptions` from its language definition, as JSON text.
pub default_initialization_options: Option<String>,
}
/// Streamed install progress.
@@ -209,6 +213,8 @@ struct Usage {
command: Option<String>,
kind: Option<ToolKind>,
install_hint: Option<String>,
args: Vec<String>,
initialization_options: Option<String>,
}
fn usages(langs: &[LanguageConfig]) -> BTreeMap<String, Usage> {
@@ -243,6 +249,14 @@ fn usages(langs: &[LanguageConfig]) -> BTreeMap<String, Usage> {
let languages = map.get(*host).map(|u| u.languages.clone()).unwrap_or_default();
map.entry(plugin.to_string()).or_default().languages = languages;
}
// A server's defaults come from the first definition using it.
for s in langs.iter().flat_map(|l| &l.language_servers).rev() {
if let Some(u) = map.get_mut(&s.name) {
u.args = s.args.clone();
u.initialization_options =
s.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok()).map(|v| v.to_string());
}
}
map
}
@@ -455,6 +469,8 @@ impl Tools {
install_hint,
homepage: None,
custom_error: None,
default_args: u.args.clone(),
default_initialization_options: u.initialization_options.clone(),
})
.map(|info| self.apply_custom(info, None));
};
@@ -477,6 +493,8 @@ impl Tools {
install_hint,
homepage: Some(spec.homepage.to_string()),
custom_error: None,
default_args: usage.map(|u| u.args.clone()).unwrap_or_default(),
default_initialization_options: usage.and_then(|u| u.initialization_options.clone()),
})
.map(|info| self.apply_custom(info, Some(spec)))
}
+72 -8
Переглянути файл
@@ -106,20 +106,33 @@ fn json_to_toml(value: &Json) -> IdeResult<toml_edit::Value> {
})
}
/// Sets (or removes, for `None`) a dotted key in a TOML document.
fn set_in_document(doc: &mut DocumentMut, segments: &[&str], value: Option<toml_edit::Value>) {
/// Sets (or removes, for `None`) a dotted key in a TOML document. A new
/// `map_entry` object becomes a `[languageServers.ruff]` table rather than an
/// inline table under an explicit `[languageServers]` header.
fn set_in_document(doc: &mut DocumentMut, segments: &[&str], value: Option<toml_edit::Value>, map_entry: bool) {
let (last, parents) = segments.split_last().expect("non-empty key");
let mut table: &mut dyn TableLike = doc.as_table_mut();
let mut in_inline = false;
for seg in parents {
if !table.get(seg).is_some_and(Item::is_table_like) {
if value.is_none() {
return;
}
table.insert(seg, Item::Table(Table::new()));
// Implicit: no `[languageServers]` header above `[languageServers.ruff]`.
let mut new = Table::new();
new.set_implicit(true);
table.insert(seg, Item::Table(new));
}
table = table.get_mut(seg).and_then(Item::as_table_like_mut).expect("table just ensured");
let item = table.get_mut(seg).expect("table just ensured");
in_inline |= item.is_inline_table();
table = item.as_table_like_mut().expect("table just ensured");
}
match value {
Some(toml_edit::Value::InlineTable(t))
if map_entry && !in_inline && !matches!(table.get(last), Some(Item::Value(_))) =>
{
table.insert(last, Item::Table(t.into_table()));
}
Some(v) => match table.get_mut(last) {
// Keep the key's decor (comments, spacing) when replacing a value.
Some(Item::Value(existing)) => {
@@ -188,9 +201,19 @@ impl SettingsStore {
if segments.iter().any(|s| s.is_empty()) {
return Err(IdeError::invalid(format!("invalid settings key {key:?}")));
}
let mut cursor = &defaults_json();
for seg in &segments {
cursor = cursor.get(seg).ok_or_else(|| IdeError::invalid(format!("unknown setting {key:?}")))?;
let defaults = defaults_json();
let mut cursor = &defaults;
let mut map_entry = false;
for (i, seg) in segments.iter().enumerate() {
match cursor.get(seg) {
Some(next) => cursor = next,
// An entry of a map setting (`languageServers.rust-analyzer`): the merge below validates it.
None if cursor.as_object().is_some_and(|m| m.is_empty()) => {
map_entry = i + 1 == segments.len();
break;
}
None => return Err(IdeError::invalid(format!("unknown setting {key:?}"))),
}
}
let text = match std::fs::read_to_string(&file) {
@@ -202,7 +225,7 @@ impl SettingsStore {
.parse()
.map_err(|e| IdeError::invalid(format!("{} is not valid TOML; fix it first: {e}", file.display())))?;
let new_value = if value.is_null() { None } else { Some(json_to_toml(&value)?) };
set_in_document(&mut doc, &segments, new_value);
set_in_document(&mut doc, &segments, new_value, map_entry);
let new_text = doc.to_string();
// Validate the resulting stack before touching the disk.
@@ -350,6 +373,47 @@ mod tests {
let s =
store.set(SettingsScope::Global, "appearance.statusBarWidgets", json!({"editor.caret": false})).unwrap();
assert_eq!(s.appearance.status_bar_widgets.len(), 1);
// One entry of a map setting, set and removed on its own.
let s = store
.set(
SettingsScope::Global,
"languageServers.rust-analyzer",
json!({"args": ["--log"], "initializationOptions": {"check": {"command": "clippy"}}}),
)
.unwrap();
let ra = &s.language_servers["rust-analyzer"];
assert!(ra.enabled);
assert_eq!(ra.args.as_deref(), Some(&["--log".to_string()][..]));
assert_eq!(ra.initialization_options, Some(json!({"check": {"command": "clippy"}})));
assert_eq!(
store
.set(SettingsScope::Global, "languageServers.rust-analyzer", json!({"enabled": "no"}))
.unwrap_err()
.kind,
ide_core::error::ErrorKind::InvalidInput
);
let s = store.set(SettingsScope::Global, "languageServers.rust-analyzer", json!(null)).unwrap();
assert!(s.language_servers.is_empty());
// New parent tables stay implicit: no empty `[languageServers]` header.
let fresh = tmp.path().join("fresh");
let s = SettingsStore::load(&fresh, None)
.set(SettingsScope::Global, "languageServers.ruff.languages", json!(["python"]))
.unwrap();
assert!(s.language_servers["ruff"].is_custom());
let text = std::fs::read_to_string(fresh.join("settings.toml")).unwrap();
assert_eq!(text, "[languageServers.ruff]\nlanguages = [\"python\"]\n");
// A whole new entry: a table of its own, still under an implicit parent.
let added = tmp.path().join("added");
let s = SettingsStore::load(&added, None)
.set(
SettingsScope::Global,
"languageServers.ruff",
json!({"command": "ruff", "args": ["server"], "languages": ["python"]}),
)
.unwrap();
assert_eq!(s.language_servers["ruff"].command, "ruff");
let text = std::fs::read_to_string(added.join("settings.toml")).unwrap();
assert_eq!(text, "[languageServers.ruff]\nargs = [\"server\"]\ncommand = \"ruff\"\nlanguages = [\"python\"]\n");
// Project layer is created on demand and wins.
let s = store.set(SettingsScope::Project, "editor.fontSize", json!(12)).unwrap();
+15 -1
Переглянути файл
@@ -3,7 +3,21 @@ import tseslint from "typescript-eslint";
import reactHooks from "eslint-plugin-react-hooks";
export default tseslint.config(
{ ignores: ["dist", "target", "src-tauri", "crates", "src/bindings.ts", "fixtures", "plugins", "test-results", "playwright-report"] },
{
ignores: [
"dist",
"target",
"src-tauri",
"crates",
"src/bindings.ts",
"fixtures",
"plugins",
"test-results",
"playwright-report",
// Agent worktrees: whole checkouts of the repo.
".claude",
],
},
js.configs.recommended,
...tseslint.configs.recommended,
{
+5
Переглянути файл
@@ -38,6 +38,11 @@ eclipse = { downloadSources = true }
references = { includeDecompiledSources = true }
signatureHelp = { enabled = true }
configuration = { updateBuildConfiguration = "automatic" }
# Generated code (implement methods, getters, toString…) indents like the editor (`indent` above).
format = { insertSpaces = true, tabSize = 4 }
# Calls complete as `name()` with the caret inside and parameter info, not guessed arguments;
# JDK internals (`sun.*`, `com.sun.*`, `jdk.*`) and AWT's `List` stay out of completion and auto-import.
completion = { guessMethodArguments = "off", filteredTypes = ["java.awt.List", "com.sun.*", "sun.*", "jdk.*", "org.graalvm.*", "io.micrometer.shaded.*"] }
[language-servers.initialization-options.settings.java.import]
# Keep Eclipse metadata (.project, .classpath, .settings) out of the project.
+2
Переглянути файл
@@ -19,6 +19,8 @@ name = "kotlin-language-server"
# Alternative: used only when the server above is not installed.
fallback = true
command = "kotlin-language-server"
# Its bundled Kotlin compiler can't parse newer JDK versions ("25.0.4.1").
max-java = 21
root-markers = ["settings.gradle.kts", "settings.gradle", "build.gradle.kts", "build.gradle", "pom.xml"]
install-hint = "brew install kotlin-language-server (https://github.com/fwcd/kotlin-language-server)"
+8
Переглянути файл
@@ -15,6 +15,14 @@ args = ["--stdio"]
root-markers = ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile", "pyrightconfig.json"]
install-hint = "pip install basedpyright (or: uv tool install basedpyright)"
# basedpyright defaults to "recommended", which flags unannotated attributes and
# every unknown type. "standard" reports real problems; a project's own
# `[tool.basedpyright]` / pyrightconfig.json still takes precedence.
[language-servers.initialization-options.settings.basedpyright.analysis]
typeCheckingMode = "standard"
# Off whenever analysis settings are sent without it: `src/` layouts would stop resolving.
autoSearchPaths = true
[[language-servers]]
name = "pyright"
# Alternative: used only when the server above is not installed.
+1 -1
Переглянути файл
@@ -22,7 +22,7 @@ tauri-plugin-single-instance = "2"
tauri-plugin-updater = "2"
tracing-appender = "0.2"
tauri-specta = { version = "=2.0.0-rc.25", features = ["derive", "typescript"] }
specta-typescript = "0.0.12"
specta-typescript.workspace = true
specta.workspace = true
serde.workspace = true
serde_json.workspace = true
+7
Переглянути файл
@@ -309,6 +309,13 @@ pub fn lsp_servers(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<
ide_host::ops::lsp::lsp_servers(&state.host, window.label())
}
/// Re-emits the language servers' current diagnostics (the UI loaded after they arrived).
#[tauri::command]
#[specta::specta]
pub fn lsp_resend_diagnostics(window: Window, state: State<'_, AppState>) -> IdeResult<()> {
ide_host::ops::lsp::lsp_resend_diagnostics(&state.host, window.label())
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_restart(window: Window, state: State<'_, AppState>, server: ServerId) -> IdeResult<()> {
+1
Переглянути файл
@@ -174,6 +174,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
lsp::lsp_call_hierarchy,
lsp::lsp_type_hierarchy,
lsp::lsp_servers,
lsp::lsp_resend_diagnostics,
lsp::lsp_restart,
lsp::apply_workspace_edit,
lsp::lsp_execute_command,
+74
Переглянути файл
@@ -336,6 +336,8 @@ export const commands = {
lspCallHierarchy: (doc: DocId, pos: Pos, direction: HierarchyDirection) => typedError<HierarchyItem[], IdeError>(__TAURI_INVOKE("lsp_call_hierarchy", { doc, pos, direction })),
lspTypeHierarchy: (doc: DocId, pos: Pos, direction: HierarchyDirection) => typedError<HierarchyItem[], IdeError>(__TAURI_INVOKE("lsp_type_hierarchy", { doc, pos, direction })),
lspServers: () => typedError<ServerInfo[], IdeError>(__TAURI_INVOKE("lsp_servers")),
/** Re-emits the language servers' current diagnostics (the UI loaded after they arrived). */
lspResendDiagnostics: () => typedError<null, IdeError>(__TAURI_INVOKE("lsp_resend_diagnostics")),
lspRestart: (server: ServerId) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_restart", { server })),
/** Applies a (previewed) workspace edit, e.g. after rename confirmation. */
applyWorkspaceEdit: (edit: WorkspaceEdit) => typedError<null, IdeError>(__TAURI_INVOKE("apply_workspace_edit", { edit })),
@@ -3433,6 +3435,64 @@ export type LanguageInfo_Serialize = {
firstLine?: string | null,
};
export type LanguageServerSettings = LanguageServerSettings_Serialize | LanguageServerSettings_Deserialize;
export type LanguageServerSettings_Deserialize = {
/** `false` keeps the server from starting for any language. */
enabled?: boolean,
/**
* Executable to launch instead of the definition's; required for a server
* defined here (one with `languages`).
*/
command?: string,
/** Replaces the definition's arguments. */
args?: string[] | null,
/** Added to the server's environment. */
env?: { [key in string]: string },
/** Merged over the definition's `initializationOptions` (sent once at startup). */
initializationOptions?: unknown | null,
/**
* Answers the server's `workspace/configuration` requests; changes are pushed
* with `workspace/didChangeConfiguration` without a restart.
*/
settings?: unknown | null,
/**
* Language ids a server defined here serves (`python`); empty for the servers
* of the language definitions.
*/
languages?: string[],
/** Files marking a workspace root for a server defined here (`pyproject.toml`). */
rootMarkers?: string[],
};
export type LanguageServerSettings_Serialize = {
/** `false` keeps the server from starting for any language. */
enabled: boolean,
/**
* Executable to launch instead of the definition's; required for a server
* defined here (one with `languages`).
*/
command: string,
/** Replaces the definition's arguments. */
args?: string[] | null,
/** Added to the server's environment. */
env: { [key in string]: string },
/** Merged over the definition's `initializationOptions` (sent once at startup). */
initializationOptions?: unknown | null,
/**
* Answers the server's `workspace/configuration` requests; changes are pushed
* with `workspace/didChangeConfiguration` without a restart.
*/
settings?: unknown | null,
/**
* Language ids a server defined here serves (`python`); empty for the servers
* of the language definitions.
*/
languages: string[],
/** Files marking a workspace root for a server defined here (`pyproject.toml`). */
rootMarkers: string[],
};
export type LanguagesSettings = {
python?: PythonSettings,
node?: NodeSettings,
@@ -4859,6 +4919,11 @@ export type Settings_Deserialize = {
* command the language definition launches (`elixir-ls`, `codelldb`).
*/
tools?: { [key in string]: ToolSettings },
/**
* Per language server, by name (`rust-analyzer`): launch and protocol
* options on top of the language definition, or a server defined here.
*/
languageServers?: { [key in string]: LanguageServerSettings_Deserialize },
/** Editor › Inspections profiles. */
inspections?: InspectionSettings,
/** Editor › Natural Languages › Spelling. */
@@ -4907,6 +4972,11 @@ export type Settings_Serialize = {
* command the language definition launches (`elixir-ls`, `codelldb`).
*/
tools: { [key in string]: ToolSettings },
/**
* Per language server, by name (`rust-analyzer`): launch and protocol
* options on top of the language definition, or a server defined here.
*/
languageServers: { [key in string]: LanguageServerSettings_Serialize },
/** Editor › Inspections profiles. */
inspections: InspectionSettings,
/** Editor › Natural Languages › Spelling. */
@@ -5406,6 +5476,10 @@ export type ToolInfo = {
homepage: string | null,
/** Why the executable chosen in settings cannot be used (status is then `Missing`). */
customError: string | null,
/** A language server's arguments from its language definition. */
defaultArgs: string[],
/** A language server's `initializationOptions` from its language definition, as JSON text. */
defaultInitializationOptions: string | null,
};
export type ToolKind = "languageServer" | "debugger" |
+6
Переглянути файл
@@ -192,6 +192,12 @@ export function whenSynced(view: EditorView): Promise<void> {
return view.state.facet(documentSynced)?.() ?? Promise.resolve();
}
/** Every open editor's edits reached the backend (language servers answer from its copy). */
export function whenAllSynced(): Promise<void> {
const editors = useEditorRegistry.getState().editors;
return editors.size ? Promise.all([...editors].map((e) => whenSynced(e.view))).then(() => {}) : Promise.resolve();
}
/** True for doc changes that did not originate from typing in *this* view. */
export function isExternalChange(tr: Transaction): boolean {
return !!tr.annotation(remoteChange) || !!tr.annotation(mirroredChange);
+17 -2
Переглянути файл
@@ -52,6 +52,7 @@ import {
removePane,
reopenClosed,
setActivePane,
splitAtEdge,
sortTabs,
splitPane,
tabOptions,
@@ -784,7 +785,7 @@ export class EditorController implements SlotHost {
this.navSuppress++;
try {
let s = useTabs.getState();
let paneId = s.activePane;
let paneId = o.pane && s.panes[o.pane] ? o.pane : s.activePane;
if (o.side) {
const right = neighbourPane(s, paneId);
if (right) paneId = right;
@@ -799,7 +800,7 @@ export class EditorController implements SlotHost {
}
const found = findTab(s, input.key, paneId);
let tabId: string;
if (found && (!o.side || found.paneId === paneId)) {
if (found && (!(o.side || o.pane) || found.paneId === paneId)) {
paneId = found.paneId;
s = activateTab(setActivePane(s, paneId), paneId, found.tab.id);
if (!o.preview) s = promoteTab(s, paneId, found.tab.id);
@@ -935,6 +936,20 @@ export class EditorController implements SlotHost {
if (slot?.view) slot.focus();
else if (slot) slot.wantsFocus = true;
}
/** Files dropped on an editor: opened in that pane, or in a new split at `edge`. */
async openFilesIn(paths: readonly string[], paneId: string, edge: SplitEdge | "center") {
const s = useTabs.getState();
if (!s.panes[paneId] || !paths.length) return;
let target = paneId;
if (edge !== "center") {
const r = splitAtEdge(s, paneId, edge);
useTabs.setState(r.state, true);
target = r.paneId;
}
for (const [i, path] of paths.entries()) await this.openFile(path, { pane: target, focus: i === paths.length - 1 });
const pane = useTabs.getState().panes[target];
if (pane && !pane.tabs.length) this.apply((st) => removePane(st, target));
}
/** IDEA "Move to Opposite Group"; without a split, "Split and Move Right". */
moveToOpposite(paneId: string, tabId: string) {
const target = neighbourPane(useTabs.getState(), paneId);
+13 -1
Переглянути файл
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { initialTabsState, moveTabToNewSplit, openTab, paneIds, splitPane, togglePin, type TabsState } from "./tabs";
import { initialTabsState, moveTabToNewSplit, openTab, paneIds, splitAtEdge, splitPane, togglePin, type TabsState } from "./tabs";
import { loadSession, parseSession, restoreTabsState, serializeSession, slashPath } from "./session";
const file = (path: string) => ({ kind: "file", key: `file:${path}`, path });
@@ -145,3 +145,15 @@ describe("sessions saved with Windows backslash paths", () => {
}
});
});
describe("splitAtEdge", () => {
it("adds an empty active pane on the given side", () => {
const s = open(initialTabsState(), "/a");
const pane = s.activePane;
const r = splitAtEdge(s, pane, "right");
expect(paneIds(r.state)).toEqual([pane, r.paneId]);
expect(r.state.panes[r.paneId]!.tabs).toEqual([]);
expect(r.state.activePane).toBe(r.paneId);
expect(paths(r.state, pane)).toEqual(["/a"]);
});
});
+14 -6
Переглянути файл
@@ -425,21 +425,29 @@ export function moveTabToNewSplit(
const tab = src?.tabs.find((t) => t.id === tabId);
if (!src || !tab || !s.panes[targetPane]) return null;
if (fromPane === targetPane && src.tabs.length === 1) return null;
let next = { ...removeTabs(s, fromPane, new Set([tabId])), closed: s.closed };
const next = { ...removeTabs(s, fromPane, new Set([tabId])), closed: s.closed };
// The source pane may have collapsed away; split the target if it survived, else the active pane.
const anchor = next.panes[targetPane] ? targetPane : next.activePane;
const id = nextId("pane");
const moved: Tab = { ...tab, preview: false };
const pane: Pane = { id, tabs: [moved], active: moved.id, mru: [moved.id] };
return splitAtEdge(next, anchor, edge, { tabs: [moved], active: moved.id, mru: [moved.id] });
}
/** A new pane (empty unless `content` is given) at `edge` of `anchor`, made active. */
export function splitAtEdge(
s: TabsState,
anchor: string,
edge: SplitEdge,
content: Omit<Pane, "id"> = { tabs: [], active: null, mru: [] },
): { state: TabsState; paneId: string } {
const id = nextId("pane");
const dir = edge === "left" || edge === "right" ? "row" : "column";
const before = edge === "left" || edge === "top";
const layout = mapLayout(next.layout, (n) => {
const layout = mapLayout(s.layout, (n) => {
if (n.kind === "pane" && n.paneId === anchor) {
const added: LayoutNode = { kind: "pane", paneId: id };
return { kind: "split", id: nextId("split"), dir, children: before ? [added, n] : [n, added] };
}
return n;
})!;
next = { ...next, layout, panes: { ...next.panes, [id]: pane }, activePane: id };
return { state: next, paneId: id };
return { state: { ...s, layout, panes: { ...s.panes, [id]: { id, ...content } }, activePane: id }, paneId: id };
}
+31 -29
Переглянути файл
@@ -4,7 +4,7 @@
* decorations, middle-click close, Alt+click close others, double-click to
* keep a preview / maximize the editor, context menu) and the active editor.
*/
import { Fragment, useMemo, useRef, useState, type DragEvent, type FocusEvent, type ReactNode } from "react";
import { Fragment, useEffect, useMemo, useRef, useState, type FocusEvent, type ReactNode } from "react";
import clsx from "clsx";
import { useShallow } from "zustand/react/shallow";
import { executeAction } from "@/platform/actions";
@@ -32,6 +32,8 @@ import {
SplitPanel,
Tabs,
showContextMenu,
registerDropTarget,
FILES_DRAG,
type TabItem,
type TabsDnd,
} from "@/ui";
@@ -197,6 +199,33 @@ function PaneView({ paneId }: { paneId: string }) {
return { all: strip(0), rest: strip(pinnedCount) };
}, [ctrl, paneId, pinnedCount]);
// Dropping a tab or project files on the editor: an edge splits, the middle opens / moves here.
const contentRef = useRef<HTMLDivElement>(null);
const hasPane = !!pane;
useEffect(() => {
const el = contentRef.current;
if (!el) return;
const zoneAt = (x: number, y: number) => dropZoneAt(x, y, el.getBoundingClientRect());
return registerDropTarget(el, {
accepts: (type) => type === EDITOR_TAB_MIME || type === FILES_DRAG,
over: (_, x, y) => setDropZone(zoneAt(x, y)),
leave: () => setDropZone(null),
drop: (data, x, y) => {
const zone = zoneAt(x, y);
setDropZone(null);
if (data.type === FILES_DRAG) {
void ctrl.openFilesIn(data.payload.split("\n").filter(Boolean), paneId, zone);
return;
}
const p = parseTabPayload(data.payload);
if (!p) return;
const target = useTabs.getState().panes[paneId];
if (zone === "center") ctrl.moveTab(p.paneId, p.tabId, paneId, target?.tabs.length ?? 0);
else ctrl.moveTabToSplit(p.paneId, p.tabId, paneId, zone);
},
});
}, [ctrl, paneId, hasPane]);
if (!pane) return null;
const active = pane.tabs.find((t) => t.id === pane.active) ?? null;
@@ -208,33 +237,6 @@ function PaneView({ paneId }: { paneId: string }) {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setContext("editorFocus", false);
};
// Dropping a tab on the editor: an edge splits, the middle moves the tab here.
const isTabDrag = (e: DragEvent) => [...e.dataTransfer.types].includes(EDITOR_TAB_MIME);
const contentDnd = {
onDragOverCapture: (e: DragEvent<HTMLDivElement>) => {
if (!isTabDrag(e)) return;
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = "move";
const zone = dropZoneAt(e.clientX, e.clientY, e.currentTarget.getBoundingClientRect());
if (zone !== dropZone) setDropZone(zone);
},
onDragLeave: (e: DragEvent<HTMLDivElement>) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setDropZone(null);
},
onDropCapture: (e: DragEvent<HTMLDivElement>) => {
if (!isTabDrag(e)) return;
e.preventDefault();
e.stopPropagation();
const zone = dropZoneAt(e.clientX, e.clientY, e.currentTarget.getBoundingClientRect());
setDropZone(null);
const p = parseTabPayload(e.dataTransfer.getData(EDITOR_TAB_MIME));
if (!p) return;
if (zone === "center") ctrl.moveTab(p.paneId, p.tabId, paneId, pane.tabs.length);
else ctrl.moveTabToSplit(p.paneId, p.tabId, paneId, zone);
},
};
const hidden = tabPrefs.placement === "none" || distractionFree;
const strip = (stripItems: TabItem[], stripDnd: TabsDnd, trailing: ReactNode) => (
<Tabs
@@ -299,7 +301,7 @@ function PaneView({ paneId }: { paneId: string }) {
role="tabpanel"
id={active ? `editor-${paneId}-panel-${active.id}` : undefined}
aria-labelledby={active ? `editor-${paneId}-tab-${active.id}` : undefined}
{...contentDnd}
ref={contentRef}
>
{active ? <PaneContent paneId={paneId} tab={active} /> : <EmptyEditor />}
{dropZone && <div className={clsx(styles.dropZone, styles[`drop-${dropZone}`])} aria-hidden="true" />}
-4
Переглянути файл
@@ -178,10 +178,6 @@
}
.bulb {
flex: none;
color: var(--warning);
}
.bulbFix {
color: var(--danger);
}
.empty {
font-size: var(--fs-ui);
+1 -1
Переглянути файл
@@ -44,7 +44,7 @@ import { useUsagesStatus } from "./navigation";
import styles from "./Popups.module.css";
export function BulbIcon({ fix }: { fix?: boolean }) {
return <Icon name="bulb" size={16} className={clsx(styles.bulb, fix && styles.bulbFix)} />;
return <Icon name={fix ? "bulb-fix" : "bulb"} size={16} className={styles.bulb} />;
}
function ItemIcon({ item }: { item: ListPopupItem }) {
+11 -2
Переглянути файл
@@ -10,7 +10,8 @@ import { quickDefinition, quickDocumentation } from "./hover";
import { expressionTypeInfo } from "./typeInfo";
import { gotoTargets, highlightUsages } from "./navigation";
import { gotoDiagnostic } from "./diagnostics";
import { applyKindSilently, runKindAction, showIntentions } from "./intentions";
import { applyKindSilently, applyQuickFix, runKindAction, showIntentions } from "./intentions";
import { implementPythonAbstractMethods } from "./pythonMembers";
import { workflowSettings, type ActionsOnSaveValid } from "@/platform/workflowSettings";
import { startRename } from "./rename";
import { formatDocument, reformatDialog } from "./format";
@@ -154,6 +155,9 @@ export function registerLspActions(): () => void {
editorAction("code.showIntentions", "Show Context Actions", "Code", showIntentions, {
keywords: ["intention", "quick fix", "lightbulb"],
}),
editorAction("code.applyQuickFix", "Apply Quick Fix", "Code", applyQuickFix, {
keywords: ["fix error", "problem", "lightbulb"],
}),
editorAction("code.reformat", "Reformat Code", "Code", reformat, {
keywords: ["format", "prettier"],
}),
@@ -228,7 +232,12 @@ export function registerLspActions(): () => void {
// Implement / Override Methods: the server's code actions for them (jdtls "Override/Implement
// Methods…", rust-analyzer "Implement missing members", TS "Implement interface"…).
editorAction("code.implementMethods", "Implement Methods…", "Code", (v) =>
runKindAction(v, "", { title: IMPLEMENT_TITLE, none: "Nothing to implement", label: "Implement Members" }),
runKindAction(v, "", {
title: IMPLEMENT_TITLE,
none: "Nothing to implement",
label: "Implement Members",
fallback: () => implementPythonAbstractMethods(v),
}),
),
editorAction("code.overrideMethods", "Override Methods…", "Code", (v) =>
runKindAction(v, "", { title: OVERRIDE_TITLE, none: "Nothing to override", label: "Override Members" }),
+59
Переглянути файл
@@ -0,0 +1,59 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { IdeEvent } from "@/bindings";
const listeners = vi.hoisted(() => new Set<(e: IdeEvent) => void>());
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: () => true,
onIdeEvent: (_type: string, fn: (e: IdeEvent) => void) => {
listeners.add(fn);
return () => listeners.delete(fn);
},
};
});
const { onServerSettled } = await import("./availability");
const status = (s: string) => {
for (const fn of listeners) fn({ type: "languageServer", server: 1, status: s } as unknown as IdeEvent);
};
describe("onServerSettled", () => {
afterEach(() => {
vi.useRealTimers();
listeners.clear();
});
it("re-runs a callback that keeps the server busy only once", () => {
vi.useFakeTimers();
const fn = vi.fn();
onServerSettled(fn);
status("starting");
status("ready");
expect(fn).toHaveBeenCalledTimes(1);
for (let i = 0; i < 2; i++) {
status("busy");
vi.advanceTimersByTime(2000);
status("ready");
}
expect(fn).toHaveBeenCalledTimes(2);
// Indexing that starts later is a new settle.
vi.advanceTimersByTime(10_000);
status("busy");
vi.advanceTimersByTime(5000);
status("ready");
expect(fn).toHaveBeenCalledTimes(3);
});
it("ignores short busy spells", () => {
vi.useFakeTimers();
const fn = vi.fn();
onServerSettled(fn);
status("busy");
vi.advanceTimersByTime(100);
status("ready");
expect(fn).not.toHaveBeenCalled();
});
});
+37
Переглянути файл
@@ -46,6 +46,43 @@ export function onLspRefresh(kind: LspRefreshKind, fn: () => void): () => void {
};
}
/** A busy spell at least this long is indexing / a build, not the server answering a request. */
const LONG_BUSY_MS = 1500;
/** A busy spell starting this soon after `fn` ran may be `fn`'s own requests. */
const ECHO_MS = 2000;
/**
* Calls `fn` when a server becomes ready after starting or after a long busy
* spell (indexing), when earlier answers may have been incomplete. Short busy
* spells are ignored: jdtls reports progress for the very requests a caller
* sends, and re-asking on each of them would never stop. For the same reason
* a long spell that began right after `fn` ran (slow requests `fn` sent, or
* indexing right after start) re-runs it only once in a row.
*/
export function onServerSettled(fn: () => void): () => void {
if (!isTauri()) return () => {};
const since = new Map<number, number>();
const fired = new Map<number, { at: number; echoed: boolean }>();
return onIdeEvent("languageServer", (e) => {
if (e.status === "starting") {
since.set(e.server, -Infinity);
fired.delete(e.server);
} else if (e.status === "busy") {
if (!since.has(e.server)) since.set(e.server, Date.now());
} else if (e.status === "ready") {
const t = since.get(e.server);
since.delete(e.server);
if (t === undefined || Date.now() - t < LONG_BUSY_MS) return;
const last = fired.get(e.server);
const echo = !!last && t - last.at < ECHO_MS;
if (echo && last.echoed) return;
fired.set(e.server, { at: Date.now(), echoed: echo });
fn();
} else since.delete(e.server);
});
}
export function installAvailabilityEvents(): () => void {
return onIdeEvent("languageServer", (e) => {
if (e.status === "ready") serverBackoff.clear();
+71 -2
Переглянути файл
@@ -1,8 +1,17 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorState, StateEffect } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { CompletionItem } from "@/bindings";
import { completionSymbolKind, identifierEnd, toCmCompletion, triggerCharacter } from "./completionItems";
import type { EditorDocContext } from "@/editor/api";
import { lspDoc } from "./lsp";
import {
completionSymbolKind,
identifierEnd,
toCmCompletion,
triggerCharacter,
typeColumnText,
withoutDuplicates,
} from "./completionItems";
import {
applyLspCompletion,
callParens,
@@ -63,6 +72,23 @@ describe("toCmCompletion", () => {
expect(c.displayLabel).toBe("@GetMapping");
});
it("filters on the label when filterText only adds the call or body", () => {
for (const filterText of ["String(${0})", "List<>()", "Runnable() {\n\t${0}\n};"]) {
const label = filterText.match(/^\w+/)![0];
const c = toCmCompletion(item({ label, filterText }));
expect(c.label).toBe(label);
expect(c.displayLabel).toBeUndefined();
}
expect(toCmCompletion(item({ label: "foo", filterText: "foo_bar" })).label).toBe("foo_bar");
});
it("lists identical items once", () => {
const ctor = item({ label: "String()", kind: "constructor", data: "1" });
const overload = item({ label: "String()", kind: "constructor", labelDetail: "(bytes: ByteArray)" });
const out = withoutDuplicates([ctor, { ...ctor, data: "2" }, overload, { ...ctor, server: 2 }]);
expect(out).toEqual([ctor, overload, { ...ctor, server: 2 }]);
});
it("boosts preselected and demotes deprecated items", () => {
expect(toCmCompletion(item({ preselect: true })).boost).toBe(99);
expect(toCmCompletion(item({ deprecated: true })).boost).toBeLessThan(0);
@@ -122,12 +148,31 @@ describe("applying completions", () => {
expect(view.state.selection.main.head).toBe(14);
});
it("keeps overloads sharing a filterText apart", () => {
const { req } = setup("x.ti|");
const [a, b] = ["times(other: Int)", "times(other: Long)"].map((label) =>
makeCompletion(item({ label, filterText: "times" }), req),
);
expect([a!.label, b!.label]).toEqual(["times", "times"]);
expect(a!.apply).not.toBe(b!.apply);
});
it("replaces the rest of the identifier with ⇥", () => {
const { view, req } = setup("service.cr|Order()");
applyLspCompletion(view, makeCompletion(item({ insertText: "create" }), req), 8, 10, "replace");
expect(view.state.doc.toString()).toBe("service.create()");
});
it("leaves the caret inside a call snippet without stops, past `)` once nothing takes arguments", async () => {
const { view, req } = setup("new Arr|");
view.dispatch({ effects: StateEffect.appendConfig.of(lspDoc.of({ doc: 1 } as EditorDocContext)) });
apply(view, makeCompletion(item({ kind: "constructor", insertText: "ArrayList<>()", isSnippet: true }), req), 4);
expect(view.state.doc.toString()).toBe("new ArrayList<>()");
expect(view.state.selection.main.head).toBe(16);
// Signature help fails outside Tauri: nothing to pass.
await vi.waitFor(() => expect(view.state.selection.main.head).toBe(17));
});
it("uses the server's ⇥ range when given", () => {
const { view, req } = setup("a.cr|Order.x");
const c = makeCompletion(
@@ -280,3 +325,27 @@ describe("explicit completion", () => {
view.destroy();
});
});
describe("typeColumnText", () => {
const edit = (new_text: string) => [{ range: { start: { line: 0, col: 0 }, end: { line: 0, col: 0 } }, new_text }];
it("names the module an auto-import comes from", () => {
expect(typeColumnText({ detail: "Auto-import", additionalEdits: edit("\nfrom collections import OrderedDict") })).toBe(
"collections",
);
expect(typeColumnText({ detail: "Map<K, V>", additionalEdits: edit("import java.util.HashMap;\n") })).toBe(
"Map<K, V> (java.util)",
);
expect(typeColumnText({ detail: null, additionalEdits: edit("use std::collections::HashMap;\n") })).toBe(
"std::collections",
);
expect(typeColumnText({ detail: null, additionalEdits: edit('import { a } from "./money";\n') })).toBe("./money");
});
it("keeps a detail that already says where", () => {
expect(typeColumnText({ detail: "java.util.ArrayList", additionalEdits: edit("import java.util.ArrayList;\n") })).toBe(
"java.util.ArrayList",
);
expect(typeColumnText({ detail: "fn() ", additionalEdits: [] })).toBe("fn() ");
});
});
+84 -13
Переглянути файл
@@ -35,14 +35,21 @@ import {
type RequestId,
} from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { completionSymbolKind, identifierEnd, toCmCompletion, triggerCharacter } from "./completionItems";
import {
completionSymbolKind,
identifierEnd,
toCmCompletion,
triggerCharacter,
typeColumnText,
withoutDuplicates,
} from "./completionItems";
import { lspSnippetToCm, snippetVariables } from "./snippet";
import { docOf, isUnavailable, lspDoc, lspRequest, reportLspError } from "./lsp";
import { offsetToPos, posToOffset, textEditsToChanges } from "./positions";
import { isEmptyMarkup, renderCode, renderMarkup } from "./markdown";
import { selectableText } from "@/ui/selectableText";
import { iconNode } from "./iconMarkup";
import { triggerSignatureHelp } from "./signature";
import { parameterInfoOrLeave, triggerSignatureHelp } from "./signature";
import { serverBackoff } from "./availability";
import { pathCompletionSource } from "./fileReferences";
import { editorPrefs } from "@/platform/editorSettings";
@@ -71,17 +78,42 @@ const isLsp = (c: Completion): c is LspCompletion => "lsp" in c;
// Resolve (documentation, lazily computed edits)
const resolving = new WeakMap<CompletionItem, Promise<CompletionItem>>();
/** Items whose resolve has answered, for accepting them synchronously. */
const resolvedItems = new WeakMap<CompletionItem, CompletionItem>();
function resolveItem(doc: number, item: CompletionItem): Promise<CompletionItem> {
if (item.data == null && !isEmptyMarkup(item.documentation)) return Promise.resolve(item);
let p = resolving.get(item);
if (!p) {
p = lspRequest(() => commands.lspResolveCompletion(doc, item)).catch(() => item);
p = lspRequest(() => commands.lspResolveCompletion(doc, item)).then(
(r) => {
resolvedItems.set(item, r);
return r;
},
() => item,
);
resolving.set(item, p);
}
return p;
}
/**
* Resolves the selected lookup item ahead of acceptance: some servers compute
* its extra edits (rust-analyzer's `use` import) only on resolve, against the
* text as it was, so resolving after the insertion finds nothing.
*/
const prefetchResolve = ViewPlugin.fromClass(
class {
private last: Completion | null = null;
update(u: ViewUpdate) {
const c = selectedCompletion(u.state);
if (c === this.last) return;
this.last = c;
if (c && isLsp(c) && c.lsp.data != null && !c.lsp.additionalEdits.length) void resolveItem(c.req.doc, c.lsp);
}
},
);
/**
* F1 in the lookup (IDEA's documentation popup next to the lookup): docs then
* follow the selection until the lookup closes. Without the auto-popup setting
@@ -166,7 +198,7 @@ export function applyLspCompletion(
) {
if (!isLsp(completion)) return;
const { req } = completion;
const item = completion.resolved ?? completion.lsp;
const item = completion.resolved ?? resolvedItems.get(completion.lsp) ?? completion.lsp;
const state = view.state;
const delta = to - req.pos;
const mapOld = (offset: number) =>
@@ -191,6 +223,7 @@ export function applyLspCompletion(
.filter((c) => c.to <= start || c.from >= end);
let insertedParens: ReturnType<typeof callParens> = null;
let bareCall: number | null = null;
if (item.isSnippet) {
if (extra.length) {
const tr = state.update({ changes: extra, userEvent: "input.complete" });
@@ -199,6 +232,19 @@ export function applyLspCompletion(
end = tr.changes.mapPos(end, 1);
}
snippet(lspSnippetToCm(item.insertText, snippetVariables(req.path)))(view, completion, start, end);
// A call snippet without a stop (`ArrayList<>()`): the caret goes inside until
// signature help says there is nothing to pass.
const head = view.state.selection.main.head;
if (
editorPrefs().completion.insertParentheses &&
CALLABLE.has(item.kind ?? "") &&
/\(\)$/.test(item.insertText) &&
!/\$/.test(item.insertText) &&
view.state.sliceDoc(head - 2, head) === "()"
) {
view.dispatch({ selection: EditorSelection.cursor(head - 1) });
bareCall = head - 1;
}
} else {
const parens = editorPrefs().completion.insertParentheses
? callParens(item, state.doc.lineAt(start), start, end)
@@ -215,9 +261,15 @@ export function applyLspCompletion(
});
}
if (!completion.resolved && !item.additionalEdits.length && item.data != null)
if (item === completion.lsp && !item.additionalEdits.length && item.data != null)
void applyLateEdits(view, completion, start);
if (insertedParens === "inside" && !item.command) setTimeout(() => triggerSignatureHelp(view), 0);
// Parameter info for a call left open, plain (`()` added here) or a server snippet (`fly(${1})`).
const callSnippet = item.isSnippet && CALLABLE.has(item.kind ?? "") && /\(\$\{?\d/.test(item.insertText);
// Unless the item's command asks for it itself (other commands, like jdtls's
// `java.completion.onDidSelect`, are bookkeeping).
const hintsCommand = item.command?.command === "editor.action.triggerParameterHints";
if ((insertedParens === "inside" || callSnippet) && !hintsCommand) setTimeout(() => triggerSignatureHelp(view), 0);
else if (bareCall !== null) void parameterInfoOrLeave(view, bareCall);
runCommand(view, item);
}
@@ -314,7 +366,13 @@ export function makeCompletion(item: CompletionItem, req: RequestContext): LspCo
return Object.assign(cm, {
lsp: item,
req,
apply: applyLsp,
// CodeMirror merges options with the same label, detail and `apply`: overloads
// sharing a filterText (`times(other: Int)`, `times(other: Long)`…) and the same
// name imported from different modules need their own.
apply:
cm.displayLabel || (item.filterText && item.filterText !== item.label) || item.additionalEdits.length
? (...a: Parameters<typeof applyLsp>) => applyLsp(...a)
: applyLsp,
info: (c: Completion) => renderInfo(c as LspCompletion),
});
}
@@ -369,7 +427,10 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe
});
let list;
try {
list = await lspRequest(() => commands.lspCompletion(id, doc.doc, offsetToPos(ctx.state.doc, ctx.pos), trigger));
list = await lspRequest(
() => commands.lspCompletion(id, doc.doc, offsetToPos(ctx.state.doc, ctx.pos), trigger),
() => inflight === id,
);
} catch (e) {
if (isUnavailable(e)) {
serverBackoff.mark(doc.doc);
@@ -383,9 +444,18 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe
const req: RequestContext = { doc: doc.doc, path: doc.path, language: doc.uiMode, pos: ctx.pos, text: ctx.state.doc };
const prefs = editorPrefs().completion;
const typed = word?.text ?? "";
const items = prefs.matchCase
? list.items.filter((it) => matchesCase(it.filterText ?? it.label, typed, prefs.caseSensitivity))
: list.items;
let items = withoutDuplicates(
prefs.matchCase
? list.items.filter((it) => matchesCase(it.filterText ?? it.label, typed, prefs.caseSensitivity))
: list.items,
);
// A server snippet named like a live template (jdtls `sout`, `fori`) would be listed twice; the template wins.
if (items.some((it) => it.kind === "snippet")) {
const own = await contributedSource(ctx);
if (ctx.aborted) return null;
const names = new Set(own?.options.map((o) => o.label));
if (names.size) items = items.filter((it) => it.kind !== "snippet" || !names.has(it.label));
}
return {
from: word ? word.from : ctx.pos,
options: items.map((item) => makeCompletion(item, req)),
@@ -616,11 +686,11 @@ function kindBadge(c: Completion): Node | null {
}
function typeColumn(c: Completion): Node | null {
const detail = isLsp(c) ? c.lsp.detail : (c as RichCompletion).typeText;
const detail = isLsp(c) ? typeColumnText(c.lsp) : (c as RichCompletion).typeText?.replace(/\s+/g, " ");
if (!detail) return null;
const span = document.createElement("span");
span.className = "cm-lsp-type";
span.textContent = detail.replace(/\s+/g, " ");
span.textContent = detail;
return span;
}
@@ -684,6 +754,7 @@ const completionFooter = ViewPlugin.fromClass(
export function completionExtension() {
return [
lookupKeys,
prefetchResolve,
autocompletion({
override: [gated(lspCompletionSource), gated(contributedSource), gated(pathCompletionSource)],
icons: false,
+57 -1
Переглянути файл
@@ -41,7 +41,7 @@ export function completionSymbolKind(kind: CompletionKind | null): string {
* original label is shown through `displayLabel`.
*/
export function toCmCompletion(item: CompletionItem): Completion {
const filter = item.filterText && item.filterText !== item.label ? item.filterText : null;
const filter = item.filterText && item.filterText !== item.label && !extendsLabel(item) ? item.filterText : null;
const c: Completion = {
label: filter ?? item.label,
type: completionSymbolKind(item.kind),
@@ -55,6 +55,62 @@ export function toCmCompletion(item: CompletionItem): Completion {
return c;
}
/**
* A `filterText` that is the label plus what the item inserts after it (jdtls
* `String(${0})`, `List<>()`): typing a word never reaches that part, and
* matching on it would rank the exact `String` like `StringBuilder`.
*/
function extendsLabel(item: CompletionItem): boolean {
const rest = item.filterText!.slice(item.label.length);
return item.filterText!.startsWith(item.label) && /^[^\p{L}\p{N}_$]/u.test(rest);
}
/**
* Items that look and insert the same, listed once. kotlin-language-server
* repeats a class once per classpath entry declaring it (`String()` ×3);
* these all have their own `apply` (see `makeCompletion`), so CodeMirror
* wouldn't merge them.
*/
export function withoutDuplicates(items: readonly CompletionItem[]): CompletionItem[] {
const seen = new Set<string>();
return items.filter((it) => {
const key = JSON.stringify([it.server, it.label, it.labelDetail, it.detail, it.kind, it.insertText, it.additionalEdits]);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
const IMPORT_SOURCE = [
/^\s*from\s+([\w.]+)\s+import\b/m, // Python
/^\s*import\s+(?:static\s+)?([\w.]+?)\.\w+;?\s*$/m, // Java, Kotlin
/^\s*use\s+([\w:]+)::/m, // Rust
/\bfrom\s+["']([^"']+)["']/, // JS / TS
];
/**
* Where an auto-import item comes from (`collections`, `java.util`): the
* module its import edit names. Servers like pyright put it nowhere else, so
* same-named items (`OrderedDict` from typing / collections) look identical.
*/
export function importSource(item: Pick<CompletionItem, "additionalEdits">): string | null {
for (const e of item.additionalEdits) {
for (const re of IMPORT_SOURCE) {
const m = re.exec(e.new_text);
if (m) return m[1]!;
}
}
return null;
}
/** Text of the right-aligned type column: the detail, with the import source when it lacks one. */
export function typeColumnText(item: Pick<CompletionItem, "detail" | "additionalEdits">): string | null {
const detail = item.detail?.replace(/\s+/g, " ") || null;
const source = importSource(item);
if (!source || detail?.includes(source)) return detail;
return !detail || /^auto[- ]?import$/i.test(detail) ? source : `${detail} (${source})`;
}
const WORD_CHAR = /[\p{L}\p{N}_$]/u;
/** End of the identifier starting at `pos` in `line` (for ⇥ Replace without a server range). */
+22 -2
Переглянути файл
@@ -9,7 +9,8 @@ import { EditorSelection, StateEffect, StateField } from "@codemirror/state";
import { EditorView, ViewPlugin } from "@codemirror/view";
import { forEachDiagnostic, linter, setDiagnostics, type Diagnostic as LintDiagnostic } from "@codemirror/lint";
import type { Diagnostic, Severity } from "@/bindings";
import { onIdeEvent } from "@/platform/ipc";
import { commands, ideEventsReady, isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { publishLocalDiagnostics } from "@/platform/localDiagnostics";
import { scrollbarMarks, type ScrollbarMark } from "@/editor/api";
import { rangeToOffsets } from "./positions";
@@ -89,11 +90,20 @@ export function subscribeDiagnostics(path: string, l: Listener): () => void {
export function installDiagnosticsEvents(): () => void {
const off = onIdeEvent("diagnostics", (e) => storeDiagnostics(e.path, e.source, e.items));
// Diagnostics published before this window (re)loaded were missed: ask for them again.
const resend = () => {
if (isTauri()) void ideEventsReady().then(() => commands.lspResendDiagnostics()).catch(() => {});
};
if (useProject.getState().project) resend();
const offProject = useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root && s.project) resend();
});
// Another inspection profile (or edits to it) re-filters every open file.
const offProfile = subscribeInspectionProfile(() => listeners.forEach((set) => set.forEach((l) => l())));
return () => {
off();
offProfile();
offProject();
};
}
@@ -118,13 +128,16 @@ export function toLintDiagnostics(doc: Text, items: readonly Diagnostic[]): Lint
to,
severity: d.severity,
message: d.message,
source: [d.source, d.code].filter(Boolean).join(" ") || undefined,
source: [d.source, isInternalCode(d.code) ? null : d.code].filter(Boolean).join(" ") || undefined,
markClass: classes.length ? classes.join(" ") : undefined,
};
});
return out.sort((a, b) => a.from - b.from || SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity]);
}
/** Problem ids that mean nothing to a reader (jdtls: `67109264`); short ones (TS `2322`) stay. */
const isInternalCode = (code: string | null | undefined) => !!code && /^\d{6,}$/.test(code);
const MARK_COLOR: Partial<Record<Severity, string>> = {
error: "var(--danger)",
warning: "var(--warning)",
@@ -218,6 +231,13 @@ const lintTheme = EditorView.theme({
},
".cm-lintRange.cm-lsp-unnecessary *": { color: "var(--fg-unused, var(--fg-faint))" },
".cm-lintRange.cm-lsp-deprecated": { textDecoration: "line-through", textDecorationColor: "var(--fg-muted)" },
// An error or warning on the same range (merged into one mark) keeps its underline.
".cm-lintRange-error.cm-lsp-typo, .cm-lintRange-error.cm-lsp-unnecessary": {
textDecoration: "var(--editor-error-decoration, underline wavy var(--danger))",
},
".cm-lintRange-warning.cm-lsp-typo, .cm-lintRange-warning.cm-lsp-unnecessary": {
textDecoration: "var(--editor-warning-decoration, underline wavy var(--warning))",
},
".cm-lintRange-active": { backgroundColor: "transparent" },
".cm-lintRange-warning.cm-lintRange-active": { backgroundColor: "var(--editor-warning-background, transparent)" },
".cm-lintPoint:after": { display: "none" },
+9 -1
Переглянути файл
@@ -7,7 +7,7 @@ import {
protectedRegions,
type FormatGuardOptions,
} from "@/platform/formatGuard";
import { formattedLines } from "./format";
import { dedentsToColumnZero, formattedLines } from "./format";
describe("formattedLines", () => {
const doc = Text.of(["fn main(){", "let x=1;", "}", "", "fn other() {}"]);
@@ -97,3 +97,11 @@ describe("formatter markers and Do not format", () => {
expect(formatExcluded("/p/other/docs.md", "/p", globs)).toBe(false);
});
});
describe("dedentsToColumnZero", () => {
it("spots range formatting done without the surrounding code", () => {
expect(dedentsToColumnZero("\n override fun f() { }\n", "\noverride fun f() {}\n")).toBe(true);
expect(dedentsToColumnZero("\n\tfun f() {\n\t}\n", "\n fun f() {\n }\n")).toBe(false);
expect(dedentsToColumnZero("fun f() {}\n", "fun f() { }\n")).toBe(false);
});
});
+47 -2
Переглянути файл
@@ -7,7 +7,7 @@
*/
import { indentUnit } from "@codemirror/language";
import { isolateHistory } from "@codemirror/commands";
import type { Text } from "@codemirror/state";
import type { EditorState, Text } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { commands } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
@@ -63,6 +63,12 @@ function formattedHint(view: EditorView, lines: number) {
});
}
/** LSP `FormattingOptions`: with spaces the indent width is the indent unit, not the tab size. */
export function formatOptionsOf(state: EditorState): { tabSize: number; insertSpaces: boolean } {
const unit = state.facet(indentUnit);
return unit.includes("\t") ? { tabSize: state.tabSize, insertSpaces: false } : { tabSize: unit.length || state.tabSize, insertSpaces: true };
}
export async function formatDocument(
view: EditorView,
opts: { explicit: boolean; selectionOnly?: boolean } = { explicit: true },
@@ -90,7 +96,7 @@ async function format(view: EditorView, opts: { explicit: boolean; selectionOnly
const sel = state.selection.main;
const useSelection = (opts.selectionOnly ?? true) && !sel.empty;
const range = useSelection ? { start: offsetToPos(state.doc, sel.from), end: offsetToPos(state.doc, sel.to) } : null;
const options = { tabSize: state.tabSize, insertSpaces: !state.facet(indentUnit).includes("\t") };
const options = formatOptionsOf(state);
let edits;
try {
edits = await lspRequest(() => commands.lspFormat(doc.doc, range, options));
@@ -116,6 +122,45 @@ async function format(view: EditorView, opts: { explicit: boolean; selectionOnly
return { applied: true, changes: changes.length, lines: formattedLines(state.doc, changes) };
}
/** Whether `after` has a non-blank line at column 0 where all of `before` was indented. */
export function dedentsToColumnZero(before: string, after: string): boolean {
const minIndent = (t: string) =>
Math.min(...t.split("\n").filter((l) => l.trim()).map((l) => l.length - l.trimStart().length));
return minIndent(before) > 0 && minIndent(after) === 0;
}
/**
* Reformats lines `from..to` silently (generated code: quick fixes, Generate),
* merged into the edit's undo step. False when the server can't format ranges.
*/
export async function formatLines(view: EditorView, from: number, to: number): Promise<boolean> {
const doc = docOf(view);
if (!doc || doc.readOnly) return false;
const { project, settings } = useProject.getState();
if (formatExcluded(doc.path, project?.root ?? null, formatGuardOptions(settings).doNotFormat)) return false;
await whenSynced(view);
const state = view.state;
const range = { start: offsetToPos(state.doc, from), end: offsetToPos(state.doc, to) };
const options = formatOptionsOf(state);
let edits;
try {
edits = await lspRequest(() => commands.lspFormat(doc.doc, range, options));
} catch {
return false;
}
if (view.state.doc !== state.doc) return false;
// Only inside the range: some servers answer a range request with whole-file edits.
const changes = textEditsToChanges(state.doc, edits).filter((c) => c.from >= from && c.to <= to && state.sliceDoc(c.from, c.to) !== c.insert);
if (!changes.length) return true;
// A server formatting the range out of context (kotlin-language-server) moves
// indented code to column 0: its answer is ignored then.
const delta = changes.reduce((d, c) => d + c.insert.length - (c.to - c.from), 0);
const next = state.update({ changes }).state.doc;
if (dedentsToColumnZero(state.sliceDoc(from, to), next.sliceString(from, to + delta))) return false;
view.dispatch({ changes, userEvent: "format", scrollIntoView: false });
return true;
}
function applyContributedFormat(
view: EditorView,
format: ContributedFormatter,
+29 -2
Переглянути файл
@@ -31,6 +31,7 @@ import { docWindowVisible, moveDocPopupToWindow, showInDocWindow } from "./docs"
import { structure } from "@/editor/structure";
import { basename } from "@/platform/project";
import { iconNode } from "./iconMarkup";
import { applyCodeAction, quickFixesAt } from "./intentions";
import { editorPrefs } from "@/platform/editorSettings";
import { CONTRIBUTED_HOVER, contributedAt, type ContributedHover } from "@/editor/api";
import { navigationModifierHeld, onNavigationModifier, pointerTarget } from "@/platform/navigationModifier";
@@ -50,7 +51,10 @@ export async function requestHover(view: EditorView, pos: number): Promise<Hover
if (hoverRequest !== null && isTauri()) void commands.cancelRequest(hoverRequest);
const id = (hoverRequest = nextRequestId());
try {
const h = await lspRequest(() => commands.lspHover(id, doc.doc, offsetToPos(view.state.doc, pos)));
const h = await lspRequest(
() => commands.lspHover(id, doc.doc, offsetToPos(view.state.doc, pos)),
() => hoverRequest === id,
);
return h && !isEmptyMarkup(h.contents) ? h : null;
} finally {
if (hoverRequest === id) hoverRequest = null;
@@ -60,7 +64,7 @@ export async function requestHover(view: EditorView, pos: number): Promise<Hover
function renderDiagnostics(view: EditorView, diags: PlacedDiagnostic[]): HTMLElement {
const box = document.createElement("div");
box.className = "cm-lsp-hover-diagnostics";
for (const { diagnostic: d, from } of diags) {
for (const { diagnostic: d, from, to } of diags) {
const row = document.createElement("div");
row.className = `cm-lsp-diag cm-lsp-diag-${d.severity}`;
row.appendChild(
@@ -87,6 +91,7 @@ function renderDiagnostics(view: EditorView, diags: PlacedDiagnostic[]): HTMLEle
fix.className = "cm-lsp-link-button";
const keys = shortcutLabel("code.showIntentions");
fix.textContent = keys ? `More actions… ${keys}` : "More actions…";
if (d.severity === "error" || d.severity === "warning") offerQuickFix(view, meta, fix, from, to);
fix.addEventListener("mousedown", (e) => e.preventDefault());
fix.addEventListener("click", () => {
view.dispatch({ selection: EditorSelection.cursor(from) });
@@ -100,6 +105,28 @@ function renderDiagnostics(view: EditorView, diags: PlacedDiagnostic[]): HTMLEle
return box;
}
/** IDEA's hover link to the problem's preferred quick fix, shown once the server named one. */
function offerQuickFix(view: EditorView, meta: HTMLElement, before: HTMLElement, from: number, to: number) {
const doc = view.state.doc;
void quickFixesAt(view, from, to)
.then(([action]) => {
if (!action || view.state.doc !== doc || !before.isConnected) return;
const link = document.createElement("button");
link.type = "button";
link.className = "cm-lsp-link-button";
const keys = shortcutLabel("code.applyQuickFix");
link.textContent = keys ? `${action.title} ${keys}` : action.title;
link.addEventListener("mousedown", (e) => e.preventDefault());
link.addEventListener("click", () => {
view.dispatch({ effects: closeHoverTooltips });
view.focus();
void applyCodeAction(view, action);
});
meta.insertBefore(link, before);
})
.catch(() => {});
}
/**
* Whether the plain hover (problems + quick documentation) stays out: while
* ⌘/Ctrl is held the ⌘-hover link and its brief info (`navigation.ts`) own the
+3 -2
Переглянути файл
@@ -163,8 +163,9 @@ export async function requestInline(view: EditorView, automatic: boolean): Promi
const id = (inflight = nextRequestId());
const caret = sel.main.head;
try {
const items = await lspRequest(() =>
commands.lspInlineCompletion(id, doc.doc, offsetToPos(state.doc, caret), automatic),
const items = await lspRequest(
() => commands.lspInlineCompletion(id, doc.doc, offsetToPos(state.doc, caret), automatic),
() => inflight === id,
);
if (view.state.doc !== state.doc || !view.state.selection.eq(sel)) return false;
const suggestions = toSuggestions(view.state, caret, items);
+70 -1
Переглянути файл
@@ -28,7 +28,8 @@ vi.mock("@/platform/ipc", async (orig) => {
return { ...actual, isTauri: () => true, commands: { ...actual.commands, lspResolveCodeAction } };
});
const { intentionPreview, withInspectionControls } = await import("./intentions");
const { bulbLine, changedLines, indentUnderBrace, intentionPreview, lightsBulb, listedCodeActions, withInspectionControls } =
await import("./intentions");
const { setFileDiagnostics } = await import("./diagnostics");
const { lspDoc } = await import("./lsp");
@@ -109,3 +110,71 @@ describe("intention preview", () => {
expect(lspResolveCodeAction).toHaveBeenCalledOnce();
});
});
describe("listedCodeActions", () => {
const action = (title: string, kind: string): CodeAction => ({ ...resolved, title, kind, edit: null });
it("lists one action per title, quick fixes first", () => {
const list = listedCodeActions([
action("Generate toString()", "quickassist"),
action("Add unimplemented methods", "quickfix"),
action("Generate toString()", "source.generate.toString"),
]);
expect(list.map((a) => [a.title, a.kind])).toEqual([
["Add unimplemented methods", "quickfix"],
["Generate toString()", "quickassist"],
]);
});
});
describe("changedLines", () => {
const text = (s: string) => EditorState.create({ doc: s }).doc;
it("spans the lines an edit inserted", () => {
expect(changedLines(text("class A {\n}\n"), text("class A {\n f() {\n }\n}\n"))).toEqual([{ from: 2, to: 3 }]);
});
it("keeps separate edits apart", () => {
const before = text("package p;\n\nclass A {\n int a;\n int b;\n void f() {\n }\n}\n");
const after = text("package p;\n\nimport java.util.List;\n\nclass A {\n int a;\n int b;\n void f() {\n List<String> x = null;\n x.size();\n }\n}\n");
expect(changedLines(before, after)).toEqual([
{ from: 3, to: 4 },
{ from: 9, to: 10 },
]);
});
it("is empty for equal texts", () => {
expect(changedLines(text("a\nb"), text("a\nb"))).toEqual([]);
});
});
describe("bulbLine", () => {
const state = (s: string) => EditorState.create({ doc: s });
it("prefers an indented caret line, then the lines around it", () => {
expect(bulbLine(state(" x\ny"), 1)).toEqual({ line: 1, gutter: false });
expect(bulbLine(state("x\n\ny"), 1)).toEqual({ line: 2, gutter: false });
});
it("falls back to the gutter when no nearby line has room", () => {
expect(bulbLine(state("x\n y\nz"), 1)).toEqual({ line: 1, gutter: true });
});
});
describe("lightsBulb", () => {
const kinds = (k: string | null) => lightsBulb({ ...resolved, kind: k });
it("lights for fixes and refactorings only", () => {
expect([null, "quickfix", "refactor.extract", "quickassist"].map(kinds)).toEqual([true, true, true, true]);
expect(["source.organizeImports", "source.doc", "gopls.doc.features"].map(kinds)).toEqual([false, false, false]);
});
});
describe("indentUnderBrace", () => {
const text = (s: string) => EditorState.create({ doc: s }).doc;
it("moves code generated at the brace's column one level in", () => {
const doc = text("class A : B {\noverride fun f() {\n g()\n}\n}");
expect(indentUnderBrace(doc, 2, 4, " ").map((c) => [doc.lineAt(c.from).number, c.insert])).toEqual([
[2, " "],
[3, " "],
[4, " "],
]);
});
it("leaves code already indented, or not under a brace", () => {
expect(indentUnderBrace(text("class A {\n f()\n}"), 2, 2, " ")).toEqual([]);
expect(indentUnderBrace(text("class A:\npass\nx"), 2, 3, " ")).toEqual([]);
});
});
+166 -21
Переглянути файл
@@ -3,15 +3,19 @@
* intentions popup (quick fixes first, preferred in bold), Optimize Imports and
* Generate. Refactor This and the Refactor menu live in `@/editor/refactor`.
*/
import { StateEffect, StateField, type Extension } from "@codemirror/state";
import { StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { forEachDiagnostic } from "@codemirror/lint";
import { indentUnit } from "@codemirror/language";
import { diff } from "@codemirror/merge";
import { commands, isCancelled, type CodeAction } from "@/platform/ipc";
import { contributedIntentions, whenSynced } from "@/editor/api";
import { contributedIntentions, intentionProviders, whenSynced } from "@/editor/api";
import { shortcutLabel } from "@/platform/keymap";
import { debounce, docOf, isUnavailable, lspRequest, reportLspError } from "./lsp";
import { offsetsToRange } from "./positions";
import { showHint } from "./hint";
import { formatLines } from "./format";
import { pythonMemberIntentions } from "./pythonMembers";
import { caretAnchor, openPopup, type ListPopupItem, type ListPreview } from "./popupStore";
import { editPreviewLines } from "./workspaceEdit";
import { serverBackoff } from "./availability";
@@ -88,6 +92,43 @@ async function fetchIntentions(view: EditorView): Promise<CodeAction[]> {
return actions;
}
/** Enabled quick fixes of the problem at `from..to`, preferred first. */
export async function quickFixesAt(view: EditorView, from: number, to: number): Promise<CodeAction[]> {
const doc = docOf(view);
if (!doc) return [];
await whenSynced(view);
const actions = await lspRequest(() => commands.lspCodeActions(doc.doc, offsetsToRange(view.state.doc, from, to), ["quickfix"]));
return sortCodeActions(actions.filter((a) => isQuickFix(a) && !a.disabledReason));
}
/**
* ⌥⇧↵: applies the preferred (else first) quick fix of the most severe problem
* at the caret, or of one elsewhere on the caret line.
*/
export async function applyQuickFix(view: EditorView) {
const state = view.state;
const caret = state.selection.main.head;
const line = state.doc.lineAt(caret);
const problems: Array<PlacedProblem & { rank: number }> = [];
forEachDiagnostic(state, (d, from, to) => {
if (d.severity === "hint" || to < line.from || from > line.to) return;
const rank = (d.severity === "error" ? 0 : d.severity === "warning" ? 1 : 2) + (from <= caret && caret <= to ? 0 : 3);
problems.push({ from, to, severity: d.severity, rank });
});
problems.sort((a, b) => a.rank - b.rank);
try {
for (const p of problems) {
const fix = (await quickFixesAt(view, p.from, p.to))[0];
if (view.state.doc !== state.doc) return;
if (fix) return applyCodeAction(view, fix);
}
} catch (e) {
reportLspError(view, e, true);
return;
}
showHint(view, "No quick fixes available");
}
export async function applyCodeAction(view: EditorView, action: CodeAction) {
const doc = docOf(view);
if (!doc) return;
@@ -95,11 +136,82 @@ export async function applyCodeAction(view: EditorView, action: CodeAction) {
showHint(view, action.disabledReason);
return;
}
const before = view.state.doc;
try {
await lspRequest(() => commands.lspApplyCodeAction(doc.doc, action));
} catch (e) {
reportLspError(view, e, true);
return;
}
if (!action.kind?.startsWith("source.organizeImports") && !action.kind?.startsWith("source.fixAll"))
await reformatGenerated(view, before);
}
/**
* Code the server generated follows its own indentation (jdtls tabs,
* tsserver 4 spaces); like IDEA, the lines an action inserted are reformatted
* to the file's style.
*/
async function reformatGenerated(view: EditorView, before: Text) {
for (let i = 0; i < 100 && view.state.doc === before; i++) await new Promise((r) => setTimeout(r, 20));
// Bottom up, so the line numbers of the hunks above stay valid.
for (const lines of changedLines(before, view.state.doc).reverse()) {
if (lines.to - lines.from < 1) continue;
const doc = view.state.doc;
const shift = indentUnderBrace(doc, lines.from, lines.to, view.state.facet(indentUnit));
// A server that generated code without its context formats ranges the same
// way (back to column 0): its range formatting is skipped then.
if (shift.length) view.dispatch({ changes: shift, userEvent: "format", scrollIntoView: false });
else if (!(await formatLines(view, doc.line(lines.from).from, doc.line(lines.to).to)) && view.state.doc !== doc) return;
}
}
/**
* Generated lines right under a `{` line but not indented past it (servers
* that format the snippet on its own, kotlin-language-server): the block moves
* one level in, keeping its own nesting. Never applies to indentation-based
* languages, whose blocks don't open with `{`.
*/
export function indentUnderBrace(doc: Text, fromLine: number, toLine: number, unit: string): Array<{ from: number; insert: string }> {
if (fromLine < 2) return [];
const prev = doc.line(fromLine - 1).text;
if (!prev.trimEnd().endsWith("{")) return [];
const lead = (t: string) => t.slice(0, t.length - t.trimStart().length);
const target = lead(prev) + unit;
let first: string | null = null;
for (let n = fromLine; n <= toLine && first === null; n++) if (doc.line(n).text.trim()) first = lead(doc.line(n).text);
if (first === null || first.length > lead(prev).length || !target.startsWith(first)) return [];
const extra = target.slice(first.length);
const out: Array<{ from: number; insert: string }> = [];
for (let n = fromLine; n <= toLine; n++) {
const line = doc.line(n);
if (line.text.trim()) out.push({ from: line.from, insert: extra });
}
return out;
}
/**
* 1-based line spans of `after` that an edit changed, top to bottom: an added
* import and the code using it are separate spans, so the user's code between
* them is left alone.
*/
export function changedLines(before: Text, after: Text): Array<{ from: number; to: number }> {
if (before.eq(after)) return [];
const spans: Array<{ from: number; to: number }> = [];
const a = before.toString();
const b = after.toString();
for (const c of diff(a, b)) {
// Text inserted at a line's end or start (`{⏎ added`, `added⏎`) leaves that line as it was.
const lead = b[c.fromB] === "\n" && (c.toA === c.fromA || a[c.fromA] === "\n");
const trail = c.toB > c.fromB && b[c.toB - 1] === "\n" && (c.toA === c.fromA || a[c.toA - 1] === "\n");
const from = after.lineAt(lead ? c.fromB + 1 : c.fromB).number;
const end = trail ? c.toB - 1 : c.toB;
const to = Math.max(from, after.lineAt(end).number);
const last = spans[spans.length - 1];
if (last && from <= last.to + 1) last.to = Math.max(last.to, to);
else spans.push({ from, to });
}
return spans;
}
/**
@@ -127,8 +239,17 @@ export async function applyKindSilently(view: EditorView, kind: string): Promise
return true;
}
/**
* Sorted, one action per title: servers can report the same action under two
* kinds (jdtls: "Generate toString()" as quickassist and source.generate).
*/
export function listedCodeActions(actions: readonly CodeAction[]): CodeAction[] {
const seen = new Set<string>();
return sortCodeActions(actions).filter((a) => !seen.has(a.title) && !!seen.add(a.title));
}
function actionItems(view: EditorView, actions: CodeAction[], resolved?: Map<CodeAction, Promise<CodeAction>>): ListPopupItem[] {
return sortCodeActions(actions).map((a, i) => ({
return listedCodeActions(actions).map((a, i) => ({
id: `${i}`,
label: a.title,
icon: isQuickFix(a) ? "bulb-fix" : "bulb",
@@ -217,7 +338,7 @@ export async function showIntentions(view: EditorView) {
} catch (e) {
failure = { error: e };
}
const sorted = sortCodeActions(actions);
const sorted = listedCodeActions(actions);
const resolved = new Map<CodeAction, Promise<CodeAction>>();
const items = withInspectionControls(view, [...local, ...actionItems(view, sorted, resolved)]);
if (!items.length) {
@@ -305,6 +426,16 @@ function noActionReason(view: EditorView, none: string): string {
// ---------------------------------------------------------------------------
// Lightbulb
/**
* Fixes and refactorings light the bulb; source actions (organize imports,
* generate…) and server extras (gopls "Browse documentation") are offered on
* almost every line and only appear in the ⌥↵ list.
*/
export function lightsBulb(a: CodeAction): boolean {
const kind = a.kind ?? "";
return !kind || kind === "quickassist" || /^(quickfix|refactor)(\.|$)/.test(kind);
}
interface Bulb {
line: number;
quickFix: boolean;
@@ -331,11 +462,19 @@ const bulbPlugin = ViewPlugin.fromClass(
this.lookup();
}
update(u: ViewUpdate) {
if (u.docChanged || u.selectionSet) this.lookup();
if (u.docChanged || u.selectionSet || (u.focusChanged && u.view.hasFocus)) this.lookup();
else if (u.focusChanged) {
this.lookup.cancel();
// A blur dispatched from inside the update is not allowed.
queueMicrotask(() => {
if (!this.view.hasFocus && this.view.state.field(bulbField, false)) this.view.dispatch({ effects: setBulb.of(null) });
});
}
}
async run() {
const doc = docOf(this.view);
if (!doc || doc.readOnly || !this.view.dom.isConnected) return;
// As in IDEA, only the focused editor shows the bulb.
if (!doc || doc.readOnly || !this.view.dom.isConnected || !this.view.hasFocus) return;
const state = this.view.state;
const typoFix = spellingIntentions(this.view).length > 0;
const local = typoFix || contributedIntentions(this.view).length > 0;
@@ -350,9 +489,9 @@ const bulbPlugin = ViewPlugin.fromClass(
if (!local) return;
}
}
if (this.view.state.doc !== state.doc || !this.view.state.selection.eq(state.selection)) return;
if (this.view.state.doc !== state.doc || !this.view.state.selection.eq(state.selection) || !this.view.hasFocus) return;
const line = state.doc.lineAt(state.selection.main.head).number;
const any = actions.length > 0 || local;
const any = actions.some(lightsBulb) || local;
this.view.dispatch({
effects: setBulb.of(any ? { line, quickFix: typoFix || actions.some(isQuickFix) } : null),
});
@@ -365,21 +504,20 @@ const bulbPlugin = ViewPlugin.fromClass(
/**
* New-UI bulb: floats at the start of the text on the caret line, or on the
* line below / above when the caret line's text starts at the left edge.
* line below / above when the caret line's text starts at the left edge; in
* the gutter when none of them has room.
*/
const BULB_COLUMNS = 3;
function bulbLine(state: EditorView["state"], line: number): number {
export function bulbLine(state: EditorView["state"], line: number): { line: number; gutter: boolean } {
const doc = state.doc;
const free = (n: number) => {
if (n < 1 || n > doc.lines) return false;
const text = doc.line(n).text;
return text.length - text.trimStart().length >= BULB_COLUMNS || !text.trim();
};
if (free(line)) return line;
if (free(line + 1)) return line + 1;
if (free(line - 1)) return line - 1;
return line;
for (const n of [line, line + 1, line - 1]) if (free(n)) return { line: n, gutter: false };
return { line, gutter: true };
}
class FloatingBulb {
@@ -393,6 +531,7 @@ class FloatingBulb {
this.dom.setAttribute("aria-label", "Show intentions");
this.dom.style.display = "none";
this.dom.appendChild(iconNode("bulb", 16));
this.dom.appendChild(iconNode("bulb-fix", 16, "cm-lsp-bulb-fix-icon"));
this.dom.addEventListener("mousedown", (e) => {
e.preventDefault();
e.stopPropagation();
@@ -420,18 +559,24 @@ class FloatingBulb {
this.view.requestMeasure({
key: this,
read: (view) => {
const line = view.state.doc.line(bulbLine(view.state, bulb.line));
const block = view.lineBlockAt(line.from);
const at = bulbLine(view.state, bulb.line);
const line = view.state.doc.line(at.line);
const content = view.contentDOM.getBoundingClientRect();
const scroller = view.scrollDOM.getBoundingClientRect();
// The text row: the line's block also holds inline widgets above it (code vision).
const coords = view.coordsAtPos(line.from, 1);
const block = view.lineBlockAt(line.from);
const textTop = coords ? coords.top - scroller.top : block.top + view.documentTop - scroller.top;
return {
top: block.top + (view.documentTop - scroller.top) + view.scrollDOM.scrollTop,
left: content.left - scroller.left + view.scrollDOM.scrollLeft + 4,
height: block.height,
top: textTop + view.scrollDOM.scrollTop,
left: content.left - scroller.left + view.scrollDOM.scrollLeft + (at.gutter ? -20 : 4),
height: coords ? coords.bottom - coords.top : block.height,
gutter: at.gutter,
};
},
write: ({ top, left, height }) => {
write: ({ top, left, height, gutter }) => {
this.dom.style.display = "";
this.dom.classList.toggle("cm-lsp-bulb-gutter", gutter);
this.dom.style.top = `${top}px`;
this.dom.style.left = `${left}px`;
this.dom.style.height = `${Math.min(height, this.view.defaultLineHeight)}px`;
@@ -447,5 +592,5 @@ class FloatingBulb {
const floatingBulb = ViewPlugin.fromClass(FloatingBulb);
export function intentionsExtension(): Extension {
return [bulbField, bulbPlugin, floatingBulb];
return [bulbField, bulbPlugin, floatingBulb, intentionProviders.of(pythonMemberIntentions)];
}
+29
Переглянути файл
@@ -0,0 +1,29 @@
import { describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { _addEditor, _removeEditor, documentSynced, type EditorDocContext } from "@/editor/api";
vi.mock("@/platform/ipc", async (orig) => {
const actual = await orig<typeof import("@/platform/ipc")>();
return { ...actual, isTauri: () => true };
});
const { lspRequest } = await import("./lsp");
describe("lspRequest", () => {
it("waits until open editors' edits reached the backend", async () => {
let synced!: () => void;
const pending = new Promise<void>((r) => (synced = r));
const view = new EditorView({ state: EditorState.create({ extensions: documentSynced.of(() => pending) }) });
const handle = { view, ctx: {} as EditorDocContext };
_addEditor(handle);
const run = vi.fn(async () => ({ status: "ok" as const, data: 1 }));
const result = lspRequest(run);
await Promise.resolve();
expect(run).not.toHaveBeenCalled();
synced();
expect(await result).toBe(1);
_removeEditor(handle);
view.destroy();
});
});
+7 -2
Переглянути файл
@@ -1,7 +1,7 @@
/** Shared plumbing: per-editor document facet, IPC wrapper and error policy. */
import { Facet } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import type { EditorDocContext } from "@/editor/api";
import { whenAllSynced, type EditorDocContext } from "@/editor/api";
import { IpcError, call, isCancelled, isTauri } from "@/platform/ipc";
import type { IdeError } from "@/bindings";
import { showHint } from "./hint";
@@ -20,10 +20,15 @@ type Result<T> = { status: "ok"; data: T } | { status: "error"; error: IdeError
/**
* Runs an LSP command. Synchronous throws (no Tauri runtime in a plain browser)
* become `unavailable` rejections so callers have a single error path.
* `wanted` is checked once pending edits are synced: a request cancelled
* meanwhile is not sent (the backend ignores cancelling an id it hasn't seen).
*/
export async function lspRequest<T>(run: () => Promise<Result<T>>): Promise<T> {
export async function lspRequest<T>(run: () => Promise<Result<T>>, wanted?: () => boolean): Promise<T> {
if (!isTauri()) throw new IpcError({ kind: "unavailable", message: "No language server available" });
try {
// Edits typed just before (⌘B right after typing) must reach the server first.
await whenAllSynced();
if (wanted && !wanted()) throw new IpcError({ kind: "cancelled", message: "cancelled" });
return await call(run());
} catch (e) {
if (e instanceof IpcError) throw e;
+20 -1
Переглянути файл
@@ -128,6 +128,22 @@ export function pinToFind(symbol: string, locations: readonly Location[]) {
};
}
/** When each editor's document last changed (`performance.now()`). */
const editedAt = new WeakMap<EditorView, number>();
/**
* Some servers analyse an edit asynchronously and answer from the previous
* version meanwhile (kotlin-language-server: nothing for ~300 ms after typing).
* An empty answer right after an edit is asked again a few times.
*/
async function gotoAfterEdits(view: EditorView, request: () => Promise<DeclarationTarget[]>) {
for (let attempt = 0; ; attempt++) {
const locs = await request();
if (locs.length || attempt >= 3 || performance.now() - (editedAt.get(view) ?? -Infinity) > 1500) return locs;
await new Promise((r) => setTimeout(r, 250));
}
}
export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number) {
const offset = at ?? view.state.selection.main.head;
if (kind === "definition" || kind === "declaration") {
@@ -142,7 +158,7 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number)
const declaration = kind === "definition" || kind === "declaration";
let serverDown = false;
try {
locs = dedupeLocations(await lspRequest(() => commands.lspGoto(doc.doc, pos, kind)));
locs = dedupeLocations(await gotoAfterEdits(view, () => lspRequest(() => commands.lspGoto(doc.doc, pos, kind))));
} catch (e) {
if (isCancelled(e) || !declaration) {
reportLspError(view, e, true);
@@ -630,6 +646,9 @@ const highlightPlugin = ViewPlugin.fromClass(
export function navigationExtension(): Extension {
return [
EditorView.updateListener.of((u) => {
if (u.docChanged) editedAt.set(u.view, performance.now());
}),
linkField,
linkPlugin,
highlightField,
+72
Переглянути файл
@@ -0,0 +1,72 @@
import { describe, expect, it } from "vitest";
import { classMembers, enclosingClass, memberStubs } from "./pythonMembers";
const src = `from abc import ABC, abstractmethod
class Shape(ABC):
@property
@abstractmethod
def name(self) -> str: ...
@abstractmethod
def area(
self, scale: float = 1.0
) -> float:
"""Area."""
def describe(self) -> str:
return self.name
class Square(Shape):
def __init__(self, side: float):
self.side = side
`.split("\n");
describe("python members", () => {
it("finds the class enclosing a line", () => {
expect(enclosingClass(src, 4)).toBe(4);
expect(enclosingClass(src, 13)).toBe(4);
expect(enclosingClass(src, 21)).toBe(19);
expect(enclosingClass(src, 1)).toBeNull();
});
it("lists methods with their decorators and signatures", () => {
const members = classMembers(src, 4);
expect(members.map((m) => [m.name, m.abstract])).toEqual([
["name", true],
["area", true],
["describe", false],
]);
expect(members[0]!.lines).toEqual(["@property", "def name(self) -> str:"]);
expect(members[1]!.lines).toEqual(["def area(", " self, scale: float = 1.0", ") -> float:"]);
});
it("stops at a nested class without bases", () => {
const nested = ["class Outer(Base):", " class Inner:", " x = 1", ""];
expect(enclosingClass(nested, 3)).toBeNull();
});
it("keeps a body going through an unindented string", () => {
const lines = [
"class A(ABC):",
" @abc.abstractproperty",
" def doc(self):",
' return """',
"text",
'"""',
" @abstractmethod",
" def run(self): ...",
"x = 1",
];
const members = classMembers(lines, 1);
expect(members.map((m) => m.lines)).toEqual([["@property", "def doc(self):"], ["def run(self):"]]);
expect(members.every((m) => m.abstract)).toBe(true);
});
it("writes stubs at the body's indentation", () => {
const [name] = classMembers(src, 4);
expect(memberStubs([name!], " ", " ")).toBe(" @property\n def name(self) -> str:\n pass");
});
});
+209
Переглянути файл
@@ -0,0 +1,209 @@
/**
* Python "Implement abstract methods": Python servers (pyright, basedpyright)
* offer no such code action. The bases of the class at the caret are resolved
* with Go to Declaration; their `@abstractmethod`s the class lacks get stubs
* at the end of its body.
*/
import { indentUnit } from "@codemirror/language";
import type { EditorView } from "@codemirror/view";
import { commands } from "@/platform/ipc";
import type { ContributedIntention } from "@/editor/api";
import { docOf, lspRequest, reportLspError } from "./lsp";
import { offsetToPos } from "./positions";
import { readFileLines } from "./files";
import { showHint } from "./hint";
const CLASS_HEADER = /^(\s*)class\s+\w+\s*\((.*)\)\s*:/;
const CLASS = /^\s*class\s/;
const DEF = /^\s*(?:async\s+)?def\s+(\w+)/;
const indentOf = (line: string) => line.length - line.trimStart().length;
const isPython = (view: EditorView) => docOf(view)?.uiMode === "Python";
/** 1-based number of the class header line enclosing `line` (or on it); null unless it has bases. */
export function enclosingClass(lines: readonly string[], line: number): number | null {
let limit = Infinity;
for (let n = line; n >= 1; n--) {
const text = lines[n - 1]!;
if (!text.trim()) continue;
const indent = indentOf(text);
if (n !== line && indent >= limit) continue;
if (CLASS.test(text)) return CLASS_HEADER.test(text) ? n : null;
limit = Math.min(limit, indent);
if (indent === 0 && n !== line) return null;
}
return null;
}
/** Last 1-based line of the body of the class headed at `header`. */
function bodyEnd(lines: readonly string[], header: number): number {
const indent = indentOf(lines[header - 1]!);
let last = header;
let quote: string | null = null;
for (let n = header + 1; n <= lines.length; n++) {
const text = lines[n - 1]!;
// Lines inside a triple-quoted string belong to it, however indented.
const inString = quote !== null;
for (const q of text.match(/"""|'''/g) ?? []) {
if (quote === null) quote = q;
else if (q === quote) quote = null;
}
if (inString) {
last = n;
continue;
}
if (!text.trim()) continue;
if (indentOf(text) <= indent) break;
last = n;
}
return last;
}
export interface PythonMember {
name: string;
abstract: boolean;
/** Decorators (without `@abstractmethod`) and the signature, dedented. */
lines: string[];
}
/** Methods declared directly in the class headed at `header` (1-based). */
export function classMembers(lines: readonly string[], header: number): PythonMember[] {
const end = bodyEnd(lines, header);
const out: PythonMember[] = [];
let memberIndent = -1;
let decorators: string[] = [];
for (let n = header + 1; n <= end; n++) {
const text = lines[n - 1]!;
if (!text.trim()) continue;
const indent = indentOf(text);
if (memberIndent < 0) memberIndent = indent;
if (indent !== memberIndent) continue;
const trimmed = text.trim();
if (trimmed.startsWith("@")) {
decorators.push(trimmed);
continue;
}
const def = DEF.exec(text);
if (def) {
// The signature may span lines: up to the `:` closing it.
const sig: string[] = [];
let depth = 0;
for (let m = n; m <= end; m++) {
const part = lines[m - 1]!;
sig.push(part.slice(Math.min(memberIndent, indentOf(part))));
for (const ch of part) depth += ch === "(" || ch === "[" ? 1 : ch === ")" || ch === "]" ? -1 : 0;
if (depth <= 0 && /:\s*(#.*)?$|:\s*\.\.\.\s*$|:\s*\S/.test(part)) break;
}
// `def f(self) -> int: ...` keeps only the signature.
sig[sig.length - 1] = sig[sig.length - 1]!.replace(/:\s*(\.\.\.|pass)?\s*(#.*)?$/, ":");
const abstract = decorators.some((d) => /^@(abc\.)?abstract(method|property)\b/.test(d));
out.push({
name: def[1]!,
abstract,
lines: [
...decorators
.filter((d) => !/^@(abc\.)?abstractmethod\b/.test(d))
.map((d) => d.replace(/^@(abc\.)?abstractproperty\b/, "@property")),
...sig,
],
});
}
decorators = [];
}
return out;
}
/** Base class names of a header and where each starts in the line. */
function bases(header: string): Array<{ name: string; col: number }> {
const m = CLASS_HEADER.exec(header);
if (!m) return [];
const start = header.indexOf("(") + 1;
const out: Array<{ name: string; col: number }> = [];
for (const b of m[2]!.matchAll(/(?:^|,)\s*([A-Za-z_][\w.]*)\s*(?=,|$|\[)/g)) {
const name = b[1]!;
if (name === "object" || name.includes("=")) continue;
// The last segment of `abc.ABC`: that's what Go to Declaration resolves.
const col = start + b.index! + b[0].indexOf(name) + name.lastIndexOf(".") + 1;
out.push({ name, col });
}
return out;
}
/** Stub text for `members`, indented by `indent`. */
export function memberStubs(members: readonly PythonMember[], indent: string, unit: string): string {
return members.map((m) => [...m.lines.map((l) => indent + l), `${indent}${unit}pass`].join("\n")).join("\n\n");
}
async function abstractMembersOfBases(view: EditorView, header: number): Promise<PythonMember[]> {
const doc = docOf(view)!;
const state = view.state;
const line = state.doc.line(header);
const out = new Map<string, PythonMember>();
for (const base of bases(line.text)) {
const pos = offsetToPos(state.doc, line.from + base.col);
const [loc] = await lspRequest(() => commands.lspGoto(doc.doc, pos, "definition"));
if (!loc) continue;
const lines = await readFileLines(loc.path);
if (!lines) continue;
const target = enclosingClass(lines, loc.range.start.line + 1);
if (!target) continue;
for (const m of classMembers(lines, target)) if (m.abstract && !out.has(m.name)) out.set(m.name, m);
}
return [...out.values()];
}
/** ⌃I / the intention: stubs for the abstract methods of the bases the class lacks. */
export async function implementPythonAbstractMethods(view: EditorView): Promise<boolean> {
if (!isPython(view)) return false;
const lines = view.state.doc.toJSON();
const header = enclosingClass(lines, view.state.doc.lineAt(view.state.selection.main.head).number);
if (!header) return false;
let abstract: PythonMember[];
try {
abstract = await abstractMembersOfBases(view, header);
} catch (e) {
reportLspError(view, e, true);
return true;
}
const state = view.state;
if (state.doc.toJSON().join("\n") !== lines.join("\n")) return true;
const own = new Set(classMembers(lines, header).map((m) => m.name));
const missing = abstract.filter((m) => !own.has(m.name));
if (!missing.length) {
showHint(view, "No abstract methods to implement");
return true;
}
const end = bodyEnd(lines, header);
const unit = state.facet(indentUnit) || " ";
const bodyLines = [];
for (let n = header + 1; n <= end; n++) if (lines[n - 1]!.trim()) bodyLines.push(n);
const first = bodyLines[0] ? lines[bodyLines[0] - 1]! : null;
const indent = first
? first.slice(0, indentOf(first))
: lines[header - 1]!.slice(0, indentOf(lines[header - 1]!)) + unit;
const stubs = memberStubs(missing, indent, unit);
// A body that is only `pass` / `...` is replaced.
const placeholder = bodyLines.length === 1 && /^\s*(pass|\.\.\.)\s*$/.test(first!);
const changes = !bodyLines.length
? { from: state.doc.line(header).to, insert: `\n${stubs}` }
: placeholder
? { from: state.doc.line(bodyLines[0]!).from, to: state.doc.line(end).to, insert: stubs }
: { from: state.doc.line(end).to, insert: `\n\n${stubs}` };
view.dispatch({ changes, userEvent: "input.complete", scrollIntoView: true });
return true;
}
/** The bulb on a Python class header with bases. */
export function pythonMemberIntentions(view: EditorView): ContributedIntention[] {
if (!isPython(view)) return [];
const line = view.state.doc.lineAt(view.state.selection.main.head);
if (!bases(line.text).length) return [];
return [
{
id: "python.implementAbstract",
label: "Implement abstract methods",
icon: "bulb",
run: () => void implementPythonAbstractMethods(view),
},
];
}
+19
Переглянути файл
@@ -107,6 +107,25 @@ async function fetchSignature(view: EditorView, explicit: boolean) {
}
}
/**
* The caret was left inside the `()` of a completed call whose snippet doesn't
* say whether it takes arguments (jdtls `new ArrayList<>()`): parameter info
* when some signature has parameters, else the caret moves past `)`.
*/
export async function parameterInfoOrLeave(view: EditorView, inside: number) {
const doc = docOf(view);
const state = view.state;
let help: SignatureHelp | null = null;
try {
if (doc) help = await lspRequest(() => commands.lspSignatureHelp(doc.doc, offsetToPos(state.doc, inside)));
} catch {
// No signature help: treated as nothing to fill in.
}
if (view.state.doc !== state.doc || view.state.selection.main.head !== inside) return;
if (help?.signatures.some((sig) => sig.parameters.length)) view.dispatch({ effects: setSignature.of({ pos: inside, help }) });
else view.dispatch({ selection: EditorSelection.cursor(inside + 1) });
}
/** ⌘P or the completion command `editor.action.triggerParameterHints`. */
export function triggerSignatureHelp(view: EditorView, explicit = false) {
void fetchSignature(view, explicit);
+1
Переглянути файл
@@ -447,6 +447,7 @@ describe("modifier-hover navigation recovery", () => {
await vi.advanceTimersByTimeAsync(3001);
cmd.lspGoto.mockReturnValueOnce(ok([target]));
move(view);
await vi.advanceTimersByTimeAsync(0);
expect(cmd.lspGoto).toHaveBeenCalledTimes(2);
} finally {
vi.useRealTimers();
+6 -2
Переглянути файл
@@ -202,7 +202,8 @@ export const lspTheme = EditorView.theme({
".cm-lsp-diag-warning .cm-lsp-diag-icon": { color: "var(--warning)" },
".cm-lsp-diag-info .cm-lsp-diag-icon, .cm-lsp-diag-hint .cm-lsp-diag-icon": { color: "var(--info)" },
".cm-lsp-diag-message": { color: "var(--fg-strong)", whiteSpace: "pre-wrap", lineHeight: "18px" },
".cm-lsp-diag-meta": { display: "flex", gap: "12px", marginTop: "6px", alignItems: "baseline" },
".cm-lsp-diag-meta": { display: "flex", flexWrap: "wrap", columnGap: "12px", rowGap: "2px", marginTop: "6px", alignItems: "baseline" },
".cm-lsp-diag-meta > *": { whiteSpace: "nowrap" },
".cm-lsp-diag-source": { color: "var(--fg-subtle)", fontSize: "var(--fs-small)" },
".cm-lsp-link-button": {
border: "none",
@@ -311,9 +312,12 @@ export const lspTheme = EditorView.theme({
color: "var(--fg-bulb, var(--warning))",
cursor: "pointer",
},
// Above the sticky gutters (z-index 200).
".cm-lsp-bulb-gutter": { zIndex: "201", backgroundColor: "var(--bg-editor-gutter, var(--bg-editor))" },
".cm-lsp-bulb .cm-openidea-icon": { display: "inline-flex", borderRadius: "var(--radius-small)", padding: "1px" },
".cm-lsp-bulb:hover .cm-openidea-icon": { backgroundColor: "var(--bg-toolbar-hover)" },
".cm-lsp-bulb-fix": { color: "var(--danger)" },
".cm-lsp-bulb .cm-lsp-bulb-fix-icon, .cm-lsp-bulb-fix .cm-openidea-icon:first-child": { display: "none" },
".cm-lsp-bulb-fix .cm-lsp-bulb-fix-icon": { display: "inline-flex" },
// --- inlay hints (rounded grey chips) -------------------------------------
".cm-lsp-inlay": {
+2 -4
Переглянути файл
@@ -14,7 +14,7 @@ import { RangeSet, StateEffect, StateField, type Extension, type Text } from "@c
import { EditorView, GutterMarker, ViewPlugin, gutter, type ViewUpdate } from "@codemirror/view";
import type { EditorDocContext } from "@/editor/api";
import { docOf, debounce, isUnavailable, lspRequest } from "@/editor/lsp/lsp";
import { serverBackoff } from "@/editor/lsp/availability";
import { onServerSettled, serverBackoff } from "@/editor/lsp/availability";
import { readManyFileLines, withDocument } from "@/editor/lsp/files";
import { locationItems, navigateTo, pinToFind } from "@/editor/lsp/navigation";
import { openPopup } from "@/editor/lsp/popupStore";
@@ -22,7 +22,6 @@ import {
commands,
isCancelled,
nextRequestId,
onIdeEvent,
type HierarchyItem,
type Location,
type OutlineItem,
@@ -241,8 +240,7 @@ class MarkersPlugin {
if (s.settings !== prev.settings) this.refresh();
});
// Answers given while a server was starting or indexing may be incomplete.
this.offServers = onIdeEvent("languageServer", (e) => {
if (e.status !== "ready") return;
this.offServers = onServerSettled(() => {
this.invalidate();
this.refresh();
});
+5 -2
Переглянути файл
@@ -5,7 +5,7 @@ import { getAction, executeAction } from "@/platform/actions";
import { BarButton, Button, IconButton, Popup, T } from "@/ui";
import { downloadJdkActions } from "@/platform/jdk";
import { relativePath, useProject } from "@/platform/project";
import { STATUS_LABEL, restartServer, serversSummary, useServers } from "./servers";
import { STATUS_LABEL, restartServer, servedByOther, serversSummary, useServers } from "./servers";
import styles from "./ServerStatus.module.css";
import { tx } from "@/platform/i18n";
@@ -49,7 +49,10 @@ export function ServerStatus() {
return (
<div key={s.id} className={styles.server}>
<div className={styles.line}>
<span className={clsx(styles.dot, styles[toneOf(s.status)])} aria-hidden />
<span
className={clsx(styles.dot, styles[s.status === "missing" && servedByOther(s, servers) ? "idle" : toneOf(s.status)])}
aria-hidden
/>
<span className={styles.name}>{s.name}</span>
<span className={styles.status}>{STATUS_LABEL[s.status]}</span>
<span className={styles.spacer} />
+16 -1
Переглянути файл
@@ -20,7 +20,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
const { emitLocalIdeEvent } = await import("@/platform/ipc");
const { useProject } = await import("@/platform/project");
const { installServerEvents, useServers } = await import("./servers");
const { installServerEvents, serversSummary, useServers } = await import("./servers");
describe("server status", () => {
let dispose = () => {};
@@ -40,3 +40,18 @@ describe("server status", () => {
expect(useServers.getState().servers.get(id)).toMatchObject({ status: "missing", message: "install jdtls" });
});
});
describe("serversSummary", () => {
const entry = (id: number, name: string, status: ServerInfo["status"]) => ({
id: id as ServerId,
name,
status,
message: null,
languages: ["typescript"],
root: "/p",
});
it("doesn't flag a missing server whose languages another one serves", () => {
expect(serversSummary([entry(1, "vtsls", "missing"), entry(2, "typescript-language-server", "ready")])?.tone).toBe("ok");
expect(serversSummary([entry(1, "vtsls", "missing")])?.tone).toBe("error");
});
});
+14 -1
Переглянути файл
@@ -129,10 +129,23 @@ export const STATUS_LABEL: Record<ServerStatus, string> = {
misconfigured: "Not started",
};
/**
* A missing server whose languages another installed one serves (vtsls missing,
* typescript-language-server running as its fallback) is not a problem.
*/
export function servedByOther(server: ServerEntry, servers: readonly ServerEntry[]): boolean {
return (
server.languages.length > 0 &&
server.languages.every((l) => servers.some((o) => o !== server && o.status !== "missing" && o.languages.includes(l)))
);
}
/** One-line summary for the status bar. */
export function serversSummary(servers: readonly ServerEntry[]): { text: string; tone: "ok" | "busy" | "error" | "idle" } | null {
if (!servers.length) return null;
const bad = servers.filter((s) => s.status === "crashed" || s.status === "missing" || s.status === "misconfigured");
const bad = servers.filter(
(s) => s.status === "crashed" || s.status === "misconfigured" || (s.status === "missing" && !servedByOther(s, servers)),
);
const busy = servers.filter((s) => s.status === "starting" || s.status === "busy");
const tone = bad.length ? "error" : busy.length ? "busy" : servers.some((s) => s.status === "ready") ? "ok" : "idle";
const names = [...new Set(servers.map((s) => s.name))];
+13
Переглянути файл
@@ -28,14 +28,17 @@ import { useEffectiveRoots } from "@/platform/projectRoots";
import { macStroke, strokeOf } from "@/platform/keymap";
import { prepareMenuGroups, useFileDecoration } from "@/workbench/contributions";
import {
FILES_DRAG,
HighlightedText,
Icon,
Popup,
dragSession,
Tree,
acquirePopup,
fileIconName,
folderIconName,
showContextMenu,
type DragSession,
type TreeHandle,
type TreeRowState,
} from "@/ui";
@@ -443,6 +446,8 @@ export function ProjectView() {
startY = e.clientY;
let active = false;
let paths: string[] = [];
// Files (not folders) can also be dropped on an editor to open them there.
let files: DragSession | null = null;
const move = (ev: PointerEvent) => {
if (!active) {
if (Math.hypot(ev.clientX - startX, ev.clientY - startY) < DRAG_THRESHOLD) return;
@@ -454,10 +459,14 @@ export function ProjectView() {
const nodes = keys.map((k) => m.byKey.get(k)).filter((n): n is ProjectNode => !!n && !n.root && !n.placeholder);
paths = nodes.map((n) => n.path);
if (!paths.length) return cleanup();
const filePaths = nodes.filter((n) => !n.dir).map((n) => n.path);
if (filePaths.length) files = dragSession({ type: FILES_DRAG, payload: filePaths.join("\n") });
}
const target = folderAt(containerRef.current, ev.clientX, ev.clientY);
const valid = target && !paths.some((p) => target.path === p || isInside(target.path, p));
setDropTarget(valid ? target.key : null);
if (target) files?.cancel();
else files?.move(ev.clientX, ev.clientY);
setDrag({
paths,
label: paths.length === 1 ? nameOf(paths[0]!) : tx`${paths.length} items`,
@@ -469,8 +478,11 @@ export function ProjectView() {
const up = (ev: PointerEvent) => {
const target = active ? folderAt(containerRef.current, ev.clientX, ev.clientY) : null;
const valid = target && !paths.some((p) => target.path === p || isInside(target.path, p));
const session = files;
files = null;
cleanup();
if (active && valid) void dropPaths(paths, target.path, ev.altKey);
else if (active && !target) session?.drop(ev.clientX, ev.clientY);
};
const key = (ev: KeyboardEvent) => {
if (ev.key === "Escape" && active) {
@@ -483,6 +495,7 @@ export function ProjectView() {
window.removeEventListener("pointermove", move);
window.removeEventListener("pointerup", up);
window.removeEventListener("keydown", key, true);
files?.cancel();
setDropTarget(null);
setDrag(null);
};
+27
Переглянути файл
@@ -53,6 +53,33 @@ describe("settings staging", () => {
expect(pendingChanges(s())).toHaveLength(1);
});
it("stages entries of map settings and fields inside them", () => {
const page = "languages.servers";
const s = () => useSettingsDialog.getState();
// A field of an entry nobody has set yet; reading the map shows it.
stage(page, "global", "languageServers.rust-analyzer.args", ["--log"]);
expect(stagedValue(s(), "global", "languageServers")).toEqual({ "rust-analyzer": { args: ["--log"] } });
// Cleared again: nothing to write.
stage(page, "global", "languageServers.rust-analyzer.args", null);
expect(pendingChanges(s())).toEqual([]);
// A new entry, then an edit inside it: one write of the whole entry.
stage(page, "global", "languageServers.ruff", { command: "ruff", languages: ["python"] });
stage(page, "global", "languageServers.ruff.args", ["server"]);
stage(page, "global", "languageServers.ruff.command", null);
expect(stagedValue(s(), "global", "languageServers.ruff.args")).toEqual(["server"]);
expect(pendingChanges(s()).map((c) => [c.key, c.value])).toEqual([
["languageServers.ruff", { languages: ["python"], args: ["server"] }],
]);
// Removing an entry drops the edits staged inside it.
stage(page, "global", "languageServers.gopls.env", { GOFLAGS: "-mod=mod" });
stage(page, "global", "languageServers.gopls", null);
stage(page, "global", "languageServers.ruff", null);
expect(pendingChanges(s())).toEqual([]);
expect(stagedValue(s(), "global", "languageServers")).toEqual({});
});
it("opens Settings for New Projects on request", () => {
expect(useSettingsDialog.getState().newProjects).toBe(false);
openSettings("languages.java", { newProjects: true });
+3 -9
Переглянути файл
@@ -8,6 +8,7 @@
import { executeAction, type Action } from "@/platform/actions";
import { call, commands, isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { setDragRequiresAlt } from "@/ui";
import { ZOOM_LIMITS } from "./model/behaviorSchema";
import { DEFAULT_SETTINGS, validateSettings, type ValidSettings } from "./model/schema";
@@ -126,16 +127,9 @@ export function zoomActions(): Action[] {
// ---------------------------------------------------------------------------
// Drag-and-drop with Alt pressed only (tool window buttons and editor tabs)
const DRAG_SOURCES = "[data-stripe-button], [role='tab']";
export function installAltDragGuard(enabled: () => boolean): () => void {
const onDragStart = (e: DragEvent) => {
if (!enabled() || e.altKey) return;
const el = e.target instanceof Element ? e.target : null;
if (el?.closest(DRAG_SOURCES)) e.preventDefault();
};
document.addEventListener("dragstart", onDragStart, true);
return () => document.removeEventListener("dragstart", onDragStart, true);
setDragRequiresAlt(enabled);
return () => setDragRequiresAlt(() => false);
}
// ---------------------------------------------------------------------------
+21 -1
Переглянути файл
@@ -1,5 +1,6 @@
/** Page context for the form components: which page / scope they edit and the search query. */
import { createContext, useCallback, useContext } from "react";
import { createContext, useCallback, useContext, useMemo } from "react";
import type { SettingsForm } from "@/workbench/contributions";
import { stage, stagedValue, useSettingsDialog, type Scope } from "../model/staging";
import { labelMatches } from "../model/pages";
@@ -23,6 +24,25 @@ export function useSetting<T>(key: string, scopeOverride?: Scope): [T, (value: T
return [value, set];
}
/** `stagedValue` for components; recomputed only when the base or the staged edits change. */
export function useStagedValue(scope: Scope, key: string): unknown {
const base = useSettingsDialog((s) => (scope === "global" ? s.globalBase : s.base));
const staged = useSettingsDialog((s) => s.staged);
return useMemo(() => stagedValue({ base, globalBase: base, staged }, scope, key), [base, staged, scope, key]);
}
/** The form contributed pages edit through (`useSettingsForm`). */
export function useSettingsFormFor(pageId: string, scope: Scope): SettingsForm {
return useMemo(
() => ({
scope,
useValue: (key: string) => useStagedValue(scope, key),
set: (key: string, value: unknown) => stage(pageId, scope, key, value),
}),
[pageId, scope],
);
}
export function useSearchQuery(): string {
return useSettingsDialog((s) => s.query);
}
+45 -42
Переглянути файл
@@ -9,7 +9,7 @@
import { useMemo, useRef, useState } from "react";
import clsx from "clsx";
import { useProject } from "@/platform/project";
import { useSettingsPages, type SettingsPageContribution } from "@/workbench/contributions";
import { SettingsFormContext, useSettingsPages, type SettingsPageContribution } from "@/workbench/contributions";
import {
Dialog,
DialogButtons,
@@ -22,7 +22,7 @@ import {
type TreeHandle,
T,
} from "@/ui";
import { PageContext } from "../components/context";
import { PageContext, useSettingsFormFor } from "../components/context";
import { SearchLabel } from "../components/Form";
import { breadcrumb, buildPageTree, filterPageTree, flatten, groupKey, type PageNode } from "../model/pages";
import {
@@ -102,60 +102,63 @@ function PageHost({
const hasProject = useProject((s) => !!s.project);
const newProjects = useSettingsDialog((s) => s.newProjects);
const spec = page ? builtinSpec(page.id) : undefined;
const projectScope = !!spec?.projectScope && hasProject && !newProjects;
const projectScope = !!(spec?.projectScope ?? page?.projectScope) && hasProject && !newProjects;
const scopeKey = spec?.scopeGroup ?? pageId;
const chosen = useSettingsDialog((s) => s.scopes[scopeKey]) ?? spec?.defaultScope;
const scope: Scope = projectScope && chosen === "project" ? "project" : "global";
// Where a project value is the norm, say what the global one is for.
const globalNote = newProjects || (projectScope && scope === "global" && spec?.defaultScope === "project");
const ctx = useMemo(() => ({ pageId, scope }), [pageId, scope]);
const form = useSettingsFormFor(pageId, scope);
if (!node) return <EmptyState title="Nothing found" icon="search" />;
const Body = page?.component;
return (
<PageContext.Provider value={ctx}>
<div className={styles.pageHeader}>
<div className={styles.crumbs} aria-label={tx("Breadcrumb")}>
{crumbs.map((c, i) => (
<span key={i} className={styles.crumb}>
{i > 0 && <Icon name="chevron-right" size={12} className={styles.crumbSep} />}
<span>
<T>{c}</T>
<SettingsFormContext.Provider value={form}>
<div className={styles.pageHeader}>
<div className={styles.crumbs} aria-label={tx("Breadcrumb")}>
{crumbs.map((c, i) => (
<span key={i} className={styles.crumb}>
{i > 0 && <Icon name="chevron-right" size={12} className={styles.crumbSep} />}
<span>
<T>{c}</T>
</span>
</span>
</span>
))}
))}
</div>
{dirty && (
<button type="button" className={styles.reset} onClick={onReset}>
<T>Reset</T>
</button>
)}
{projectScope && !spec?.ownScopeSwitch && <ScopeSwitch pageId={scopeKey} scope={scope} />}
<span className={styles.history}>
<IconButton icon="arrow-left" title="Back" size="small" disabled={!history.back} onClick={history.back} />
<IconButton
icon="arrow-right"
title="Forward"
size="small"
disabled={!history.forward}
onClick={history.forward}
/>
</span>
</div>
{dirty && (
<button type="button" className={styles.reset} onClick={onReset}>
<T>Reset</T>
</button>
{scope === "project" && (
<div className={styles.scopeNote}>
<Icon name="info" size={14} />
<T>Saved to .openidea/settings.toml in this project; overrides the global value.</T>
</div>
)}
{projectScope && !spec?.ownScopeSwitch && <ScopeSwitch pageId={scopeKey} scope={scope} />}
<span className={styles.history}>
<IconButton icon="arrow-left" title="Back" size="small" disabled={!history.back} onClick={history.back} />
<IconButton
icon="arrow-right"
title="Forward"
size="small"
disabled={!history.forward}
onClick={history.forward}
/>
</span>
</div>
{scope === "project" && (
<div className={styles.scopeNote}>
<Icon name="info" size={14} />
<T>Saved to .openidea/settings.toml in this project; overrides the global value.</T>
{globalNote && (
<div className={styles.scopeNote}>
<Icon name="info" size={14} />
<T>Saved to the global settings: used by new projects and by projects without their own value.</T>
</div>
)}
<div className={styles.pageBody}>
<PageErrorBoundary pageId={pageId}>{Body ? <Body /> : <GroupPage node={node} />}</PageErrorBoundary>
</div>
)}
{globalNote && (
<div className={styles.scopeNote}>
<Icon name="info" size={14} />
<T>Saved to the global settings: used by new projects and by projects without their own value.</T>
</div>
)}
<div className={styles.pageBody}>
<PageErrorBoundary pageId={pageId}>{Body ? <Body /> : <GroupPage node={node} />}</PageErrorBoundary>
</div>
</SettingsFormContext.Provider>
</PageContext.Provider>
);
}
+30 -6
Переглянути файл
@@ -5,12 +5,8 @@
* back to the default (mirrors `ide-core::settings` defaults).
*/
import { DEFAULT_IGNORED_NAMES } from "@/platform/ignoredNames";
import {
validateFileTypeOverrides,
validateFileTypes,
type FileTypeAssociations,
} from "@/platform/fileTypes";
import type { Settings } from "@/platform/ipc";
import { validateFileTypeOverrides, validateFileTypes, type FileTypeAssociations } from "@/platform/fileTypes";
import type { LanguageServerSettings, Settings } from "@/platform/ipc";
import {
DEFAULT_LANGUAGES,
DEFAULT_PROJECT_STRUCTURE,
@@ -86,8 +82,15 @@ export interface ValidSettings extends WorkflowSettings {
inspections: InspectionSettingsValid;
/** Editor › Natural Languages › Spelling. */
spelling: SpellingValid;
/** Executables chosen for language servers / debug adapters, by command. */
tools: Record<string, { path: string }>;
/** Settings › Language Servers, by server name (as the backend sends them). */
languageServers: Record<string, LanguageServerEntry>;
}
/** One `languageServers.<name>` entry; every field optional, like in settings.toml. */
export type LanguageServerEntry = Partial<LanguageServerSettings>;
export interface SpellingValid {
ideWords: string[];
projectWords: string[];
@@ -144,6 +147,8 @@ export const DEFAULT_SETTINGS: ValidSettings = {
projectStructure: DEFAULT_PROJECT_STRUCTURE,
inspections: DEFAULT_INSPECTIONS,
spelling: { ideWords: [], projectWords: [], customDictionaries: [] },
tools: {},
languageServers: {},
...DEFAULT_WORKFLOW,
};
@@ -244,6 +249,15 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
projectStructure: validateProjectStructure(root.projectStructure),
inspections: validateInspections(root.inspections),
spelling: validateSpelling(root.spelling),
tools: Object.fromEntries(
Object.entries(obj(root.tools)).flatMap(([cmd, t]) => {
const path = obj(t).path;
return typeof path === "string" ? [[cmd, { path }]] : [];
}),
),
languageServers: Object.fromEntries(
Object.entries(obj(root.languageServers)).map(([name, ls]) => [name, obj(ls) as LanguageServerEntry]),
),
...validateWorkflow(root),
};
}
@@ -265,6 +279,16 @@ export function setAt<T>(source: T, key: string, value: unknown): T {
return { ...base, [head!]: rest.length ? setAt(base[head!], rest.join("."), value) : value } as T;
}
/** Like `setAt`, but `null` / `undefined` removes the key (as a settings write of `null` does). */
export function putAt<T>(source: T, key: string, value: unknown): T {
const [head, ...rest] = key.split(".");
const base = { ...obj(source) };
if (rest.length) base[head!] = putAt(base[head!], rest.join("."), value);
else if (value == null) delete base[head!];
else base[head!] = value;
return base as T;
}
export function deepEqual(a: unknown, b: unknown): boolean {
if (a === b) return true;
if (typeof a !== typeof b || !a || !b || typeof a !== "object") return false;
+36 -7
Переглянути файл
@@ -6,7 +6,7 @@
import { create } from "zustand";
import { call, commands, isTauri, type Settings } from "@/platform/ipc";
import { loadSettings, useProject } from "@/platform/project";
import { deepEqual, getAt, setAt, validateSettings, type ValidSettings } from "./schema";
import { deepEqual, getAt, putAt, setAt, validateSettings, type ValidSettings } from "./schema";
export type Scope = "global" | "project";
@@ -119,19 +119,48 @@ export function setPageScope(pageId: string, scope: Scope) {
useSettingsDialog.setState((s) => ({ scopes: { ...s.scopes, [pageId]: scope } }));
}
/** Current value of `key` as the page shows it: staged edit, else the effective value. */
const isInside = (key: string, parent: string) => key.startsWith(`${parent}.`);
/**
* Current value of `key` as the page shows it: staged edit, else the effective
* value. Edits staged for a parent (a whole map entry) or inside `key` (one
* field of it) show through too.
*/
export function stagedValue(s: Bases & Pick<SettingsDialogState, "staged">, scope: Scope, key: string): unknown {
const hit = s.staged[stageKey(scope, key)];
return hit ? hit.value : getAt(baseFor(s, scope), key);
if (hit) return hit.value;
const related = Object.values(s.staged).filter(
(c) => c.scope === scope && (isInside(key, c.key) || isInside(c.key, key)),
);
let value = getAt(baseFor(s, scope), key);
for (const c of related.sort((a, b) => a.key.length - b.key.length)) {
value = isInside(key, c.key)
? (getAt(c.value, key.slice(c.key.length + 1)) ?? undefined)
: putAt(value, c.key.slice(key.length + 1), c.value);
}
return value;
}
/**
* Stages `value` for `key`; `null` removes the key on Apply. An edit inside an
* entry staged as a whole (a map entry just added) goes into that entry; a new
* value for `key` drops the edits staged inside it.
*/
export function stage(page: string, scope: Scope, key: string, value: unknown) {
useSettingsDialog.setState((s) => {
const staged = { ...s.staged };
const parent = Object.values(staged).find((c) => c.scope === scope && isInside(key, c.key));
if (parent) {
const merged = putAt(parent.value, key.slice(parent.key.length + 1), value);
staged[stageKey(scope, parent.key)] = { ...parent, value: merged };
return { staged, error: null };
}
for (const [id, c] of Object.entries(staged)) if (c.scope === scope && isInside(c.key, key)) delete staged[id];
const id = stageKey(scope, key);
const next = value === undefined ? null : value;
// Back to the scope's current value: nothing to write.
if (deepEqual(value, getAt(baseFor(s, scope), key))) delete staged[id];
else staged[id] = { scope, key, value, page };
if (deepEqual(next ?? undefined, getAt(baseFor(s, scope), key))) delete staged[id];
else staged[id] = { scope, key, value: next, page };
return { staged, error: null };
});
}
@@ -147,7 +176,7 @@ export function resetPage(page: string) {
/** Writes to perform, global layer first so a project value still wins afterwards. */
export function pendingChanges(s: Bases & Pick<SettingsDialogState, "staged">): StagedChange[] {
return Object.values(s.staged)
.filter((c) => !deepEqual(c.value, getAt(baseFor(s, c.scope), c.key)))
.filter((c) => !deepEqual(c.value ?? undefined, getAt(baseFor(s, c.scope), c.key)))
.sort((a, b) => (a.scope === b.scope ? a.key.localeCompare(b.key) : a.scope === "global" ? -1 : 1));
}
@@ -217,7 +246,7 @@ export async function applySettings(deps?: PersistDeps): Promise<boolean> {
globalBase: useProject.getState().project
? changes
.filter((c) => c.scope === "global" && done.has(stageKey(c.scope, c.key)))
.reduce((g, c) => setAt(g, c.key, c.value), st.globalBase)
.reduce((g, c) => putAt(g, c.key, c.value), st.globalBase)
: base,
staged: Object.fromEntries(Object.entries(st.staged).filter(([k]) => !done.has(k))),
}));
+29 -41
Переглянути файл
@@ -25,7 +25,7 @@
display: flex;
flex: none;
flex-direction: column;
width: 300px;
width: 264px;
min-height: 0;
border-right: 1px solid var(--border);
}
@@ -39,6 +39,13 @@
flex: 1;
min-width: 0;
}
.toolbarSep {
flex: none;
width: 1px;
height: 16px;
margin: 0 2px;
background: var(--border);
}
.segmented {
display: flex;
height: var(--h-control-small);
@@ -111,6 +118,10 @@
outline: none;
background: var(--bg-hover);
}
.rowOff .rowName,
.rowOff .rowLanguages {
color: var(--fg-muted);
}
.rowName {
flex: none;
max-width: 60%;
@@ -162,6 +173,7 @@
gap: 12px;
}
.headerText {
flex: 1;
min-width: 0;
}
.title {
@@ -178,60 +190,36 @@
}
.actions {
display: flex;
flex: none;
align-items: center;
gap: 4px;
}
.fields {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
column-gap: 16px;
row-gap: 8px;
align-items: baseline;
margin-top: 4px;
}
.field {
display: contents;
}
.fieldLabel {
color: var(--fg-secondary);
}
.fieldValue {
min-width: 0;
color: var(--fg);
}
code.fieldValue {
font-family: var(--font-mono);
.linkButton {
padding: 0;
border: 0;
background: none;
color: var(--link);
font: inherit;
font-size: var(--fs-small);
cursor: pointer;
}
.breakAll {
overflow-wrap: anywhere;
.linkButton:hover {
color: var(--link-hover);
text-decoration: underline;
}
.version {
font-variant-numeric: tabular-nums;
}
.pathRow {
display: flex;
align-items: center;
gap: 4px;
}
.pathInput {
flex: 1;
min-width: 0;
.linkButton:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.fieldHint {
margin-top: 2px;
margin-top: -4px;
color: var(--fg-muted);
font-size: var(--fs-small);
}
.fieldError,
.error {
color: var(--danger);
overflow-wrap: anywhere;
}
.fieldError {
margin-top: 2px;
font-size: var(--fs-small);
}
.notice {
padding: 6px 8px;
border-radius: var(--radius-small);
@@ -265,7 +253,7 @@ code.fieldValue {
font-size: var(--fs-small);
}
.log {
margin: 0;
margin: 4px 0 0;
padding: 6px 8px;
max-height: 240px;
overflow: auto;
+189 -159
Переглянути файл
@@ -1,18 +1,23 @@
/**
* Settings › Languages & Frameworks › Language Servers, laid out like the
* Plugins page: language servers and debug adapters in a list on the left,
* the selected tool's location, custom path and install actions on the right.
* Plugins page: language servers and debug adapters in a list on the left
* (+ adds a server of one's own, − removes it), the selected tool's install
* actions and settings on the right. Settings are staged in the dialog and
* written on Apply / OK; installs run right away.
*/
import { useEffect, useId, useMemo, useState, type KeyboardEvent } from "react";
import { useEffect, useMemo, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import type { ToolInfo } from "@/bindings";
import { Badge, Button, EmptyState, IconButton, Input, ProgressBar, SearchField, Spinner, T } from "@/ui";
import { toolsBackend } from "./backend";
import { Badge, Button, EmptyState, IconButton, ProgressBar, SearchField, Spinner, T } from "@/ui";
import { onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useSettingsForm } from "@/workbench/contributions";
import { languageNames, NewServerDialog, ServerSettings, ToolSettings, useLanguageChoices } from "./ServerSettings";
import { serverKey, type ServerEntry } from "./serverConfig";
import {
cancelInstall,
installTool,
refreshTools,
setCustomPath,
STATUS_LABEL,
uninstallTool,
useTools,
@@ -46,6 +51,29 @@ export function filterTools(tools: readonly ToolInfo[], query: string, filter: F
});
}
/** A server added in this dialog, listed before Apply checks its executable. */
function pendingTool(name: string, entry: ServerEntry, languages: string[]): ToolInfo {
return {
name,
displayName: name,
kind: "languageServer",
command: entry.command ?? "",
languages,
status: "missing",
path: null,
version: null,
installMethod: null,
canInstall: false,
unavailableReason: null,
canUninstall: false,
installHint: null,
homepage: null,
customError: null,
defaultArgs: [],
defaultInitializationOptions: null,
};
}
function JobRow({ name, job }: { name: string; job: InstallJob }) {
return (
<div className={styles.job}>
@@ -62,140 +90,117 @@ function JobRow({ name, job }: { name: string; job: InstallJob }) {
);
}
function ToolRow({ tool, selected, onSelect }: { tool: ToolInfo; selected: boolean; onSelect: () => void }) {
function ToolRow({
tool,
selected,
off,
pending,
onSelect,
}: {
tool: ToolInfo;
selected: boolean;
off: boolean;
pending: boolean;
onSelect: () => void;
}) {
return (
<li className={clsx(styles.row, selected && styles.rowSelected)}>
<button
type="button"
className={styles.rowMain}
className={clsx(styles.rowMain, off && styles.rowOff)}
aria-current={selected || undefined}
data-tool={tool.name}
title={`${tool.displayName} — ${tool.languages.join(", ")}`}
onClick={onSelect}
>
<Badge dot tone={STATUS_TONE[tool.status]}>
{STATUS_LABEL[tool.status]}
<Badge dot tone={pending ? "accent" : STATUS_TONE[tool.status]}>
{pending ? tx("New") : STATUS_LABEL[tool.status]}
</Badge>
<span className={styles.rowName}>{tool.displayName}</span>
{pending && (
<span className={styles.kindTag}>
<T>New</T>
</span>
)}
{tool.kind !== "languageServer" && (
<span className={styles.kindTag}>
<T>{KIND_LABEL[tool.kind]}</T>
</span>
)}
{off && (
<span className={styles.kindTag}>
<T>Disabled</T>
</span>
)}
<span className={styles.rowLanguages}>{tool.languages.join(", ")}</span>
</button>
</li>
);
}
/** "Path" field: an executable to launch instead of the detected one, saved when committed. */
function CustomPath({ tool }: { tool: ToolInfo }) {
const id = useId();
const saved = tool.status === "custom" || tool.customError ? (tool.path ?? "") : "";
const [draft, setDraft] = useState<string | null>(null);
const value = draft ?? (tool.status === "custom" ? saved : "");
const commit = async (next: string) => {
setDraft(null);
if (next.trim() !== saved) await setCustomPath(tool.command, next);
};
return (
<div className={styles.field}>
<label className={styles.fieldLabel} htmlFor={id}>
<T>Path</T>
</label>
<div className={styles.fieldValue}>
<span className={styles.pathRow}>
<Input
id={id}
mono
className={styles.pathInput}
value={value}
invalid={!!tool.customError}
placeholder={tool.status !== "custom" && tool.path ? tool.path : "Auto-detect"}
onChange={(e) => setDraft(e.target.value)}
onBlur={() => draft !== null && void commit(draft)}
onKeyDown={(e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") void commit(e.currentTarget.value);
if (e.key === "Escape" && draft !== null) {
e.stopPropagation();
setDraft(null);
}
}}
/>
<IconButton
icon="folder-open"
size="small"
title="Browse…"
onClick={async () => {
const picked = await toolsBackend().chooseExecutable(`Select ${tool.command}`, value || undefined);
if (picked) await commit(picked);
}}
/>
{tool.status === "custom" && (
<IconButton icon="close" size="small" title="Use auto-detected" onClick={() => void commit("")} />
)}
</span>
{tool.customError ? (
<div className={styles.fieldError} role="alert">
{tool.customError}
</div>
) : (
<div className={styles.fieldHint}>
<T>Leave empty to use the IDE-installed copy, else the one on PATH.</T>
</div>
)}
</div>
</div>
);
}
function Details({ tool }: { tool: ToolInfo }) {
function Details({ tool, pending }: { tool: ToolInfo; pending: boolean }) {
const job = useTools((s) => s.jobs[tool.name]);
const last = useTools((s) => s.logs[tool.name]);
const [logOpen, setLogOpen] = useState(false);
const log = job?.lines ?? last?.lines ?? [];
const lastError = !job && last?.error !== "Cancelled" ? last?.error : null;
const busy = !!job;
const manualHint = !tool.canInstall && tool.status === "missing";
// Servers and adapters show the install hint next to their executable.
const manualHint =
!pending &&
!tool.canInstall &&
tool.status === "missing" &&
(tool.unavailableReason ?? (tool.kind === "plugin" ? tool.installHint : null));
return (
<div className={styles.details} aria-label={`${tool.displayName} details`}>
<div className={styles.header}>
<div className={styles.headerText}>
<div className={styles.title}>
<span>{tool.displayName}</span>
<Badge tone={STATUS_TONE[tool.status]}>{STATUS_LABEL[tool.status]}</Badge>
{pending ? (
<Badge tone="accent">
<T>New</T>
</Badge>
) : (
<Badge tone={STATUS_TONE[tool.status]}>{STATUS_LABEL[tool.status]}</Badge>
)}
</div>
<div className={styles.subtitle}>
<T>{KIND_LABEL[tool.kind]}</T>
{tool.languages.length > 0 && <> · {tool.languages.join(", ")}</>}
{tool.version && <> · {tool.version}</>}
{tool.homepage && (
<>
{" · "}
<a href={tool.homepage} target="_blank" rel="noreferrer">
<T>Homepage</T>
</a>
</>
)}
</div>
</div>
</div>
<div className={styles.actions}>
{tool.canInstall && (
<Button
size="small"
variant={tool.status === "missing" ? "primary" : "secondary"}
disabled={busy}
onClick={() => void installTool(tool.name)}
aria-label={
tool.status === "installed" ? tx`Reinstall ${tool.displayName}` : tx`Install ${tool.displayName}`
}
>
{tool.status === "installed" ? "Reinstall" : "Install"}
</Button>
)}
{tool.canUninstall && (
<Button size="small" variant="ghost" disabled={busy} onClick={() => void uninstallTool(tool.name)}>
<T>Uninstall</T>
</Button>
)}
{log.length > 0 && (
<Button size="small" variant="ghost" aria-expanded={logOpen} onClick={() => setLogOpen(!logOpen)}>
{logOpen ? "Hide install log" : "Show install log"}
</Button>
)}
<div className={styles.actions}>
{tool.canInstall && (
<Button
size="small"
variant={tool.status === "missing" ? "primary" : "secondary"}
disabled={busy}
title={
tool.installMethod ? tx`Installs into the IDE's own tools folder via ${tool.installMethod}` : undefined
}
onClick={() => void installTool(tool.name)}
aria-label={
tool.status === "installed" ? tx`Reinstall ${tool.displayName}` : tx`Install ${tool.displayName}`
}
>
{tool.status === "installed" ? "Reinstall" : "Install"}
</Button>
)}
{tool.canUninstall && (
<Button size="small" variant="ghost" disabled={busy} onClick={() => void uninstallTool(tool.name)}>
<T>Uninstall</T>
</Button>
)}
</div>
</div>
{job && <JobRow name={tool.displayName} job={job} />}
{lastError && (
@@ -205,58 +210,31 @@ function Details({ tool }: { tool: ToolInfo }) {
)}
{manualHint && (
<div className={styles.notice} role="note">
{tool.unavailableReason ?? tool.installHint ?? "Install it manually and put it on PATH."}
{manualHint}
</div>
)}
{tool.canInstall && tool.status === "missing" && tool.unavailableReason === null && tool.installMethod && (
<div className={styles.fieldHint}>
<T>Installs into the IDE&apos;s own tools folder via</T> {tool.installMethod}.
{log.length > 0 && (
<div>
<button
type="button"
className={styles.linkButton}
aria-expanded={logOpen}
onClick={() => setLogOpen(!logOpen)}
>
{logOpen ? tx("Hide install log") : tx("Show install log")}
</button>
{logOpen && (
<pre className={styles.log} aria-label={`${tool.displayName} install log`}>
{log.join("\n")}
</pre>
)}
</div>
)}
<div className={styles.fields}>
<div className={styles.field}>
<span className={styles.fieldLabel}>
<T>Command</T>
</span>
<code className={styles.fieldValue}>{tool.command}</code>
</div>
{tool.kind !== "plugin" && <CustomPath key={`${tool.name}:${tool.path ?? ""}`} tool={tool} />}
{tool.status !== "custom" && (
<div className={styles.field}>
<span className={styles.fieldLabel}>
<T>Location</T>
</span>
<code className={clsx(styles.fieldValue, styles.breakAll)}>{tool.path ?? "—"}</code>
</div>
)}
<div className={styles.field}>
<span className={styles.fieldLabel}>
<T>Version</T>
</span>
<span className={clsx(styles.fieldValue, styles.version)}>{tool.version ?? "—"}</span>
</div>
{tool.homepage && (
<div className={styles.field}>
<span className={styles.fieldLabel}>
<T>Homepage</T>
</span>
<a
className={clsx(styles.fieldValue, styles.breakAll)}
href={tool.homepage}
target="_blank"
rel="noreferrer"
>
{tool.homepage}
</a>
</div>
)}
</div>
{logOpen && log.length > 0 && (
<pre className={styles.log} aria-label={`${tool.displayName} install log`}>
{log.join("\n")}
</pre>
{tool.kind === "languageServer" ? (
<ServerSettings tool={tool} pending={pending} />
) : (
tool.kind === "debugger" && <ToolSettings tool={tool} />
)}
</div>
);
@@ -264,20 +242,44 @@ function Details({ tool }: { tool: ToolInfo }) {
export function LanguageServersPage() {
const { tools, loaded, loading, error } = useTools();
const form = useSettingsForm();
const [query, setQuery] = useState("");
const [filter, setFilter] = useState<Filter>("all");
const [selectedName, setSelectedName] = useState<string | null>(null);
const [adding, setAdding] = useState(false);
const known = useLanguageChoices();
const staged = form.useValue("languageServers") as Record<string, ServerEntry> | undefined;
const servers = useMemo(() => staged ?? {}, [staged]);
const applied = useProject((s) => s.settings?.languageServers);
useEffect(() => {
void refreshTools();
// Applied paths and servers change what is found and listed.
return onIdeEvent("settingsChanged", (e) => {
if (!e.key || /^(tools|languageServers)(\.|$)/.test(e.key)) void refreshTools();
});
}, []);
const shown = useMemo(() => filterTools(tools, query, filter), [tools, query, filter]);
// The backend's list, minus servers removed here and plus servers added here (until Apply).
const { all, pending } = useMemo(() => {
const isCustom = (e: ServerEntry | undefined) => (e?.languages?.length ?? 0) > 0;
const list = tools.filter((t) => !isCustom(applied?.[t.name]) || isCustom(servers[t.name]));
const added = new Set<string>();
for (const [name, entry] of Object.entries(servers)) {
if (!isCustom(entry) || list.some((t) => t.name === name)) continue;
list.push(pendingTool(name, entry, languageNames(entry.languages ?? [], known)));
added.add(name);
}
return { all: list, pending: added };
}, [tools, servers, applied, known]);
const shown = useMemo(() => filterTools(all, query, filter), [all, query, filter]);
const ready = shown.filter((t) => t.status !== "missing");
const missing = shown.filter((t) => t.status === "missing");
const ordered = [...ready, ...missing];
const selected = ordered.find((t) => t.name === selectedName) ?? ordered[0] ?? null;
const missingCount = tools.filter((t) => t.status === "missing").length;
const missingCount = all.filter((t) => t.status === "missing").length;
const removable = !!selected && (servers[selected.name]?.languages?.length ?? 0) > 0;
const onListKey = (e: KeyboardEvent<HTMLUListElement>) => {
if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
@@ -296,7 +298,14 @@ export function LanguageServersPage() {
<T>{title}</T> <span className={styles.groupCount}>{list.length}</span>
</li>
{list.map((t) => (
<ToolRow key={t.name} tool={t} selected={t === selected} onSelect={() => setSelectedName(t.name)} />
<ToolRow
key={t.name}
tool={t}
selected={t === selected}
off={servers[t.name]?.enabled === false}
pending={pending.has(t.name)}
onSelect={() => setSelectedName(t.name)}
/>
))}
</>
);
@@ -315,13 +324,15 @@ export function LanguageServersPage() {
<div className={styles.body}>
<div className={styles.side}>
<div className={styles.toolbar}>
<SearchField
className={styles.search}
value={query}
onChange={setQuery}
placeholder="Filter by tool or language"
aria-label="Filter language servers"
<IconButton icon="plus" size="small" title="Add Language Server…" onClick={() => setAdding(true)} />
<IconButton
icon="minus"
size="small"
title="Remove Language Server"
disabled={!removable}
onClick={() => selected && form.set(serverKey(selected.name), null)}
/>
<span className={styles.toolbarSep} aria-hidden />
{loading ? (
<Spinner size={14} label="Checking tools" />
) : (
@@ -332,6 +343,13 @@ export function LanguageServersPage() {
onClick={() => void refreshTools()}
/>
)}
<SearchField
className={styles.search}
value={query}
onChange={setQuery}
placeholder="Filter by tool or language"
aria-label="Filter language servers"
/>
</div>
<div className={styles.segmented} role="radiogroup" aria-label="Show">
{(["all", "missing", "installed"] as const).map((f) => (
@@ -343,7 +361,7 @@ export function LanguageServersPage() {
className={clsx(styles.segment, filter === f && styles.segmentOn)}
onClick={() => setFilter(f)}
>
{f === "all" ? "All" : f === "missing" ? `Missing (${missingCount})` : "Available"}
{f === "all" ? tx("All") : f === "missing" ? tx`Missing (${missingCount})` : tx("Available")}
</button>
))}
</div>
@@ -363,11 +381,23 @@ export function LanguageServersPage() {
</ul>
</div>
{selected ? (
<Details key={selected.name} tool={selected} />
<Details key={selected.name} tool={selected} pending={pending.has(selected.name)} />
) : (
<EmptyState className={styles.detailsEmpty} title={loaded ? "No tool selected" : "Loading…"} />
)}
</div>
{adding && (
<NewServerDialog
existing={all.map((t) => t.name)}
onClose={() => setAdding(false)}
onAdded={(name) => {
setAdding(false);
setFilter("all");
setQuery("");
setSelectedName(name);
}}
/>
)}
</div>
);
}
+188
Переглянути файл
@@ -0,0 +1,188 @@
.form {
display: flex;
flex-direction: column;
gap: 16px;
min-width: 0;
}
/* IDEA titled separator: "Startup ─────────". */
.section {
min-width: 0;
}
.sectionTitle {
display: flex;
align-items: center;
gap: 8px;
height: 22px;
margin-bottom: 4px;
color: var(--fg-strong);
}
.sectionRule {
flex: 1;
height: 1px;
background: var(--border);
}
.sectionToggle {
width: 100%;
padding: 0;
border: 0;
background: none;
font: inherit;
text-align: left;
cursor: pointer;
}
.sectionToggle:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.sectionBody {
display: flex;
flex-direction: column;
gap: 10px;
padding: 4px 0 0 12px;
}
/* Label above a full-width control: the details pane is narrow. */
.row {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
.label {
color: var(--fg);
}
.label::after {
content: ":";
}
.control {
display: flex;
align-items: flex-start;
gap: 4px;
min-width: 0;
}
.hint {
color: var(--fg-subtle);
font-size: var(--fs-small);
line-height: 1.4;
overflow-wrap: anywhere;
}
.note {
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.error {
color: var(--danger);
}
.code {
font-family: var(--font-mono);
}
.grow {
flex: 1;
min-width: 0;
}
.area {
flex: 1;
min-width: 0;
padding: 4px 6px;
border: 0;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border-strong);
background: var(--bg-input);
color: var(--fg);
font-family: var(--font-mono);
font-size: var(--fs-small);
line-height: 1.45;
resize: vertical;
}
.area:focus {
outline: none;
box-shadow: inset 0 0 0 2px var(--accent);
}
.area::placeholder {
color: var(--fg-muted);
}
.invalid,
.invalid:focus {
box-shadow: inset 0 0 0 2px var(--danger);
}
.picker {
display: flex;
flex: 1;
align-items: center;
gap: 6px;
min-width: 0;
height: var(--h-control);
padding: 0 8px;
border: 0;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border-strong);
background: var(--bg-input);
color: var(--fg);
font: inherit;
text-align: left;
}
.picker:focus-visible {
outline: none;
box-shadow: inset 0 0 0 2px var(--accent);
}
.pickerText {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.placeholder {
color: var(--fg-muted);
}
.pickerPopup {
display: flex;
flex-direction: column;
gap: 6px;
width: 260px;
padding: 8px;
}
.pickerList {
display: flex;
flex-direction: column;
gap: 2px;
max-height: 240px;
overflow: auto;
}
.link {
padding: 0;
border: 0;
background: none;
color: var(--link);
font: inherit;
cursor: pointer;
}
.link:hover {
color: var(--link-hover);
text-decoration: underline;
}
.link:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.dialogBody {
display: flex;
flex-direction: column;
gap: 8px;
padding: 12px 16px 4px;
}
/* Dialogs are wide enough for "Label: [control]". */
.dialogBody .row {
display: grid;
grid-template-columns: 90px minmax(0, 1fr);
align-items: center;
column-gap: 8px;
}
.dialogBody .control {
align-items: center;
}
+567
Переглянути файл
@@ -0,0 +1,567 @@
/**
* Settings › Language Servers, right-hand side: the selected tool's executable
* and, for a language server, its startup options and workspace configuration
* (`languageServers.<name>`), plus the New Language Server dialog. Edits are
* staged in the Settings dialog and written on Apply / OK.
*/
import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";
import clsx from "clsx";
import type { ToolInfo } from "@/bindings";
import { Checkbox, Dialog, Icon, IconButton, Input, Popup, SearchField, T } from "@/ui";
import { tx } from "@/platform/i18n";
import { useSettingsForm } from "@/workbench/contributions";
import { toolsBackend, type LanguageChoice } from "./backend";
import {
formatArgs,
formatEnv,
formatJson,
formatList,
nameFromCommand,
parseArgs,
parseEnv,
parseJsonObject,
parseList,
SERVER_NAME,
serverKey,
toolPathKey,
type ServerEntry,
type ServerField,
} from "./serverConfig";
import styles from "./ServerSettings.module.css";
let languageList: Promise<LanguageChoice[]> | null = null;
/** Languages a server can be used for, loaded once. */
export function useLanguageChoices(): LanguageChoice[] {
const [langs, setLangs] = useState<LanguageChoice[]>([]);
useEffect(() => {
let live = true;
languageList ??= toolsBackend()
.languages()
.catch(() => {
languageList = null;
return [];
});
void languageList.then((l) => live && setLangs(l));
return () => {
live = false;
};
}, []);
return langs;
}
/** Test hook: forget the loaded language list. */
export function resetLanguageChoices() {
languageList = null;
}
export function languageNames(ids: readonly string[], known: readonly LanguageChoice[]): string[] {
return ids.map((id) => known.find((l) => l.id === id)?.name ?? id);
}
// ---------------------------------------------------------------------------
// Form building blocks (IDEA layout: "Label: [control]", titled separators)
/** A titled separator; `collapsible` ones fold away like IDEA's hideable separators. */
function Section({
title,
note,
collapsible,
defaultOpen = true,
children,
}: {
title: string;
note?: string;
collapsible?: boolean;
defaultOpen?: boolean;
children: ReactNode;
}) {
const [open, setOpen] = useState(defaultOpen);
const shown = !collapsible || open;
return (
<section className={styles.section} aria-label={tx(title)}>
{collapsible ? (
<button
type="button"
className={clsx(styles.sectionTitle, styles.sectionToggle)}
aria-expanded={open}
onClick={() => setOpen(!open)}
>
<Icon name={open ? "chevron-down" : "chevron-right"} size={12} />
<T>{title}</T>
<span className={styles.sectionRule} aria-hidden />
</button>
) : (
<div className={styles.sectionTitle}>
<T>{title}</T>
<span className={styles.sectionRule} aria-hidden />
</div>
)}
{shown && (
<div className={styles.sectionBody}>
{note && (
<div className={styles.note}>
<T>{note}</T>
</div>
)}
{children}
</div>
)}
</section>
);
}
/** "Label:" above its control (beside it in dialogs), the hint below. */
function Row({
label,
htmlFor,
hint,
children,
}: {
label: string;
htmlFor?: string;
hint?: ReactNode;
children: ReactNode;
}) {
return (
<div className={styles.row}>
<label className={styles.label} htmlFor={htmlFor}>
<T>{label}</T>
</label>
<div className={styles.control}>{children}</div>
{hint && <div className={styles.hint}>{hint}</div>}
</div>
);
}
interface FieldProps<V> {
label: string;
value: V | undefined;
format: (v: V | undefined) => string;
/** Text → value (null removes the setting); throws with a message when invalid. */
parse: (text: string) => V | null;
onChange: (value: V | null) => void;
placeholder?: string;
hint?: ReactNode;
multiline?: boolean;
trailing?: ReactNode;
}
/**
* A text field over a setting: valid text is staged as it is typed; invalid
* text stays in the field, marked, and isn't staged.
*/
function Field<V>({ label, value, format, parse, onChange, placeholder, hint, multiline, trailing }: FieldProps<V>) {
const id = useId();
const [draft, setDraft] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const text = draft ?? format(value);
const change = (next: string) => {
setDraft(next);
try {
onChange(parse(next));
setError(null);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
}
};
const common = {
id,
value: text,
placeholder,
"aria-invalid": error ? true : undefined,
// Valid text is reformatted from the staged value once the field is left.
onBlur: () => !error && setDraft(null),
};
return (
<Row
label={label}
htmlFor={id}
hint={
error ? (
<span className={styles.error} role="alert">
{error}
</span>
) : (
hint
)
}
>
{multiline ? (
<textarea
{...common}
spellCheck={false}
rows={Math.min(14, Math.max(3, text.split("\n").length + 1, (placeholder ?? "").split("\n").length))}
className={clsx(styles.area, error && styles.invalid)}
onChange={(e) => change(e.target.value)}
/>
) : (
<Input {...common} mono invalid={!!error} className={styles.grow} onChange={(e) => change(e.target.value)} />
)}
{trailing}
</Row>
);
}
/** "Python, TypeScript ▾": checkboxes in a popup, with a filter. */
export function LanguagePicker({
id,
value,
onChange,
invalid,
}: {
id?: string;
value: readonly string[];
onChange: (ids: string[]) => void;
invalid?: boolean;
}) {
const known = useLanguageChoices();
const anchor = useRef<HTMLButtonElement>(null);
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const shown = useMemo(() => {
const q = query.trim().toLowerCase();
return q ? known.filter((l) => l.name.toLowerCase().includes(q) || l.id.includes(q)) : known;
}, [known, query]);
const label = languageNames(value, known).join(", ");
return (
<>
<button
id={id}
ref={anchor}
type="button"
aria-haspopup="dialog"
aria-expanded={open}
aria-invalid={invalid || undefined}
className={clsx(styles.picker, invalid && styles.invalid)}
onClick={() => setOpen(!open)}
>
<span className={clsx(styles.pickerText, !label && styles.placeholder)}>
{label || tx("Choose languages…")}
</span>
<Icon name="chevron-down" size={12} />
</button>
<Popup
open={open}
onClose={() => setOpen(false)}
anchor={anchor}
placement="bottom-start"
role="dialog"
aria-label={tx("Languages")}
className={styles.pickerPopup}
>
<SearchField
value={query}
onChange={setQuery}
placeholder="Filter languages"
aria-label="Filter languages"
data-autofocus
/>
<div className={styles.pickerList}>
{shown.map((l) => (
<Checkbox
key={l.id}
checked={value.includes(l.id)}
label={l.name}
onChange={(on) => onChange(on ? [...value, l.id] : value.filter((v) => v !== l.id))}
/>
))}
{shown.length === 0 && (
<div className={styles.note}>
<T>No languages match.</T>
</div>
)}
</div>
</Popup>
</>
);
}
// ---------------------------------------------------------------------------
// The tool's settings
function useServerEntry(name: string): ServerEntry {
const form = useSettingsForm();
return (form.useValue(serverKey(name)) ?? {}) as ServerEntry;
}
/** Where the executable was found, or what is wrong with it. */
function executableHint(tool: ToolInfo, pending: boolean): ReactNode {
if (pending) return <T>Checked when the settings are applied.</T>;
if (tool.customError) return <span className={styles.error}>{tool.customError}</span>;
if (tool.path) {
return (
<>
<T>Using</T> <code className={styles.code}>{tool.path}</code>
{tool.version && <> ({tool.version})</>}
</>
);
}
return tool.installHint ?? <T>Not found on PATH.</T>;
}
function ExecutableRow({ tool, pending }: { tool: ToolInfo; pending: boolean }) {
const form = useSettingsForm();
const entry = useServerEntry(tool.name);
const custom = (entry.languages?.length ?? 0) > 0;
// A server defined in settings names its executable itself; others may point elsewhere.
const key = custom ? serverKey(tool.name, "command") : toolPathKey(tool.command);
const tools = form.useValue("tools") as Record<string, { path: string }> | undefined;
const value = custom ? entry.command : tools?.[tool.command]?.path;
const set = (path: string | null) => {
if (custom || !tool.command.includes(".")) form.set(key, path);
else {
// A command with dots can't be a key segment: replace the map.
const next = { ...tools };
if (path) next[tool.command] = { path };
else delete next[tool.command];
form.set("tools", next);
}
};
return (
<Field<string>
key={key}
label={custom ? "Command" : "Path"}
value={value}
format={(v) => v ?? ""}
parse={(t) => t.trim() || null}
onChange={set}
placeholder={custom ? tx("Executable name or path") : tx("Auto-detect")}
hint={executableHint(tool, pending)}
trailing={
<IconButton
icon="folder-open"
size="small"
title="Browse…"
onClick={async () => {
const picked = await toolsBackend().chooseExecutable(tx`Select ${tool.command || tool.name}`, value);
if (picked) set(picked);
}}
/>
}
/>
);
}
/** Debug adapters: only where the executable is. */
export function ToolSettings({ tool }: { tool: ToolInfo }) {
return (
<Section title="Executable">
<ExecutableRow tool={tool} pending={false} />
</Section>
);
}
/** A language server: on/off, executable, startup options, workspace configuration. */
export function ServerSettings({ tool, pending }: { tool: ToolInfo; pending: boolean }) {
const form = useSettingsForm();
const entry = useServerEntry(tool.name);
const custom = (entry.languages?.length ?? 0) > 0;
const set = (field: ServerField) => (value: unknown) => form.set(serverKey(tool.name, field), value);
const known = useLanguageChoices();
const languagesId = useId();
const languages = custom ? languageNames(entry.languages ?? [], known) : tool.languages;
const defaultOptions = useMemo(() => {
try {
return tool.defaultInitializationOptions ? JSON.parse(tool.defaultInitializationOptions) : null;
} catch {
return null;
}
}, [tool.defaultInitializationOptions]);
const overridden = !custom && Object.keys(entry).length > 0;
return (
<div className={styles.form}>
<Checkbox
checked={entry.enabled !== false}
label={
languages.length ? tx`Use ${tool.displayName} for ${languages.join(", ")} files` : tx`Use ${tool.displayName}`
}
// Enabled is the default; a project says so explicitly to win over a global "off".
onChange={(on) => set("enabled")(on ? (form.scope === "project" ? true : null) : false)}
/>
<Section title="Executable">
<ExecutableRow tool={tool} pending={pending} />
{custom && (
<>
<Row label="Languages" htmlFor={languagesId}>
<LanguagePicker
id={languagesId}
value={entry.languages ?? []}
invalid={!entry.languages?.length}
onChange={(ids) => set("languages")(ids.length ? ids : null)}
/>
</Row>
<Field<string[]>
label="Root markers"
value={entry.rootMarkers}
format={formatList}
parse={parseList}
onChange={set("rootMarkers")}
placeholder="pyproject.toml, .git"
hint={<T>Files marking the workspace root.</T>}
/>
</>
)}
</Section>
<Section
title="Startup"
note="Changing these restarts the server."
collapsible
defaultOpen={!!(entry.args || entry.env || entry.initializationOptions)}
>
<Field<string[]>
label="Arguments"
value={entry.args ?? undefined}
format={formatArgs}
parse={parseArgs}
onChange={set("args")}
placeholder={formatArgs(tool.defaultArgs) || tx("None")}
/>
<Field<Record<string, string>>
label="Environment variables"
value={entry.env}
format={formatEnv}
parse={parseEnv}
onChange={set("env")}
placeholder="NAME=value; OTHER=value"
/>
<Field<Record<string, unknown>>
label="Initialization options"
multiline
value={entry.initializationOptions as Record<string, unknown> | undefined}
format={formatJson}
parse={parseJsonObject}
onChange={set("initializationOptions")}
placeholder={defaultOptions ? formatJson(defaultOptions) : '{ "key": "value" }'}
hint={defaultOptions ? <T>Merged over the defaults shown when empty.</T> : undefined}
/>
</Section>
<Section
title="Workspace Configuration"
note="Sent to the running server; no restart needed."
collapsible
defaultOpen={!!entry.settings}
>
<Field<Record<string, unknown>>
label="Settings"
multiline
value={entry.settings as Record<string, unknown> | undefined}
format={formatJson}
parse={parseJsonObject}
onChange={set("settings")}
placeholder={'{ "section": { "key": "value" } }'}
/>
</Section>
{overridden && (
<div>
<button type="button" className={styles.link} onClick={() => form.set(serverKey(tool.name), null)}>
<T>Restore Defaults</T>
</button>
</div>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// New Language Server
/** Asks for a name, command and languages; stages the new server on OK. */
export function NewServerDialog({
existing,
onClose,
onAdded,
}: {
existing: readonly string[];
onClose: () => void;
onAdded: (name: string) => void;
}) {
const form = useSettingsForm();
const ids = { name: useId(), command: useId(), languages: useId() };
const [commandLine, setCommandLine] = useState("");
const [name, setName] = useState<string | null>(null);
const [languages, setLanguages] = useState<string[]>([]);
// "ruff server": the executable, then its arguments.
let words: string[] = [];
let quoteError: string | null = null;
try {
words = parseArgs(commandLine) ?? [];
} catch (e) {
quoteError = e instanceof Error ? e.message : String(e);
}
const [command = "", ...args] = words;
const effectiveName = (name ?? nameFromCommand(command)).trim();
const problem =
quoteError ??
(!command
? tx("Enter the command that starts the server.")
: !SERVER_NAME.test(effectiveName)
? tx("Name: letters, digits, - _ + only.")
: existing.includes(effectiveName)
? tx`${effectiveName} already exists.`
: !languages.length
? tx("Choose the languages it serves.")
: null);
const add = () => {
if (problem) return;
const entry: ServerEntry = { command, languages };
if (args.length) entry.args = args;
form.set(serverKey(effectiveName), entry);
onAdded(effectiveName);
};
return (
<Dialog
open
onClose={onClose}
title={tx("New Language Server")}
width={480}
buttons={[
{ label: "OK", role: "default", disabled: !!problem, title: problem ?? undefined, onClick: add },
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.dialogBody}>
<Row label="Command" htmlFor={ids.command}>
<Input
id={ids.command}
mono
autoFocus
className={styles.grow}
value={commandLine}
placeholder="ruff server"
onChange={(e) => setCommandLine(e.target.value)}
/>
<IconButton
icon="folder-open"
size="small"
title="Browse…"
onClick={async () => {
const picked = await toolsBackend().chooseExecutable(tx("Select the server executable"), command);
if (picked) setCommandLine(formatArgs([picked, ...args]));
}}
/>
</Row>
<Row label="Name" htmlFor={ids.name}>
<Input
id={ids.name}
mono
className={styles.grow}
value={name ?? nameFromCommand(command)}
onChange={(e) => setName(e.target.value)}
/>
</Row>
<Row label="Languages" htmlFor={ids.languages}>
<LanguagePicker id={ids.languages} value={languages} onChange={setLanguages} />
</Row>
<div className={styles.note}>
{problem ?? <T>Any language server that talks LSP over stdio, with its arguments.</T>}
</div>
</div>
</Dialog>
);
}
+169
Переглянути файл
@@ -0,0 +1,169 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useProject } from "@/platform/project";
import { provideNotificationService } from "@/workbench/contributions";
import { MemoryToolsBackend, sampleTools, setToolsBackend } from "../backend";
import { LanguageServersPage } from "../LanguageServersPage";
import { resetLanguageChoices } from "../ServerSettings";
import { useTools } from "../store";
import { formatArgs, nameFromCommand, parseArgs, parseEnv, parseJsonObject, parseList } from "../serverConfig";
import { resetTestForm, stagedFor, TestSettingsForm, useTestForm } from "./settingsForm";
describe("server settings text fields", () => {
it("splits arguments like a shell and formats them back", () => {
expect(parseArgs(`--stdio --log "a b" 'c"d' e\\ f`)).toEqual(["--stdio", "--log", "a b", 'c"d', "e f"]);
expect(parseArgs(" ")).toBeNull();
expect(parseArgs('""')).toEqual([""]);
expect(() => parseArgs('"open')).toThrow(/Unclosed/);
const args = ["--x", "a b", 'q"t', ""];
expect(parseArgs(formatArgs(args))).toEqual(args);
});
it("parses environment variables separated by semicolons", () => {
expect(parseEnv("A=1; B_2 = x=y;\n C=")).toEqual({ A: "1", B_2: "x=y", C: "" });
expect(parseEnv(" ; ")).toBeNull();
expect(() => parseEnv("A=1; nope")).toThrow("Expected NAME=value: nope");
});
it("accepts JSON objects without nulls", () => {
expect(parseJsonObject('{ "a": { "b": [1] } }')).toEqual({ a: { b: [1] } });
expect(parseJsonObject(" ")).toBeNull();
expect(() => parseJsonObject("[1]")).toThrow("Expected a JSON object");
expect(() => parseJsonObject('{ "a": { "b": null } }')).toThrow("at a.b");
expect(() => parseJsonObject("{")).toThrow();
});
it("splits lists and names servers after their executable", () => {
expect(parseList("python, typescript python")).toEqual(["python", "typescript"]);
expect(parseList(",")).toBeNull();
expect(nameFromCommand("/opt/bin/ruff")).toBe("ruff");
expect(nameFromCommand("C:\\tools\\my server.exe")).toBe("my-server");
});
});
describe("Language Servers page settings", () => {
let backend: MemoryToolsBackend;
const listItem = (name: string) =>
screen.getByRole("list", { name: /language servers/i }).querySelector<HTMLElement>(`[data-tool="${name}"]`);
const details = (name: string) => screen.getByLabelText(`${name} details`);
const renderPage = () =>
render(
<TestSettingsForm>
<LanguageServersPage />
</TestSettingsForm>,
);
beforeEach(() => {
provideNotificationService({ notify: () => {} });
backend = new MemoryToolsBackend(
sampleTools().map((t) =>
t.name === "rust-analyzer"
? { ...t, defaultArgs: ["--stdio"], defaultInitializationOptions: '{"checkOnSave":true}' }
: t,
),
1,
);
setToolsBackend(backend);
resetLanguageChoices();
resetTestForm();
useTools.setState({ tools: [], loaded: false, loading: false, error: null, jobs: {}, logs: {} });
useProject.setState({ project: null, settings: null });
});
afterEach(() => setToolsBackend(null));
it("stages startup options, showing the defaults they replace", async () => {
const user = userEvent.setup();
renderPage();
const pane = await screen.findByLabelText("rust-analyzer details");
// Folded while nothing is set there.
expect(within(pane).queryByRole("textbox", { name: "Arguments" })).toBeNull();
await user.click(within(pane).getByRole("button", { name: "Startup" }));
const args = within(pane).getByRole("textbox", { name: "Arguments" });
expect(args).toHaveAttribute("placeholder", "--stdio");
expect(within(pane).getByRole("textbox", { name: "Initialization options" })).toHaveAttribute(
"placeholder",
JSON.stringify({ checkOnSave: true }, null, 2),
);
await user.type(args, '--log "a b"');
expect(stagedFor("languageServers.rust-analyzer.args")).toEqual(["--log", "a b"]);
await user.type(within(pane).getByRole("textbox", { name: "Environment variables" }), "RA_LOG=info");
expect(stagedFor("languageServers.rust-analyzer.env")).toEqual({ RA_LOG: "info" });
// Invalid JSON is marked and not staged; valid JSON is.
const init = within(pane).getByRole("textbox", { name: "Initialization options" });
await user.click(init);
await user.paste('{ "check": null }');
expect(within(pane).getByRole("alert")).toHaveTextContent("null is not supported");
expect(stagedFor("languageServers.rust-analyzer.initializationOptions")).toBeUndefined();
await user.clear(init);
await user.paste('{ "check": { "command": "clippy" } }');
expect(stagedFor("languageServers.rust-analyzer.initializationOptions")).toEqual({ check: { command: "clippy" } });
// Turned off: marked in the list.
await user.click(within(pane).getByRole("checkbox", { name: /Use rust-analyzer for Rust files/ }));
expect(stagedFor("languageServers.rust-analyzer.enabled")).toBe(false);
expect(listItem("rust-analyzer")).toHaveTextContent("Disabled");
await user.click(within(pane).getByRole("button", { name: "Restore Defaults" }));
expect(stagedFor("languageServers.rust-analyzer")).toBeNull();
expect(listItem("rust-analyzer")).not.toHaveTextContent("Disabled");
expect(args).toHaveValue("");
});
it("adds a server of one's own from its command line, then removes it", async () => {
const user = userEvent.setup();
renderPage();
await screen.findByLabelText("rust-analyzer details");
await user.click(screen.getByRole("button", { name: "Add Language Server…" }));
const dialog = screen.getByRole("dialog", { name: "New Language Server" });
const ok = within(dialog).getByRole("button", { name: "OK" });
await user.type(within(dialog).getByRole("textbox", { name: "Command" }), "/opt/bin/ruff server");
expect(within(dialog).getByRole("textbox", { name: "Name" })).toHaveValue("ruff");
expect(ok).toBeDisabled();
expect(dialog).toHaveTextContent("Choose the languages it serves.");
const picker = within(dialog).getByRole("button", { name: "Languages" });
expect(picker).toHaveTextContent("Choose languages…");
await user.click(picker);
await user.click(await screen.findByRole("checkbox", { name: "Python" }));
await user.keyboard("{Escape}");
expect(picker).toHaveTextContent("Python");
await user.click(ok);
expect(stagedFor("languageServers.ruff")).toEqual({
command: "/opt/bin/ruff",
args: ["server"],
languages: ["python"],
});
// Listed and selected before Apply, as a new server.
await waitFor(() => expect(listItem("ruff")).toHaveAttribute("aria-current", "true"));
expect(listItem("ruff")).toHaveTextContent("New");
const pane = details("ruff");
expect(within(pane).getByRole("textbox", { name: "Command" })).toHaveValue("/opt/bin/ruff");
expect(within(pane).getByRole("textbox", { name: "Arguments" })).toHaveValue("server");
expect(pane).toHaveTextContent("Checked when the settings are applied.");
// Edits go into the staged entry.
await user.type(within(pane).getByRole("textbox", { name: "Root markers" }), "pyproject.toml");
expect(useTestForm.getState().values).toMatchObject({
languageServers: { ruff: { rootMarkers: ["pyproject.toml"] } },
});
await user.click(screen.getByRole("button", { name: "Remove Language Server" }));
expect(stagedFor("languageServers.ruff")).toBeNull();
expect(listItem("ruff")).toBeNull();
});
it("keeps the remove button for servers of one's own", async () => {
const user = userEvent.setup();
resetTestForm({ languageServers: { ruff: { command: "ruff", languages: ["python"] } } });
renderPage();
await screen.findByLabelText("rust-analyzer details");
expect(screen.getByRole("button", { name: "Remove Language Server" })).toBeDisabled();
await user.click(listItem("ruff")!);
expect(screen.getByRole("button", { name: "Remove Language Server" })).toBeEnabled();
});
});
+48
Переглянути файл
@@ -0,0 +1,48 @@
/** A Settings dialog stand-in: a page's form over plain values, staging into `staged`. */
import { useMemo, type ReactNode } from "react";
import { create } from "zustand";
import { SettingsFormContext, type SettingsForm } from "@/workbench/contributions";
interface FormState {
values: Record<string, unknown>;
/** Staged writes in order, as `settingsSet` would get them on Apply. */
staged: Array<[string, unknown]>;
}
export const useTestForm = create<FormState>(() => ({ values: {}, staged: [] }));
const getAt = (v: unknown, key: string) =>
key
.split(".")
.reduce<unknown>((cur, k) => (cur && typeof cur === "object" ? (cur as Record<string, unknown>)[k] : undefined), v);
function putAt(source: unknown, key: string, value: unknown): Record<string, unknown> {
const [head, ...rest] = key.split(".");
const base = { ...(source as Record<string, unknown> | undefined) };
if (rest.length) base[head!] = putAt(base[head!], rest.join("."), value);
else if (value == null) delete base[head!];
else base[head!] = value;
return base;
}
export function resetTestForm(values: Record<string, unknown> = {}) {
useTestForm.setState({ values, staged: [] });
}
/** The last value staged for `key`. */
export function stagedFor(key: string): unknown {
return useTestForm.getState().staged.findLast(([k]) => k === key)?.[1];
}
export function TestSettingsForm({ children }: { children: ReactNode }) {
const form = useMemo<SettingsForm>(
() => ({
scope: "global",
useValue: (key) => useTestForm((s) => getAt(s.values, key)),
set: (key, value) =>
useTestForm.setState((s) => ({ values: putAt(s.values, key, value), staged: [...s.staged, [key, value]] })),
}),
[],
);
return <SettingsFormContext.Provider value={form}>{children}</SettingsFormContext.Provider>;
}
+24 -13
Переглянути файл
@@ -8,6 +8,7 @@ import { MemoryToolsBackend, sampleTools, setToolsBackend } from "../backend";
import { cancelInstall, installTool, refreshTools, uninstallTool, useTools } from "../store";
import { filterTools, LanguageServersPage } from "../LanguageServersPage";
import { installMissingServerPrompts, missingKey } from "../missing";
import { resetTestForm, stagedFor, TestSettingsForm } from "./settingsForm";
type Note = Parameters<NotificationService["notify"]>[0];
let notes: Note[];
@@ -126,12 +127,19 @@ describe("missing language server prompt", () => {
});
describe("LanguageServersPage", () => {
beforeEach(() => resetTestForm());
const renderPage = () =>
render(
<TestSettingsForm>
<LanguageServersPage />
</TestSettingsForm>,
);
const listItem = (name: string) =>
screen.getByRole("list", { name: /language servers/i }).querySelector<HTMLElement>(`[data-tool="${name}"]`)!;
it("lists tools and installs from the details pane", async () => {
const user = userEvent.setup();
render(<LanguageServersPage />);
renderPage();
await screen.findByText("gopls");
await user.click(listItem("gopls"));
const details = screen.getByLabelText("gopls details");
@@ -148,7 +156,7 @@ describe("LanguageServersPage", () => {
it("explains why a tool cannot be installed", async () => {
const user = userEvent.setup();
render(<LanguageServersPage />);
renderPage();
await screen.findByText("solargraph");
await user.click(listItem("solargraph"));
expect(screen.getByText("gem install solargraph")).toBeInTheDocument();
@@ -156,23 +164,26 @@ describe("LanguageServersPage", () => {
expect(screen.getByText("curl is required to download tools")).toBeInTheDocument();
});
it("sets and clears a custom path", async () => {
it("stages and clears a custom path", async () => {
const user = userEvent.setup();
render(<LanguageServersPage />);
renderPage();
await screen.findByText("gopls");
await user.click(listItem("gopls"));
const path = within(screen.getByLabelText("gopls details")).getByRole("textbox", { name: "Path" });
await user.type(path, "/opt/go/bin/gopls{Enter}");
await waitFor(() => expect(screen.getByLabelText("gopls details")).toHaveTextContent("Custom"));
expect(backend.customPaths).toEqual({ gopls: "/opt/go/bin/gopls" });
await user.click(screen.getByRole("button", { name: "Use auto-detected" }));
await waitFor(() => expect(backend.customPaths).toEqual({}));
expect(screen.getByLabelText("gopls details")).toHaveTextContent("Missing");
await user.type(path, "/opt/go/bin/gopls");
expect(stagedFor("tools.gopls.path")).toBe("/opt/go/bin/gopls");
await user.clear(path);
expect(stagedFor("tools.gopls.path")).toBeNull();
// Picked with the file chooser.
backend.chosen = "/usr/local/bin/gopls";
await user.click(within(screen.getByLabelText("gopls details")).getByRole("button", { name: "Browse…" }));
expect(stagedFor("tools.gopls.path")).toBe("/usr/local/bin/gopls");
expect(path).toHaveValue("/usr/local/bin/gopls");
});
it("moves the selection with the arrow keys", async () => {
const user = userEvent.setup();
render(<LanguageServersPage />);
renderPage();
await screen.findByText("gopls");
await user.click(listItem("rust-analyzer"));
await user.keyboard("{ArrowDown}");
@@ -181,7 +192,7 @@ describe("LanguageServersPage", () => {
it("filters to missing tools", async () => {
const user = userEvent.setup();
render(<LanguageServersPage />);
renderPage();
await screen.findByText("gopls");
await user.click(screen.getByRole("radio", { name: /missing/i }));
expect(screen.queryByText("rust-analyzer")).not.toBeInTheDocument();
@@ -193,7 +204,7 @@ describe("LanguageServersPage", () => {
it("shows backend errors", async () => {
vi.spyOn(backend, "list").mockRejectedValueOnce(new Error("boom"));
render(<LanguageServersPage />);
renderPage();
expect(await screen.findByRole("alert")).toHaveTextContent("boom");
});
});
+20 -20
Переглянути файл
@@ -5,7 +5,11 @@
import { Channel } from "@tauri-apps/api/core";
import type { InstallEvent, RequestId, ToolInfo } from "@/bindings";
import { call, commands, IpcError, isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
export interface LanguageChoice {
id: string;
name: string;
}
export interface ToolsBackend {
list(): Promise<ToolInfo[]>;
@@ -14,10 +18,10 @@ export interface ToolsBackend {
cancel(request: RequestId): void;
/** Restarts running language servers named `name` (after an install). */
restartServers(name: string): Promise<void>;
/** Launches `command` from `path` instead of the detected one (global setting); "" clears it. */
setCustomPath(command: string, path: string): Promise<void>;
/** File chooser for an executable; null when cancelled. */
chooseExecutable(title: string, defaultPath?: string): Promise<string | null>;
/** Languages a server defined in settings can serve. */
languages(): Promise<LanguageChoice[]>;
}
export const tauriToolsBackend: ToolsBackend = {
@@ -40,18 +44,13 @@ export const tauriToolsBackend: ToolsBackend = {
servers.filter((s) => s.name === name).map((s) => call(commands.lspRestart(s.id)).catch(() => {})),
);
},
setCustomPath: async (command, path) => {
const tools = { ...(await commands.settingsGet()).tools };
if (path) tools[command] = { path };
else delete tools[command];
const settings = await call(commands.settingsSet("global", "tools", JSON.stringify(tools)));
useProject.setState({ settings });
},
chooseExecutable: async (title, defaultPath) => {
const { open } = await import("@tauri-apps/plugin-dialog");
const picked = await open({ directory: false, multiple: false, title, defaultPath: defaultPath || undefined });
return (Array.isArray(picked) ? picked[0] : picked) ?? null;
},
languages: async () =>
(await commands.languages()).map((l) => ({ id: l.id, name: l.name })).sort((a, b) => a.name.localeCompare(b.name)),
};
function tool(partial: Partial<ToolInfo> & Pick<ToolInfo, "name" | "languages">): ToolInfo {
@@ -69,6 +68,8 @@ function tool(partial: Partial<ToolInfo> & Pick<ToolInfo, "name" | "languages">)
installHint: null,
homepage: null,
customError: null,
defaultArgs: [],
defaultInitializationOptions: null,
...partial,
};
}
@@ -202,22 +203,21 @@ export class MemoryToolsBackend implements ToolsBackend {
this.restarted.push(name);
}
/** Paths set through `setCustomPath`, by command. */
customPaths: Record<string, string> = {};
/** What `chooseExecutable` answers. */
chosen: string | null = null;
async setCustomPath(command: string, path: string) {
if (path) this.customPaths[command] = path;
else delete this.customPaths[command];
for (const t of this.tools.filter((x) => x.command === command)) {
this.replace(path ? { ...t, status: "custom", path, version: null } : { ...t, status: "missing", path: null });
}
}
async chooseExecutable() {
return this.chosen;
}
async languages() {
return [
{ id: "go", name: "Go" },
{ id: "python", name: "Python" },
{ id: "rust", name: "Rust" },
{ id: "typescript", name: "TypeScript" },
];
}
}
let backend: ToolsBackend | null = null;
+13 -1
Переглянути файл
@@ -19,7 +19,19 @@ export function activateSettingsPages(): () => void {
title: "Language Servers",
group: "Languages & Frameworks",
order: 400,
keywords: ["lsp", "language server", "debugger", "adapter", "dap", "install", "rust-analyzer", "gopls", "pyright"],
keywords: [
"lsp",
"language server",
"debugger",
"adapter",
"dap",
"install",
"initialization options",
"rust-analyzer",
"gopls",
"pyright",
],
projectScope: true,
component: lazyComponent(() => import("./LanguageServersPage").then((m) => m.LanguageServersPage)),
});
}
+119
Переглянути файл
@@ -0,0 +1,119 @@
/**
* Settings › Language Servers entries (`languageServers.<name>` in settings.toml):
* text ↔ value conversions for the editor fields. Parsers return `null` for an
* empty field (the setting is removed) and throw `Error` with a user-facing message.
*/
import type { LanguageServerSettings } from "@/bindings";
/** What the settings set for a server (any field may be absent). */
export type ServerEntry = Partial<LanguageServerSettings>;
export type ServerField = keyof LanguageServerSettings;
/** Settings keys of a server's entry and of a tool's executable. */
export const serverKey = (name: string, field?: ServerField) =>
field ? `languageServers.${name}.${field}` : `languageServers.${name}`;
export const toolPathKey = (command: string) => `tools.${command}.path`;
/** The server's name proposed for an executable (`/opt/bin/ruff` → `ruff`). */
export function nameFromCommand(command: string): string {
const base = command.trim().split(/[\\/]/).pop() ?? "";
return base.replace(/\.(exe|cmd|bat)$/i, "").replace(/[^A-Za-z0-9_+-]/g, "-");
}
/** Names become settings keys: no dots or spaces. */
export const SERVER_NAME = /^[A-Za-z0-9][A-Za-z0-9_+-]*$/;
/** Shell-like split: whitespace separates, quotes group, backslash escapes. */
export function parseArgs(text: string): string[] | null {
const out: string[] = [];
let cur = "";
let started = false;
let quote: '"' | "'" | null = null;
for (let i = 0; i < text.length; i++) {
const c = text[i]!;
if (quote) {
if (c === quote) quote = null;
else if (c === "\\" && quote === '"' && i + 1 < text.length) cur += text[++i];
else cur += c;
} else if (c === '"' || c === "'") {
quote = c;
started = true;
} else if (c === "\\" && i + 1 < text.length) {
cur += text[++i];
started = true;
} else if (/\s/.test(c)) {
if (started) out.push(cur);
cur = "";
started = false;
} else {
cur += c;
started = true;
}
}
if (quote) throw new Error(`Unclosed ${quote} quote`);
if (started) out.push(cur);
return out.length ? out : null;
}
export function formatArgs(args: readonly string[] | undefined | null): string {
return (args ?? []).map((a) => (a === "" || /[\s"'\\]/.test(a) ? `"${a.replace(/["\\]/g, "\\$&")}"` : a)).join(" ");
}
/** `NAME=value` pairs separated by `;` (or new lines), as in run configurations. */
export function parseEnv(text: string): Record<string, string> | null {
const env: Record<string, string> = {};
for (const raw of text.split(/[;\n]/)) {
const pair = raw.trim();
if (!pair) continue;
const eq = pair.indexOf("=");
const key = eq < 0 ? "" : pair.slice(0, eq).trim();
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw new Error(`Expected NAME=value: ${pair}`);
env[key] = pair.slice(eq + 1).trim();
}
return Object.keys(env).length ? env : null;
}
export function formatEnv(env: Record<string, string> | undefined | null): string {
return Object.entries(env ?? {})
.map(([k, v]) => `${k}=${v}`)
.join("; ");
}
/** A JSON object (settings.toml has no `null`, so neither may the object). */
export function parseJsonObject(text: string): Record<string, unknown> | null {
if (!text.trim()) return null;
let value: unknown;
try {
value = JSON.parse(text);
} catch (e) {
throw new Error(e instanceof Error ? e.message : String(e), { cause: e });
}
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("Expected a JSON object");
const nullAt = findNull(value, "");
if (nullAt !== null) throw new Error(`null is not supported (at ${nullAt || "top level"})`);
return value as Record<string, unknown>;
}
function findNull(v: unknown, path: string): string | null {
if (v === null) return path;
if (typeof v !== "object") return null;
for (const [k, child] of Object.entries(v as Record<string, unknown>)) {
const hit = findNull(child, Array.isArray(v) ? `${path}[${k}]` : path ? `${path}.${k}` : k);
if (hit !== null) return hit;
}
return null;
}
export function formatJson(value: unknown): string {
return value == null ? "" : JSON.stringify(value, null, 2);
}
/** Comma / whitespace separated names. */
export function parseList(text: string): string[] | null {
const items = text.split(/[\s,]+/).filter(Boolean);
return items.length ? [...new Set(items)] : null;
}
export function formatList(items: readonly string[] | undefined | null): string {
return (items ?? []).join(", ");
}
-17
Переглянути файл
@@ -180,23 +180,6 @@ export async function uninstallTool(name: string): Promise<boolean> {
}
}
/** Launches `command` from `path` (empty: auto-detect again), then re-checks the tools. */
export async function setCustomPath(command: string, path: string): Promise<boolean> {
try {
await toolsBackend().setCustomPath(command, path.trim());
await refreshTools();
return true;
} catch (e) {
notifications().notify({
group: "tools",
level: "error",
title: `Failed to set the path of ${command}`,
body: errorText(e),
});
return false;
}
}
export const STATUS_LABEL: Record<ToolInfo["status"], string> = {
installed: "Installed",
onPath: "On PATH",
+34 -29
Переглянути файл
@@ -1,6 +1,6 @@
/** Commit tool window: change list with inclusion checkboxes, message, stashes. */
import { useWorkflowSettings } from "@/platform/workflowSettings";
import { useCallback, useEffect, useMemo, useRef, useState, type DragEvent, type MouseEvent } from "react";
import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent, type PointerEvent } from "react";
import { tx } from "@/platform/i18n";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
@@ -18,7 +18,9 @@ import {
Tabs,
Tree,
fileIconName,
registerDropTarget,
showContextMenu,
startPointerDrag,
type MenuItem,
type TreeHandle,
T,
@@ -424,35 +426,38 @@ function ChangesPanel() {
{n.label}
</span>
);
// Pointer-driven (HTML5 drag and drop never reaches the Tauri webview):
// files and folders drag; any row takes them into its changelist.
const list = n.changelist;
const dnd =
n.changelist !== undefined
? {
draggable: n.type !== "group",
onDragStart: (e: DragEvent<HTMLSpanElement>) => {
const paths =
selected.has(n.key) && selected.size > 1
? filesOf(selectedNodes()).map((f) => f.path)
: n.files.map((f) => f.path);
e.dataTransfer.setData(CHANGES_MIME, paths.map(stripSlash).join("\n"));
e.dataTransfer.effectAllowed = "move";
},
onDragOver: (e: DragEvent<HTMLSpanElement>) => {
if (![...e.dataTransfer.types].includes(CHANGES_MIME)) return;
e.preventDefault();
e.dataTransfer.dropEffect = "move";
if (dropTarget !== n.changelist) setDropTarget(n.changelist ?? null);
},
onDragLeave: () => setDropTarget(null),
onDrop: (e: DragEvent<HTMLSpanElement>) => {
const data = e.dataTransfer.getData(CHANGES_MIME);
setDropTarget(null);
if (!data || !n.changelist) return;
e.preventDefault();
moveToChangelist(data.split("\n"), n.changelist);
},
onDragEnd: () => setDropTarget(null),
}
: {};
list === undefined
? {}
: {
ref: (el: HTMLSpanElement | null) =>
el
? registerDropTarget(el, {
accepts: (type) => type === CHANGES_MIME,
over: () => setDropTarget(list),
leave: () => setDropTarget(null),
drop: (data) => {
setDropTarget(null);
moveToChangelist(data.payload.split("\n"), list);
},
})
: undefined,
...(n.type !== "group" && {
onPointerDown: (e: PointerEvent<HTMLSpanElement>) => {
const paths =
selected.has(n.key) && selected.size > 1
? filesOf(selectedNodes()).map((f) => f.path)
: n.files.map((f) => f.path);
startPointerDrag(e, e.currentTarget, {
type: CHANGES_MIME,
payload: paths.map(stripSlash).join("\n"),
});
},
}),
};
return (
<span
className={clsx(
+6
Переглянути файл
@@ -57,6 +57,12 @@ function ensureListening() {
});
}
/** Resolves once backend events reach this window's handlers. */
export async function ideEventsReady(): Promise<void> {
ensureListening();
await unlisten;
}
/** Subscribes to one backend event type (or `"*"`); returns an unsubscribe function. */
export function onIdeEvent<K extends IdeEvent["type"]>(type: K | "*", handler: (event: EventOf<K>) => void): () => void {
ensureListening();
+1
Переглянути файл
@@ -82,6 +82,7 @@ export const intellijMacos: Record<string, string[]> = {
"code.quickDocumentation": ["F1", "Ctrl+J"],
"code.quickDefinition": ["Alt+Space", "Meta+Y"],
"code.showIntentions": ["Alt+Enter"],
"code.applyQuickFix": ["Alt+Shift+Enter"],
"code.reformat": ["Meta+Alt+L"],
"code.reformatDialog": ["Meta+Alt+Shift+L"],
"code.optimizeImports": ["Ctrl+Alt+O"],
+1
Переглянути файл
@@ -83,6 +83,7 @@ export const intellijWindows: Record<string, string[]> = {
"code.quickDocumentation": ["Ctrl+Q"],
"code.quickDefinition": ["Ctrl+Shift+I"],
"code.showIntentions": ["Alt+Enter"],
"code.applyQuickFix": ["Alt+Shift+Enter"],
"code.reformat": ["Ctrl+Alt+L"],
"code.reformatDialog": ["Ctrl+Alt+Shift+L"],
"code.optimizeImports": ["Ctrl+Alt+O"],
+1
Переглянути файл
@@ -83,6 +83,7 @@ export const vscodeMacos: Record<string, string[]> = {
"code.quickDocumentation": ["Meta+K Meta+I"],
"code.quickDefinition": ["Alt+F12"],
"code.showIntentions": ["Meta+."],
"code.applyQuickFix": [],
"code.generate": [],
"code.reformat": ["Alt+Shift+F"],
"code.reformatDialog": [],
+35 -5
Переглянути файл
@@ -847,6 +847,7 @@
"Hide Library Frames": "隐藏库帧",
"Hide Replace": "隐藏替换",
"Hide debug window on process termination": "进程终止时隐藏调试窗口",
"Auto-detect": "自动检测",
"Hide install log": "隐藏安装日志",
"Hierarchies": "层次结构",
"Hierarchy": "层次结构",
@@ -2384,14 +2385,11 @@
"Language server": "语言服务器",
"Path": "路径",
"Missing": "缺失",
"Leave empty to use the IDE-installed copy, else the one on PATH.": "留空则使用 IDE 安装的副本,否则使用 PATH 上的版本。",
"Installs into the IDE's own tools folder via": "安装到 IDE 自己的工具目录,方式:",
"Installs into the IDE's own tools folder via {installMethod}": "通过 {installMethod} 安装到 IDE 自己的工具文件夹",
"No tool selected": "未选择工具",
"Use auto-detected": "使用自动检测",
"Custom": "自定义",
"On PATH": "PATH 中",
"Reinstall": "重新安装",
"Auto-detect": "自动检测",
"Move focus to the Editor with Escape": "按 Escape 将焦点移到编辑器",
"Otherwise Escape goes to the shell.": "否则 Escape 发送给 shell。",
"Configure terminal keybindings": "配置终端快捷键",
@@ -3143,6 +3141,10 @@
"The file changed; rename cancelled": "文件已更改,重命名已取消",
"No suggestions": "无建议",
"No intentions available": "没有可用的意图操作",
"No quick fixes available": "没有可用的快速修复",
"No abstract methods to implement": "没有需要实现的抽象方法",
"Implement abstract methods": "实现抽象方法",
"Apply Quick Fix": "应用快速修复",
"The document changed; invoke the refactoring again": "文档已更改,请重新调用重构",
"The document changed; the name was not applied": "文档已更改,名称未应用",
"The file changed; Safe Delete cancelled": "文件已更改,安全删除已取消",
@@ -3596,7 +3598,6 @@
"Failed to download JDK {version}": "下载 JDK {version} 失败",
"Java Settings…": "Java 设置…",
"{name} needs JDK {version} to run": "{name} 需要 JDK {version} 才能运行",
"Failed to set the path of {command}": "设置 {command} 的路径失败",
"Search for branches, actions, repositories": "搜索分支、操作、仓库",
"Git Settings": "Git 设置",
"Repositories and branches": "仓库和分支",
@@ -3976,6 +3977,35 @@
"Delete the layout '{name}'?": "是否删除布局 '{name}'?",
"In {left}, not in {right}": "在 {left} 中,不在 {right} 中",
"Local branch '{local}' has commits that do not exist in '{remote}'. Rebase '{local}' onto '{remote}', or drop local commits?": "本地分支 '{local}' 有 '{remote}' 中不存在的提交。是将 '{local}' 变基到 '{remote}',还是丢弃本地提交?",
"Add Language Server…": "添加语言服务器…",
"Use {displayName}": "使用 {displayName}",
"Select {name}": "选择 {name}",
"Root markers": "根标记",
"Initialization options": "初始化选项",
"Global": "全局",
"This project": "此项目",
"Executable name or path": "可执行文件名或路径",
"Select the server executable": "选择服务器可执行文件",
"Remove Language Server": "移除语言服务器",
"Missing ({missingCount})": "缺失 ({missingCount})",
"Choose languages…": "选择语言…",
"Filter languages": "筛选语言",
"No languages match.": "没有匹配的语言。",
"Checked when the settings are applied.": "应用设置后检查。",
"Using": "使用",
"Not found on PATH.": "在 PATH 中未找到。",
"Use {displayName} for {join} files": "对 {join} 文件使用 {displayName}",
"Files marking the workspace root.": "标记工作区根目录的文件。",
"Merged over the defaults shown when empty.": "与默认值(为空时显示)合并。",
"Workspace Configuration": "工作区配置",
"Enter the command that starts the server.": "请输入启动服务器的命令。",
"Name: letters, digits, - _ + only.": "名称:只能包含字母、数字、- _ +。",
"{effectiveName} already exists.": "{effectiveName} 已存在。",
"Choose the languages it serves.": "请选择它服务的语言。",
"New Language Server": "新建语言服务器",
"Any language server that talks LSP over stdio, with its arguments.": "任何通过 stdio 使用 LSP 的语言服务器,可带参数。",
"Changing these restarts the server.": "修改这些设置会重启服务器。",
"Sent to the running server; no restart needed.": "发送给运行中的服务器,无需重启。",
"SSH Configurations": "SSH 配置",
"User name": "用户名",
"Authentication type": "身份验证类型",
+4
Переглянути файл
@@ -182,9 +182,13 @@ const UNTRANSLATED = new Set<string>([
"kebab-case",
"KEY=value; OTHER=value",
"NAME",
"NAME=value; OTHER=value",
"node_modules/typescript",
"PascalCase",
"pyproject.toml, .git",
"ruff server",
"snake_case",
'{ "section": { "key": "value" } }',
// Identifiers that only look like text: icon names, error codes, categories, console output
"app",
"cancelled",
+39 -40
Переглянути файл
@@ -11,7 +11,6 @@ import {
useRef,
useState,
type CSSProperties,
type DragEvent,
type KeyboardEvent,
type MouseEvent,
type ReactNode,
@@ -21,6 +20,7 @@ import { Icon, type IconName } from "./icons";
import { IconButton } from "./Button";
import { Menu, type MenuItem } from "./Menu";
import { tooltipAttrs } from "./Tooltip";
import { registerDropTarget, startPointerDrag } from "./pointerDrag";
import { T } from "./T";
import styles from "./Tabs.module.css";
import { tx } from "@/platform/i18n";
@@ -148,37 +148,36 @@ export function Tabs({
[register],
);
const accepts = (e: DragEvent) => !!dnd && [...e.dataTransfer.types].includes(dnd.type);
const indexAt = (e: DragEvent) =>
dropIndex(
vertical ? e.clientY : e.clientX,
items.map((it) => {
const r = tabRefs.current.get(it.id)?.parentElement?.getBoundingClientRect();
return vertical ? { left: r?.top ?? 0, width: r?.height ?? 0 } : { left: r?.left ?? 0, width: r?.width ?? 0 };
}),
);
const dropHandlers = dnd
? {
onDragOver: (e: DragEvent<HTMLDivElement>) => {
if (!accepts(e)) return;
e.preventDefault();
e.dataTransfer.dropEffect = "move";
const i = indexAt(e);
if (i !== drop) setDrop(i);
},
onDragLeave: (e: DragEvent<HTMLDivElement>) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setDrop(null);
},
onDrop: (e: DragEvent<HTMLDivElement>) => {
if (!accepts(e)) return;
e.preventDefault();
const payload = e.dataTransfer.getData(dnd.type);
const i = indexAt(e);
setDrop(null);
if (payload) dnd.onDrop(payload, i);
},
}
: {};
const stripRef = useRef<HTMLDivElement>(null);
// Re-read on every drag event: items and handlers change while the strip stays registered.
const dropState = useRef({ items, dnd, vertical });
useLayoutEffect(() => {
dropState.current = { items, dnd, vertical };
});
const dndType = dnd?.type;
useEffect(() => {
const el = stripRef.current;
if (!el || !dndType) return;
const indexAt = (x: number, y: number) => {
const { items, vertical } = dropState.current;
return dropIndex(
vertical ? y : x,
items.map((it) => {
const r = tabRefs.current.get(it.id)?.parentElement?.getBoundingClientRect();
return vertical ? { left: r?.top ?? 0, width: r?.height ?? 0 } : { left: r?.left ?? 0, width: r?.width ?? 0 };
}),
);
};
return registerDropTarget(el, {
accepts: (type) => type === dropState.current.dnd?.type,
over: (_, x, y) => setDrop(indexAt(x, y)),
leave: () => setDrop(null),
drop: (data, x, y) => {
setDrop(null);
dropState.current.dnd?.onDrop(data.payload, indexAt(x, y));
},
});
}, [dndType]);
useLayoutEffect(() => {
const el = scrollRef.current;
@@ -249,7 +248,7 @@ export function Tabs({
closePosition === "left" && styles.closeLeft,
className,
)}
{...dropHandlers}
ref={stripRef}
>
{vertical && trailing && <div className={styles.trailing}>{trailing}</div>}
<div
@@ -279,17 +278,17 @@ export function Tabs({
item.tint && styles.tinted,
)}
style={item.tint ? ({ "--tab-tint": item.tint } as CSSProperties) : undefined}
draggable={!!dnd}
onDragStart={
onPointerDown={
dnd
? (e) => {
e.dataTransfer.setData(dnd.type, dnd.payload(item.id));
e.dataTransfer.effectAllowed = "move";
setDragging(item.id);
if ((e.target as Element).closest("[data-tab-close]")) return;
startPointerDrag(e, e.currentTarget, { type: dnd.type, payload: dnd.payload(item.id) }, {
onStart: () => setDragging(item.id),
onEnd: () => setDragging(null),
});
}
: undefined
}
onDragEnd={dnd ? () => (setDragging(null), setDrop(null)) : undefined}
onMouseDown={(e) => {
if (e.button === 1 && closable) {
e.preventDefault();
@@ -324,7 +323,7 @@ export function Tabs({
{item.modified && !closable && <span className={styles.modified} aria-label="Modified" />}
</button>
{closable && (
<span className={styles.closeSlot}>
<span className={styles.closeSlot} data-tab-close>
{item.modified && <span className={styles.modified} aria-label="Modified" />}
<IconButton
icon="close"
+6
Переглянути файл
@@ -0,0 +1,6 @@
<!-- Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="5.70142" y="12" width="4.6" height="1" fill="#6C707E"/>
<path d="M6 14H10C10 14.5523 9.55228 15 9 15H7C6.44772 15 6 14.5523 6 14Z" fill="#6C707E"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M10.8704 9.14748C12.0417 8.27221 12.8 6.87465 12.8 5.3C12.8 2.64903 10.6509 0.5 7.99995 0.5C5.34898 0.5 3.19995 2.64903 3.19995 5.3C3.19995 6.87464 3.95817 8.27218 5.12943 9.14746L5.49994 11H10.4999L10.8704 9.14748Z" fill="#E55765"/>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 670 B

+6
Переглянути файл
@@ -0,0 +1,6 @@
<!-- Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="5.70142" y="12" width="4.6" height="1" fill="#CED0D6"/>
<path d="M6 14H10C10 14.5523 9.55228 15 9 15H7C6.44772 15 6 14.5523 6 14Z" fill="#CED0D6"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M10.8704 9.14748C12.0417 8.27221 12.8 6.87465 12.8 5.3C12.8 2.64903 10.6509 0.5 7.99995 0.5C5.34898 0.5 3.19995 2.64903 3.19995 5.3C3.19995 6.87464 3.95817 8.27218 5.12943 9.14746L5.49994 11H10.4999L10.8704 9.14748Z" fill="#DB5C5C"/>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 670 B

+1
Переглянути файл
@@ -247,6 +247,7 @@ const ICONS = {
list: "general/listFiles",
keyboard: "general/keyboard",
bulb: "codeInsight/intentionBulb",
"bulb-fix": "codeInsight/quickfixBulb",
package: "nodes/package",
plugin: "nodes/plugin",
"soft-wrap": "general/softWrap",
+1
Переглянути файл
@@ -6,6 +6,7 @@ export * from "./Input";
export * from "./Checkbox";
export * from "./Select";
export * from "./Tabs";
export { FILES_DRAG, dragRequiresAlt, dragSession, registerDropTarget, setDragRequiresAlt, startPointerDrag, type DragData, type DragSession, type DropTarget } from "./pointerDrag";
export * from "./Tree";
export * from "./List";
export * from "./Popup";
+19
Переглянути файл
@@ -0,0 +1,19 @@
.ghost {
position: fixed;
z-index: var(--z-tooltip);
margin: 0;
opacity: 0.85;
pointer-events: none;
box-shadow: var(--shadow-tooltip);
background: var(--bg-popup);
}
.noTarget {
opacity: 0.5;
}
.dragging,
.dragging * {
cursor: grabbing !important;
user-select: none !important;
}
+156
Переглянути файл
@@ -0,0 +1,156 @@
/**
* Pointer-driven drag & drop between components. HTML5 drag and drop can't be
* used: with the window's native file drop enabled, the webview never sees
* dragover / drop for drags that start inside it. Sources start a drag with
* `startPointerDrag` (or drive a `DragSession` themselves); targets register
* an element with `registerDropTarget` and are told about drags over it.
*/
import styles from "./pointerDrag.module.css";
/** What is dragged: `type` is matched by targets (e.g. `application/x-openidea-editor-tab`). */
export interface DragData {
type: string;
payload: string;
}
/** Project files dragged from the Project view: `payload` is the paths joined by `\n`. */
export const FILES_DRAG = "application/x-openidea-files";
export interface DropTarget {
accepts(type: string): boolean;
/** The pointer moved over the target. */
over(data: DragData, x: number, y: number): void;
/** The pointer left the target, or the drag ended elsewhere / was cancelled. */
leave(): void;
drop(data: DragData, x: number, y: number): void;
}
const targets = new Map<Element, DropTarget>();
export function registerDropTarget(el: Element, target: DropTarget): () => void {
targets.set(el, target);
return () => {
if (targets.get(el) === target) targets.delete(el);
};
}
/** The innermost registered target under (x, y) accepting `type`. */
function targetAt(type: string, x: number, y: number): DropTarget | null {
for (let el = document.elementFromPoint(x, y); el; el = el.parentElement) {
const t = targets.get(el);
if (t?.accepts(type)) return t;
}
return null;
}
export interface DragSession {
/** Updates hover feedback; true when a target under (x, y) accepts the drag. */
move(x: number, y: number): boolean;
/** Drops on the target under (x, y); false when there is none. */
drop(x: number, y: number): boolean;
cancel(): void;
}
export function dragSession(data: DragData): DragSession {
let current: DropTarget | null = null;
const enter = (t: DropTarget | null) => {
if (t === current) return;
current?.leave();
current = t;
};
return {
move(x, y) {
enter(targetAt(data.type, x, y));
current?.over(data, x, y);
return !!current;
},
drop(x, y) {
const t = targetAt(data.type, x, y);
enter(null);
t?.drop(data, x, y);
return !!t;
},
cancel: () => enter(null),
};
}
/** Movement before a press becomes a drag, px. */
const DRAG_THRESHOLD = 4;
/** Settings › Appearance › "Drag-and-drop with Alt pressed only" for tabs and stripe buttons. */
let requiresAlt = () => false;
export function setDragRequiresAlt(fn: () => boolean) {
requiresAlt = fn;
}
export const dragRequiresAlt = () => requiresAlt();
/**
* Starts a drag from a primary-button press on `source` once the pointer moved
* past the threshold; a ghost copy of `source` follows the pointer. Escape
* cancels. `onEnd` gets whether the drag happened (to swallow the click).
*/
export function startPointerDrag(
e: { button: number; clientX: number; clientY: number; altKey: boolean },
source: HTMLElement,
data: DragData,
opts: { onStart?: () => void; onEnd?: (dragged: boolean) => void } = {},
) {
if (e.button !== 0 || (requiresAlt() && !e.altKey)) return;
const start = { x: e.clientX, y: e.clientY };
let ghost: HTMLElement | null = null;
const session = dragSession(data);
const onMove = (ev: PointerEvent) => {
if (!ghost) {
if (Math.hypot(ev.clientX - start.x, ev.clientY - start.y) < DRAG_THRESHOLD) return;
const r = source.getBoundingClientRect();
ghost = source.cloneNode(true) as HTMLElement;
ghost.removeAttribute("id");
ghost.querySelectorAll("[id]").forEach((n) => n.removeAttribute("id"));
ghost.classList.add(styles.ghost!);
ghost.setAttribute("aria-hidden", "true");
Object.assign(ghost.style, {
left: `${r.left}px`,
top: `${r.top}px`,
width: `${r.width}px`,
height: `${r.height}px`,
});
document.body.appendChild(ghost);
document.documentElement.classList.add(styles.dragging!);
opts.onStart?.();
}
ghost.style.transform = `translate(${ev.clientX - start.x}px, ${ev.clientY - start.y}px)`;
ghost.classList.toggle(styles.noTarget!, !session.move(ev.clientX, ev.clientY));
};
const onUp = (ev: PointerEvent) => {
const dragged = !!ghost;
cleanup();
if (dragged) session.drop(ev.clientX, ev.clientY);
opts.onEnd?.(dragged);
};
const onKey = (ev: KeyboardEvent) => {
if (ev.key !== "Escape" || !ghost) return;
ev.preventDefault();
ev.stopPropagation();
session.cancel();
cleanup();
opts.onEnd?.(true);
};
const cleanup = () => {
window.removeEventListener("pointermove", onMove);
window.removeEventListener("pointerup", onUp);
window.removeEventListener("pointercancel", onCancel);
window.removeEventListener("keydown", onKey, true);
ghost?.remove();
document.documentElement.classList.remove(styles.dragging!);
};
const onCancel = () => {
session.cancel();
const dragged = !!ghost;
cleanup();
opts.onEnd?.(dragged);
};
window.addEventListener("pointermove", onMove);
window.addEventListener("pointerup", onUp);
window.addEventListener("pointercancel", onCancel);
window.addEventListener("keydown", onKey, true);
}
+50 -13
Переглянути файл
@@ -8,7 +8,15 @@
* The workbench renders whatever is registered; the action
* `toolwindow.<id>` toggles it (registered automatically).
*/
import { useEffect, useRef, type ComponentType, type ReactNode, type RefObject } from "react";
import {
createContext,
useContext,
useEffect,
useRef,
type ComponentType,
type ReactNode,
type RefObject,
} from "react";
import type { RunConfig } from "@/bindings";
import type { MenuItem } from "@/ui/Menu";
import { create } from "zustand";
@@ -371,6 +379,8 @@ export interface OpenOptions {
preview?: boolean;
/** Open to the side (split right). */
side?: boolean;
/** Open in this editor pane, in a tab of its own even when another pane shows the file. */
pane?: string;
focus?: boolean;
/** Open in the text editor even when a file editor provider claims the file (SVG as text). */
asText?: boolean;
@@ -453,7 +463,10 @@ export interface EmbeddedTerminalOptions {
"aria-label"?: string;
}
export type EmbeddedTerminalFactory = (host: HTMLElement, options: EmbeddedTerminalOptions) => Promise<EmbeddedTerminal>;
export type EmbeddedTerminalFactory = (
host: HTMLElement,
options: EmbeddedTerminalOptions,
) => Promise<EmbeddedTerminal>;
const services: {
editor?: EditorService;
@@ -587,6 +600,29 @@ export interface SettingsPageContribution {
/** Extra words matched by the settings search. */
keywords?: string[];
component: ComponentType;
/** The page edits settings that a project can override (Global / This project switch). */
projectScope?: boolean;
}
/**
* What a settings page edits through: values of the page's scope with the
* edits not applied yet. Edits are written on Apply / OK and dropped on Cancel.
*/
export interface SettingsForm {
scope: "global" | "project";
/** Value of a dotted key (map entries too, e.g. `languageServers.ruff.args`). */
useValue(key: string): unknown;
/** Stages a value; `null` removes the key on Apply. */
set(key: string, value: unknown): void;
}
export const SettingsFormContext = createContext<SettingsForm | null>(null);
/** The form of the settings page being shown (provided by the Settings dialog). */
export function useSettingsForm(): SettingsForm {
const form = useContext(SettingsFormContext);
if (!form) throw new Error("useSettingsForm outside a settings page");
return form;
}
export const useSettingsPages = create<{ pages: Map<string, SettingsPageContribution> }>(() => ({ pages: new Map() }));
@@ -684,14 +720,7 @@ export function projectViewRoots(map: ReadonlyMap<string, ProjectViewRootContrib
// in `paths[0]`, the target directory (features/templates: file templates, http-client: HTTP Request).
export type ContextMenuId =
| "editor"
| "projectView"
| "editorTab"
| "editorGutter"
| "openIn"
| "stopProcess"
| "selectIn"
| "new";
"editor" | "projectView" | "editorTab" | "editorGutter" | "openIn" | "stopProcess" | "selectIn" | "new";
export interface MenuGroupContext {
/** Files / directories the menu is for (absolute paths; a virtual URI for virtual documents). */
@@ -883,7 +912,9 @@ export interface RunConfigTypeContribution {
debugAdapter?: string;
}
export const useRunConfigTypes = create<{ types: Map<string, RunConfigTypeContribution> }>(() => ({ types: new Map() }));
export const useRunConfigTypes = create<{ types: Map<string, RunConfigTypeContribution> }>(() => ({
types: new Map(),
}));
export function registerRunConfigType(type: RunConfigTypeContribution): () => void {
useRunConfigTypes.setState((s) => ({ types: new Map(s.types).set(type.id, type) }));
@@ -1019,7 +1050,11 @@ export function setLocalChanges(provider: string, lists: LocalChangelist[]): ()
}
/** Paths of the changed files, of one list (`listId`) or all; `existing` leaves out deleted files. */
export function localChangedPaths(lists: readonly LocalChangelist[], listId?: string | null, existing = false): string[] {
export function localChangedPaths(
lists: readonly LocalChangelist[],
listId?: string | null,
existing = false,
): string[] {
const out: string[] = [];
for (const l of lists) {
if (listId && l.id !== listId) continue;
@@ -1067,7 +1102,9 @@ export function registerRunAnythingProvider(p: RunAnythingProvider): () => void
/** Registered providers in order. */
export function runAnythingProviderList(): RunAnythingProvider[] {
return [...runAnythingProviders.values()].sort((a, b) => (a.order ?? 100) - (b.order ?? 100) || a.id.localeCompare(b.id));
return [...runAnythingProviders.values()].sort(
(a, b) => (a.order ?? 100) - (b.order ?? 100) || a.id.localeCompare(b.id),
);
}
// ---------------------------------------------------------------------------
+2 -2
Переглянути файл
@@ -15,7 +15,7 @@ import { create } from "zustand";
import { call, commands } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { useProject } from "@/platform/project";
import { Icon, IconButton, Menu, showContextMenu, tooltipAttrs, type MenuItem, T } from "@/ui";
import { dragRequiresAlt, Icon, IconButton, Menu, showContextMenu, tooltipAttrs, type MenuItem, T } from "@/ui";
import { FOCUSABLE } from "@/ui/popupState";
import { TabStripRegistry } from "@/ui/Tabs";
import { useContributions, type ToolWindowAnchor, type ToolWindowContribution } from "../contributions";
@@ -303,7 +303,7 @@ function stripeDropAt(x: number, y: number): StripeDrop | null {
}
function startStripeDrag(e: PointerEvent<HTMLButtonElement>, id: string) {
if (e.button !== 0) return;
if (e.button !== 0 || (dragRequiresAlt() && !e.altKey)) return;
const button = e.currentTarget;
const start = { x: e.clientX, y: e.clientY };
let ghost: HTMLElement | null = null;