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

...
Автор SHA1 Повідомлення Дата
arookieofc 4630857d6c Revert "feat(website): add responsive homepage and GitHub Pages deployment (#…"
This reverts commit bb508d4118.
2026-11-07 01:27:55 +08:00
Jaw bb508d4118 feat(website): add responsive homepage and GitHub Pages deployment (#277)
* feat(website): add responsive homepage and Pages deployment

* feat(website): add platform-specific installer download pages
2026-11-07 01:17:04 +08:00
Vadim Lazukтаarookieofc fa5d6d3d47 fix(mybatis): skip method-level annotations when parsing method declarations (#1759) (#1793)
Signed-off-by: Inf1mum <[email protected]>
Co-authored-by: arookieofc <[email protected]>
2026-11-07 01:04:59 +08:00
Vadim Lazuk fb694aaceb feat(debugger): flash the taskbar when a breakpoint is hit in an unfocused window (#1810)
A breakpoint stop now grabs attention like IDEA's: the owning window's
taskbar button flashes while the window is in the background (new
window_flash_taskbar command wrapping request_user_attention, which never
flashes a focused window), and the flash is stopped when the window is
focused, the paused thread resumes, or the session ends. A window running
with Focus application on breakpoint still focuses instead of flashing,
and repeated hits while already flashing do not re-request attention.

Closes #1742

Signed-off-by: Inf1mum <[email protected]>
2026-11-07 01:03:58 +08:00
arookieofc 1f969694a0 feat(build): link file locations in the build console (#1869)
Compiler output in the Build tool window now gets the same clickable
file locations as the run console: Maven's `path:[line,col]` errors,
`path:line:col` diagnostics and URLs open the file (or the browser)
when clicked, resolving against the directory of the step that printed
the line (reactor modules run in their own), then the project root
and a name search.

Closes l0ng-ai/openidea#1867
2026-11-07 00:59:30 +08:00
Shohruh Ismoilov 5b6dd007c6 fix(vcs): show GitHub commit checks in the Git Log (#1861) 2026-11-07 00:26:42 +08:00
Vadim LazukтаInf1mum 0ac3f82dfb fix(editor): cover edge cases of multiline paste with multiple cursors (#1853)
dispatchPaste spread the clipboard only when the line count equaled the
caret count and pasted the whole block at every caret otherwise. Follow
IntelliJ's ClipboardTextPerCaretSplitter instead: caret i gets line i,
extra carets get an empty insert, lines beyond the caret count are
dropped, and a single line repeats at every caret unchanged (a lone
trailing newline stays a single line).

Closes #1828

Signed-off-by: Inf1mum <[email protected]>
Co-authored-by: Inf1mum <[email protected]>
2026-11-07 00:24:39 +08:00
Vadim Lazuk c08657ba17 fix(workbench): keep the active tab close button visible when the editor area narrows (#1784)
Signed-off-by: Inf1mum <[email protected]>
2026-11-07 00:22:19 +08:00
arookieofc 6e18f32a32 fix(smoke): wait for the server before deleting its data directory (#1858)
The java smoke flakes on teardown: the run.test.ts afterEach kills
openidea-server and immediately removes its home directory, but jdtls's
JVM is still shutting down inside it, so rmdir fails ENOTEMPTY. Now
close() resolves once the process exits, and the removal retries for
ten seconds instead of one.
2026-11-07 00:16:14 +08:00
arookieofc 148ae62681 fix(plugins): let find-files reach hidden folders (#1855)
Project scope visits hidden files and folders (the search engine's
walk_files documents exactly that), but find-files left every dot-folder
out on both paths: the index filter dropped them and the disk walk ran
with hidden(true). Hidden folders are now visited like anywhere else;
only .git internals stay out.

Fixes #1850
2026-11-07 00:11:11 +08:00
Jaw 632a98987f fix(vcs): keep Show History working past Windows' command-line limit (#1808) (#1831)
CI / Changes (push) Successful in 1s
Language smoke / Language smoke (go) (push) Failing after 6s
Language smoke / Language smoke (python) (push) Failing after 4s
Language smoke / Language smoke (rust) (push) Failing after 5s
Language smoke / Language smoke (java) (push) Failing after 4s
Language smoke / Language smoke (kotlin) (push) Failing after 5s
Language smoke / Language smoke (typescript) (push) Failing after 5s
CI / Rust (ubuntu-22.04) (push) Failing after 44s
CI / Cargo deny (push) Failing after 13s
CI / Remote server (linux musl) (push) Failing after 59s
CI / Plugins (SDK, official, fixtures) (push) Failing after 1m2s
CI / E2E (push) Failing after 16m55s
CI / Frontend (push) Successful in 26m3s
CI / Rust (macos-latest) (push) Canceled after 0s
CI / Rust (windows-latest) (push) Canceled after 0s
File history passed one ^<sha>^@ exclusion per created file, and path-filtered
log passed every selected path, as git arguments. A large module blew past
Windows' ~32K command line (os error 206). Pass them through git log --stdin.

Following renames only makes sense for a file: on a directory each created file
cut the history short, leaving a single commit. Directories now use plain path
filtering.
2026-11-07 00:06:25 +08:00
l0ng-ai 9c5372c7ab chore: v0.1.38 2026-11-06 23:23:32 +08:00
Arnaud Ritti abdbc39d0d feat(plugins): let a command ask the user with a picker, an input box or a confirmation (#1779)
Plugin API 1.2 adds `ui.pick`, `ui.pick-many`, `ui.input`, `ui.confirm` and `views.reveal`. The dialogs show in the window whose command or event asked and block that call until the user answers; the wait is added to the call's deadline, so it doesn't use up the time budget. They need no capability and return `invalid` without a window (events without a client, rendering, editor providers). Prompts are withdrawn when the call is cancelled or the plugin stops, and reach remote windows through the dispatcher (`plugin_answer_prompt`). `views.reveal` brings one of the plugin's declared views to the front. The Rust SDK and its mock gain `pick`, `pick_many`, `input`, `confirm` and `reveal_view`. All components are rebuilt for the WIT change.

Closes #1768

Co-authored-by: arnaud-ritti <[email protected]>
2026-11-06 23:18:30 +08:00
Vadim Lazuk 52eed40fc8 fix(settings): align fallback font and size fields on the Appearance page (#1782)
The custom font block laid its three fields out as inline flex options that
wrapped freely, so the UI font picker, the fallback font picker and the Size
input started at different x positions depending on what preceded them on
their wrapped line. The block is now a two-column grid: the Use custom font
checkbox, the Fallback font label and the Size label share one label column,
and all three controls start at the same x, matching the Editor > Font page
and IntelliJ's Settings > Appearance layout.

The change is scoped to the Appearance page's own CSS module; no shared form
styles are touched.

Signed-off-by: Inf1mum <[email protected]>
2026-11-06 23:14:06 +08:00
arookieofc dbba16686c fix(agents): don't offer the previous model's thinking levels for a new task (#1846) 2026-11-06 23:05:22 +08:00
Arnaud Ritti a3d5336642 feat(plugins): let plugin code set context keys for its when clauses (#1762)
Plugin API 1.2 adds `ui.set-context(key, value)` and `ui.remove-context(key)`: a plugin sets `plugin.<id>.<key>` for `when` clauses, typed as `context-value` (flag, number or text), in the window the call came from or every window outside a command or event; a window's value wins over the global one. Keys are 1-64 of `A-Za-z0-9_-`, at most 100 per plugin, kept across window reloads and idle reclaim, dropped when the plugin stops or the window closes; remote windows get them through the dispatcher. The Rust SDK takes `impl Into<ContextValue>`. All components are rebuilt for the WIT change.

Closes #1622

Co-authored-by: arnaud-ritti <[email protected]>
2026-11-06 23:02:34 +08:00
Arnaud Ritti 708f1b051b feat(plugins): let a command read every file selected in the Project view (#1744)
Plugin API 1.2 adds `invocation.selected-paths`: the files and folders a Project view or editor tab menu ran the command on, as absolute paths (the command's argument stays the first of them, so existing plugins see no change). The frontend passes the menu's selection to `plugin_run_command` on the desktop and through the remote dispatcher; the Rust SDK and its mock gain `Invocation::selected_paths`. All components are rebuilt for the WIT change.

Closes #1621

Co-authored-by: arnaud-ritti <[email protected]>
2026-11-06 22:54:44 +08:00
l0ng-ai 068dcfdb0a docs(readme): show contributor avatars in the Community section (#1848) 2026-11-06 22:51:10 +08:00
l0ng-ai 3a6c77dce4 fix(terminal): remove redundant scroll-to-end button (#1849) 2026-11-06 22:50:10 +08:00
124 змінених файлів з 3340 додано та 317 видалено

No files matched your search

Створено
+37 -37
Переглянути файл
@@ -4106,7 +4106,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"dunce",
"encoding_rs",
@@ -4129,7 +4129,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4143,7 +4143,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"ide-core",
"serde",
@@ -4154,7 +4154,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"blake3",
"dirs 6.0.0",
@@ -4170,7 +4170,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
@@ -4179,7 +4179,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"dunce",
"encoding_rs",
@@ -4196,7 +4196,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"ide-core",
"ide-run",
@@ -4210,7 +4210,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"futures",
"ide-core",
@@ -4230,7 +4230,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"bb8",
"dirs 6.0.0",
@@ -4257,7 +4257,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"ide-core",
"serde",
@@ -4270,7 +4270,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4290,7 +4290,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4302,7 +4302,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4315,7 +4315,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"base64 0.22.1",
"criterion",
@@ -4376,7 +4376,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"ide-core",
"parking_lot",
@@ -4394,7 +4394,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"blake3",
"criterion",
@@ -4416,7 +4416,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"encoding_rs",
"futures",
@@ -4433,7 +4433,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"blake3",
"criterion",
@@ -4489,7 +4489,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"dunce",
"futures",
@@ -4515,7 +4515,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"futures",
"ide-core",
@@ -4538,7 +4538,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"blake3",
"ide-core",
@@ -4559,7 +4559,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"ide-core",
"ide-run",
@@ -4572,7 +4572,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"globset",
"ide-core",
@@ -4590,7 +4590,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"dunce",
"encoding_rs",
@@ -4613,7 +4613,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"dunce",
"ide-core",
@@ -4632,7 +4632,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"criterion",
"globset",
@@ -4652,7 +4652,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"ide-core",
"parking_lot",
@@ -4665,7 +4665,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4687,7 +4687,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"ide-core",
"ide-language",
@@ -4702,7 +4702,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"ide-core",
"libc",
@@ -4715,7 +4715,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"criterion",
"ide-core",
@@ -4728,7 +4728,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"flate2",
"hex",
@@ -4749,7 +4749,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"blake3",
"dunce",
@@ -4770,7 +4770,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"chardetng",
"dunce",
@@ -4792,7 +4792,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"ide-core",
"open",
@@ -4808,7 +4808,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"blake3",
"dunce",
@@ -6357,7 +6357,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.37"
version = "0.1.38"
dependencies = [
"base64 0.22.1",
"blake3",
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.37"
version = "0.1.38"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+6
Переглянути файл
@@ -64,6 +64,12 @@ the [official plugins](plugins/official). The plugin API is still a preview.
<img src="docs/assets/wechat-group.png" alt="WeChat group QR code" width="200">
### Contributors
<a href="https://github.com/l0ng-ai/openidea/graphs/contributors">
<img src="https://contrib.rocks/image?repo=l0ng-ai/openidea&max=100" alt="OpenIDEA contributors">
</a>
## License
[Apache 2.0](LICENSE). Bundled third-party assets are listed in [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md).
+5
Переглянути файл
@@ -125,6 +125,11 @@ impl Shared {
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
let mut config = self.known.lock().get(provider).map(|k| k.config.clone()).unwrap_or_default();
// A thinking level's values depend on the model (low/medium/high on one, none or a
// different set on another), but what ran last is remembered wholesale — after a
// model switch the New Task page would offer the previous model's levels. Until the
// session reports the new model's own, don't show the option at all.
config.retain(|o| o.category.as_deref() != Some("thought_level"));
config::add_client_options(provider, &mut config);
if let Some((o, v)) = config::bypass_mode(&config).map(|(o, v)| (o.id.clone(), v.value.clone()))
&& let Some(o) = config.iter_mut().find(|c| c.id == o)
+39 -3
Переглянути файл
@@ -11,6 +11,8 @@ struct FakeAgent {
calls: Mutex<Vec<String>>,
/// Without `loadSession` (a session lives only as long as its process).
no_load: bool,
/// Config options `session/new` reports after the model one (per-model efforts, say).
extra_options: Mutex<Vec<Value>>,
}
impl FakeAgent {
@@ -94,10 +96,15 @@ impl Handler for FakeAgent {
Ok(json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": !self.no_load,
"sessionCapabilities": {"fork": {}}, "_meta": {"openidea": {"rollback": true, "steer": true}}}}))
}
"session/new" => Ok(json!({"sessionId": "s1",
"session/new" => {
let mut options = vec![json!({"id": "model", "category": "model", "type": "select",
"currentValue": "big",
"options": [{"value": "big", "name": "Big"}, {"value": "small", "name": "Small"}]})];
options.extend(self.extra_options.lock().iter().cloned());
Ok(json!({"sessionId": "s1",
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]},
"configOptions": [{"id": "model", "category": "model", "type": "select", "currentValue": "big",
"options": [{"value": "big", "name": "Big"}, {"value": "small", "name": "Small"}]}]})),
"configOptions": options}))
}
"session/fork" => Ok(json!({"sessionId": "s2"})),
"_openidea/rollback" | "_openidea/steer" => {
let detail = params.get("turns").cloned().unwrap_or_else(|| params["prompt"][0]["text"].clone());
@@ -788,6 +795,35 @@ async fn usage_limits_and_late_settings() {
assert_eq!(config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("high"));
}
#[tokio::test(flavor = "multi_thread")]
async fn remembered_settings_drop_per_model_choices_for_the_next_task() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
// The effort list depends on the model: what the last session ran means nothing once
// the user picks another model, so the New Task page shows the option without a choice.
*agent.extra_options.lock() = vec![json!({"id": "effort", "category": "thought_level",
"type": "select", "currentValue": "high",
"options": [{"value": "low", "name": "Low"}, {"value": "high", "name": "High"}]})];
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let provider = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
assert!(provider.config.iter().all(|o| o.id != "effort"), "a per-model option isn't offered stale");
let model = provider.config.iter().find(|o| o.id == "model").unwrap();
assert_eq!(model.current.as_deref(), Some("big"), "the model choice survives");
}
#[test]
fn retry_updates_become_a_countdown() {
let update =
+197 -9
Переглянути файл
@@ -1,14 +1,14 @@
//! [`HostApi`] for one plugin's code: what its imports reach in the IDE.
//! Capabilities were checked by the runtime before any of this runs.
use super::{PluginEvent, PluginEventSink};
use super::{PluginContextKey, PluginEvent, PluginEventSink};
use ide_core::ipc_path::to_ipc;
use ide_core::{CancellationToken, TextEdit};
use ide_extension::Package;
use ide_language::ProgramPin;
use ide_plugin::{
EventKind, HostApi, HostError, HttpRequest, HttpResponse, NotificationLevel, ProcessOutput, RepositoryStatus,
StatusItem,
EventKind, HostApi, HostError, HttpRequest, HttpResponse, NotificationLevel, ProcessOutput, Prompt,
RepositoryStatus, StatusItem,
};
use parking_lot::{Mutex, RwLock};
use std::collections::{BTreeMap, BTreeSet, HashMap};
@@ -22,6 +22,10 @@ const MAX_STORAGE: usize = 1 << 20;
const MAX_KEY: usize = 256;
/// Most status bar items per plugin.
const MAX_STATUS_ITEMS: usize = 8;
const MAX_CONTEXT_KEYS: usize = 100;
/// (window or `None` for every window, plugin, key).
type ContextKey = (Option<String>, String, String);
/// What plugins see of the open projects; provided by the app
/// ([`super::PluginHost::set_workspace`]), over [`crate::Host`] on the desktop.
@@ -146,6 +150,12 @@ struct TaskEntry {
cancelled: bool,
}
/// A question a plugin's call waits on.
struct PromptEntry {
plugin: String,
answer: std::sync::mpsc::SyncSender<Option<Vec<String>>>,
}
/// State shared by the host and every plugin's [`PluginApi`].
pub(super) struct Shared {
pub sink: Arc<dyn PluginEventSink>,
@@ -154,8 +164,15 @@ pub(super) struct Shared {
pub data_dir: PathBuf,
tasks: Mutex<HashMap<u64, TaskEntry>>,
next_task: AtomicU64,
prompts: Mutex<HashMap<u64, PromptEntry>>,
/// Plugins being stopped: their calls may not open new prompts (taken before `prompts`).
prompts_blocked: Mutex<BTreeSet<String>>,
next_prompt: AtomicU64,
/// (plugin, item id) → item, for windows opened later.
status: Mutex<BTreeMap<(String, String), StatusItem>>,
/// (scope, plugin, key) → JSON value.
contexts: Mutex<BTreeMap<ContextKey, String>>,
closed_clients: Mutex<BTreeSet<String>>,
/// plugin → kinds subscribed at run time (kept across idle reclaim).
pub subscriptions: Mutex<HashMap<String, BTreeSet<EventKind>>>,
/// plugin → files it shows problems for, withdrawn when it stops.
@@ -183,7 +200,12 @@ impl Shared {
data_dir,
tasks: Mutex::default(),
next_task: AtomicU64::new(1),
prompts: Mutex::default(),
prompts_blocked: Mutex::default(),
next_prompt: AtomicU64::new(1),
status: Mutex::default(),
contexts: Mutex::default(),
closed_clients: Mutex::default(),
subscriptions: Mutex::default(),
diagnostics: Mutex::default(),
})
@@ -226,6 +248,34 @@ impl Shared {
self.status.lock().iter().map(|((p, id), item)| (p.clone(), id.clone(), item.clone())).collect()
}
pub fn context_keys(&self, client: Option<&str>) -> Vec<PluginContextKey> {
let contexts = self.contexts.lock();
let mut keys: BTreeMap<(&str, &str), &str> = BTreeMap::new();
for ((_, plugin, key), value) in contexts.iter().filter(|((s, ..), _)| s.is_none()) {
keys.insert((plugin, key), value);
}
if let Some(client) = client {
for ((_, plugin, key), value) in contexts.iter().filter(|((s, ..), _)| s.as_deref() == Some(client)) {
keys.insert((plugin, key), value);
}
}
keys.into_iter()
.map(|((p, k), v)| PluginContextKey { plugin_id: p.to_owned(), key: k.to_owned(), value: v.to_owned() })
.collect()
}
/// Drops the context keys scoped to window `client` (it closed), without events, and
/// refuses further writes for it (late commands) until [`Self::reopen_client`].
pub fn forget_client(&self, client: &str) {
self.closed_clients.lock().insert(client.to_owned());
self.contexts.lock().retain(|(scope, ..), _| scope.as_deref() != Some(client));
}
/// A window labelled `client` is being created (labels are reused after a close).
pub fn reopen_client(&self, client: &str) {
self.closed_clients.lock().remove(client);
}
/// Withdraws a plugin's run-time state (it stopped or failed). Its
/// subscriptions go only with `subscriptions`, as they survive restarts.
pub fn clear_plugin(&self, plugin: &str, subscriptions: bool) {
@@ -240,6 +290,19 @@ impl Shared {
for id in removed {
self.sink.emit(None, PluginEvent::StatusItemChanged { plugin_id: plugin.to_owned(), id, item: None });
}
self.withdraw_prompts(plugin);
let removed: Vec<(Option<String>, String)> = {
let mut contexts = self.contexts.lock();
let keys: Vec<_> = contexts.keys().filter(|(_, p, _)| p == plugin).cloned().collect();
for key in &keys {
contexts.remove(key);
}
keys.into_iter().map(|(scope, _, key)| (scope, key)).collect()
};
for (scope, key) in removed {
self.sink
.emit(scope.as_deref(), PluginEvent::ContextChanged { plugin_id: plugin.to_owned(), key, value: None });
}
let tasks: Vec<u64> = self.tasks.lock().iter().filter(|(_, t)| t.plugin == plugin).map(|(id, _)| *id).collect();
for id in tasks {
self.end_task(id);
@@ -265,6 +328,40 @@ impl Shared {
true
}
/// Closes the prompts `plugin` waits on: the calls waiting for the user
/// wake up cancelled (dropping the senders).
fn withdraw_prompts(&self, plugin: &str) {
let ids: Vec<u64> = {
let mut prompts = self.prompts.lock();
let ids: Vec<u64> = prompts.iter().filter(|(_, p)| p.plugin == plugin).map(|(id, _)| *id).collect();
for id in &ids {
prompts.remove(id);
}
ids
};
for id in ids {
self.sink.emit(None, PluginEvent::PromptClosed { prompt_id: id.to_string() });
}
}
/// `plugin` is about to be stopped: withdraws its prompts, and its queued
/// calls can't open new ones (they'd keep the stop waiting) until
/// [`allow_prompts`](Self::allow_prompts).
pub fn block_prompts(&self, plugin: &str) {
self.prompts_blocked.lock().insert(plugin.to_owned());
self.withdraw_prompts(plugin);
}
pub fn allow_prompts(&self, plugin: &str) {
self.prompts_blocked.lock().remove(plugin);
}
/// The user answered (`Some`) or dismissed (`None`) a prompt.
pub fn answer_prompt(&self, id: u64, answer: Option<Vec<String>>) -> bool {
let Some(prompt) = self.prompts.lock().remove(&id) else { return false };
prompt.answer.send(answer).is_ok()
}
fn end_task(&self, id: u64) {
if let Some(t) = self.tasks.lock().remove(&id) {
self.sink.emit(None, PluginEvent::TaskEnded { plugin_id: t.plugin, task_id: id.to_string() });
@@ -343,6 +440,52 @@ impl HostApi for PluginApi {
Ok(())
}
fn ask(
&self,
client: Option<&str>,
prompt: Prompt,
cancel: &CancellationToken,
) -> Result<Option<Vec<String>>, HostError> {
let client = from_window(client, "ask the user")?;
let id = self.shared.next_prompt.fetch_add(1, Ordering::Relaxed);
let (answer, answers) = std::sync::mpsc::sync_channel(1);
{
let blocked = self.shared.prompts_blocked.lock();
if blocked.contains(self.id()) {
return Err(HostError::Cancelled);
}
self.shared.prompts.lock().insert(id, PromptEntry { plugin: self.id().to_owned(), answer });
}
let prompt_id = id.to_string();
self.shared.sink.emit(
Some(client),
PluginEvent::PromptRequested { plugin_id: self.id().to_owned(), prompt_id: prompt_id.clone(), prompt },
);
loop {
match answers.recv_timeout(Duration::from_millis(100)) {
Ok(answer) => return Ok(answer),
Err(std::sync::mpsc::RecvTimeoutError::Timeout) if !cancel.is_cancelled() => {}
Err(_) => {
self.shared.prompts.lock().remove(&id);
self.shared.sink.emit(Some(client), PluginEvent::PromptClosed { prompt_id });
return Err(HostError::Cancelled);
}
}
}
}
fn reveal_view(&self, client: Option<&str>, view: &str) -> Result<(), HostError> {
let client = from_window(client, "reveal a view")?;
let declared = self.shared.ui.items(super::ui_points::VIEWS, Some(self.id())).iter().any(|i| i.key == view);
if !declared {
return Err(HostError::NotFound(format!("the plugin declares no view {view:?}")));
}
self.shared
.sink
.emit(Some(client), PluginEvent::RevealView { plugin_id: self.id().to_owned(), view: view.to_owned() });
Ok(())
}
fn status_item(&self, id: &str, item: Option<StatusItem>) {
let key = (self.id().to_owned(), id.to_owned());
{
@@ -371,6 +514,37 @@ impl HostApi for PluginApi {
.emit(None, PluginEvent::StatusItemChanged { plugin_id: self.id().to_owned(), id: id.to_owned(), item });
}
fn set_context(&self, client: Option<&str>, key: &str, value: Option<String>) -> Result<(), HostError> {
let map_key = (client.map(str::to_owned), self.id().to_owned(), key.to_owned());
{
let mut contexts = self.shared.contexts.lock();
if client.is_some_and(|c| self.shared.closed_clients.lock().contains(c)) {
return Ok(());
}
match &value {
Some(value) => {
if contexts.get(&map_key) == Some(value) {
return Ok(());
}
let count = contexts.keys().filter(|(_, p, _)| p == self.id()).count();
if !contexts.contains_key(&map_key) && count >= MAX_CONTEXT_KEYS {
return Err(HostError::Invalid(format!("more than {MAX_CONTEXT_KEYS} context keys")));
}
contexts.insert(map_key, value.clone());
}
None => {
if contexts.remove(&map_key).is_none() {
return Ok(());
}
}
}
}
self.shared
.sink
.emit(client, PluginEvent::ContextChanged { plugin_id: self.id().to_owned(), key: key.to_owned(), value });
Ok(())
}
fn projects(&self) -> Vec<PathBuf> {
self.shared.workspace().map(|w| w.projects()).unwrap_or_default()
}
@@ -464,8 +638,9 @@ impl HostApi for PluginApi {
.build()
.map_err(|e| HostError::Invalid(format!("{glob:?}: {e}")))?
.compile_matcher();
// Hidden files and folders are left out, as in the walk below.
let visible = |rel: &Path| !rel.iter().any(|c| c.to_str().is_some_and(|c| c.starts_with('.')));
// Project scope visits hidden files and folders (`.github`, `.config`):
// only `.git` internals stay out, as in the walk below.
let visible = |rel: &Path| !rel.iter().any(|c| c == ".git");
// The project index already lists the files: walking a large tree on every call can take
// longer than an editor provider's deadline (the plugin is then stopped as crashed).
if let Some(files) = self
@@ -478,7 +653,13 @@ impl HostApi for PluginApi {
return Ok(out);
}
let mut out = Vec::new();
for (n, entry) in ignore::WalkBuilder::new(root).hidden(true).build().flatten().enumerate() {
for (n, entry) in ignore::WalkBuilder::new(root)
.hidden(false)
.filter_entry(|e| e.file_name() != ".git")
.build()
.flatten()
.enumerate()
{
if n >= MAX_WALK || out.len() >= limit {
break;
}
@@ -883,20 +1064,27 @@ mod tests {
let api = api(&root, Arc::default());
*api.shared.workspace.write() = Some(Arc::new(Indexed(
root.clone(),
vec!["src/b/UserMapper.xml", "src/a/OrderMapper.xml", ".idea/workspace.xml", "pom.xml"],
vec!["src/b/UserMapper.xml", "src/a/OrderMapper.xml", ".idea/workspace.xml", ".git/index.xml", "pom.xml"],
)));
// Listed by the index, not walked: none of these exist on disk.
assert_eq!(
api.find_files(&root, "**/*Mapper.xml", 10).unwrap(),
[to_ipc(&root.join("src/a/OrderMapper.xml")), to_ipc(&root.join("src/b/UserMapper.xml"))]
);
assert_eq!(api.find_files(&root, "**/*.xml", 10).unwrap().len(), 3, "hidden folders are left out");
// Hidden folders are visited like any project scope; `.git` internals are not.
assert_eq!(api.find_files(&root, "**/*.xml", 10).unwrap().len(), 4);
assert_eq!(api.find_files(&root, ".idea/*.xml", 10).unwrap(), [to_ipc(&root.join(".idea/workspace.xml"))]);
assert_eq!(api.find_files(&root, "**/*.xml", 1).unwrap().len(), 1);
// Another root: no index covers it, so the disk is walked.
let other = root.join("other");
std::fs::create_dir_all(&other).unwrap();
std::fs::create_dir_all(other.join(".config/tool")).unwrap();
std::fs::write(other.join("a.xml"), "").unwrap();
std::fs::write(other.join(".config/tool/index.xml"), "").unwrap();
assert_eq!(api.find_files(&other, "*.xml", 10).unwrap(), [to_ipc(&other.join("a.xml"))]);
assert_eq!(
api.find_files(&other, ".config/tool/*.xml", 10).unwrap(),
[to_ipc(&other.join(".config/tool/index.xml"))]
);
}
#[test]
+6 -1
Переглянути файл
@@ -121,7 +121,12 @@ pub async fn plugin_navigation_index(
plugins.index_navigation(
&project.root,
crate::plugins::navigation::Snapshot { path: &path, version, text: &text, symbols: &symbols, scope },
Invocation { client: Some(client.clone()), workspace_root: Some(project.root.clone()), editor: None },
Invocation {
client: Some(client.clone()),
workspace_root: Some(project.root.clone()),
editor: None,
selected_paths: Vec::new(),
},
)?;
// A document edit while WASM was executing must not publish stale ranges.
if cancel.is_cancelled() || document.is_some_and(|id| project.documents.version(id).ok() != version) {
+30
Переглянути файл
@@ -1260,11 +1260,34 @@ impl PluginHost {
self.shared.status_items()
}
/// Plugin context keys in effect for window `client`: global keys overlaid with its own.
pub fn context_keys(&self, client: Option<&str>) -> Vec<PluginContextKey> {
self.shared.context_keys(client)
}
/// A window labelled `label` is about to exist again (labels are reused).
pub fn reopen_client(&self, label: &str) {
self.shared.reopen_client(label);
}
/// Window `label` closed: drops its context keys and queued events, and ignores
/// context writes of commands still running for it.
pub fn forget_client(&self, label: &str) {
self.queues.lock().retain(|(_, client), _| client.as_deref() != Some(label));
self.shared.forget_client(label);
}
/// The user cancelled a plugin task (`task_id` from `TaskStarted`).
pub fn cancel_task(&self, task_id: &str) -> bool {
task_id.parse().is_ok_and(|id| self.shared.cancel_task(id))
}
/// The user answered (`Some`) or dismissed (`None`) a prompt
/// (`PromptRequested`); false when it is no longer waiting.
pub fn answer_prompt(&self, prompt_id: &str, answer: Option<Vec<String>>) -> bool {
prompt_id.parse().is_ok_and(|id| self.shared.answer_prompt(id, answer))
}
/// Kinds of workbench events some running or activatable plugin wants;
/// the UI reports only these.
pub fn event_kinds(&self) -> BTreeSet<EventKind> {
@@ -1393,6 +1416,7 @@ impl PluginHost {
workspace_root: client.as_deref().and_then(|c| self.shared.project_of(c)),
client: client.clone(),
editor: None,
selected_paths: Vec::new(),
};
let kinds: BTreeSet<EventKind> = events.iter().map(WorkbenchEvent::kind).collect();
{
@@ -1567,6 +1591,9 @@ impl PluginHost {
/// Deactivates every plugin (also done on drop).
pub fn shutdown(&self) {
let actors: Vec<_> = self.plugins.read().values().filter_map(|p| p.runtime.lock().take()).collect();
for id in self.plugins.read().keys() {
self.shared.block_prompts(id);
}
for a in &actors {
a.stop(false);
}
@@ -1880,6 +1907,7 @@ impl PluginHost {
Err(e) => return Err(IdeError::internal(format!("plugin {:?}: {e}", plugin.id()))),
};
*runtime = Some(actor.clone());
self.shared.allow_prompts(plugin.id());
let mut meta = plugin.meta.lock();
meta.status = PluginStatus::Active;
meta.has_syntax = has_syntax;
@@ -1977,6 +2005,8 @@ impl PluginHost {
fn stop(&self, plugin: &LoadedPlugin) {
self.clear_plugin_navigation(plugin.id());
// A call waiting on the user would keep the join below waiting.
self.shared.block_prompts(plugin.id());
if let Some(actor) = plugin.runtime.lock().take() {
actor.stop(true);
}
+18 -2
Переглянути файл
@@ -13,8 +13,8 @@
//!
//! The commands a window needs at run time (`plugin_run_command`,
//! `plugin_post_events`, `plugin_event_kinds`, `plugin_status_items`,
//! `plugin_cancel_task`, `plugin_set_active_file`, `plugin_line_markers`,
//! `plugin_view_render`, `plugin_view_event`)
//! `plugin_context_keys`, `plugin_cancel_task`, `plugin_answer_prompt`, `plugin_set_active_file`,
//! `plugin_line_markers`, `plugin_view_render`, `plugin_view_event`)
//! carry the desktop commands' names and arguments, so a remote window's UI
//! routes them here unchanged. Plugin results come back as `plugin`
//! notifications ([`PluginEventMessage`]); secrets stay in the desktop's
@@ -107,6 +107,7 @@ pub fn forwarded(event: &PluginEvent) -> bool {
event,
PluginEvent::Notification { .. }
| PluginEvent::StatusItemChanged { .. }
| PluginEvent::ContextChanged { .. }
| PluginEvent::TaskStarted { .. }
| PluginEvent::TaskProgress { .. }
| PluginEvent::TaskEnded { .. }
@@ -117,6 +118,9 @@ pub fn forwarded(event: &PluginEvent) -> bool {
| PluginEvent::OpenLocation { .. }
| PluginEvent::CopyToClipboard { .. }
| PluginEvent::OpenUrl { .. }
| PluginEvent::PromptRequested { .. }
| PluginEvent::PromptClosed { .. }
| PluginEvent::RevealView { .. }
)
}
@@ -367,10 +371,12 @@ impl RemotePlugins {
let command_id: String = c.arg("commandId")?;
let arg: Option<String> = c.arg("arg")?;
let editor: Option<PluginEditor> = c.arg("editor")?;
let paths: Option<Vec<PathBuf>> = c.arg("paths")?;
let invocation = Invocation {
client: Some(c.window.clone()),
workspace_root: c.host.project(&c.window).ok().map(|p| p.root.clone()),
editor: editor.map(PluginEditor::context),
selected_paths: paths.unwrap_or_default(),
};
blocking(move || host.run_command(&plugin_id, &command_id, arg.as_deref(), invocation)).await
}
@@ -400,11 +406,21 @@ impl RemotePlugins {
}
});
let h = host.clone();
d.add("plugin_context_keys", move |c| {
let h = h.clone();
async move { Ok(alive(&h)?.context_keys(Some(&c.window))) }
});
let h = host.clone();
d.add("plugin_cancel_task", move |c| {
let h = h.clone();
async move { Ok(alive(&h)?.cancel_task(&c.arg::<String>("taskId")?)) }
});
let h = host.clone();
d.add("plugin_answer_prompt", move |c| {
let h = h.clone();
async move { Ok(alive(&h)?.answer_prompt(&c.arg::<String>("promptId")?, c.arg("answer")?)) }
});
let h = host.clone();
d.add("plugin_set_active_file", move |c| {
let h = h.clone();
async move {
+26 -1
Переглянути файл
@@ -3,7 +3,9 @@
use super::theme::ThemeDef;
use ide_extension::package::PluginIcon;
use ide_extension::{CapabilityInfo, ContributionInfo, UiContribution};
pub use ide_plugin::{ActionPerformed, ActionSource, EventKind, NotificationLevel, StatusItem, WorkbenchEvent};
pub use ide_plugin::{
ActionPerformed, ActionSource, EventKind, NotificationLevel, PickItem, Prompt, StatusItem, WorkbenchEvent,
};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -166,6 +168,10 @@ pub enum PluginEvent {
/// A plugin's status bar item was set (`item`) or removed.
#[serde(rename_all = "camelCase")]
StatusItemChanged { plugin_id: String, id: String, item: Option<StatusItem> },
/// A plugin's context key was set (`value`: JSON text) or removed, in the
/// emitted window (every window when the client is `None`).
#[serde(rename_all = "camelCase")]
ContextChanged { plugin_id: String, key: String, value: Option<String> },
/// A plugin began a task: show it with the background tasks.
#[serde(rename_all = "camelCase")]
TaskStarted { plugin_id: String, task_id: String, title: String, cancellable: bool },
@@ -208,6 +214,16 @@ pub enum PluginEvent {
/// Open `url` (`http(s)://`) in the system browser.
#[serde(rename_all = "camelCase")]
OpenUrl { plugin_id: String, url: String },
/// A command waits for the user's answer: show `prompt`, then report it with
/// `plugin_answer_prompt(prompt_id, …)`.
#[serde(rename_all = "camelCase")]
PromptRequested { plugin_id: String, prompt_id: String, prompt: Prompt },
/// The call that asked gave up (cancelled, or its plugin stopped): close the prompt.
#[serde(rename_all = "camelCase")]
PromptClosed { prompt_id: String },
/// Bring the tool window of the plugin's view `view` to the front.
#[serde(rename_all = "camelCase")]
RevealView { plugin_id: String, view: String },
}
/// Delivers events to the UI. `client` is the window that invoked the plugin
@@ -254,6 +270,15 @@ pub struct PluginStatusItem {
pub item: StatusItem,
}
/// A plugin's context key for `when` clauses (`value` is JSON text).
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PluginContextKey {
pub plugin_id: String,
pub key: String,
pub value: String,
}
/// A gutter marker from a plugin's `line-markers` provider.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+6 -1
Переглянути файл
@@ -25,7 +25,12 @@ pub fn view_invocation(
Some(EditorContext { path: info.path.0, language: info.language.0, selections: Vec::new() })
}
};
Ok(Invocation { client: Some(window.to_owned()), workspace_root: project.as_ref().map(|p| p.root.clone()), editor })
Ok(Invocation {
client: Some(window.to_owned()),
workspace_root: project.as_ref().map(|p| p.root.clone()),
editor,
..Invocation::default()
})
}
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
+1 -1
Переглянути файл
@@ -58,7 +58,7 @@ fn fixture() -> Fixture {
}
fn inv() -> Invocation {
Invocation { client: Some("main".into()), workspace_root: None, editor: None }
Invocation { client: Some("main".into()), workspace_root: None, editor: None, selected_paths: Vec::new() }
}
fn misbehave() -> PathBuf {
+6 -1
Переглянути файл
@@ -171,7 +171,12 @@ fn two_windows_of_same_root_keep_unsaved_snapshots_isolated() {
.index_navigation(
&f.root,
Snapshot { path, version: Some(1), text, symbols: &symbols, scope: "" },
Invocation { client: Some(client.into()), workspace_root: Some(f.root.clone()), editor: None },
Invocation {
client: Some(client.into()),
workspace_root: Some(f.root.clone()),
editor: None,
selected_paths: Vec::new(),
},
)
.unwrap();
}
+263 -2
Переглянути файл
@@ -231,7 +231,12 @@ fn fixture(limits: Limits) -> Fixture {
impl Fixture {
fn inv(&self) -> Invocation {
Invocation { client: Some("main".into()), workspace_root: Some(self.project.clone()), editor: None }
Invocation {
client: Some("main".into()),
workspace_root: Some(self.project.clone()),
editor: None,
selected_paths: Vec::new(),
}
}
fn install(&self, dir: &Path) -> PluginInfo {
@@ -357,7 +362,7 @@ fn read_file_is_confined_to_the_project() {
assert!(err.contains("outside the project root"), "{err}");
assert!(f.run("misbehave", "read", Some("/etc/hosts")).is_err());
// Without a project there is nothing to read.
let inv = Invocation { client: None, workspace_root: None, editor: None };
let inv = Invocation::default();
let err = f.host.run_command("misbehave", "read", Some("src/notes.txt"), inv).unwrap_err().message;
assert!(err.contains("no project is open"), "{err}");
assert_eq!(f.run("misbehave", "root", None).unwrap().unwrap(), to_ipc(&f.project));
@@ -2142,6 +2147,17 @@ fn views_open_project_files_at_a_line() {
assert!(opened.is_none());
}
#[test]
fn commands_see_the_paths_they_were_run_on() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
let (a, b) = (f.project.join("src/a.txt"), f.project.join("src/b.txt"));
let inv = Invocation { selected_paths: vec![a.clone(), b.clone()], ..f.inv() };
let out = f.host.run_command("jobs", "selection", Some(&to_ipc(&a)), inv).unwrap();
assert_eq!(out.as_deref(), Some(format!("{}\n{}", to_ipc(&a), to_ipc(&b)).as_str()));
assert_eq!(f.run("jobs", "selection", None).unwrap().as_deref(), Some(""));
}
#[test]
fn vcs_remotes_clipboard_and_open_url() {
let f = fixture(Limits::default());
@@ -2198,6 +2214,126 @@ fn vcs_remotes_clipboard_and_open_url() {
}
}
/// Runs `cmd` of the jobs plugin; once it asks the user, answers after `delay`
/// (`None`: dismisses). Returns the command's result and what it asked.
fn run_and_answer(
f: &Fixture,
cmd: &str,
arg: Option<&str>,
answer: Option<&[&str]>,
delay: Duration,
) -> (Result<Option<String>, String>, ide_plugin::Prompt) {
std::thread::scope(|scope| {
let running = scope.spawn(|| f.run("jobs", cmd, arg));
let deadline = Instant::now() + Duration::from_secs(10);
let (client, prompt_id, prompt) = loop {
let asked = f.take_events().into_iter().find_map(|(client, e)| match e {
PluginEvent::PromptRequested { prompt_id, prompt, .. } => Some((client, prompt_id, prompt)),
_ => None,
});
if let Some(asked) = asked {
break asked;
}
assert!(Instant::now() < deadline && !running.is_finished(), "the command never asked");
std::thread::sleep(Duration::from_millis(10));
};
assert_eq!(client.as_deref(), Some("main"), "asks in the window that ran the command");
std::thread::sleep(delay);
let answer = answer.map(|a| a.iter().map(|s| (*s).to_owned()).collect());
assert!(f.host.answer_prompt(&prompt_id, answer));
assert!(!f.host.answer_prompt(&prompt_id, None), "an answer counts once");
(running.join().unwrap(), prompt)
})
}
#[test]
fn commands_ask_the_user_and_reveal_their_views() {
use ide_plugin::{PickItem, Prompt};
let f = fixture(Limits { timeout: Duration::from_millis(500), ..Limits::default() });
let info = f.install(&sample("jobs"));
assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error);
let none = Duration::ZERO;
let (result, prompt) = run_and_answer(&f, "pick", None, Some(&["b"]), none);
assert_eq!(result.unwrap().as_deref(), Some("b"));
let items = vec![
PickItem { key: "a".into(), label: "Alpha".into(), description: Some("first".into()) },
PickItem { key: "b".into(), label: "Beta".into(), description: None },
PickItem { key: "c".into(), label: "Gamma".into(), description: None },
];
assert_eq!(prompt, Prompt::QuickPick { title: "Pick".into(), items, multiple: false });
let (result, prompt) = run_and_answer(&f, "pick-many", None, Some(&["a", "c"]), none);
assert_eq!(result.unwrap().as_deref(), Some("a,c"));
assert!(matches!(prompt, Prompt::QuickPick { multiple: true, .. }));
assert_eq!(run_and_answer(&f, "pick", None, None, none).0.unwrap().as_deref(), Some("none"));
let (result, prompt) = run_and_answer(&f, "input", Some("Main"), Some(&["Other"]), none);
assert_eq!(result.unwrap().as_deref(), Some("Other"));
assert_eq!(prompt, Prompt::Input { prompt: "Name".into(), value: Some("Main".into()) });
assert_eq!(run_and_answer(&f, "input", None, None, none).0.unwrap().as_deref(), Some("none"));
let (result, prompt) = run_and_answer(&f, "confirm", None, Some(&[]), none);
assert_eq!(result.unwrap().as_deref(), Some("true"));
assert_eq!(prompt, Prompt::Confirm { title: "Delete".into(), message: "Really?".into() });
assert_eq!(run_and_answer(&f, "confirm", None, None, none).0.unwrap().as_deref(), Some("false"));
// The wait is not part of the call's 500 ms budget.
let (result, _) = run_and_answer(&f, "confirm", None, Some(&[]), Duration::from_millis(1200));
assert_eq!(result.unwrap().as_deref(), Some("true"));
// Keys come back as given: one that doesn't fit is refused, not cut.
f.take_events();
let err = f.run("jobs", "pick", Some("long-key")).unwrap_err();
assert!(err.contains("item key is longer"), "{err}");
assert!(f.take_events().iter().all(|(_, e)| !matches!(e, PluginEvent::PromptRequested { .. })));
// Without a window there is nothing to attach the dialog to.
f.take_events();
let no_window = Invocation { client: None, ..f.inv() };
for cmd in ["pick", "input", "confirm"] {
let err = f.host.run_command("jobs", cmd, None, no_window.clone()).unwrap_err().message;
assert!(err.contains("from a command the user invoked"), "{cmd}: {err}");
}
assert!(f.take_events().iter().all(|(_, e)| !matches!(e, PluginEvent::PromptRequested { .. })));
// `views.reveal` only knows the plugin's own declared views.
f.take_events();
f.run("jobs", "reveal", Some("jobs")).unwrap();
let revealed = f.take_events().into_iter().find_map(|(client, e)| match e {
PluginEvent::RevealView { plugin_id, view } => Some((client, plugin_id, view)),
_ => None,
});
assert_eq!(revealed, Some((Some("main".into()), "jobs".into(), "jobs".into())));
for view in ["greetings", ""] {
let err = f.run("jobs", "reveal", Some(view)).unwrap_err();
assert!(err.contains("declares no view"), "{view:?}: {err}");
}
assert!(f.run("jobs", "reveal", Some("jobs")).is_ok(), "the instance survives");
}
#[test]
fn disabling_a_plugin_that_waits_for_an_answer_does_not_hang() {
let f = fixture(Limits::default());
let info = f.install(&sample("jobs"));
assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error);
std::thread::scope(|scope| {
let running = scope.spawn(|| f.run("jobs", "confirm", None));
let deadline = Instant::now() + Duration::from_secs(10);
while !f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. })) {
assert!(Instant::now() < deadline && !running.is_finished(), "the command never asked");
std::thread::sleep(Duration::from_millis(10));
}
let started = Instant::now();
f.host.set_enabled("jobs", false).unwrap();
assert!(started.elapsed() < Duration::from_secs(5), "disabling waited for the user");
assert!(running.join().unwrap().is_err(), "the waiting command ends with an error");
});
f.host.set_enabled("jobs", true).unwrap();
let (result, _) = run_and_answer(&f, "confirm", None, Some(&[]), Duration::ZERO);
assert_eq!(result.unwrap().as_deref(), Some("true"), "prompts work again after the restart");
}
#[test]
fn views_can_use_an_svg_icon_from_the_package() {
let f = fixture(Limits::default());
@@ -2675,6 +2811,131 @@ fn completion_quick_fixes_problems_and_event_kinds_of_api_1() {
assert_eq!((d[0].unnecessary, d[0].deprecated, d[0].source.as_deref()), (true, false, Some("lint")));
}
#[test]
fn plugins_set_their_own_context_keys() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
f.take_events();
f.run("jobs", "context", Some("connected=true")).unwrap();
let changed: Vec<_> = f
.take_events()
.into_iter()
.filter_map(|(client, e)| match e {
PluginEvent::ContextChanged { plugin_id, key, value } => Some((client, plugin_id, key, value)),
_ => None,
})
.collect();
assert_eq!(changed, [(Some("main".into()), "jobs".into(), "connected".into(), Some("true".into()))]);
assert_eq!(f.host.context_keys(Some("main")).len(), 1);
assert!(f.host.context_keys(Some("other")).is_empty(), "window-scoped");
for bad in ["bad key=true", "a.b=true", "x=NaN"] {
assert!(f.run("jobs", "context", Some(bad)).unwrap_err().contains("invalid"), "{bad}");
}
f.run("jobs", "context", Some("connected=")).unwrap();
assert!(f.host.context_keys(Some("main")).is_empty());
f.run("jobs", "context", Some("connected=true")).unwrap();
f.host.set_enabled("jobs", false).unwrap();
assert!(f.host.context_keys(Some("main")).is_empty(), "cleared when the plugin stops");
}
#[test]
fn context_keys_are_capped_and_windows_overlay_global_ones() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
for i in 0..100 {
f.run("jobs", "context", Some(&format!("k{i}=1"))).unwrap();
}
assert!(f.run("jobs", "context", Some("k100=1")).unwrap_err().contains("invalid"));
f.run("jobs", "context", Some("k0=2")).unwrap();
for i in 1..4 {
f.run("jobs", "context", Some(&format!("k{i}="))).unwrap();
}
let global = Invocation { client: None, ..f.inv() };
f.host.run_command("jobs", "context", Some("g=1"), global.clone()).unwrap();
f.host.run_command("jobs", "context", Some("w=global"), global).unwrap();
f.run("jobs", "context", Some("w=window")).unwrap();
let w = |client| f.host.context_keys(Some(client)).into_iter().find(|k| k.key == "w").map(|k| k.value);
assert_eq!(w("main").as_deref(), Some("\"window\""));
assert_eq!(w("other").as_deref(), Some("\"global\""));
f.run("jobs", "context", Some("w=")).unwrap();
assert_eq!(w("main").as_deref(), Some("\"global\""), "removing the window key reveals the global one");
}
#[test]
fn context_values_are_stored_as_json_and_bounded() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
let value = |arg: &str| {
f.run("jobs", "context", Some(arg)).unwrap();
f.host.context_keys(Some("main")).into_iter().find(|k| k.key == "x").unwrap().value
};
assert_eq!(value("x=true"), "true");
assert_eq!(value("x=2.5"), "2.5");
assert_eq!(value("x=say \"hi\""), "\"say \\\"hi\\\"\"");
assert_eq!(value("x=1"), "1");
f.take_events();
f.run("jobs", "context", Some("x=1.0")).unwrap();
assert!(f.take_events().is_empty(), "the same value emits nothing");
let long = format!("x={}", "a".repeat(1025));
assert!(f.run("jobs", "context", Some(&long)).unwrap_err().contains("invalid"));
}
#[test]
fn forgetting_a_window_drops_its_context_keys_silently() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
f.run("jobs", "context", Some("w=1")).unwrap();
f.take_events();
f.host.forget_client("main");
assert!(f.host.context_keys(Some("main")).is_empty());
assert!(f.take_events().is_empty());
}
#[test]
fn a_closed_window_ignores_late_context_writes_until_its_label_is_reused() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
f.host.forget_client("main");
f.take_events();
f.run("jobs", "context", Some("late=1")).unwrap();
assert!(f.host.context_keys(Some("main")).is_empty());
let events = f.take_events();
assert!(
!events.iter().any(|(_, e)| matches!(e, PluginEvent::ContextChanged { .. })),
"no context event: {events:?}"
);
f.host.reopen_client("main");
f.run("jobs", "context", Some("fresh=1")).unwrap();
assert_eq!(f.host.context_keys(Some("main"))[0].key, "fresh");
}
#[test]
fn stopping_a_plugin_withdraws_each_context_key_in_its_own_scope() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
let global = Invocation { client: None, ..f.inv() };
f.host.run_command("jobs", "context", Some("g=1"), global).unwrap();
f.run("jobs", "context", Some("w=1")).unwrap();
f.take_events();
f.host.set_enabled("jobs", false).unwrap();
let mut removed: Vec<_> = f
.take_events()
.into_iter()
.filter_map(|(client, e)| match e {
PluginEvent::ContextChanged { key, value: None, .. } => Some((client, key)),
_ => None,
})
.collect();
removed.sort();
assert_eq!(removed, [(None, "g".to_owned()), (Some("main".to_owned()), "w".to_owned())]);
}
/// A data-only package `id` in `dir` whose manifest ends with `extra`, plus `files`.
fn icon_package(dir: &Path, id: &str, extra: &str, files: &[(&str, &str)]) -> PathBuf {
let pkg = dir.join(id);
+26
Переглянути файл
@@ -300,5 +300,31 @@ async fn remote_projects_get_plugin_views_and_custom_editors() {
})
})
.await;
invoke(
&peer,
"plugin_run_command",
json!({ "pluginId": "jobs", "commandId": "context", "arg": "mode=true", "editor": null }),
)
.await
.unwrap();
until("the context key's event", 5, || {
client.plugin_events.lock().iter().any(|m| {
m.window.as_deref() == Some("main")
&& matches!(&m.event, PluginEvent::ContextChanged { key, value, .. } if key == "mode" && value.as_deref() == Some("true"))
})
})
.await;
let keys = invoke(&peer, "plugin_context_keys", json!({})).await.unwrap();
assert_eq!(keys, json!([{ "pluginId": "jobs", "key": "mode", "value": "true" }]), "{keys}");
let selected = invoke(
&peer,
"plugin_run_command",
json!({ "pluginId": "jobs", "commandId": "selection", "arg": null, "editor": null, "paths": ["/srv/src/a.txt"] }),
)
.await
.unwrap();
assert_eq!(selected, "/srv/src/a.txt");
plugins.host().shutdown();
}
+32 -1
Переглянути файл
@@ -5,7 +5,7 @@
use crate::types::{CodeAction, CompletionItem, InlineSuggestion, LineMarker, Location, ProviderDocument};
use crate::types::{
EventKind, HostError, HttpRequest, HttpResponse, Invocation, Limits, NotificationLevel, ProcessOutput,
EventKind, HostError, HttpRequest, HttpResponse, Invocation, Limits, NotificationLevel, ProcessOutput, Prompt,
RepositoryStatus, StatusItem, SyntaxFold, SyntaxSymbol, SyntaxToken, WorkbenchEvent,
};
use crate::types::{
@@ -55,8 +55,32 @@ pub trait HostApi: Send + Sync {
let _ = (client, url);
Ok(())
}
/// Shows `prompt` in `client`'s window and waits for the answer until the
/// user gives one or `cancel` fires: the chosen keys (`QuickPick`), the
/// text (`Input`, one element) or any value (`Confirm`: OK); `None` when
/// dismissed.
fn ask(
&self,
client: Option<&str>,
prompt: Prompt,
cancel: &CancellationToken,
) -> Result<Option<Vec<String>>, HostError> {
let _ = (client, prompt, cancel);
Ok(None)
}
/// Brings the plugin's declared view to the front in `client`'s window.
fn reveal_view(&self, client: Option<&str>, view: &str) -> Result<(), HostError> {
let _ = (client, view);
Ok(())
}
/// Sets (`Some`) or removes the plugin's status bar item `id`.
fn status_item(&self, id: &str, item: Option<StatusItem>);
/// Sets (`Some`, validated JSON text) or removes the plugin's context key,
/// for window `client` (every window if `None`).
fn set_context(&self, client: Option<&str>, key: &str, value: Option<String>) -> Result<(), HostError> {
let _ = (client, key, value);
Ok(())
}
/// Roots of the open projects.
fn projects(&self) -> Vec<std::path::PathBuf>;
/// Unsaved text of an open editor's file.
@@ -358,6 +382,8 @@ pub struct StoreData {
pub(crate) granted: Vec<Capability>,
pub(crate) host: Arc<dyn HostApi>,
pub(crate) invocation: Invocation,
/// The running call is a command or an event, so it may ask the user.
pub(crate) interactive: bool,
/// Tasks begun by the running call and not ended yet.
pub(crate) open_tasks: Vec<u64>,
pub(crate) last_report: Option<Instant>,
@@ -538,6 +564,7 @@ impl Runtime {
granted: setup.granted,
host: setup.host,
invocation: Invocation::default(),
interactive: false,
open_tasks: Vec::new(),
last_report: None,
};
@@ -837,6 +864,7 @@ impl Runtime {
) -> Result<Option<String>, CallError> {
let result = self.call(invocation, self.limits.timeout, |e, store| {
let ctx = store.data_mut().new_invocation()?;
store.data_mut().interactive = true;
let r = e.plugin.openidea_plugin_commands().call_run(
&mut *store,
id,
@@ -887,6 +915,7 @@ impl Runtime {
let event = event_to_wit_view(event);
let result = self.call(invocation, self.limits.timeout, |e, store| {
let ctx = store.data_mut().new_invocation()?;
store.data_mut().interactive = true;
let views = e.views.as_ref().expect("checked");
let r = views.call_handle(&mut *store, view, &event, wasmtime::component::Resource::new_borrow(ctx.rep()));
store.data_mut().drop_invocation(ctx);
@@ -900,6 +929,7 @@ impl Runtime {
let events: Vec<wit_events::Event> = events.into_iter().take(MAX_BATCH).map(event_to_wit).collect();
self.call(invocation, self.limits.timeout, |e, store| {
let ctx = store.data_mut().new_invocation()?;
store.data_mut().interactive = true;
let r = e.plugin.openidea_plugin_event_handler().call_handle(
&mut *store,
&events,
@@ -936,6 +966,7 @@ impl Runtime {
let result = f(&self.exports, &mut self.store);
let data = self.store.data_mut();
data.invocation = Invocation::default();
data.interactive = false;
// Tasks don't outlive the call that began them.
for id in std::mem::take(&mut data.open_tasks) {
data.host.task_end(id);
+23
Переглянути файл
@@ -28,6 +28,8 @@ pub struct Invocation {
pub client: Option<String>,
pub workspace_root: Option<PathBuf>,
pub editor: Option<EditorContext>,
/// Files and folders the command was run on.
pub selected_paths: Vec<PathBuf>,
}
/// A failed host call, as the plugin sees it (WIT `types.error`).
@@ -66,6 +68,27 @@ pub struct StatusItem {
pub command: Option<String>,
}
/// An entry of a plugin's `pick` or `pick-many`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PickItem {
pub key: String,
pub label: String,
pub description: Option<String>,
}
/// What a plugin asks the user (`ui.pick`, `ui.pick-many`, `ui.input`, `ui.confirm`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum Prompt {
#[serde(rename_all = "camelCase")]
QuickPick { title: String, items: Vec<PickItem>, multiple: bool },
#[serde(rename_all = "camelCase")]
Input { prompt: String, value: Option<String> },
#[serde(rename_all = "camelCase")]
Confirm { title: String, message: String },
}
/// Kinds of workbench events a plugin can subscribe to (`on-event:<kind>`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "kebab-case")]
+113 -2
Переглянути файл
@@ -2,9 +2,11 @@
//! types and the implementation of every import. Capabilities are checked
//! here; a missing one returns `error::denied` (the plugin can degrade).
use crate::runtime::{StoreData, clip};
use crate::runtime::{MAX_TITLE, StoreData, clip};
use crate::sandbox;
use crate::types::{EditorContext, EventKind, HostError, HttpRequest, NotificationLevel, StatusItem, net_host};
use crate::types::{
EditorContext, EventKind, HostError, HttpRequest, NotificationLevel, PickItem, Prompt, StatusItem, net_host,
};
use ide_core::ipc_path::to_ipc;
use ide_extension::Capability;
use std::path::{Path, PathBuf};
@@ -133,6 +135,8 @@ const MAX_DIAGNOSTICS: usize = 5_000;
const MAX_REQUEST_BODY: usize = 8 << 20;
const MAX_FIND: u32 = 10_000;
const MAX_STATUS_TEXT: usize = 128;
const MAX_PICK_ITEMS: usize = 5000;
const MAX_PICK_KEY: usize = 256;
type Fallible<T> = wasmtime::Result<Result<T, wit::Error>>;
@@ -212,6 +216,52 @@ impl log::Host for StoreData {
}
}
impl StoreData {
/// Asks the user and waits; the wait doesn't count against the call's
/// wall-clock budget.
fn ask(&mut self, prompt: Prompt) -> Result<Option<Vec<String>>, wit::Error> {
self.require_interactive()?;
let client = self.invocation.client.clone();
let started = Instant::now();
let answer = self.host.ask(client.as_deref(), prompt, &self.cancel.token());
let waited = started.elapsed();
self.deadline += waited;
self.call_started += waited;
answer.map_err(to_wit)
}
fn pick_prompt(
&mut self,
title: String,
items: Vec<ui::PickItem>,
multiple: bool,
) -> Result<Option<Vec<String>>, wit::Error> {
if items.len() > MAX_PICK_ITEMS {
return Err(wit::Error::Invalid(format!("more than {MAX_PICK_ITEMS} items")));
}
if items.iter().any(|i| i.key.len() > MAX_PICK_KEY) {
return Err(wit::Error::Invalid(format!("an item key is longer than {MAX_PICK_KEY} bytes")));
}
let items = items
.into_iter()
.map(|i| PickItem {
key: i.key,
label: clip(i.label, MAX_TITLE),
description: i.description.map(|d| clip(d, 1024)),
})
.collect();
self.ask(Prompt::QuickPick { title: clip(title, MAX_TITLE), items, multiple })
}
/// Dialogs belong to commands and events; rendering and providers have no one to ask.
fn require_interactive(&self) -> Result<(), wit::Error> {
if self.interactive {
return Ok(());
}
Err(wit::Error::Invalid("can only ask the user from a command or event".into()))
}
}
impl ui::Host for StoreData {
fn show_notification(
&mut self,
@@ -244,6 +294,36 @@ impl ui::Host for StoreData {
Ok(())
}
fn set_context(&mut self, key: String, value: ui::ContextValue) -> Fallible<()> {
let valid_key =
(1..=64).contains(&key.len()) && key.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'));
if !valid_key {
return Ok(Err(wit::Error::Invalid(format!("context key {key:?}: expected 1-64 of A-Za-z0-9_-"))));
}
// Kept as JSON text, which the windows parse into their context.
let json = match value {
ui::ContextValue::Flag(b) => b.to_string(),
ui::ContextValue::Number(n) if n.fract() == 0.0 && n.abs() < 9e15 => (n as i64).to_string(),
ui::ContextValue::Number(n) => match serde_json::Number::from_f64(n) {
Some(n) => n.to_string(),
None => return Ok(Err(wit::Error::Invalid("context value: not a finite number".into()))),
},
ui::ContextValue::Text(t) if t.len() <= 1024 => serde_json::Value::String(t).to_string(),
ui::ContextValue::Text(_) => {
return Ok(Err(wit::Error::Invalid("context value: text longer than 1024 bytes".into())));
}
};
let client = self.invocation.client.clone();
Ok(self.host.set_context(client.as_deref(), &key, Some(json)).map_err(to_wit))
}
fn remove_context(&mut self, key: String) -> wasmtime::Result<()> {
let client = self.invocation.client.clone();
// Nothing to remove under an invalid key.
let _ = self.host.set_context(client.as_deref(), &key, None);
Ok(())
}
fn copy_to_clipboard(&mut self, text: String) -> Fallible<()> {
if let Err(e) = self.require(Capability::Clipboard) {
return Ok(Err(e));
@@ -261,6 +341,25 @@ impl ui::Host for StoreData {
let client = self.invocation.client.clone();
Ok(self.host.open_url(client.as_deref(), trimmed.to_owned()).map_err(to_wit))
}
fn pick(&mut self, title: String, items: Vec<ui::PickItem>) -> Fallible<Option<String>> {
let answer = self.pick_prompt(title, items, false);
Ok(answer.map(|keys| keys.and_then(|keys| keys.into_iter().next())))
}
fn pick_many(&mut self, title: String, items: Vec<ui::PickItem>) -> Fallible<Option<Vec<String>>> {
Ok(self.pick_prompt(title, items, true))
}
fn input(&mut self, prompt: String, value: Option<String>) -> Fallible<Option<String>> {
let prompt = Prompt::Input { prompt: clip(prompt, MAX_TITLE), value: value.map(|v| clip(v, 4096)) };
Ok(self.ask(prompt).map(|answer| answer.and_then(|text| text.into_iter().next())))
}
fn confirm(&mut self, title: String, body: String) -> Fallible<bool> {
let prompt = Prompt::Confirm { title: clip(title, MAX_TITLE), message: clip(body, 16 << 10) };
Ok(self.ask(prompt).map(|answer| answer.is_some()))
}
}
impl storage::Host for StoreData {
@@ -419,6 +518,10 @@ impl invocation::HostInvocation for StoreData {
}
}
fn selected_paths(&mut self, _this: Resource<InvocationRes>) -> wasmtime::Result<Vec<String>> {
Ok(self.invocation.selected_paths.iter().take(MAX_FIND as usize).map(|p| to_ipc(p)).collect())
}
fn drop(&mut self, rep: Resource<InvocationRes>) -> wasmtime::Result<()> {
// Owned by the host for the duration of the call.
let _ = rep;
@@ -649,6 +752,14 @@ impl views::Host for StoreData {
Ok(())
}
fn reveal(&mut self, view: String) -> Fallible<()> {
if let Err(e) = self.require_interactive() {
return Ok(Err(e));
}
let client = self.invocation.client.clone();
Ok(self.host.reveal_view(client.as_deref(), &clip(view, 64)).map_err(to_wit))
}
fn post_message(&mut self, view: String, message: String) -> Fallible<()> {
if message.len() > MAX_VIEW_MESSAGE {
return Ok(Err(wit::Error::Invalid(format!("messages are limited to {MAX_VIEW_MESSAGE} bytes"))));
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
42044c4b2e3d768b922d6e5026ff4e725d37b265896ea7f383f1d737e2feffb7
20ce53ecb41ad94e9c7d59cd4ac51f63081c9f150832fd7febe07887fa3c07ab
+1 -1
Переглянути файл
@@ -1 +1 @@
87eb2a28875abbc649b98d2a7f87263da217f9ad28f1395d96a61db5f781d9f0
2e7d8932329d9383ecd4938225a111851f8a9805c6da558431dea84b7cecbe1c
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
3d3e43d4e49efa7a97984335f7f2df2cb286321bd0368251f37818aa6c1b70ad
7f58bace9b60d8b6b87c97e78dd8cca4955bd13d5f0737efe9d9a362cd1552bf
+10
Переглянути файл
@@ -25,6 +25,16 @@ id = "follow"
title = "Jobs: Follow Selected Job"
category = "Jobs"
[[contributes.commands]]
id = "context"
title = "Jobs: Set Context"
category = "Jobs"
[[contributes.commands]]
id = "selection"
title = "Jobs: Show Selected Paths"
category = "Jobs"
[contributes.settings]
title = "Jobs"
schema = "settings.schema.json"
+35 -1
Переглянути файл
@@ -4,7 +4,7 @@
use openidea_plugin::host;
use openidea_plugin::views::{Body, Button, TreeItem, View, ViewEvent, Viewport, Views};
use openidea_plugin::{Error, Invocation, Plugin, register_plugin};
use openidea_plugin::{Error, Invocation, NotificationLevel, PickItem, Plugin, register_plugin};
pub const VIEW: &str = "jobs";
@@ -40,6 +40,19 @@ impl Plugin for Jobs {
let remotes = project.vcs_remotes()?;
Ok(Some(remotes.into_iter().map(|(n, u)| format!("{n}={u}")).collect::<Vec<_>>().join("\n")))
}
"context" => {
// `key=` removes; `true` / `false`, numbers and other text set.
let (key, value) = arg.unwrap_or_default().split_once('=').ok_or("expected key=value")?;
match value {
"" => host::remove_context(key),
"true" | "false" => host::set_context(key, value == "true")?,
_ => match value.parse::<f64>() {
Ok(n) => host::set_context(key, n)?,
Err(_) => host::set_context(key, value)?,
},
}
Ok(None)
}
"copy" => {
host::copy_to_clipboard(arg.unwrap_or_default())?;
Ok(None)
@@ -48,6 +61,27 @@ impl Plugin for Jobs {
host::open_url(arg.unwrap_or_default())?;
Ok(None)
}
"pick" | "pick-many" => {
let long_key = "k".repeat(300);
let items = [
PickItem::new(if arg == Some("long-key") { &long_key } else { "a" }, "Alpha").description("first"),
PickItem::new("b", "Beta"),
PickItem::new("c", "Gamma"),
];
let picked = match id {
"pick" => host::pick("Pick", &items)?.map(|key| vec![key]),
_ => host::pick_many("Pick", &items)?,
};
Ok(Some(picked.map_or("none".to_owned(), |keys| keys.join(","))))
}
"input" => Ok(Some(host::input("Name", arg)?.unwrap_or_else(|| "none".to_owned()))),
"confirm" => Ok(Some(host::confirm("Delete", "Really?")?.to_string())),
"reveal" => host::reveal_view(arg.unwrap_or_default()).map(|()| None),
"selection" => {
let paths = ctx.selected_paths().join("\n");
host::notify(NotificationLevel::Info, "Selected paths", &paths);
Ok(Some(paths))
}
_ => Err(Error::NotFound(format!("command {id}"))),
}
}
+1 -1
Переглянути файл
@@ -1 +1 @@
1d8561e04cb777efbafc6f64963473b9b69654a72ebb2be34f49c6c53c6f76e2
ee5ba9209eaf963ccc423828ca2e8ba221345c9c246635283214562668a872ad
+41 -1
Переглянути файл
@@ -361,14 +361,48 @@ pub(crate) fn run_cancellable(root: &Path, args: &[&str], cancel: &CancellationT
/// Cancellable capture preserving exit codes for commands with documented non-error states.
pub(crate) fn run_cancellable_raw(root: &Path, args: &[&str], cancel: &CancellationToken) -> IdeResult<Output> {
run_cancellable_raw_stdin(root, args, None, cancel)
}
/// Like `run_cancellable`, feeding `stdin` to git. Revisions and paths passed through
/// `--stdin` are not bound by the command-line length limit (Windows: ~32K characters).
pub(crate) fn run_cancellable_stdin(
root: &Path,
args: &[&str],
stdin: &[u8],
cancel: &CancellationToken,
) -> IdeResult<Output> {
let out = run_cancellable_raw_stdin(root, args, Some(stdin), cancel)?;
if out.code == Some(0) { Ok(out) } else { Err(failure(args, &out.stderr, &out.stdout, out.code)) }
}
fn run_cancellable_raw_stdin(
root: &Path,
args: &[&str],
stdin: Option<&[u8]>,
cancel: &CancellationToken,
) -> IdeResult<Output> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut cmd = command(root)?;
cmd.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
cmd.args(args)
.stdin(if stdin.is_some() { Stdio::piped() } else { Stdio::null() })
.stdout(Stdio::piped())
.stderr(Stdio::piped());
own_group(&mut cmd);
let mut session = CommandSession::start(&mut cmd);
let mut child = cmd.spawn().map_err(spawn_error)?;
let writer = match (stdin, child.stdin.take()) {
(Some(data), Some(mut pipe)) => {
let data = data.to_vec();
Some(std::thread::spawn(move || {
// A broken pipe just means git stopped reading early; its exit status tells the story.
let _ = pipe.write_all(&data);
}))
}
_ => None,
};
let capture = |mut pipe: Box<dyn Read + Send>| {
std::thread::spawn(move || {
let mut bytes = Vec::new();
@@ -382,6 +416,9 @@ pub(crate) fn run_cancellable_raw(root: &Path, args: &[&str], cancel: &Cancellat
terminate_tree(&mut child, KILL_GRACE);
let _ = stdout.join();
let _ = stderr.join();
if let Some(w) = writer {
let _ = w.join();
}
return Err(IdeError::cancelled());
}
if let Some(status) = child.try_wait()? {
@@ -389,6 +426,9 @@ pub(crate) fn run_cancellable_raw(root: &Path, args: &[&str], cancel: &Cancellat
}
std::thread::sleep(Duration::from_millis(20));
};
if let Some(w) = writer {
let _ = w.join();
}
let join = |thread: std::thread::JoinHandle<std::io::Result<Vec<u8>>>| {
thread.join().map_err(|_| IdeError::internal("git output reader panicked"))?.map_err(IdeError::from)
};
+51 -15
Переглянути файл
@@ -80,12 +80,18 @@ fn git_select(
args.push("--first-parent".into());
}
args.extend(filter.iter().cloned());
// Past this many bytes of paths the command line risks Windows' ~32K limit.
let stdin = (paths.iter().map(|p| p.len() + 12).sum::<usize>() > 8 * 1024).then(|| paths_stdin(paths));
if stdin.is_some() {
args.push("--stdin".into());
}
args.push("--end-of-options".into());
args.extend(scope.split_whitespace().map(str::to_string));
args.push("--".into());
args.extend(paths.iter().map(|p| format!(":(literal){p}")));
let output =
crate::cli::run_cancellable(r.root(), &args.iter().map(String::as_str).collect::<Vec<_>>(), cancel)?;
if stdin.is_none() {
args.push("--".into());
args.extend(paths.iter().map(|p| format!(":(literal){p}")));
}
let output = run_log(r, args, stdin.as_deref(), cancel)?;
for line in output.stdout_str().lines() {
ids.insert(ObjectId::from_hex(line.as_bytes()).map_err(gx)?);
}
@@ -93,6 +99,28 @@ fn git_select(
Ok(ids)
}
/// Stdin for `git log --stdin` that limits the walk to `paths`, however many there are.
fn paths_stdin(paths: &[String]) -> String {
let mut text = String::from("--\n");
for p in paths {
text.push_str(&format!(":(literal){p}\n"));
}
text
}
fn run_log(
r: &Repo,
args: Vec<String>,
stdin: Option<&str>,
cancel: &CancellationToken,
) -> IdeResult<crate::cli::Output> {
let argv: Vec<&str> = args.iter().map(String::as_str).collect();
match stdin {
Some(text) => crate::cli::run_cancellable_stdin(r.root(), &argv, text.as_bytes(), cancel),
None => crate::cli::run_cancellable(r.root(), &argv, cancel),
}
}
/// The commits of a file's history and the path it had in each. The commits that changed
/// the path, merges included (`--full-history --simplify-merges`); where it appears, a
/// rename from any parent continues the history under the old path from that parent.
@@ -114,21 +142,27 @@ fn file_history(
if !started.insert((revs.clone(), path.clone())) {
continue;
}
let mut args: Vec<String> =
let mut opts: Vec<String> =
["log", "--format=%x00%H", "--name-status", "-z", "--full-history", "--simplify-merges", "--no-follow"]
.map(String::from)
.into();
if first_parent {
args.push("--first-parent".into());
opts.push("--first-parent".into());
}
args.push("--end-of-options".into());
args.extend(revs);
let pathspec = ["--".to_string(), format!(":(literal){path}")];
let run = |args: &[String]| -> IdeResult<Vec<(ObjectId, Option<char>)>> {
let argv: Vec<&str> = args.iter().chain(&pathspec).map(String::as_str).collect();
Ok(parse_name_status_log(&crate::cli::run_cancellable(r.root(), &argv, cancel)?.stdout_str()))
// `excluded` can name a revision per created file, so it goes through stdin.
let run = |excluded: &[String]| -> IdeResult<Vec<(ObjectId, Option<char>)>> {
let mut args = opts.clone();
if !excluded.is_empty() {
args.push("--stdin".into());
}
args.push("--end-of-options".into());
args.extend(revs.iter().cloned());
args.extend(pathspec.iter().cloned());
let stdin = (!excluded.is_empty()).then(|| excluded.join("\n") + "\n");
Ok(parse_name_status_log(&run_log(r, args, stdin.as_deref(), cancel)?.stdout_str()))
};
let records = run(&args)?;
let records = run(&[])?;
// Where the file appears its history ends: what is behind that is another file of
// the same name (a rename continues the history below). The commits of the history
// are those not behind a creation; the statuses come from the full listing (with
@@ -137,8 +171,8 @@ fn file_history(
let kept: Option<HashSet<ObjectId>> = if created.is_empty() {
None
} else {
args.extend(created.iter().map(|id| format!("^{id}^@")));
Some(run(&args)?.into_iter().map(|(id, _)| id).collect())
let excluded: Vec<String> = created.iter().map(|id| format!("^{id}^@")).collect();
Some(run(&excluded)?.into_iter().map(|(id, _)| id).collect())
};
let mut created = Vec::new();
for (id, first_status) in records {
@@ -354,7 +388,9 @@ fn log_indexed(
let mut history_paths = HashMap::new();
let path_ids = if paths.is_empty() {
None
} else if q.follow && paths.len() == 1 {
} else if q.follow && paths.len() == 1 && !r.root().join(&paths[0]).is_dir() {
// Following renames is for a file: a directory gains files all the time, and each
// creation would cut its history short.
let (ids, at) = file_history(r, &scopes, &paths[0], q.first_parent, cancel)?;
history_paths = at;
Some(ids)
+51
Переглянути файл
@@ -649,3 +649,54 @@ fn file_history_through_a_cyclic_rename() {
pairs(&[("b to a", "a.txt"), ("Modified b", "b.txt"), ("a to b", "b.txt"), ("Created a", "a.txt")])
);
}
/// One commit per file under `dir/`, made with fast-import so hundreds stay quick.
fn commit_files(repo_dir: &Path, count: usize, name: impl Fn(usize) -> String) {
let mut stream = String::new();
for i in 0..count {
let path = name(i);
stream.push_str(&format!(
"commit refs/heads/main\ncommitter T <[email protected]> {} +0000\ndata 3\nc{}\n",
1_700_000_000 + i,
i % 10
));
stream.push_str(&format!("M 100644 inline {path}\ndata 1\nx\n\n"));
}
let mut child = Command::new("git")
.current_dir(repo_dir)
.args(["fast-import", "--quiet"])
.stdin(Stdio::piped())
.spawn()
.unwrap();
child.stdin.take().unwrap().write_all(stream.as_bytes()).unwrap();
assert!(child.wait().unwrap().success());
git(repo_dir, &["symbolic-ref", "HEAD", "refs/heads/main"]);
git(repo_dir, &["reset", "-q", "--hard"]);
}
#[test]
fn followed_directory_history_survives_hundreds_of_created_files() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
// Every created file adds a `^<sha>^@` exclusion: ~800 of them passed as arguments exceed
// Windows' command-line limit (os error 206).
commit_files(dir, 800, |i| format!("module/src/main/java/com/example/generated/Class{i:04}.java"));
let repo = Repo::discover(dir).unwrap().unwrap();
let log = repo.log(&LogQuery { path: Some("module".into()), follow: true, ..Default::default() }).unwrap();
assert_eq!(log.len(), 800);
}
#[test]
fn many_selected_paths_filter_history_without_a_huge_command_line() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
commit_files(dir, 600, |i| format!("module/src/main/java/com/example/generated/Class{i:04}.java"));
let repo = Repo::discover(dir).unwrap().unwrap();
let paths: Vec<String> =
(0..500).map(|i| format!("module/src/main/java/com/example/generated/Class{i:04}.java")).collect();
let paths = paths.into_iter().map(Into::into).collect();
let log = repo.log(&LogQuery { paths, text: Some("c3".into()), ..Default::default() }).unwrap();
assert_eq!(log.len(), 50);
}
+148
Переглянути файл
@@ -0,0 +1,148 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("shows GitHub check statuses for each commit's repository", async ({ workbench: page }) => {
await page.clock.install();
await stubDesktop(page);
await page.evaluate(async () => {
const primary = "/dev/acme-api";
const linked = "/dev/acme-web";
const tip = "1".repeat(40);
const pending = "2".repeat(40);
const missing = "3".repeat(40);
const h = window.__ipc.handlers;
h.vcs_roots = () =>
[
{ root: primary, head: "main" },
{ root: linked, head: "release" },
].map((repo) => ({ ...repo, operation: null, headCommit: tip }));
h.vcs_branch_info = ({ repo }) => ({
head: repo === linked ? "release" : "main",
headCommit: tip,
upstream: null,
ahead: 0,
behind: 0,
operation: null,
});
h.vcs_branches = ({ repo }) =>
[repo === linked ? "origin/dev" : "origin/other"].map((name) => ({
name,
commit: tip,
remote: true,
current: false,
upstream: null,
ahead: 0,
behind: 0,
lastCommitMs: 0,
}));
h.vcs_log = ({ repo }) => {
const rows: [string, string][] =
repo === linked
? [[tip, "Linked repository commit"]]
: [
[tip, "Primary repository commit"],
[pending, "Pending commit"],
[missing, "Local-only commit"],
];
return rows.map(([id, summary], i) => ({
id,
shortId: id.slice(0, 8),
parents: [],
refs: i === 0 ? [repo === linked ? "origin/dev" : "origin/other"] : [],
author: "A",
email: "[email protected]",
timeMs: 0,
summary,
message: summary,
}));
};
h.vcs_log_refs = () => ({});
h.vcs_log_details_batch = ({ revisions }) =>
(revisions as string[]).map(() => ({
message: "Linked repository commit",
containingBranches: [],
signature: "N",
signer: "",
key: "",
fingerprint: "",
}));
h.vcs_commit_files = () => [];
h.vcs_config_get = () => null;
h.vcs_tags = () => [];
h.vcs_status = () => [];
h.vcs_remotes = ({ repo }) => [
{ name: "origin", url: `[email protected]:example/${repo === linked ? "web" : "api"}.git` },
];
let pendingQueries = 0;
h.gh_api = ({ repo, request }) => {
const { variables } = JSON.parse((request as { body: string }).body) as { variables: Record<string, string> };
const linkedRepo = repo === linked;
const state = linkedRepo ? "FAILURE" : "SUCCESS";
if (variables.oid)
return JSON.stringify({
data: {
repository: {
object: {
statusCheckRollup: {
contexts: {
nodes: [{ __typename: "StatusContext", context: "Frontend", state, targetUrl: null }],
pageInfo: { hasNextPage: false, endCursor: null },
},
},
},
},
},
});
const statuses = Object.entries(variables)
.filter(([key]) => /^oid\d+$/.test(key))
.map(([key, revision]) => [
key.replace("oid", "c"),
revision === missing
? null
: { statusCheckRollup: { state: revision === pending && ++pendingQueries === 1 ? "PENDING" : state } },
]);
return JSON.stringify({ data: { repository: Object.fromEntries(statuses) } });
};
const vcsModule = "/src/features/vcs/store.ts";
const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule);
useVcs.setState({ available: true, root: primary, repo: primary });
await refreshNow();
const contextModule = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ contextModule);
setContext("vcsAvailable", true);
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("vcs.showLog");
});
const primary = page.getByRole("option", { name: /Primary repository commit/ });
const linked = page.getByRole("option", { name: /Linked repository commit/ });
await expect(primary).toBeVisible();
expect(await ipcCalls(page, "gh_api")).toEqual([]);
await page.getByRole("button", { name: "View Options" }).first().click();
await page.getByRole("menuitem", { name: "Columns", exact: true }).hover();
await page.getByRole("menuitemcheckbox", { name: "GitHub Commit Checks" }).click({ timeout: 4000 });
await expect(primary.getByRole("button", { name: "Checks passed" })).toBeVisible();
await expect(linked.getByRole("button", { name: "Checks failed" })).toBeVisible();
await expect(
page.getByRole("option", { name: /Pending commit/ }).getByRole("button", { name: "Checks in progress…" }),
).toBeVisible();
await expect(
page.getByRole("option", { name: /Local-only commit/ }).getByRole("button", { name: /^Checks / }),
).toHaveCount(0);
const calls = await ipcCalls(page, "gh_api");
expect(calls.map((c) => c.repo).sort()).toEqual(["/dev/acme-api", "/dev/acme-web"]);
expect(calls.map((c) => JSON.parse((c.request as { body: string }).body).variables.repoName).sort()).toEqual([
"api",
"web",
]);
await linked.getByRole("button", { name: "Checks failed" }).click();
await expect(page.getByRole("option", { name: /Frontend/ })).toBeVisible();
expect((await ipcCalls(page, "gh_api")).at(-1)).toMatchObject({ repo: "/dev/acme-web" });
await page.keyboard.press("Escape");
await page.clock.fastForward(31_000);
await expect(
page.getByRole("option", { name: /Pending commit/ }).getByRole("button", { name: "Checks passed" }),
).toBeVisible();
});
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.37",
"version": "0.1.38",
"license": "Apache-2.0",
"type": "module",
"scripts": {
+10 -1
Переглянути файл
@@ -187,6 +187,10 @@ The path is exact (no globs) and relative to the project root; in a workspace th
key is true when any of its projects contains the path. It updates when
files change. An IDE that doesn't know the key treats it as
false: the plugin still installs and the key reads as false there.
Plugins can set their own keys, `plugin.<id>.<key>`, with `host::set_context`:
a key set from a command or event applies to that window, one set outside any
applies to every window, and a window's value wins over the global one. Keys are
kept across a window reload and idle reclaim, and dropped when the plugin stops.
### Background associations
@@ -349,22 +353,27 @@ then run `openidea-plugin check`.
| `host::begin_task(title, cancellable)` → `Task` | `tasks.begin` | Shown with the background tasks; `report`, `is_cancelled`; the call may run 60 s instead of 5 s while it is open; dropping it ends it. |
| `host::storage::{get, set, delete, keys}` | `storage` | Survives restarts; the instance's memory does not. Deleted on uninstall. |
| `host::set_status_item(id, item)`, `remove_status_item` | `ui` | `text`, `tooltip`, `command` (one of yours, run on click); at most 8; kept while the plugin is idle. |
| `host::set_context(key, value)`, `remove_context` | `ui.{set,remove}-context` | Sets `plugin.<id>.<key>` for `when` clauses in the window the call came from (`true`, `3.5`, `"text"`; `ContextValue`). Key 1–64 of `A-Za-z0-9_-`, 100 per plugin; gone when the plugin stops. |
| `host::notify(level, title, body)` | `ui.show-notification` | Balloon in the window the command or events came from (every window otherwise). |
| `host::copy_to_clipboard(text)` | `ui.copy-to-clipboard` | Copies `text` to the system clipboard. Needs `clipboard`. |
| `host::open_url(url)` | `ui.open-url` | Opens an `http://` or `https://` URL in the user's default browser. |
| `host::pick(title, items)`, `pick_many` | `ui.pick`, `ui.pick-many` | Asks the user to pick from `PickItem`s and waits: the chosen key(s), or `None` when dismissed. Only from a command or event of a window (else `invalid`); the wait isn't charged to the time limit. |
| `host::input(prompt, value)` | `ui.input` | A one-line text box pre-filled with `value`; `None` when dismissed. Same rules as `pick`. |
| `host::confirm(title, body)` | `ui.confirm` | OK / Cancel; `true` on OK. Same rules as `pick`. |
| `host::log(level, msg)` | `log` | IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. |
| `Project::find_files(glob, limit)` | `workspace.project.find-files` | Project-relative glob (`**/*Mapper.xml`); honours `.gitignore`; at most `limit` paths. |
| `host::publish_diagnostics(path, items)` | `diagnostics.publish` | Replaces this plugin's problems for the file (editor squiggles and the Problems view); an empty list clears them. |
| `host::fetch(request)` → `{status, headers, body}` | `net.fetch` | See _Network_. |
| `Project::run_process(program, args, stdin)` → `{code, stdout, stderr}` | `process.run` | Only the pinned program of a `process:` grant; runs in the project root of a trusted project; 4 MiB of output; killed when the call is cancelled or times out. |
| `host::refresh_view(view)` | `views.refresh` | The view (or custom editors) render again; call it when the content changed. |
| `host::reveal_view(view)` | `views.reveal` | Brings one of your declared `[[contributes.views]]` to the front in the calling window. |
| `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. |
| `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:<program>` in the project root: output that keeps coming, interactive sessions. |
| `host::open_location(path, line, column)` | `views.open-location` | Opens a file inside the project in an editor of the invoking window, the caret at `line`/`column` (0-based, UTF-16): a view's links to code. Needs `project.read`. |
| `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. |
`run-command` receives an optional string argument: `executeAction("plugin.<plugin id>.<command id>", "arg")`
from another feature, or nothing when run from Search Everywhere / a shortcut.
from another feature, or nothing when run from Search Everywhere / a shortcut. `ctx.selected_paths()` lists the files and folders a Project view or editor tab menu ran the command on (the argument is the first of them); it is empty otherwise. No capability is needed.
### Events
+1 -1
Переглянути файл
@@ -1 +1 @@
5a707c0a9efb6f98f43d93f1b4207cc0ab21ac84d693e0fd9981d143e7552a1c
fd5d8c0b9c6828bbeb0a93e394a0468abe83f051d1c20e50a7ac91fe12d5ab68
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
34728307b2054d6a494040f0523caf6f62b96c0f67f5b5e9a7e4508370e79419
eb4d8c5d84dd2ea0171297f756cdf56bf72d3db88b8f4736bc2b3ab8346bd5eb
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
c8de2df9607fef2a7e75023e78db06ac83de8598a43632b684756d4e0df6b51b
5db8c9213f6bef54f92c39c994717c8dfd4623a46b615293fe10b7a2990014a9
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2523894a6fb5a75d29429ab096fdd9acf150c05eb4ea13c9e92920c8d8ca4459
b95b4b5c2e4451e670d1b013ad03662469456de03fabdbd8a3c62eccd93fb0f0
+1 -1
Переглянути файл
@@ -1 +1 @@
b534a088809e38ff210ed169b6968f3e793fa0fdcb12d022d2bcee5a58834514
6b800f268041ebb169117dfa31eead60315f51ebd92e409751f2670c92eac473
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
145bad8868c73368d4e83087861293fad309aaa87263bb12508a6acf693c25da
6a2c0c1f354b9c8defbcc9ec4a098fd956991dfb656ef2a4df92a219e60102d7
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
f2f4a7d3fbe4b86369e35969782dd66150df6ae4451e375122d3c1b232caeac1
341466108d3a98c295a33d56c6f2a11736ced33dc0c4358d395cb376c24be663
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
5e7f7adc2c49503d2278ed2a446f18f69561ce51df264100f77f50d69804c277
a6d1331afb12c8b215d8dc4450b8c4a424a6951b359dadb925da5ef0c52ecedc
+227 -58
Переглянути файл
@@ -70,51 +70,156 @@ fn ident(c: char) -> bool {
c.is_alphanumeric() || c == '_' || c == '$'
}
/// Index of the `(` opening a method's parameter list inside a declaration
/// fragment. `(`s that belong to annotation arguments — `@Anno(…)` — are
/// skipped so `@DataPermission(column = "id") int count()` finds the paren
/// after `count`, not the one after `DataPermission`.
fn method_paren(stmt: &str) -> Option<usize> {
let mut rest = stmt;
let mut base = 0;
while let Some(i) = rest.find('(') {
// Is the token right before this `(` an annotation name (`@Anno`, `@a.b.Anno`)?
let before = rest[..i].trim_end();
let annotation = before.rfind('@').is_some_and(|a| before[a + 1..].chars().all(|c| ident(c) || c == '.'));
if !annotation {
return Some(base + i);
/// The index just past the string or char literal opening at `bytes[i]`.
fn skip_string(bytes: &[u8], mut i: usize) -> usize {
let quote = bytes[i];
i += 1;
while i < bytes.len() {
match bytes[i] {
b'\\' => i += 2,
b if b == quote => return i + 1,
_ => i += 1,
}
// Skip the annotation's argument list (it may nest and hold literals).
let mut depth = 1usize;
let mut end = None;
let mut chars = rest[i + 1..].char_indices().peekable();
while let Some((j, c)) = chars.next() {
match c {
'"' | '\'' => {
for (_, d) in chars.by_ref() {
if d == c {
break;
}
}
}
i
}
/// The index just past the `//…` or `/*…*/` comment opening at `bytes[i]`.
fn skip_comment(bytes: &[u8], mut i: usize) -> usize {
if bytes.get(i + 1) == Some(&b'/') {
bytes[i + 2..].iter().position(|&b| b == b'\n').map_or(bytes.len(), |n| i + 2 + n)
} else {
i += 2;
while i + 1 < bytes.len() && (bytes[i] != b'*' || bytes[i + 1] != b'/') {
i += 1;
}
(i + 2).min(bytes.len())
}
}
/// A method declaration in a fragment of an interface's body: the name's byte
/// range and its parameter list's `(` and `)` (offsets in the fragment).
#[derive(Debug, PartialEq, Eq)]
struct Declaration {
name: (usize, usize),
parens: (usize, usize),
}
/// The method declaration in `stmt`, skipping comments, strings and annotations
/// on the way: an annotation's arguments nest parentheses and may hold strings
/// and comments, so the name is the identifier before the first `(` left over —
/// `@Select("…") User find(…)` names `find`, not `Select`. Anything past that
/// `(` (where `@Param(…)` lives) only matters for its matching `)`, so it never
/// confuses the scan.
fn scan_declaration(stmt: &str) -> Option<Declaration> {
let bytes = stmt.as_bytes();
let mut i = 0;
let mut nested = 0usize; // paren depth inside an annotation's arguments
while i < bytes.len() {
match bytes[i] {
b' ' | b'\t' | b'\r' | b'\n' => i += 1,
b'/' if matches!(bytes.get(i + 1), Some(b'/' | b'*')) => i = skip_comment(bytes, i),
b'"' | b'\'' => i = skip_string(bytes, i),
b'@' if nested == 0 => {
// The annotation's qualified name, then (optionally) its arguments.
i += 1;
while i < bytes.len() && (ident(bytes[i] as char) || bytes[i] == b'.') {
i += 1;
}
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
end = Some(i + 1 + j + 1);
break;
}
let mut j = i;
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
j += 1;
}
if bytes.get(j) == Some(&b'(') {
nested = 1;
i = j + 1;
}
_ => {}
}
b'(' if nested > 0 => {
nested += 1;
i += 1;
}
b')' if nested > 0 => {
nested -= 1;
i += 1;
}
b'(' => {
let before = stmt[..i].trim_end();
let start = before.rfind(|c: char| !ident(c)).map_or(0, |p| p + 1);
if start == before.len() {
return None;
}
// The matching `)`, minding strings and nested parens.
let (mut close, mut depth) = (i + 1, 1usize);
while close < bytes.len() {
match bytes[close] {
b'"' | b'\'' => close = skip_string(bytes, close),
b'/' if matches!(bytes.get(close + 1), Some(b'/' | b'*')) => close = skip_comment(bytes, close),
b'(' => {
depth += 1;
close += 1;
}
b')' => {
depth -= 1;
if depth == 0 {
return Some(Declaration { name: (start, before.len()), parens: (i, close) });
}
close += 1;
}
_ => close += 1,
}
}
return None; // an unterminated parameter list is no declaration
}
_ => i += 1,
}
let skip = end?;
base += skip;
rest = &rest[skip..];
}
None
}
/// The parameter names in a declaration's parameter list: `@Param("…")` wins,
/// otherwise the parameter's last identifier. Split at commas outside nested
/// parens, braces, brackets and strings, so `@Size(min = 1, max = 5) String n`
/// stays one parameter and a `@Param("a,b")` keeps its whole name.
fn params_of(list: &str) -> Vec<String> {
let bytes = list.as_bytes();
let mut parts = Vec::new();
let (mut depth, mut start) = (0usize, 0usize);
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'"' | b'\'' => i = skip_string(bytes, i),
b'/' if matches!(bytes.get(i + 1), Some(b'/' | b'*')) => i = skip_comment(bytes, i),
b'(' | b'{' | b'[' => {
depth += 1;
i += 1;
}
b')' | b'}' | b']' => {
depth = depth.saturating_sub(1);
i += 1;
}
b',' if depth == 0 => {
parts.push(&list[start..i]);
start = i + 1;
i += 1;
}
_ => i += 1,
}
}
parts.push(&list[start..]);
parts
.into_iter()
.filter_map(|p| {
// `@Param("id") long id` → the @Param name wins.
if let Some(q) = p.find("@Param(\"") {
return p[q + 8..].split('"').next().map(str::to_owned);
}
p.split_whitespace().last().map(|n| n.trim_matches(|c: char| !ident(c)).to_owned())
})
.filter(|n| !n.is_empty())
.collect()
}
/// The interface's name and methods (with their parameter names).
pub fn parse_java(text: &str) -> MapperJava {
let package =
@@ -140,28 +245,14 @@ pub fn parse_java(text: &str) -> MapperJava {
}
';' if depth == 0 => {
let stmt = &text[stmt_start..k];
if let Some(paren) = method_paren(stmt) {
let before = stmt[..paren].trim_end();
let name_start = before.rfind(|c: char| !ident(c)).map_or(0, |p| p + 1);
let method = &before[name_start..];
if !method.is_empty() && !before.contains(" default ") {
let s = stmt_start + name_start;
let params = stmt[paren + 1..stmt.rfind(')').unwrap_or(stmt.len())]
.split(',')
.filter_map(|p| {
// `@Param("id") long id` → the @Param name wins.
if let Some(q) = p.find("@Param(\"") {
return p[q + 8..].split('"').next().map(str::to_owned);
}
p.split_whitespace().last().map(|n| n.trim_matches(|c: char| !ident(c)).to_owned())
})
.filter(|n| !n.is_empty())
.collect();
methods.push((
Named { name: method.to_owned(), range: range_of(text, s, s + method.len()) },
params,
));
}
if let Some(decl) = scan_declaration(stmt)
&& !stmt[..decl.parens.0].contains(" default ")
{
let (s, e) = (stmt_start + decl.name.0, stmt_start + decl.name.1);
methods.push((
Named { name: stmt[decl.name.0..decl.name.1].to_owned(), range: range_of(text, s, e) },
params_of(&stmt[decl.parens.0 + 1..decl.parens.1]),
));
}
stmt_start = k + 1;
}
@@ -372,6 +463,22 @@ mod tests {
assert_eq!(xml.statements[0].range, Range::new(Position::new(2, 14), Position::new(2, 22)));
}
const ANNOTATED: &str = concat!(
"package com.acme;\n\n",
"import org.apache.ibatis.annotations.Param;\n\n",
"public interface UserMapper {\n",
" @Select(\"SELECT (a, b) FROM users WHERE c = ')' OR d = 'x, y'\")\n",
" List<User> selectAnnotated(Long id);\n\n",
" @Cacheable(key = @Key(value = \"x(y)\", of = {@Part(\"a)b\"), @Part(\"c,d\")}))\n",
" @Override\n",
" // a comment (with parens) before the name\n",
" User findAnnotated(@Param(\"id\") Long id, @Size(min = 1, max = 5) String name);\n\n",
" List<User> selectPlain(Long id);\n",
"}\n"
);
const ANNOTATED_XML: &str = "<?xml version=\"1.0\"?>\n<mapper namespace=\"com.acme.UserMapper\">\n <select id=\"selectAnnotated\" resultType=\"User\">SELECT (a, b) FROM users</select>\n <select id=\"findAnnotated\">SELECT 1</select>\n</mapper>\n";
fn setup() -> MockHost {
let host = MockHost::install();
host.add_file("src/main/java/com/acme/UserMapper.java", JAVA);
@@ -380,6 +487,68 @@ mod tests {
host
}
fn annotated_setup() -> MockHost {
let host = MockHost::install();
host.add_file("src/main/java/com/acme/UserMapper.java", ANNOTATED);
host.add_file("src/main/resources/mapper/UserMapper.xml", ANNOTATED_XML);
host.add_file("pom.xml", "<project/>");
host
}
/// Methods behind method-level annotations keep their names, parameters and
/// positions: the scanner skips comments, strings and annotation arguments
/// (nested annotations, `(` `)` `{` `}` `,` in strings) before the name.
#[test]
fn parses_methods_with_annotations() {
let java = parse_java(ANNOTATED);
let names: Vec<_> = java.methods.iter().map(|(m, p)| (m.name.as_str(), p.clone())).collect();
assert_eq!(
names,
[
("selectAnnotated", vec!["id".to_owned()]),
("findAnnotated", vec!["id".to_owned(), "name".to_owned()],),
("selectPlain", vec!["id".to_owned()])
],
"annotation names must not become method names, @Param wins, argument commas must not split a parameter"
);
// ` List<User> ` before the name on its line (UTF-16 columns).
assert_eq!(java.methods[0].0.range, Range::new(Position::new(6, 15), Position::new(6, 30)));
assert_eq!(java.methods[1].0.range, Range::new(Position::new(11, 9), Position::new(11, 22)));
}
/// A multibyte annotation string on the name's line keeps UTF-16 columns:
/// `中文` is one unit each and `😀` two, while bytes would run ahead.
#[test]
fn keeps_utf16_columns_around_multibyte_annotations() {
let text = "package com.acme;\n\npublic interface UserMapper {\n @Select(\"中文 😀 注释\") List<User> find(Long id);\n}\n";
let java = parse_java(text);
assert_eq!(java.methods.len(), 1);
assert_eq!(java.methods[0].0.name, "find");
// `"中文 😀 注释"` costs 10 UTF-16 units (😀 two); `find` starts at 4 + 8 + 1 + 10 + 1 + 11 = 35.
assert_eq!(java.methods[0].0.range, Range::new(Position::new(3, 35), Position::new(3, 39)));
assert_eq!(java.methods[0].1, ["id".to_owned()]);
}
/// Annotated methods still get both directions of navigation.
#[test]
fn navigates_annotated_methods() {
let _host = annotated_setup();
let mut n = Navigator::default();
let java = doc("/project/src/main/java/com/acme/UserMapper.java", "java", ANNOTATED);
let markers = n.line_markers(&java);
assert_eq!(markers.iter().map(|m| m.line).collect::<Vec<_>>(), [6, 11], "selectPlain has no statement");
assert_eq!(markers[1].tooltip, "Go to UserMapper.xml: findAnnotated");
let xml = doc("/project/src/main/resources/mapper/UserMapper.xml", "xml", ANNOTATED_XML);
let to_java = n.definition(&xml, Position::new(2, 20));
assert_eq!(to_java.len(), 1);
assert_eq!(
(to_java[0].path.ends_with("UserMapper.java"), to_java[0].range.start),
(true, Position::new(6, 15)),
"the XML statement jumps back to the annotated method"
);
}
fn doc(path: &str, language: &str, text: &str) -> Document {
Document { path: path.into(), language: language.into(), version: 1, text: text.into() }
}
+1 -1
Переглянути файл
@@ -1 +1 @@
01c6f9e9b1e76b3328294f6a31ba4d8f3545d04a4fa56cc8069c59aa37a13f27
6e1490c35f7094221a856cf23ba2b6dab92bf8e8c130b156aad1a0ef68a52086
+1 -1
Переглянути файл
@@ -1 +1 @@
745e791fe2fde2b4d7b58b40a33a8037999aac947865a8f4a5127021b7f16156
ce28fb9dfa83dfc46bc6215f9517e2b339b34b40abb85fe12b9534fd63a76899
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
4fff5b261e8255aa2dac8342694dee129ea4a8c9520105c719d0c16a16846517
d2b50d6ee2fe2a0991b7a0006c4899930cfb884f32db231f99c3144ef7f7d0d0
+99
Переглянути файл
@@ -73,6 +73,19 @@ mod imp {
wit::ui::remove_status_item(id)
}
pub fn set_context(key: &str, value: ContextValue) -> Result<(), Error> {
let value = match value {
ContextValue::Flag(b) => wit::ui::ContextValue::Flag(b),
ContextValue::Number(n) => wit::ui::ContextValue::Number(n),
ContextValue::Text(t) => wit::ui::ContextValue::Text(t),
};
wit::ui::set_context(key, &value).map_err(error)
}
pub fn remove_context(key: &str) {
wit::ui::remove_context(key)
}
pub fn copy_to_clipboard(text: &str) -> Result<(), Error> {
wit::ui::copy_to_clipboard(text).map_err(error)
}
@@ -81,6 +94,37 @@ mod imp {
wit::ui::open_url(url).map_err(error)
}
fn pick_items(items: &[PickItem]) -> Vec<wit::ui::PickItem> {
items
.iter()
.map(|i| wit::ui::PickItem {
key: i.key.clone(),
label: i.label.clone(),
description: i.description.clone(),
})
.collect()
}
pub fn pick(title: &str, items: &[PickItem]) -> Result<Option<String>, Error> {
wit::ui::pick(title, &pick_items(items)).map_err(error)
}
pub fn pick_many(title: &str, items: &[PickItem]) -> Result<Option<Vec<String>>, Error> {
wit::ui::pick_many(title, &pick_items(items)).map_err(error)
}
pub fn input(prompt: &str, value: Option<&str>) -> Result<Option<String>, Error> {
wit::ui::input(prompt, value).map_err(error)
}
pub fn confirm(title: &str, body: &str) -> Result<bool, Error> {
wit::ui::confirm(title, body).map_err(error)
}
pub fn reveal_view(view: &str) -> Result<(), Error> {
wit::views::reveal(view).map_err(error)
}
pub fn storage_get(key: &str) -> Result<Option<String>, Error> {
wit::storage::get(key).map_err(error)
}
@@ -117,6 +161,10 @@ mod imp {
i.editor()
}
pub fn invocation_selected_paths(i: InvocationRef<'_>) -> Vec<String> {
i.selected_paths()
}
pub fn editor_path(e: &EditorRes) -> String {
e.path()
}
@@ -327,6 +375,12 @@ impl<'a> Invocation<'a> {
pub fn editor(&self) -> Option<TextEditor> {
imp::invocation_editor(self.inner).map(|inner| TextEditor { inner })
}
/// The files and folders the command was run on, as absolute paths. Empty when it was not
/// run on any, or when the menu was for a tab without a file (a virtual document).
pub fn selected_paths(&self) -> Vec<String> {
imp::invocation_selected_paths(self.inner)
}
}
/// A project open in the IDE.
@@ -545,6 +599,19 @@ pub fn remove_status_item(id: &str) {
imp::remove_status_item(id)
}
/// Sets the plugin's context key that `when` clauses test as `plugin.<id>.<key>`, in
/// the window the current command or event came from (every window when there is
/// none): `set_context("connected", true)`. A window's value takes precedence over
/// the global one. The key is 1-64 of `A-Za-z0-9_-`; at most 100 keys.
pub fn set_context(key: &str, value: impl Into<ContextValue>) -> Result<(), Error> {
imp::set_context(key, value.into())
}
/// Removes the key [`set_context`] set in the same scope.
pub fn remove_context(key: &str) {
imp::remove_context(key)
}
/// Copies `text` to the system clipboard. Needs `clipboard`.
pub fn copy_to_clipboard(text: &str) -> Result<(), Error> {
imp::copy_to_clipboard(text)
@@ -555,6 +622,38 @@ pub fn open_url(url: &str) -> Result<(), Error> {
imp::open_url(url)
}
/// Shows a list in the window the current command or event came from and
/// waits for the key of the chosen item, or `None` when the user dismisses
/// it. Needs no capability; [`Error::Invalid`] outside a command or event of a
/// window (and in editor providers). The wait doesn't count against the
/// call's time budget, but the plugin handles nothing else meanwhile.
pub fn pick(title: &str, items: &[PickItem]) -> Result<Option<String>, Error> {
imp::pick(title, items)
}
/// Like [`pick`], with any number of items chosen.
pub fn pick_many(title: &str, items: &[PickItem]) -> Result<Option<Vec<String>>, Error> {
imp::pick_many(title, items)
}
/// Asks for a line of text, pre-filled with `value`; `None` when dismissed.
/// Same rules as [`pick`].
pub fn input(prompt: &str, value: Option<&str>) -> Result<Option<String>, Error> {
imp::input(prompt, value)
}
/// Asks for confirmation: `true` on OK, `false` on Cancel or Escape.
/// Same rules as [`pick`].
pub fn confirm(title: &str, body: &str) -> Result<bool, Error> {
imp::confirm(title, body)
}
/// Brings one of the plugin's declared views to the front in the window the
/// current command or event came from.
pub fn reveal_view(view: &str) -> Result<(), Error> {
imp::reveal_view(view)
}
/// Delivers `kind` events to [`crate::Plugin::handle_events`] for the rest of
/// the session (also after the instance is reclaimed: an event activates the
/// plugin again). Needs `events` (`events.input` for `ActionPerformed`).
+101 -1
Переглянути файл
@@ -8,7 +8,7 @@
use crate::host::Invocation;
use crate::types::*;
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::marker::PhantomData;
use std::rc::Rc;
@@ -56,9 +56,11 @@ struct State {
other_projects: Vec<String>,
files: BTreeMap<String, String>,
editor: Option<Editor>,
selected_paths: Vec<String>,
notifications: Vec<Notification>,
logs: Vec<(LogLevel, String)>,
status: BTreeMap<String, StatusItem>,
context: BTreeMap<String, ContextValue>,
storage: BTreeMap<String, String>,
subscriptions: BTreeSet<EventKind>,
tasks: Vec<MockTask>,
@@ -68,6 +70,8 @@ struct State {
fetch_error: Option<Error>,
clipboard: Option<String>,
opened_urls: Vec<String>,
answers: VecDeque<Option<Vec<String>>>,
revealed_views: Vec<String>,
diagnostics: BTreeMap<String, Vec<Diagnostic>>,
secrets: BTreeMap<String, String>,
net: Option<NetHandler>,
@@ -144,6 +148,11 @@ impl MockHost {
self.state.borrow_mut().files.insert(path.to_owned(), text.to_owned());
}
/// Sets the paths invocations report as selected.
pub fn select_paths(&self, paths: &[&str]) {
self.state.borrow_mut().selected_paths = paths.iter().map(|p| (*p).to_owned()).collect();
}
/// Focuses an editor on `text` with selections `(line, col, line, col)`.
pub fn open_editor(&self, path: &str, language: &str, text: &str, selections: &[(u32, u32, u32, u32)]) {
let selections =
@@ -185,6 +194,10 @@ impl MockHost {
self.state.borrow().status.clone()
}
pub fn context_keys(&self) -> BTreeMap<String, ContextValue> {
self.state.borrow().context.clone()
}
pub fn storage(&self) -> BTreeMap<String, String> {
self.state.borrow().storage.clone()
}
@@ -224,6 +237,19 @@ impl MockHost {
self.state.borrow().opened_urls.clone()
}
/// The answer the next [`crate::host::pick`], [`crate::host::input`] or
/// [`crate::host::confirm`] gets: the chosen keys, the text (one element),
/// anything for OK, or `None` for dismissed. Unscripted prompts are dismissed.
pub fn answer_next_prompt(&self, answer: Option<&[&str]>) {
let answer = answer.map(|a| a.iter().map(|&s| s.to_owned()).collect());
self.state.borrow_mut().answers.push_back(answer);
}
/// Views brought forward with [`crate::host::reveal_view`], in order.
pub fn revealed_views(&self) -> Vec<String> {
self.state.borrow().revealed_views.clone()
}
/// Makes `vcs-fetch` fail.
pub fn fail_fetch(&self, error: Option<Error>) {
self.state.borrow_mut().fetch_error = error;
@@ -377,6 +403,15 @@ pub mod current {
with(|s| s.status.remove(id));
}
pub fn set_context(key: &str, value: ContextValue) -> Result<(), Error> {
with(|s| s.context.insert(key.to_owned(), value));
Ok(())
}
pub fn remove_context(key: &str) {
with(|s| s.context.remove(key));
}
pub fn copy_to_clipboard(text: &str) -> Result<(), Error> {
with(|s| {
require(s, "clipboard")?;
@@ -396,6 +431,36 @@ pub mod current {
})
}
pub fn pick(title: &str, items: &[PickItem]) -> Result<Option<String>, Error> {
let keys = pick_many(title, items)?;
match keys {
Some(keys) if keys.len() > 1 => Err(Error::Invalid("more than one item chosen".into())),
keys => Ok(keys.and_then(|keys| keys.into_iter().next())),
}
}
pub fn pick_many(_title: &str, items: &[PickItem]) -> Result<Option<Vec<String>>, Error> {
let answer = with(|s| s.answers.pop_front().flatten());
let Some(keys) = answer else { return Ok(None) };
if let Some(unknown) = keys.iter().find(|k| !items.iter().any(|i| &i.key == *k)) {
return Err(Error::Invalid(format!("{unknown:?} is not one of the items")));
}
Ok(Some(keys))
}
pub fn input(_prompt: &str, _value: Option<&str>) -> Result<Option<String>, Error> {
Ok(with(|s| s.answers.pop_front().flatten()).and_then(|a| a.into_iter().next()))
}
pub fn confirm(_title: &str, _body: &str) -> Result<bool, Error> {
Ok(with(|s| s.answers.pop_front().flatten()).is_some())
}
pub fn reveal_view(view: &str) -> Result<(), Error> {
with(|s| s.revealed_views.push(view.to_owned()));
Ok(())
}
pub fn storage_get(key: &str) -> Result<Option<String>, Error> {
with(|s| {
require(s, "storage")?;
@@ -473,6 +538,10 @@ pub mod current {
})
}
pub fn invocation_selected_paths(_: InvocationRef<'_>) -> Vec<String> {
with(|s| s.selected_paths.clone())
}
pub fn editor_path(_: &EditorRes) -> String {
editor(|_, e| e.path.clone())
}
@@ -717,6 +786,14 @@ mod tests {
use super::*;
use crate::host;
#[test]
fn invocations_carry_selected_paths() {
let host = MockHost::install();
assert!(host.invocation().selected_paths().is_empty());
host.select_paths(&["/p/a", "/p/b"]);
assert_eq!(host.invocation().selected_paths(), ["/p/a", "/p/b"]);
}
#[test]
fn records_and_enforces() {
let mock = MockHost::install();
@@ -733,6 +810,13 @@ mod tests {
assert_eq!(host::storage::keys("").unwrap(), ["k"]);
host::set_status_item("s", &StatusItem { text: "x".into(), tooltip: None, command: None });
assert_eq!(mock.status_items()["s"].text, "x");
host::set_context("a", 1.0).unwrap();
host::set_context("b", "x").unwrap();
assert_eq!(mock.context_keys()["a"], ContextValue::Number(1.0));
assert_eq!(mock.context_keys()["b"], ContextValue::Text("x".into()));
host::remove_context("a");
host::remove_context("b");
assert!(mock.context_keys().is_empty());
mock.set_vcs_remotes(&[("origin", "[email protected]:o/r.git")]);
assert_eq!(project.vcs_remotes().unwrap(), [("origin".into(), "[email protected]:o/r.git".into())]);
host::copy_to_clipboard("copied").unwrap();
@@ -740,6 +824,22 @@ mod tests {
host::open_url("https://example.com/a").unwrap();
assert_eq!(mock.opened_urls(), ["https://example.com/a"]);
assert!(matches!(host::open_url("file:///etc/passwd"), Err(Error::Invalid(_))));
let items = [PickItem::new("a", "A"), PickItem::new("b", "B").description("second")];
assert_eq!(host::pick("Pick", &items).unwrap(), None);
mock.answer_next_prompt(Some(&["b"]));
assert_eq!(host::pick("Pick", &items).unwrap().as_deref(), Some("b"));
mock.answer_next_prompt(Some(&["a", "b"]));
assert_eq!(host::pick_many("Pick", &items).unwrap(), Some(vec!["a".to_owned(), "b".to_owned()]));
mock.answer_next_prompt(Some(&["zzz"]));
assert!(matches!(host::pick_many("Pick", &items), Err(Error::Invalid(_))));
mock.answer_next_prompt(Some(&["x.txt"]));
assert_eq!(host::input("Name", Some("a.txt")).unwrap().as_deref(), Some("x.txt"));
mock.answer_next_prompt(Some(&[]));
assert!(host::confirm("Sure?", "Really").unwrap());
mock.answer_next_prompt(None);
assert!(!host::confirm("Sure?", "Really").unwrap());
host::reveal_view("panel").unwrap();
assert_eq!(mock.revealed_views(), ["panel"]);
{
let task = host::begin_task("Work", true);
task.report(1, Some(2), None);
+54
Переглянути файл
@@ -143,6 +143,60 @@ pub struct StatusItem {
pub command: Option<String>,
}
/// An entry of [`crate::host::pick`] and [`crate::host::pick_many`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PickItem {
/// Returned when the item is chosen.
pub key: String,
pub label: String,
pub description: Option<String>,
}
impl PickItem {
pub fn new(key: &str, label: &str) -> Self {
Self { key: key.to_owned(), label: label.to_owned(), description: None }
}
pub fn description(mut self, description: &str) -> Self {
self.description = Some(description.to_owned());
self
}
}
/// A context key's value, as `when` clauses compare it ([`crate::host::set_context`]).
#[derive(Clone, Debug, PartialEq)]
pub enum ContextValue {
Flag(bool),
/// A finite number.
Number(f64),
/// At most 1024 bytes.
Text(String),
}
impl From<bool> for ContextValue {
fn from(value: bool) -> Self {
Self::Flag(value)
}
}
impl From<f64> for ContextValue {
fn from(value: f64) -> Self {
Self::Number(value)
}
}
impl From<&str> for ContextValue {
fn from(value: &str) -> Self {
Self::Text(value.to_owned())
}
}
impl From<String> for ContextValue {
fn from(value: String) -> Self {
Self::Text(value)
}
}
/// Kinds of workbench events; later SDKs add more.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.1.0;
package openidea:plugin@1.2.0;
/// Workbench events, delivered in batches to `event-handler.handle`.
interface events {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.1.0;
package openidea:plugin@1.2.0;
interface lifecycle {
use types.{context, error};
+39 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.1.0;
package openidea:plugin@1.2.0;
/// Writes to the IDE log, tagged with the plugin id.
interface log {
@@ -17,16 +17,54 @@ interface ui {
command: option<string>,
}
record pick-item {
/// Returned when the item is chosen.
key: string,
label: string,
description: option<string>,
}
/// A context key's value, as `when` clauses compare it.
variant context-value {
flag(bool),
/// A finite number.
number(f64),
/// At most 1024 bytes.
text(string),
}
/// Shows a notification balloon in the window the current command or
/// event came from (every window when there is none).
show-notification: func(level: notification-level, title: string, body: string);
/// Shows or updates the plugin's status bar item `id` in every window.
set-status-item: func(id: string, item: status-item);
remove-status-item: func(id: string);
/// Sets the plugin's context key `key`, which `when` clauses test as
/// `plugin.<id>.<key>`, in the window the current command or event came
/// from (every window when there is none). A window's value takes
/// precedence over the global one. `key` is 1-64 of `A-Za-z0-9_-`; at most
/// 100 keys; they go away when the plugin stops.
set-context: func(key: string, value: context-value) -> result<_, error>;
/// Removes the key `set-context` set in the same scope.
remove-context: func(key: string);
/// Copies `text` to the system clipboard. Requires `clipboard`.
copy-to-clipboard: func(text: string) -> result<_, error>;
/// Opens an `http://` or `https://` URL in the user's default browser.
open-url: func(url: string) -> result<_, error>;
/// Shows a list in the window the current command or event came from and
/// waits for the key of the chosen item, or `none` when the user dismisses
/// it. Needs no capability. Returns `invalid` outside a command or event of
/// a window (including in editor providers). Waiting doesn't count against
/// the call's budget.
pick: func(title: string, items: list<pick-item>) -> result<option<string>, error>;
/// Like `pick`, with any number of items chosen.
pick-many: func(title: string, items: list<pick-item>) -> result<option<list<string>>, error>;
/// Asks for a line of text, pre-filled with `value`; `none` when dismissed.
/// Same rules as `pick`.
input: func(prompt: string, value: option<string>) -> result<option<string>, error>;
/// Asks for confirmation with OK and Cancel: `true` on OK, `false` on
/// Cancel or Escape. Same rules as `pick`.
confirm: func(title: string, body: string) -> result<bool, error>;
}
/// Persistent key-value storage of the plugin (survives restarts and idle
+60
Переглянути файл
@@ -0,0 +1,60 @@
package openidea:[email protected];
/// Cross-file associations a plugin publishes for the files it declares under
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
/// background batches (on project open, then for changed files), keeps the
/// project-wide graph, and answers Go to Declaration and gutter markers from
/// it without calling the plugin again. Requires `project.read`; trusted
/// projects only.
interface document-indexer {
use types.{range};
/// A symbol the host's syntax support found in the document.
record symbol {
name: string,
/// class, interface, method, field, … as in the structure view.
kind: string,
/// The enclosing symbol's name.
container: option<string>,
range: range,
}
/// The document to index: the editor's text while it is open, else the file's.
record document {
/// Absolute path.
path: string,
text: string,
symbols: list<symbol>,
}
/// A range of the document tied to a key the plugin chooses
/// (`com.example.UserMapper#findById`, say). Keys are compared as is.
record anchor {
key: string,
range: range,
}
/// Keys starting with `prefix` also resolve as if they started with
/// `target`; both end with `#`. A mapper that extends another finds the
/// inherited statements this way.
record alias {
prefix: string,
target: string,
}
/// What one document contributes; replaces its previous edges.
record edges {
/// Where keys are declared.
definitions: list<anchor>,
/// Ranges that go to the definitions of their key (Go to Declaration,
/// Ctrl/⌘-click). Elsewhere the language server answers as usual.
references: list<anchor>,
aliases: list<alias>,
/// Gutter icons on their first line that go to the definitions of their key.
markers: list<anchor>,
}
/// At most 4,096 definitions and references and 256 aliases per document;
/// a document over the limits is reported as not indexed.
index: func(doc: document) -> edges;
}
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.1.0;
package openidea:plugin@1.2.0;
/// Problems in files, shown in the editor and the Problems view.
interface diagnostics {
+12 -1
Переглянути файл
@@ -7,7 +7,7 @@
/// or processes beyond WASI's clocks and randomness; everything else goes
/// through the imports below, gated by the capabilities granted in
/// `plugin.toml` (a missing one returns `error::denied`).
package openidea:plugin@1.1.0;
package openidea:plugin@1.2.0;
world plugin {
import log;
@@ -50,6 +50,12 @@ world plugin-views {
export view-provider;
}
/// A plugin with a document indexer (`[[contributes.documentIndexers]]`).
world plugin-indexing {
include plugin;
export document-indexer;
}
/// Only the `syntax-provider` export: guests generate it next to `plugin`
/// (the component tools merge both into one component).
world syntax {
@@ -65,3 +71,8 @@ world editor-providers {
world views-provider {
export view-provider;
}
/// Only the `document-indexer` export, generated next to `plugin` like `syntax`.
world indexing {
export document-indexer;
}
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.1.0;
package openidea:plugin@1.2.0;
/// Editor features a plugin provides for the languages it declares under
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.1.0;
package openidea:plugin@1.2.0;
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
/// as in the editor and LSP.
+4 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.1.0;
package openidea:plugin@1.2.0;
/// Declarative views: tool windows declared
/// under `[[contributes.views]]` and custom editors under
@@ -127,6 +127,9 @@ interface views {
/// The view (or every custom editor of that id) shows outdated content:
/// the IDE renders it again.
refresh: func(view: string);
/// Brings one of the plugin's own views to the front in the window the
/// current command or event came from; `invalid` outside one.
reveal: func(view: string) -> result<_, error>;
/// Sends a message to the script of a view's `html` body.
post-message: func(view: string, message: string) -> result<_, error>;
/// Opens a terminal tab in the window the call came from, running
+6 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.1.0;
package openidea:plugin@1.2.0;
interface workspace {
use types.{error};
@@ -59,6 +59,11 @@ interface invocation {
project: func() -> option<project>;
/// The window's focused editor.
editor: func() -> option<text-editor>;
/// The files and folders the command was run on (a multi-selection in
/// a file tree, for instance), as absolute paths.
/// Empty when it was not run on any, or when the menu was for a tab
/// without a file (a virtual document).
selected-paths: func() -> list<string>;
}
}
+38
Переглянути файл
@@ -17,16 +17,54 @@ interface ui {
command: option<string>,
}
record pick-item {
/// Returned when the item is chosen.
key: string,
label: string,
description: option<string>,
}
/// A context key's value, as `when` clauses compare it.
variant context-value {
flag(bool),
/// A finite number.
number(f64),
/// At most 1024 bytes.
text(string),
}
/// Shows a notification balloon in the window the current command or
/// event came from (every window when there is none).
show-notification: func(level: notification-level, title: string, body: string);
/// Shows or updates the plugin's status bar item `id` in every window.
set-status-item: func(id: string, item: status-item);
remove-status-item: func(id: string);
/// Sets the plugin's context key `key`, which `when` clauses test as
/// `plugin.<id>.<key>`, in the window the current command or event came
/// from (every window when there is none). A window's value takes
/// precedence over the global one. `key` is 1-64 of `A-Za-z0-9_-`; at most
/// 100 keys; they go away when the plugin stops.
set-context: func(key: string, value: context-value) -> result<_, error>;
/// Removes the key `set-context` set in the same scope.
remove-context: func(key: string);
/// Copies `text` to the system clipboard. Requires `clipboard`.
copy-to-clipboard: func(text: string) -> result<_, error>;
/// Opens an `http://` or `https://` URL in the user's default browser.
open-url: func(url: string) -> result<_, error>;
/// Shows a list in the window the current command or event came from and
/// waits for the key of the chosen item, or `none` when the user dismisses
/// it. Needs no capability. Returns `invalid` outside a command or event of
/// a window (including in editor providers). Waiting doesn't count against
/// the call's budget.
pick: func(title: string, items: list<pick-item>) -> result<option<string>, error>;
/// Like `pick`, with any number of items chosen.
pick-many: func(title: string, items: list<pick-item>) -> result<option<list<string>>, error>;
/// Asks for a line of text, pre-filled with `value`; `none` when dismissed.
/// Same rules as `pick`.
input: func(prompt: string, value: option<string>) -> result<option<string>, error>;
/// Asks for confirmation with OK and Cancel: `true` on OK, `false` on
/// Cancel or Escape. Same rules as `pick`.
confirm: func(title: string, body: string) -> result<bool, error>;
}
/// Persistent key-value storage of the plugin (survives restarts and idle
+3
Переглянути файл
@@ -127,6 +127,9 @@ interface views {
/// The view (or every custom editor of that id) shows outdated content:
/// the IDE renders it again.
refresh: func(view: string);
/// Brings one of the plugin's own views to the front in the window the
/// current command or event came from; `invalid` outside one.
reveal: func(view: string) -> result<_, error>;
/// Sends a message to the script of a view's `html` body.
post-message: func(view: string, message: string) -> result<_, error>;
/// Opens a terminal tab in the window the call came from, running
+5
Переглянути файл
@@ -59,6 +59,11 @@ interface invocation {
project: func() -> option<project>;
/// The window's focused editor.
editor: func() -> option<text-editor>;
/// The files and folders the command was run on (a multi-selection in
/// a file tree, for instance), as absolute paths.
/// Empty when it was not run on any, or when the menu was for a tab
/// without a file (a virtual document).
selected-paths: func() -> list<string>;
}
}
+5 -3
Переглянути файл
@@ -128,12 +128,14 @@ let server: Server | null = null;
let disconnect: (() => void) | null = null;
let base = "";
afterEach(() => {
afterEach(async () => {
// As switching projects does: run ids restart with each server.
resetRuns();
disconnect?.();
server?.close();
if (base) rmSync(base, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
await server?.close();
// A language server's own process (jdtls's JVM) can outlive the server's for a moment:
// deleting its data directory has to wait for it.
if (base) rmSync(base, { recursive: true, force: true, maxRetries: 10, retryDelay: 1000 });
});
async function open(c: Case): Promise<string> {
+8 -3
Переглянути файл
@@ -78,9 +78,14 @@ export class Server {
}
}
close() {
this.child.stdin.end();
this.child.kill();
/** Kills the server; resolves once the process is gone (its children may still be exiting). */
async close(): Promise<void> {
if (this.child.exitCode === null && !this.child.killed) {
const exited = new Promise<void>((resolve) => this.child.once("exit", () => resolve()));
this.child.stdin.end();
this.child.kill();
await exited;
}
}
private request(method: string, params: unknown): Promise<unknown> {
+3
Переглянути файл
@@ -424,6 +424,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
window::window_open_deployment,
window::window_cycle,
window::window_toggle_fullscreen,
window::window_flash_taskbar,
window::window_set_titlebar_height,
window_drag::window_start_drag,
window::window_take_launch,
@@ -480,7 +481,9 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
plugin::plugin_post_events,
plugin::plugin_event_kinds,
plugin::plugin_status_items,
plugin::plugin_context_keys,
plugin::plugin_cancel_task,
plugin::plugin_answer_prompt,
plugin::plugin_view_render,
plugin::plugin_view_event,
plugin::plugin_web_page,
+19 -2
Переглянути файл
@@ -8,8 +8,8 @@ use ide_core::{IdeError, IdeResult};
use ide_extension::ActivationEvent;
use ide_host::plugins::intellij::{self, InstalledIntellijTheme, IntellijThemeSource};
use ide_host::plugins::{
ActiveTheme, CatalogPlugin, Consent, EventKind, HostWorkspace, InstallPreview, PackageFile, PluginEditor,
PluginEvent, PluginHost, PluginInfo, PluginStatusItem, PluginsSnapshot, WorkbenchEvent,
ActiveTheme, CatalogPlugin, Consent, EventKind, HostWorkspace, InstallPreview, PackageFile, PluginContextKey,
PluginEditor, PluginEvent, PluginHost, PluginInfo, PluginStatusItem, PluginsSnapshot, WorkbenchEvent,
};
use ide_plugin::{Invocation, Limits};
use parking_lot::Mutex;
@@ -325,6 +325,7 @@ pub async fn plugin_run_command(
command_id: String,
arg: Option<String>,
editor: Option<PluginEditor>,
paths: Option<Vec<PathBuf>>,
) -> IdeResult<Option<String>> {
let host = state.plugins.clone();
let project = state.project(window.label()).ok();
@@ -332,6 +333,7 @@ pub async fn plugin_run_command(
client: Some(window.label().to_owned()),
workspace_root: project.as_ref().map(|p| p.root.clone()),
editor: editor.map(PluginEditor::context),
selected_paths: paths.unwrap_or_default(),
};
blocking(move || host.run_command(&plugin_id, &command_id, arg.as_deref(), invocation)).await
}
@@ -369,6 +371,13 @@ pub fn plugin_status_items(state: State<'_, AppState>) -> Vec<PluginStatusItem>
.collect()
}
/// Plugin context keys in effect for this window (later changes arrive as `contextChanged`).
#[tauri::command]
#[specta::specta]
pub fn plugin_context_keys(window: Window, state: State<'_, AppState>) -> Vec<PluginContextKey> {
state.plugins.context_keys(Some(window.label()))
}
/// Cancels a plugin task (`taskStarted` with `cancellable`).
#[tauri::command]
#[specta::specta]
@@ -376,6 +385,14 @@ pub fn plugin_cancel_task(state: State<'_, AppState>, task_id: String) -> bool {
state.plugins.cancel_task(&task_id)
}
/// Reports the user's answer to a plugin's `promptRequested`: the chosen keys
/// (pick), `[text]` (input), anything (confirm: OK), or `None` when dismissed.
#[tauri::command]
#[specta::specta]
pub fn plugin_answer_prompt(state: State<'_, AppState>, prompt_id: String, answer: Option<Vec<String>>) -> bool {
state.plugins.answer_prompt(&prompt_id, answer)
}
/// Gutter markers of plugin `line-markers` providers for an open document.
#[tauri::command]
#[specta::specta]
+15
Переглянути файл
@@ -127,6 +127,21 @@ pub fn window_toggle_fullscreen(window: WebviewWindow) -> IdeResult<bool> {
crate::window_groups::toggle_fullscreen(&window)
}
/// Flash (`true`) or stop flashing (`false`) this window's taskbar button, like IDEA when a
/// breakpoint is hit while the window is in the background (macOS bounces the dock icon,
/// Linux sets the urgency hint). A focused window is never flashed: the user is already
/// looking at it, and re-flashing it would steal attention for nothing.
#[tauri::command]
#[specta::specta]
pub fn window_flash_taskbar(window: WebviewWindow, flash: bool) -> IdeResult<()> {
if flash && window.is_focused().unwrap_or(false) {
return Ok(());
}
window
.request_user_attention(flash.then_some(tauri::UserAttentionType::Critical))
.map_err(|e| IdeError::internal(e.to_string()))
}
/// Height of the web title bar in native logical pixels (CSS height × IDE zoom).
#[tauri::command]
#[specta::specta]
+1
Переглянути файл
@@ -209,6 +209,7 @@ pub fn run() {
windows::close_auxiliary_windows(window.app_handle(), window.label());
if let Some(state) = window.try_state::<AppState>() {
state.close_project(window.label());
state.plugins.forget_client(window.label());
}
}
if let Some(w) = window.try_state::<WindowsState>() {
+3
Переглянути файл
@@ -482,6 +482,9 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
config.visible = false;
}
let state = app.try_state::<AppState>();
if let Some(state) = &state {
state.plugins.reopen_client(&config.label);
}
let appearance = state.as_ref().map(|s| s.global_settings.effective().appearance);
// A plugin theme replaces the built-in one in either OS mode; the UI records its resolved frame.
let plugin_frame = state.as_ref().and_then(|s| s.plugins.startup_frame()).and_then(|c| hex_color(&c));
+1 -1
Переглянути файл
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenIDEA",
"version": "0.1.37",
"version": "0.1.38",
"identifier": "ai.l0ng.openidea",
"build": {
"beforeDevCommand": "pnpm dev",
+47 -2
Переглянути файл
@@ -863,6 +863,13 @@ export const commands = {
/** Focuses the next / previous window (⌘` / ⇧⌘`). */
windowCycle: (forward: boolean) => __TAURI_INVOKE<void>("window_cycle", { forward }),
windowToggleFullscreen: () => typedError<boolean, IdeError>(__TAURI_INVOKE("window_toggle_fullscreen")),
/**
* Flash (`true`) or stop flashing (`false`) this window's taskbar button, like IDEA when a
* breakpoint is hit while the window is in the background (macOS bounces the dock icon,
* Linux sets the urgency hint). A focused window is never flashed: the user is already
* looking at it, and re-flashing it would steal attention for nothing.
*/
windowFlashTaskbar: (flash: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("window_flash_taskbar", { flash })),
/** Height of the web title bar in native logical pixels (CSS height × IDE zoom). */
windowSetTitlebarHeight: (height: number | null) => typedError<null, IdeError>(__TAURI_INVOKE("window_set_titlebar_height", { height })),
/**
@@ -1023,15 +1030,22 @@ export const commands = {
path: string,
language: string,
selections: Range[],
} | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("plugin_run_command", { pluginId, commandId, arg, editor })),
} | null, paths: string[] | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("plugin_run_command", { pluginId, commandId, arg, editor, paths })),
/** Workbench events from this window (only the kinds of `plugin_event_kinds`). */
pluginPostEvents: (events: WorkbenchEvent[]) => __TAURI_INVOKE<void>("plugin_post_events", { events }),
/** Kinds of workbench events plugins want (re-fetch on `subscriptionsChanged`). */
pluginEventKinds: () => __TAURI_INVOKE<EventKind[]>("plugin_event_kinds"),
/** Every plugin status bar item (later changes arrive as `statusItemChanged`). */
pluginStatusItems: () => __TAURI_INVOKE<PluginStatusItem[]>("plugin_status_items"),
/** Plugin context keys in effect for this window (later changes arrive as `contextChanged`). */
pluginContextKeys: () => __TAURI_INVOKE<PluginContextKey[]>("plugin_context_keys"),
/** Cancels a plugin task (`taskStarted` with `cancellable`). */
pluginCancelTask: (taskId: string) => __TAURI_INVOKE<boolean>("plugin_cancel_task", { taskId }),
/**
* Reports the user's answer to a plugin's `promptRequested`: the chosen keys
* (pick), `[text]` (input), anything (confirm: OK), or `None` when dismissed.
*/
pluginAnswerPrompt: (promptId: string, answer: string[] | null) => __TAURI_INVOKE<boolean>("plugin_answer_prompt", { promptId, answer }),
/**
* Content of a plugin view (`doc`: the document of a custom editor; `editor`: for
* a tool window, the window's active editor, as commands get it).
@@ -5659,6 +5673,20 @@ export type PhpSettings = {
phpstanConfig?: string,
};
/** An entry of a plugin's `pick` or `pick-many`. */
export type PickItem = {
key: string,
label: string,
description: string | null,
};
/** A plugin's context key for `when` clauses (`value` is JSON text). */
export type PluginContextKey = {
pluginId: string,
key: string,
value: string,
};
/** The focused editor when a plugin command is invoked. */
export type PluginEditor = {
path: string,
@@ -5679,6 +5707,11 @@ export type PluginEvent =
{ type: "updatesAvailable"; updates: PluginUpdate[] } | { type: "notification"; pluginId: string; level: NotificationLevel; title: string; body: string } |
/** A plugin's status bar item was set (`item`) or removed. */
{ type: "statusItemChanged"; pluginId: string; id: string; item: StatusItem | null } |
/**
* A plugin's context key was set (`value`: JSON text) or removed, in the
* emitted window (every window when the client is `None`).
*/
{ type: "contextChanged"; pluginId: string; key: string; value: string | null } |
/** A plugin began a task: show it with the background tasks. */
{ type: "taskStarted"; pluginId: string; taskId: string; title: string; cancellable: boolean } | { type: "taskProgress"; pluginId: string; taskId: string; done: number; total: number | null; message: string | null } | { type: "taskEnded"; pluginId: string; taskId: string } |
/**
@@ -5705,7 +5738,16 @@ export type PluginEvent =
/** Copy `text` to the system clipboard. */
{ type: "copyToClipboard"; pluginId: string; text: string } |
/** Open `url` (`http(s)://`) in the system browser. */
{ type: "openUrl"; pluginId: string; url: string };
{ type: "openUrl"; pluginId: string; url: string } |
/**
* A command waits for the user's answer: show `prompt`, then report it with
* `plugin_answer_prompt(prompt_id, …)`.
*/
{ type: "promptRequested"; pluginId: string; promptId: string; prompt: Prompt } |
/** The call that asked gave up (cancelled, or its plugin stopped): close the prompt. */
{ type: "promptClosed"; promptId: string } |
/** Bring the tool window of the plugin's view `view` to the front. */
{ type: "revealView"; pluginId: string; view: string };
/** A plugin's own icon (`icon`, `icon-dark` of its manifest): sanitised SVG markup. */
export type PluginIcon = {
@@ -6042,6 +6084,9 @@ export type ProjectStructureSettings = {
excludeFiles?: string,
};
/** What a plugin asks the user (`ui.pick`, `ui.pick-many`, `ui.input`, `ui.confirm`). */
export type Prompt = { kind: "quickPick"; title: string; items: PickItem[]; multiple: boolean } | { kind: "input"; prompt: string; value: string | null } | { kind: "confirm"; title: string; message: string };
export type ProxyKind = "http" | "socks";
export type ProxyMode =
+34 -2
Переглянути файл
@@ -256,13 +256,45 @@ describe("multi-caret paste", () => {
);
});
it("pastes the whole text at every caret when the counts differ", () => {
it("drops the extra lines when there are more lines than carets (IDEA parity)", () => {
// IntelliJ's ClipboardTextPerCaretSplitter gives caret i line i and simply
// ignores the lines beyond the caret count: 2 carets + "x\ny\nz" → "x", "y".
const v = view("a b", [
[1, 1],
[3, 3],
]);
pasteEditorText(v, "x\ny\nz");
expect(v.state.doc.toString()).toBe("ax\ny\nz bx\ny\nz");
expect(v.state.doc.toString()).toBe("ax by");
});
it("pastes empty lines into the extra carets when there are more carets than lines", () => {
const v = view("a b c", [
[1, 1],
[3, 3],
[5, 5],
]);
pasteEditorText(v, "x\ny");
expect(v.state.doc.toString()).toBe("ax by c");
});
it("repeats a single line at every caret", () => {
const v = view("a b", [
[1, 1],
[3, 3],
]);
pasteEditorText(v, "xyz");
expect(v.state.doc.toString()).toBe("axyz bxyz");
});
it("treats a single copied line with a trailing newline as one line (IDEA parity)", () => {
// IntelliJ's splitter ignores the trailing newline of a one-line clipboard,
// so "x\n" at two carets repeats "x" instead of spreading "x" and "".
const v = view("a b", [
[1, 1],
[3, 3],
]);
pasteEditorText(v, "x\n");
expect(v.state.doc.toString()).toBe("ax bx");
});
it("pastes the whole text at a single caret", () => {
+24 -5
Переглянути файл
@@ -15,16 +15,19 @@ function clipboardFileFormatter(view: EditorView): ((paths: string[]) => string)
/**
* The dispatch shared by every paste entry point. With several carets and a
* clipboard of exactly one line per caret, each caret gets its own line
* (JetBrains behavior): `"a\nb"` at two carets inserts `a` then `b`, not the
* block twice. Any other count pastes the full text at every caret.
* multi-line clipboard, the lines spread across the carets the way IntelliJ
* does (its ClipboardTextPerCaretSplitter): caret *i* gets line *i*, missing
* lines become empty inserts, and lines beyond the caret count are dropped —
* `"a\nb"` at two carets inserts `a` then `b`, not the block twice, while a
* single line (a trailing newline doesn't make it multi-line) repeats at every
* caret without the newline.
* `userEvent` is `"input.paste"` unless the caller passes another (plain-text
* paste opts out of Reformat on Paste through `"input.pastePlain"`).
*/
export function dispatchPaste(view: EditorView, text: string, userEvent = "input.paste") {
const ranges = view.state.selection.ranges;
const lines = text.replace(/\r\n?/g, "\n").split("\n");
if (ranges.length > 1 && lines.length === ranges.length) {
const lines = pasteLinesPerCaret(text, ranges.length);
if (lines) {
let i = 0;
const spec = view.state.changeByRange((range) => {
const insert = lines[i++]!;
@@ -39,6 +42,22 @@ export function dispatchPaste(view: EditorView, text: string, userEvent = "input
}
}
/**
* The per-caret inserts for `text` at `caretCount` carets, mirroring IntelliJ's
* ClipboardTextPerCaretSplitter: line *i* for caret *i*, `""` for the carets
* left over when there are more carets than lines, and the lines beyond the
* caret count dropped. A clipboard of a single line — a lone trailing newline
* is an artifact of copying, not an extra empty line — repeats at every caret
* without its newline. `undefined` keeps the single-caret fallback.
*/
function pasteLinesPerCaret(text: string, caretCount: number): string[] | undefined {
if (caretCount <= 1) return undefined;
const lines = text.replace(/\r\n?/g, "\n").split("\n");
if (lines.length === 2 && lines[1] === "") lines.pop();
if (lines.length === 1) return Array(caretCount).fill(lines[0]!);
return Array.from({ length: caretCount }, (_, i) => lines[i] ?? "");
}
export function pasteEditorText(view: EditorView, text: string) {
if (!text || !view.dom.isConnected || view.state.readOnly) return;
dispatchPaste(view, text);
+11
Переглянути файл
@@ -113,6 +113,17 @@
color: var(--fg-subtle);
font-style: italic;
}
.link {
color: var(--link);
text-decoration: underline;
text-decoration-color: color-mix(in srgb, var(--link) 45%, transparent);
text-underline-offset: 2px;
cursor: pointer;
}
.link:hover {
color: var(--link-hover);
text-decoration-color: currentColor;
}
.titleButton {
width: 30px;
height: 30px;
+43 -2
Переглянути файл
@@ -5,7 +5,7 @@
* its source (as IDEA: selection shows, navigation jumps).
*/
import { copySelectionOnKeyDown } from "@/ui/selectableText";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent, type ReactNode } from "react";
import clsx from "clsx";
import { useVirtualizer } from "@tanstack/react-virtual";
import { basename, relativeDir, useProject } from "@/platform/project";
@@ -34,7 +34,10 @@ import {
rootNode,
type BuildNode,
type BuildStatus,
type ConsoleLine,
} from "./model";
import { findOutputLinks, type OutputLink } from "@/features/run/links";
import { openTarget, openUrl } from "@/features/run/navigate";
import { navigateToMessage, rerunBuild, selectBuildNode, useBuildRun } from "./store";
import styles from "./Build.module.css";
import { tx } from "@/platform/i18n";
@@ -201,7 +204,45 @@ function BuildTree() {
const LINE_HEIGHT = 20;
/**
* One console line: file locations and URLs (compiler diagnostics, stack
* frames) are links, resolved against the directory of the step that printed
* the line (Maven reactor modules run in their own directory), then the
* project root and a name search as in the run console.
*/
function ConsoleLineText({ line, root }: { line: ConsoleLine; root: string }) {
const links = useMemo(() => (line.kind === "system" ? [] : findOutputLinks(line.text)), [line.text, line.kind]);
const activate = (e: MouseEvent, link: OutputLink) => {
e.preventDefault();
if (window.getSelection()?.toString()) return;
if (link.kind === "url") void openUrl(link.url);
else void openTarget(link.target, line.cwd ?? root);
};
if (!links.length) return <>{line.text}</>;
const out: ReactNode[] = [];
let pos = 0;
for (const link of links) {
if (link.start > pos) out.push(line.text.slice(pos, link.start));
out.push(
<a
key={link.start}
href={link.kind === "url" ? link.url : undefined}
className={styles.link}
onClick={(e) => activate(e, link)}
role="link"
tabIndex={-1}
>
{line.text.slice(link.start, link.end)}
</a>,
);
pos = link.end;
}
out.push(line.text.slice(pos));
return <>{out}</>;
}
function BuildConsole() {
const root = useProject((s) => s.project?.root ?? "/");
const lines = useBuildRun((s) => s.lines);
const ref = useRef<HTMLDivElement>(null);
const stick = useRef(true);
@@ -236,7 +277,7 @@ function BuildConsole() {
className={clsx(styles.line, styles[line.kind])}
style={{ transform: `translateY(${v.start}px)` }}
>
{line.text || " "}
<ConsoleLineText line={line} root={root} />
</div>
);
})}
+15 -3
Переглянути файл
@@ -9,16 +9,28 @@ export type BuildStatus = "running" | "success" | "failed" | "cancelled";
export interface ConsoleLine {
text: string;
kind: "out" | "err" | "system";
/** Directory of the step that printed the line (links resolve against it). */
cwd?: string | null;
}
/** Oldest lines are dropped beyond this (IDEA's console cycle buffer). */
export const MAX_CONSOLE_LINES = 20_000;
/** Appends streamed text (one or more `\n`-terminated lines) to `lines`. */
export function appendOutput(lines: ConsoleLine[], text: string, kind: ConsoleLine["kind"]): ConsoleLine[] {
/**
* Appends streamed text (one or more `\n`-terminated lines) to `lines`.
* `cwd` is the running step's directory (a step may append several chunks).
*/
export function appendOutput(
lines: ConsoleLine[],
text: string,
kind: ConsoleLine["kind"],
cwd?: string,
): ConsoleLine[] {
const parts = text.split("\n");
if (parts.at(-1) === "") parts.pop();
const next = lines.concat(parts.map((t) => ({ text: t.replace(/\r$/, ""), kind })));
const next = lines.concat(
parts.map((t) => ({ text: t.replace(/\r$/, ""), kind, ...(cwd !== undefined ? { cwd } : {}) })),
);
return next.length > MAX_CONSOLE_LINES ? next.slice(next.length - MAX_CONSOLE_LINES) : next;
}
+6 -3
Переглянути файл
@@ -78,6 +78,8 @@ export interface BuildState {
files: string[];
/** Key of the selected tree node (a message node shows its detail beside the tree). */
selected: string | null;
/** Directory of the running step (console lines after it resolve paths against it). */
stepCwd: string | null;
}
const INITIAL: BuildState = {
@@ -93,6 +95,7 @@ const INITIAL: BuildState = {
lines: [],
files: [],
selected: null,
stepCwd: null,
};
export const useBuildRun = create<BuildState>(() => INITIAL);
@@ -103,11 +106,11 @@ const TITLES: Record<BuildKind, string> = { build: "Build", rebuild: "Rebuild",
export function applyBuildEvent(s: BuildState, e: BuildEvent): Partial<BuildState> {
switch (e.kind) {
case "started":
return { title: e.title, system: e.system };
return { title: e.title, system: e.system, stepCwd: null };
case "step":
return { lines: appendOutput(s.lines, `${e.command}\n`, "system") };
return { stepCwd: e.cwd, lines: appendOutput(s.lines, `${e.command}\n`, "system", e.cwd) };
case "output":
return { lines: appendOutput(s.lines, e.text, e.stderr ? "err" : "out") };
return { lines: appendOutput(s.lines, e.text, e.stderr ? "err" : "out", s.stepCwd ?? undefined) };
case "message":
return { messages: [...s.messages, e.message] };
case "progress":
+122
Переглянути файл
@@ -0,0 +1,122 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
const ipc = vi.hoisted(() => {
const ok = <T>(data: T) => Promise.resolve({ status: "ok" as const, data });
return {
ok,
debugCapabilities: vi.fn(async () => ok(null)),
debugThreads: vi.fn(async () => ok([{ id: 1, name: "main" }])),
debugStackTrace: vi.fn(async () => ok([])),
windowFlashTaskbar: vi.fn(async (_flash: boolean) => ok(null)),
};
});
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
const { ok: _ok, ...commands } = ipc;
return { ...real, commands: { ...real.commands, ...commands } };
});
import { useProject } from "@/platform/project";
import { adoptSession, handleDebugEvent, useDebug } from "../state";
import { stopTaskbarFlash } from "../taskbarFlash";
const stopped = (reason: string) =>
handleDebugEvent(1, { kind: "stopped", threadId: 1, reason, description: null, allThreadsStopped: false });
const flashes = () => ipc.windowFlashTaskbar.mock.calls.filter(([flash]) => flash).length;
const stops = () => ipc.windowFlashTaskbar.mock.calls.filter(([flash]) => !flash).length;
const hasFocus = vi.spyOn(document, "hasFocus");
beforeAll(() => {
(window as unknown as Record<string, unknown>).__TAURI_INTERNALS__ = {};
});
beforeEach(() => {
// Stop any flash left over from the previous test before the mock is cleared.
stopTaskbarFlash();
vi.clearAllMocks();
useDebug.setState({ sessions: {}, active: null, stopSeq: 0 });
useProject.setState({ settings: {} as never });
adoptSession(1, { adapter: "java-debug" });
});
afterAll(() => {
delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__;
hasFocus.mockRestore();
useProject.setState({ settings: null });
});
describe("taskbar flash on a breakpoint in a background window", () => {
it("flashes when a breakpoint stops an unfocused window", () => {
hasFocus.mockReturnValue(false);
stopped("breakpoint");
expect(flashes()).toBe(1);
expect(stops()).toBe(0);
});
it("does not flash when the window is focused", () => {
hasFocus.mockReturnValue(true);
stopped("breakpoint");
expect(ipc.windowFlashTaskbar).not.toHaveBeenCalled();
});
it("does not flash for a stop that is not a breakpoint", () => {
hasFocus.mockReturnValue(false);
stopped("step");
stopped("exception");
expect(ipc.windowFlashTaskbar).not.toHaveBeenCalled();
});
it("does not re-request attention for repeated breakpoints while already flashing", () => {
hasFocus.mockReturnValue(false);
stopped("breakpoint");
stopped("breakpoint");
stopped("function breakpoint");
expect(flashes()).toBe(1);
expect(stops()).toBe(0);
});
it("stops the flash when the window is focused", () => {
hasFocus.mockReturnValue(false);
stopped("breakpoint");
hasFocus.mockReturnValue(true);
window.dispatchEvent(new Event("focus"));
expect(flashes()).toBe(1);
expect(stops()).toBe(1);
// Further focus events send no more stops: the flash is forgotten. A breakpoint that
// hits afterwards finds the window focused and does not flash again (criterion 3).
window.dispatchEvent(new Event("focus"));
stopped("breakpoint");
expect(stops()).toBe(1);
expect(flashes()).toBe(1);
expect(ipc.windowFlashTaskbar).toHaveBeenCalledTimes(2);
});
it("stops the flash when the session resumes", () => {
hasFocus.mockReturnValue(false);
stopped("breakpoint");
handleDebugEvent(1, { kind: "continued", threadId: 1, allThreadsContinued: true });
expect(stops()).toBe(1);
});
it("stops the flash when the session terminates", () => {
hasFocus.mockReturnValue(false);
stopped("breakpoint");
handleDebugEvent(1, { kind: "terminated" });
expect(stops()).toBe(1);
});
it("does not flash when Focus application on breakpoint takes the window instead", () => {
useProject.setState({ settings: { debugger: { focusAppOnBreakpoint: true } } as never });
hasFocus.mockReturnValue(false);
stopped("breakpoint");
expect(ipc.windowFlashTaskbar).not.toHaveBeenCalled();
});
it("never touches the shell outside Tauri", () => {
delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__;
hasFocus.mockReturnValue(false);
stopped("breakpoint");
expect(ipc.windowFlashTaskbar).not.toHaveBeenCalled();
(window as unknown as Record<string, unknown>).__TAURI_INTERNALS__ = {};
});
});
+6
Переглянути файл
@@ -29,6 +29,7 @@ import { breakpointsOf, consumeTemporary, flushBreakpoints, refreshStates, reset
import { interpolateLog, logParts, suspends } from "./breakpoints/model";
import { syncSpecial, useSpecialBreakpoints } from "./breakpoints/special";
import { refreshExceptionFilters } from "./breakpoints/exceptions";
import { flashTaskbarForBreakpoint, stopTaskbarFlash } from "./taskbarFlash";
import { missingAdapter } from "./missingAdapter";
import { startFailureMessage } from "./startFailure";
@@ -713,6 +714,7 @@ export function sessionSupports(cap: keyof DebugCapabilities, s: DebugSession |
}
function markTerminated(id: DebugSessionId) {
stopTaskbarFlash();
patch(id, { status: "terminated", endedAt: Date.now(), frames: [], selectedFrame: null, stoppedThread: null });
const st = useDebug.getState();
if (st.active === id) {
@@ -1013,13 +1015,17 @@ export function handleDebugEvent(id: DebugSessionId, event: DebugEvent) {
} catch {
// ignore
}
// Attention for a background window: focusing the app and flashing the taskbar are
// alternatives (IDEA), so a window configured to grab focus does not also flash.
if (dbg.focusAppOnBreakpoint) focusAppWindow();
else if (isBp) flashTaskbarForBreakpoint();
break;
}
case "continued": {
const cur = useDebug.getState().sessions[id]!;
if (cur.status === "terminated") break;
if (!event.allThreadsContinued && event.threadId !== (cur.selectedThread ?? cur.stoppedThread)) break;
stopTaskbarFlash();
patch(id, {
status: "running",
frames: [],
+40
Переглянути файл
@@ -0,0 +1,40 @@
/**
* IDEA-style taskbar flash while a breakpoint holds this window in the background:
* the shell flashes the native window (`window_flash_taskbar`, which never flashes a
* focused window), this side decides when to ask — on a breakpoint stop while the
* window is unfocused — and stops the flash when the window is focused again or the
* paused session resumes or ends.
*/
import { call, commands, isTauri } from "@/platform/ipc";
/** Whether this window started a flash that nothing has stopped yet. */
let flashing = false;
/** The reset listener is attached once per page, on the first flash request. */
let listening = false;
/** Stops the flash this window started (no-op when none is running: no extra IPC). */
export function stopTaskbarFlash() {
if (!flashing) return;
flashing = false;
if (!isTauri()) return;
void call(commands.windowFlashTaskbar(false)).catch(() => undefined);
}
/**
* Asks the shell to flash the taskbar for a breakpoint hit in a background window.
* While already flashing, further hits do not re-request attention; a window that
* is focused right now (or became focused while the request was in flight) never
* flashes.
*/
export function flashTaskbarForBreakpoint() {
if (!isTauri()) return;
if (!listening) {
listening = true;
window.addEventListener("focus", stopTaskbarFlash);
}
if (flashing || document.hasFocus()) return;
flashing = true;
void call(commands.windowFlashTaskbar(true)).catch(() => {
flashing = false;
});
}
+142
Переглянути файл
@@ -0,0 +1,142 @@
import { useEffect, useRef, useState, type RefObject } from "react";
import { isTauri } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { IconButton } from "@/ui";
import { commitStatusContextsPage } from "./api/requests";
import type { GHCommitStatusRollupContext } from "./api/types";
import { watchLogCommitCheck, type LogCommitCheck } from "./data/logCommitChecks";
import { openInBrowser } from "./data/local";
import { STATUS_ICON } from "./details/model";
import { ChooserPopup } from "./ui/ChooserPopup";
const statuses = {
SUCCESS: { label: "Checks passed", icon: "success" },
FAILURE: { label: "Checks failed", icon: "failed" },
ERROR: { label: "Checks failed", icon: "failed" },
PENDING: { label: "Checks in progress…", icon: "pending" },
EXPECTED: { label: "Checks in progress…", icon: "pending" },
} as const satisfies Record<LogCommitCheck["state"], { label: string; icon: keyof typeof STATUS_ICON }>;
function checkPresentation(context: GHCommitStatusRollupContext) {
if (context.__typename === "StatusContext") {
return { text: context.context, icon: STATUS_ICON[statuses[context.state].icon] };
}
const conclusion = context.conclusion;
const icon =
conclusion === "SUCCESS"
? "success"
: conclusion === "NEUTRAL" || conclusion === "SKIPPED"
? "skipped"
: conclusion
? "failed"
: "pending";
return { text: context.name, detail: context.checkSuite?.workflowRun?.workflow.name, icon: STATUS_ICON[icon] };
}
const checkUrl = (context: GHCommitStatusRollupContext) =>
context.__typename === "CheckRun" ? context.url : context.targetUrl;
function CheckDetails({
check,
revision,
anchor,
onClose,
}: {
check: LogCommitCheck;
revision: string;
anchor: RefObject<HTMLButtonElement | null>;
onClose: () => void;
}) {
const [items, setItems] = useState<GHCommitStatusRollupContext[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
const { root, owner, name } = check.target;
useEffect(() => {
let active = true;
void (async () => {
let cursor: string | null = null;
do {
const page = await commitStatusContextsPage(revision, cursor, 100, { root, owner, name });
if (!active || !page) break;
setItems((prev) => [...prev, ...page.nodes]);
cursor = page.pageInfo.hasNextPage ? page.pageInfo.endCursor : null;
} while (cursor);
})()
.catch(() => active && setError(true))
.finally(() => active && setLoading(false));
return () => {
active = false;
};
}, [revision, root, owner, name]);
return (
<ChooserPopup
mode="single"
aria-label={tx("GitHub Commit Checks")}
anchor={anchor}
placement="top-start"
items={items}
getKey={(context) => `${checkPresentation(context).text}\0${checkUrl(context) ?? ""}`}
present={checkPresentation}
onChoose={(context) => {
const url = checkUrl(context);
if (url && /^https?:\/\//i.test(url)) void openInBrowser(url);
}}
loading={loading}
error={error ? tx("Could not load commit checks") : null}
height={Math.min(300, 40 + Math.max(1, items.length) * 28)}
onClose={onClose}
/>
);
}
export function LogCommitChecks({ root, revision }: { root: string; revision: string }) {
const [check, setCheck] = useState<LogCommitCheck | null>(null);
const [open, setOpen] = useState(false);
const anchor = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (!isTauri() || !/^[a-f0-9]{40}$/i.test(revision)) return;
let timer: ReturnType<typeof setTimeout> | undefined;
let unsubscribe: (() => void) | undefined;
const load = () => {
unsubscribe?.();
unsubscribe = watchLogCommitCheck(root, revision, ({ check, expires }) => {
setCheck(check);
if (check) timer = setTimeout(load, Math.max(0, expires - Date.now()));
});
};
load();
return () => {
clearTimeout(timer);
unsubscribe?.();
};
}, [root, revision]);
if (!check) return null;
const status = statuses[check.state];
return (
<>
<IconButton
ref={anchor}
size="small"
icon={STATUS_ICON[status.icon]}
title={status.label}
aria-haspopup="dialog"
aria-expanded={open}
onMouseDown={(e) => e.stopPropagation()}
onKeyDown={(e) => {
if (e.key === " " || e.key === "Enter") e.stopPropagation();
}}
onClick={() => setOpen(!open)}
/>
{open && (
<CheckDetails
key={`${check.target.owner}/${check.target.name}`}
check={check}
revision={revision}
anchor={anchor}
onClose={() => setOpen(false)}
/>
)}
</>
);
}
+6 -4
Переглянути файл
@@ -37,11 +37,13 @@ export function graphqlData<T>(text: string): T {
}
/** Runs a document from `queries.ts` with `variables` (undefined values are dropped). */
export async function graphql<T>(doc: string, variables: Record<string, unknown> = {}): Promise<T> {
export async function graphql<T>(
doc: string,
variables: Record<string, unknown> = {},
root: string | null = current?.root ?? null,
): Promise<T> {
const body = JSON.stringify({ query: withFragments(doc), variables: definedOnly(variables) });
const text = await call(
commands.ghApi(current?.root ?? null, { method: "POST", endpoint: "graphql", body, paginate: false }),
);
const text = await call(commands.ghApi(root, { method: "POST", endpoint: "graphql", body, paginate: false }));
return graphqlData<T>(text);
}
+9 -4
Переглянути файл
@@ -181,13 +181,18 @@ export async function pullRequestTemplates(): Promise<GHRepositoryPullRequestTem
* A page of the commit's status check rollup (`getRepositoryCommitStatusContexts`).
* @public
*/
export async function commitStatusContextsPage(oid: string, cursor: string | null, pageSize = 100) {
export async function commitStatusContextsPage(
oid: string,
cursor: string | null,
pageSize = 100,
target?: GHRepositoryCoordinates & { root: string },
) {
const data = await graphql<{
repository: {
object: { statusCheckRollup: { contexts: GHConnection<GHCommitStatusRollupContext> } | null } | null;
};
}>(Q.getRepositoryCommitStatusContexts, { ...repoVariables(), oid, pageSize, cursor });
return data.repository.object?.statusCheckRollup?.contexts ?? null;
} | null;
}>(Q.getRepositoryCommitStatusContexts, { ...repoVariables(target), oid, pageSize, cursor }, target?.root);
return data.repository?.object?.statusCheckRollup?.contexts ?? null;
}
/**
+127
Переглянути файл
@@ -0,0 +1,127 @@
/** Fetch rollups only for mounted log rows. Each GraphQL batch is scoped to one Git root. */
import { call, commands } from "@/platform/ipc";
import { graphql, repoVariables } from "../api/client";
import type { GHCommitStatusContextState, GHRepositoryCoordinates } from "../api/types";
import { githubRemotes } from "./repository";
type Target = GHRepositoryCoordinates & { root: string };
export interface LogCommitCheck {
state: GHCommitStatusContextState;
target: Target;
}
const BATCH_SIZE = 20;
const CACHE_SIZE = 2_000;
const REMOTE_TTL = 5 * 60_000;
const remoteCache = new Map<string, { targets: Target[]; expires: number }>();
async function targets(root: string): Promise<Target[]> {
const previous = remoteCache.get(root);
if (previous && previous.expires > Date.now()) return previous.targets;
const remotes = githubRemotes(await call(commands.vcsRemotes(root)).catch(() => []), root);
remotes.sort((a, b) => Number(b.remote === "origin") - Number(a.remote === "origin"));
const resolved = remotes.map(({ owner, name }) => ({ owner, name, root }));
if (remoteCache.size >= 128) remoteCache.delete(remoteCache.keys().next().value!);
remoteCache.set(root, { targets: resolved, expires: Date.now() + REMOTE_TTL });
return resolved;
}
async function queryBatch(target: Target, revisions: string[]) {
const fields = revisions
.map((_, i) => `c${i}: object(oid: $oid${i}) { ... on Commit { statusCheckRollup { state } } }`)
.join("\n");
const params = revisions.map((_, i) => `$oid${i}: GitObjectID!`).join(", ");
const doc = `query($repoOwner: String!, $repoName: String!, ${params}) {
repository(owner: $repoOwner, name: $repoName) { ${fields} }
}`;
const variables = Object.fromEntries(revisions.map((oid, i) => [`oid${i}`, oid]));
const data = await graphql<{
repository: Record<string, { statusCheckRollup: { state: GHCommitStatusContextState } | null } | null> | null;
}>(doc, { ...repoVariables(target), ...variables }, target.root);
return revisions.map((_, i) => data.repository?.[`c${i}`]?.statusCheckRollup?.state ?? null);
}
interface CachedCheck {
check: LogCommitCheck | null;
expires: number;
}
type Listener = (result: CachedCheck) => void;
interface Request {
key: string;
root: string;
revision: string;
listeners: Set<Listener>;
started: boolean;
}
const cache = new Map<string, CachedCheck>();
const requests = new Map<string, Request>();
let scheduled: ReturnType<typeof setTimeout> | undefined;
let running = false;
function isPendingCheck(check: LogCommitCheck | null): boolean {
return check?.state === "PENDING" || check?.state === "EXPECTED";
}
function schedule() {
if (running || scheduled !== undefined || !requests.size) return;
scheduled = setTimeout(() => {
scheduled = undefined;
void flush();
}, 40);
}
async function flush() {
const first = requests.values().next().value;
if (!first) return;
const batch = [...requests.values()].filter((r) => r.root === first.root).slice(0, BATCH_SIZE);
batch.forEach((r) => (r.started = true));
running = true;
const results = new Map<string, LogCommitCheck>();
try {
// Checks on an upstream can be absent from a fork, even when it contains the same commit.
for (const target of await targets(first.root)) {
const remaining = batch.filter((r) => r.listeners.size && !results.has(r.revision));
if (!remaining.length) break;
const states = await queryBatch(
target,
remaining.map((r) => r.revision),
).catch(() => []);
remaining.forEach(({ revision }, i) => {
const state = states[i];
if (state) results.set(revision, { state, target });
});
}
} finally {
for (const r of batch) {
requests.delete(r.key);
const check = results.get(r.revision) ?? null;
if (cache.size >= CACHE_SIZE) cache.delete(cache.keys().next().value!);
const ttl = isPendingCheck(check) ? 30_000 : check ? 5 * 60_000 : 60_000;
const result = { check, expires: Date.now() + ttl };
cache.set(r.key, result);
r.listeners.forEach((listener) => listener(result));
}
running = false;
schedule();
}
}
export function watchLogCommitCheck(root: string, revision: string, listener: Listener): () => void {
const key = `${root}\0${revision}`;
const previous = cache.get(key);
if (previous && previous.expires > Date.now()) {
listener(previous);
return () => {};
}
cache.delete(key);
const request = requests.get(key) ?? { key, root, revision, listeners: new Set<Listener>(), started: false };
request.listeners.add(listener);
requests.set(key, request);
schedule();
return () => {
request.listeners.delete(listener);
if (!request.started && !request.listeners.size) requests.delete(key);
};
}
+2
Переглянути файл
@@ -17,6 +17,7 @@ import {
maybeEditorService,
registerCloneSource,
registerEditorKind,
registerGitLogChecks,
registerOverlay,
registerToolWindow,
} from "@/workbench/contributions";
@@ -318,6 +319,7 @@ export function activate(): () => void {
order: 10,
component: lazyComponent(() => import("./clone/GitHubCloneSource").then((m) => m.GitHubCloneSource)),
}),
registerGitLogChecks(lazyComponent(() => import("./LogCommitChecks").then((m) => m.LogCommitChecks))),
registerToolWindow({
id: WINDOW,
title: "Pull Requests",
+24 -2
Переглянути файл
@@ -57,7 +57,7 @@ describe("macros", () => {
localStorage.setItem(
STORAGE_KEY,
JSON.stringify({
last: [{ kind: "text", text: "a" }, { kind: "action" }, { kind: "action", id: "x", arg: {} }],
last: [{ kind: "text", text: "a" }, { kind: "action" }, { kind: "action", id: "x", arg: { a: { b: 1 } } }],
saved: [{ name: "" }],
}),
);
@@ -96,7 +96,6 @@ describe("macros", () => {
expect(storableArg("x")).toBe("x");
expect(storableArg(2)).toBe(2);
expect(storableArg(undefined)).toBeUndefined();
expect(storableArg({ path: "/a" })).toBeNull();
expect(storableArg(Number.NaN)).toBeNull();
const title = (id: string) => (id === "a" ? "Action A" : id);
expect(describeStep({ kind: "action", id: "a", arg: "x" }, title)).toBe("Action A (x)");
@@ -104,6 +103,29 @@ describe("macros", () => {
expect(describeStep({ kind: "key", key: "Enter" }, title)).toBe("Press Enter");
});
it("stores a selection payload and rejects anything that is not plain data", () => {
const selection = { path: "/a", paths: ["/a", "/b"] };
expect(storableArg(selection)).toEqual(selection);
expect(storableArg(["/a"])).toEqual(["/a"]);
expect(storableArg(true)).toBe(true);
expect(storableArg({ a: { b: 1 } })).toBeNull();
expect(storableArg([1])).toBeNull();
expect(storableArg(new Date())).toBeNull();
expect(storableArg(() => 1)).toBeNull();
expect(storableArg({ n: Number.NaN })).toBeNull();
expect(storableArg(Object.create(null))).toEqual({});
});
it("round-trips an object argument through storage and describes it", () => {
const arg = { path: "/a", paths: ["/a", "/b"] };
saveMacro("Sel", [{ kind: "action", id: "p.run", arg }]);
_reloadMacros();
expect(useMacros.getState().saved[0]?.steps).toEqual([{ kind: "action", id: "p.run", arg }]);
expect(describeStep({ kind: "action", id: "p.run", arg }, (id) => id)).toBe("p.run (/a)");
expect(describeStep({ kind: "action", id: "p.run", arg: ["/a", "/b"] }, (id) => id)).toBe("p.run (/a, /b)");
expect(describeStep({ kind: "action", id: "p.run", arg: { n: 1 } }, (id) => id)).toBe('p.run ({"n":1})');
});
it("names the editor keys a macro records", () => {
const k = (key: string, mods: Partial<Record<"altKey" | "ctrlKey" | "metaKey" | "shiftKey", boolean>> = {}) =>
editorKeyName({ key, altKey: false, ctrlKey: false, metaKey: false, shiftKey: false, ...mods });
+29 -9
Переглянути файл
@@ -6,9 +6,26 @@
*/
import { create } from "zustand";
/** Plain data an action can be run with: primitives, string lists, or a flat object of those. */
export type MacroArg = MacroValue | { [key: string]: MacroValue };
type MacroValue = string | number | boolean | string[];
const isMacroValue = (v: unknown): v is MacroValue =>
typeof v === "string" ||
typeof v === "boolean" ||
(typeof v === "number" && Number.isFinite(v)) ||
(Array.isArray(v) && v.every((x) => typeof x === "string"));
function isMacroArg(v: unknown): v is MacroArg {
if (isMacroValue(v)) return true;
if (!v || typeof v !== "object") return false;
const proto = Object.getPrototypeOf(v);
return (proto === Object.prototype || proto === null) && Object.values(v).every(isMacroValue);
}
/** An editor key replayed as a CodeMirror command (see `editorKeys.ts`). */
export type MacroStep =
| { kind: "action"; id: string; arg?: string | number | boolean }
| { kind: "action"; id: string; arg?: MacroArg }
| { kind: "text"; text: string }
| { kind: "key"; key: string };
@@ -32,8 +49,7 @@ export const STORAGE_KEY = "openidea.macros.v1";
function isStep(v: unknown): v is MacroStep {
if (!v || typeof v !== "object") return false;
const s = v as Record<string, unknown>;
if (s.kind === "action")
return typeof s.id === "string" && ["undefined", "string", "number", "boolean"].includes(typeof s.arg);
if (s.kind === "action") return typeof s.id === "string" && (s.arg === undefined || isMacroArg(s.arg));
if (s.kind === "text") return typeof s.text === "string";
return s.kind === "key" && typeof s.key === "string";
}
@@ -82,12 +98,10 @@ export function recordStep(step: MacroStep) {
useMacros.setState({ recording: next });
}
/** An action's argument when it can be stored (plain values only). */
export function storableArg(arg: unknown): string | number | boolean | undefined | null {
/** An action's argument when it can be stored (plain data only). */
export function storableArg(arg: unknown): MacroArg | undefined | null {
if (arg === undefined) return undefined;
if (typeof arg === "string" || typeof arg === "boolean" || (typeof arg === "number" && Number.isFinite(arg)))
return arg;
return null;
return isMacroArg(arg) ? arg : null;
}
export function startRecording() {
@@ -127,11 +141,17 @@ export function deleteMacro(name: string) {
persist();
}
function describeArg(arg: MacroArg): string {
if (Array.isArray(arg)) return arg.join(", ");
if (typeof arg === "object") return typeof arg.path === "string" ? arg.path : JSON.stringify(arg);
return String(arg);
}
/** One line per step, for Edit Macros. */
export function describeStep(step: MacroStep, title: (id: string) => string): string {
switch (step.kind) {
case "action":
return step.arg === undefined ? title(step.id) : `${title(step.id)} (${String(step.arg)})`;
return step.arg === undefined ? title(step.id) : `${title(step.id)} (${describeArg(step.arg)})`;
case "text":
return `Type "${step.text.replace(/\n/g, "↵")}"`;
case "key":
+191 -1
Переглянути файл
@@ -26,7 +26,8 @@ import {
import { iconResolver, selectedIconTheme, useIconThemes } from "../iconThemes";
import { markerIcon, placeMarkers } from "../lineMarkerGutter";
import { SecretsDetails } from "../secrets";
import { usePluginStatusItems } from "../runtimeUi";
import { handleRuntimeEvent, startRuntimeUi, usePluginStatusItems } from "../runtimeUi";
import { evaluateWhen, getContext } from "@/platform/context";
import { useTasks } from "@/workbench/tasks";
import { defineBuiltinUiPoints } from "../points";
import { clearUiContributions, defineUiPoint, syncUiContributions } from "../projection";
@@ -446,10 +447,32 @@ describe("bridge events", () => {
language: "plaintext",
selections: [{ start: { line: 1, col: 0 }, end: { line: 1, col: 4 } }],
},
[],
],
]);
});
it("forwards a menu's path and selection to the command", async () => {
const calls: unknown[][] = [];
setPluginsBackend({
...backend,
runCommand: async (...args) => {
calls.push(args);
return null;
},
});
undefinePoints();
undefinePoints = () => {};
const stop = startPluginBridge();
await refreshPlugins();
await act(() =>
executeAction("plugin.hello.insert-date", { path: "/p/a.java", paths: ["/p/a.java", "/p/b.java"] }),
);
expect(calls[0]?.[2]).toBe("/p/a.java");
expect(calls[0]?.[4]).toEqual(["/p/a.java", "/p/b.java"]);
stop();
});
it("shows status items and tasks of running plugin code", () => {
const item = { text: "main ↑1", tooltip: "Branch", command: "refresh" };
handlePluginEvent({ type: "statusItemChanged", pluginId: "git", id: "branch", item });
@@ -481,6 +504,81 @@ describe("bridge events", () => {
});
});
describe("plugin prompts", () => {
it("shows a plugin's question and reports the answer or the dismissal", async () => {
const user = userEvent.setup();
const answerPrompt = vi.fn().mockResolvedValue(undefined);
setPluginsBackend({ ...createMemoryPluginsBackend(), answerPrompt });
render(<InputDialogsHost />);
act(() => {
handlePluginEvent({
type: "promptRequested",
pluginId: "p",
promptId: "1",
prompt: {
kind: "quickPick",
title: "Pick targets",
multiple: true,
items: [
{ key: "a", label: "Alpha", description: null },
{ key: "b", label: "Beta", description: "second" },
],
},
});
});
await user.click(await screen.findByRole("checkbox", { name: "Beta" }));
await user.click(screen.getByRole("button", { name: "OK" }));
await waitFor(() => expect(answerPrompt).toHaveBeenCalledWith("1", ["b"]));
act(() => {
handlePluginEvent({
type: "promptRequested",
pluginId: "p",
promptId: "2",
prompt: { kind: "input", prompt: "Name", value: "Main" },
});
});
await user.click(await screen.findByRole("button", { name: "Cancel" }));
await waitFor(() => expect(answerPrompt).toHaveBeenCalledWith("2", null));
});
it("returns the typed text untrimmed", async () => {
const user = userEvent.setup();
const answerPrompt = vi.fn().mockResolvedValue(undefined);
setPluginsBackend({ ...createMemoryPluginsBackend(), answerPrompt });
render(<InputDialogsHost />);
act(() => {
handlePluginEvent({
type: "promptRequested",
pluginId: "p",
promptId: "4",
prompt: { kind: "input", prompt: "Name", value: " Main " },
});
});
await user.click(await screen.findByRole("button", { name: "OK" }));
await waitFor(() => expect(answerPrompt).toHaveBeenCalledWith("4", [" Main "]));
});
it("closes a question the plugin gave up on without answering", async () => {
const answerPrompt = vi.fn().mockResolvedValue(undefined);
setPluginsBackend({ ...createMemoryPluginsBackend(), answerPrompt });
render(<InputDialogsHost />);
act(() => {
handlePluginEvent({
type: "promptRequested",
pluginId: "p",
promptId: "3",
prompt: { kind: "input", prompt: "Name", value: null },
});
});
await screen.findByRole("dialog");
act(() => handlePluginEvent({ type: "promptClosed", promptId: "3" }));
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
expect(answerPrompt).not.toHaveBeenCalled();
});
});
describe("PluginsPage", () => {
it("lists plugins, shows details, toggles and applies themes", async () => {
const user = userEvent.setup();
@@ -1053,3 +1151,95 @@ describe("catalog helpers", () => {
expect(enabled()).toEqual({ a: true, b: true, d: true });
});
});
describe("plugin context keys", () => {
it("applies plugin context keys from the backend", async () => {
let keys = [
{ pluginId: "p", key: "isEntity", value: "true" },
{ pluginId: "p", key: "kind", value: '"pod"' },
];
setPluginsBackend({
...createMemoryPluginsBackend(),
contextKeys: async () => keys,
});
const changed = {
type: "contextChanged",
pluginId: "p",
key: "isEntity",
value: "true",
} as const;
expect(handleRuntimeEvent(changed)).toBe(true);
await waitFor(() => expect(evaluateWhen("plugin.p.isEntity")).toBe(true));
expect(evaluateWhen("plugin.p.kind == pod")).toBe(true);
keys = keys.slice(1);
handleRuntimeEvent({ ...changed, value: null });
await waitFor(() => expect(evaluateWhen("plugin.p.isEntity")).toBe(false));
expect(evaluateWhen("plugin.p.kind == pod")).toBe(true);
keys = [];
handleRuntimeEvent({ ...changed, key: "kind", value: null });
await waitFor(() => expect(evaluateWhen("plugin.p.kind == pod")).toBe(false));
expect("plugin.p.kind" in getContext()).toBe(false);
expect("plugin.p.isEntity" in getContext()).toBe(false);
});
it("refreshes the keys when another backend publishes a project with the same root", async () => {
let keys = [{ pluginId: "p", key: "backend", value: '"a"' }];
setPluginsBackend({ ...createMemoryPluginsBackend(), contextKeys: async () => keys });
const project = { root: "/p", trusted: true } as never;
act(() => useProject.setState({ project }));
const stop = startRuntimeUi();
try {
keys = [{ pluginId: "p", key: "backend", value: '"b"' }];
act(() => useProject.setState({ project: { root: "/p", trusted: true } as never }));
await waitFor(() => expect(evaluateWhen("plugin.p.backend == b")).toBe(true));
} finally {
stop();
act(() => useProject.setState({ project: null }));
}
});
it("coalesces a burst of changes into one follow-up fetch", async () => {
type Keys = { pluginId: string; key: string; value: string }[];
const pending: ((k: Keys) => void)[] = [];
setPluginsBackend({
...createMemoryPluginsBackend(),
contextKeys: () => new Promise<Keys>((resolve) => pending.push(resolve)),
});
const event = { type: "contextChanged", pluginId: "p", key: "a", value: "true" } as const;
for (let i = 0; i < 5; i++) handleRuntimeEvent(event);
expect(pending).toHaveLength(1);
pending[0]!([{ pluginId: "q", key: "b", value: "true" }]);
await waitFor(() => expect(pending).toHaveLength(2));
pending[1]!([
{ pluginId: "p", key: "a", value: "true" },
{ pluginId: "q", key: "b", value: "true" },
]);
await waitFor(() => expect(evaluateWhen("plugin.p.a")).toBe(true));
expect(evaluateWhen("plugin.q.b")).toBe(true);
await Promise.resolve();
expect(pending).toHaveLength(2);
handleRuntimeEvent({ ...event, value: null });
expect(pending).toHaveLength(3);
pending[2]!([{ pluginId: "q", key: "b", value: "true" }]);
await waitFor(() => expect(evaluateWhen("plugin.p.a")).toBe(false));
expect(evaluateWhen("plugin.q.b")).toBe(true);
});
it("fetches again after a failed fetch when changes arrived meanwhile", async () => {
type Keys = { pluginId: string; key: string; value: string }[];
const pending: { resolve: (k: Keys) => void; reject: () => void }[] = [];
setPluginsBackend({
...createMemoryPluginsBackend(),
contextKeys: () =>
new Promise<Keys>((resolve, reject) => pending.push({ resolve, reject: () => reject(new Error("x")) })),
});
const event = { type: "contextChanged", pluginId: "p", key: "f", value: "true" } as const;
handleRuntimeEvent(event);
handleRuntimeEvent(event);
pending[0]!.reject();
await waitFor(() => expect(pending).toHaveLength(2));
pending[1]!.resolve([{ pluginId: "p", key: "f", value: "true" }]);
await waitFor(() => expect(evaluateWhen("plugin.p.f")).toBe(true));
});
});
+26 -2
Переглянути файл
@@ -6,7 +6,7 @@ import type { View, ViewEvent } from "@/bindings";
import { registerAction } from "@/platform/actions";
import { bindingsFor, effectiveBindings, registerExtensionBindings, useKeymap } from "@/platform/keymap";
import { createMemoryPluginsBackend, setPluginsBackend, type PluginsBackend } from "../backend";
import { defineBuiltinUiPoints } from "../points";
import { commandArgs, defineBuiltinUiPoints } from "../points";
import { clearUiContributions, syncUiContributions } from "../projection";
import { pluginMenuItems, pluginViewItemMenuItems, withPluginSetting } from "../uiPoints";
import { matchesPattern } from "../views/customEditor";
@@ -162,6 +162,13 @@ describe("plugin keymaps", () => {
});
describe("plugin menus", () => {
it("unpacks command arguments", () => {
expect(commandArgs("x")).toEqual(["x", []]);
expect(commandArgs({ path: "/a", paths: ["/a", "/b"] })).toEqual(["/a", ["/a", "/b"]]);
expect(commandArgs(undefined)).toEqual([null, []]);
expect(commandArgs({ path: 3 })).toEqual([null, []]);
});
it("projects context menu entries for their command's action", () => {
const off = registerAction({ id: "plugin.p.check", title: "Check", run: () => {} });
const plugin = {
@@ -188,9 +195,26 @@ describe("plugin menus", () => {
[plugin],
);
expect(pluginMenuItems("projectView", ["/p/a.java"])).toEqual([
{ kind: "action", action: "plugin.p.check", arg: "/p/a.java" },
{ kind: "action", action: "plugin.p.check", arg: { path: "/p/a.java", paths: ["/p/a.java"] } },
]);
expect(pluginMenuItems("projectView", ["/p/a.java", "/p/b.java"])[0]).toMatchObject({
arg: { path: "/p/a.java", paths: ["/p/a.java", "/p/b.java"] },
});
expect(pluginMenuItems("editor", ["/p/a.java"])).toEqual([]);
syncUiContributions(
[
{
pluginId: "p",
point: "menus",
key: "editor.context/always",
decl: { menu: "editor.context", command: "check" },
},
],
[plugin],
);
expect(pluginMenuItems("editor", ["/p/a.java"])).toEqual([
{ kind: "action", action: "plugin.p.check", arg: undefined },
]);
off();
});
+13 -1
Переглянути файл
@@ -14,6 +14,7 @@ import type {
InstallPreview,
IntellijThemeSource,
MarketPlugin,
PluginContextKey,
PluginEditor,
PluginEvent,
PluginInfo,
@@ -53,6 +54,7 @@ export interface PluginsBackend {
commandId: string,
arg: string | null,
editor: PluginEditor | null,
paths: string[],
): Promise<string | null>;
/** Workbench events plugins subscribed to (see `eventKinds`). */
postEvents(events: WorkbenchEvent[]): Promise<void>;
@@ -60,7 +62,10 @@ export interface PluginsBackend {
eventKinds(): Promise<EventKind[]>;
/** Plugin status bar items (later changes arrive as `statusItemChanged`). */
statusItems(): Promise<PluginStatusItem[]>;
contextKeys(): Promise<PluginContextKey[]>;
cancelTask(taskId: string): Promise<void>;
/** Reports the answer to a plugin's `promptRequested`: keys, `[text]`, anything for OK, `null` when dismissed. */
answerPrompt(promptId: string, answer: string[] | null): Promise<void>;
/** Marketplace plugins: the index read again (`refresh`) or the last one read. */
market(refresh: boolean): Promise<MarketPlugin[]>;
marketUrl(): Promise<string | null>;
@@ -150,15 +155,20 @@ export const tauriPluginsBackend: PluginsBackend = {
await call(commands.pluginUninstall(id));
},
reload: (id) => call(commands.pluginReload(id)),
runCommand: (pluginId, commandId, arg, editor) => call(commands.pluginRunCommand(pluginId, commandId, arg, editor)),
runCommand: (pluginId, commandId, arg, editor, paths) =>
call(commands.pluginRunCommand(pluginId, commandId, arg, editor, paths)),
postEvents: async (events) => {
await commands.pluginPostEvents(events);
},
eventKinds: () => commands.pluginEventKinds(),
statusItems: () => commands.pluginStatusItems(),
contextKeys: () => commands.pluginContextKeys(),
cancelTask: async (taskId) => {
await commands.pluginCancelTask(taskId);
},
answerPrompt: async (promptId, answer) => {
await commands.pluginAnswerPrompt(promptId, answer);
},
market: (refresh) => call(commands.pluginMarket(refresh)),
marketUrl: () => commands.pluginMarketUrl(),
setMarketUrl: async (url) => {
@@ -498,7 +508,9 @@ export function createMemoryPluginsBackend(
postEvents: async () => {},
eventKinds: async () => [],
statusItems: async () => [],
contextKeys: async () => [],
cancelTask: async () => {},
answerPrompt: async () => {},
market: async () => [],
marketUrl: async () => marketUrl,
setMarketUrl: async (url) => {
+10 -1
Переглянути файл
@@ -17,6 +17,14 @@ import { defineViewUiPoints, pluginSettingsPageId } from "./uiPoints";
import { isLive, runPluginCommand } from "./store";
import styles from "./PluginsPage.module.css";
/** Unpacks an action argument: a bare path, or a menu's `{ path, paths }`. */
export function commandArgs(arg: unknown): [string | null, string[]] {
if (typeof arg === "string") return [arg, []];
const { path, paths } = (arg ?? {}) as { path?: unknown; paths?: unknown };
if (typeof path !== "string" || !Array.isArray(paths)) return [null, []];
return [path, paths.filter((p): p is string => typeof p === "string")];
}
export const pluginActionId = (pluginId: string, commandId: string) => `plugin.${pluginId}.${commandId}`;
interface CommandDecl {
@@ -148,7 +156,8 @@ export function defineBuiltinUiPoints(): () => void {
keywords: ["plugin", plugin.name, pluginId],
description: tx`From plugin ${plugin.name}`,
run: async ({ arg }) => {
await runPluginCommand(pluginId, decl.id, typeof arg === "string" ? arg : null);
const [path, paths] = commandArgs(arg);
await runPluginCommand(pluginId, decl.id, path, paths);
},
}),
Details: CommandsDetails,
+111 -5
Переглянути файл
@@ -5,18 +5,21 @@
* batches.
*/
import { create } from "zustand";
import type { EventKind, PluginEvent, StatusItem, WorkbenchEvent } from "@/bindings";
import type { EventKind, PluginContextKey, PluginEvent, Prompt, StatusItem, WorkbenchEvent } from "@/bindings";
import { onEditorEvent } from "@/editor/api";
import { executeAction, getAction, onActionExecuted } from "@/platform/actions";
import { clearContext, setContext, type ContextValue } from "@/platform/context";
import { onIdeEvent } from "@/platform/ipc";
import { openExternalUrl } from "@/platform/openUrl";
import { useProject } from "@/platform/project";
import { shortcutLabel } from "@/platform/keymap";
import { BarButton } from "@/ui/BarButton";
import { maybeEditorService, registerStatusItem } from "@/workbench/contributions";
import { maybeEditorService, registerStatusItem, toolWindowService } from "@/workbench/contributions";
import { pickItems, promptInput } from "@/workbench/inputDialogs";
import { confirm } from "@/workbench/messages";
import { removeTask, upsertTask, useTasks } from "@/workbench/tasks";
import { pluginsBackend } from "./backend";
import { bumpView, deliverViewMessage } from "./views/viewStore";
import { bumpView, deliverViewMessage, pluginToolWindowId } from "./views/viewStore";
import { runPluginCommand, usePlugins } from "./store";
// --- status bar items ---------------------------------------------------------
@@ -122,6 +125,7 @@ function projectStatusItems(): () => void {
useDeclaredStatusItems.subscribe((s, prev) => s.items !== prev.items && sync()),
];
refreshStatusItems();
refreshContextKeys();
return () => {
unsubscribe.forEach((u) => u());
for (const r of registered.values()) r.dispose();
@@ -141,6 +145,60 @@ function refreshStatusItems() {
.catch(() => {});
}
function applyPluginContext(pluginId: string, key: string, value: string | null) {
const name = `plugin.${pluginId}.${key}`;
let parsed: ContextValue;
try {
parsed = value === null ? undefined : JSON.parse(value);
} catch {
parsed = undefined;
}
if (parsed === undefined) clearContext(name);
else setContext(name, parsed);
}
const appliedContextKeys = new Map<string, Set<string>>();
let contextFetching = false;
let contextDirty = false;
function applyContextKeys(keys: PluginContextKey[]) {
const fresh = new Map<string, Set<string>>();
for (const k of keys) {
applyPluginContext(k.pluginId, k.key, k.value);
if (!fresh.has(k.pluginId)) fresh.set(k.pluginId, new Set());
fresh.get(k.pluginId)!.add(k.key);
}
for (const [id, applied] of appliedContextKeys) {
for (const key of applied) {
if (!fresh.get(id)?.has(key)) applyPluginContext(id, key, null);
}
}
appliedContextKeys.clear();
for (const [id, set] of fresh) appliedContextKeys.set(id, set);
}
/**
* Re-reads the effective context keys of every plugin from the backend (the event does
* not say whether a change was window- or global-scoped) and drops keys it no longer
* reports. One fetch at a time: changes that arrive meanwhile cost a single follow-up.
*/
function refreshContextKeys() {
if (contextFetching) {
contextDirty = true;
return;
}
contextFetching = true;
contextDirty = false;
pluginsBackend()
.contextKeys()
.then(applyContextKeys)
.catch(() => {})
.finally(() => {
contextFetching = false;
if (contextDirty) refreshContextKeys();
});
}
// --- tasks --------------------------------------------------------------------
const taskId = (id: string) => `plugin:${id}`;
@@ -236,9 +294,45 @@ function trackWorkbenchEvents(): () => void {
};
}
const openPrompts = new Map<string, AbortController>();
/** The user's answer in the shape `plugin_answer_prompt` takes: `null` when dismissed. */
async function askUser(prompt: Prompt, signal: AbortSignal): Promise<string[] | null> {
switch (prompt.kind) {
case "quickPick":
return pickItems({ title: prompt.title, items: prompt.items, multiple: prompt.multiple, signal });
case "input": {
const text = await promptInput({
title: prompt.prompt,
initial: prompt.value ?? "",
validate: () => null,
keepWhitespace: true,
signal,
});
return text === null ? null : [text];
}
case "confirm":
return (await confirm({ title: prompt.title, message: prompt.message, ok: "OK", signal })) ? [] : null;
}
}
async function answerPrompt(promptId: string, prompt: Prompt) {
const controller = new AbortController();
openPrompts.set(promptId, controller);
const answer = await askUser(prompt, controller.signal);
openPrompts.delete(promptId);
if (controller.signal.aborted) return;
await pluginsBackend()
.answerPrompt(promptId, answer)
.catch(() => {});
}
/** Handles the runtime UI events; returns whether `e` was one. */
export function handleRuntimeEvent(e: PluginEvent): boolean {
switch (e.type) {
case "contextChanged":
refreshContextKeys();
return true;
case "statusItemChanged":
setStatusItem(e.pluginId, e.id, e.item);
return true;
@@ -269,6 +363,16 @@ export function handleRuntimeEvent(e: PluginEvent): boolean {
case "openUrl":
void openExternalUrl(e.url);
return true;
case "promptRequested":
void answerPrompt(e.promptId, e.prompt);
return true;
case "promptClosed":
openPrompts.get(e.promptId)?.abort();
openPrompts.delete(e.promptId);
return true;
case "revealView":
toolWindowService().show(pluginToolWindowId(e.pluginId, e.view), true);
return true;
default:
return false;
}
@@ -277,13 +381,15 @@ export function handleRuntimeEvent(e: PluginEvent): boolean {
/**
* The backend refuses the event kinds and status items until this window's
* project is open and trusted (`authorize_command`), but startup asks before
* that: ask again when it changes.
* that: ask again when it changes. Any new project object counts, even with the same
* root and trust: connecting another backend publishes one and changes where calls go.
*/
function refreshOnProjectChange(): () => void {
return useProject.subscribe((s, prev) => {
if (s.project?.root === prev.project?.root && s.project?.trusted === prev.project?.trusted) return;
if (s.project === prev.project) return;
refreshEventKinds();
refreshStatusItems();
refreshContextKeys();
});
}
+7 -2
Переглянути файл
@@ -392,10 +392,15 @@ export function commandTitle(pluginId: string, commandId: string): string {
}
/** Runs a plugin command from an action; failures become notifications. */
export async function runPluginCommand(pluginId: string, commandId: string, arg: string | null = null) {
export async function runPluginCommand(
pluginId: string,
commandId: string,
arg: string | null = null,
paths: string[] = [],
) {
const title = commandTitle(pluginId, commandId);
try {
return await pluginsBackend().runCommand(pluginId, commandId, arg, editorContext());
return await pluginsBackend().runCommand(pluginId, commandId, arg, editorContext(), paths);
} catch (e) {
await refreshPlugins();
const status = usePlugins.getState().plugins.find((p) => p.id === pluginId)?.status;
+6 -3
Переглянути файл
@@ -46,6 +46,7 @@ import { usePlugins } from "./store";
import { pluginActionId } from "./points";
import { defineUiPoint } from "./projection";
import { declareStatusItem } from "./runtimeUi";
import { pluginToolWindowId } from "./views/viewStore";
import {
CUSTOM_EDITOR_KIND,
CustomEditor,
@@ -86,7 +87,11 @@ export function pluginMenuItems(menu: ContextMenuId, paths: readonly string[]):
const action = pluginActionId(pluginId, decl.command);
if (!getAction(action)) continue;
// The editor menu runs with the focused editor; the others name their file.
out.push({ kind: "action", action, arg: menu === "editor" ? undefined : paths[0] });
out.push({
kind: "action",
action,
arg: menu === "editor" ? undefined : { path: paths[0], paths: [...paths] },
});
}
return out;
}
@@ -303,8 +308,6 @@ function projectFileIcon(pluginId: string, decl: FileIconDecl): () => void {
};
}
export const pluginToolWindowId = (pluginId: string, view: string) => `plugin.${pluginId}.${view}`;
function registerView(pluginId: string, decl: ViewDecl, icon: string): () => void {
return registerToolWindow({
id: pluginToolWindowId(pluginId, decl.id),
+3
Переглянути файл
@@ -7,6 +7,9 @@ import { create } from "zustand";
export const viewKey = (pluginId: string, view: string) => `${pluginId}/${view}`;
/** The tool window a plugin's declared view is shown in. */
export const pluginToolWindowId = (pluginId: string, view: string) => `plugin.${pluginId}.${view}`;
export const useViewRevisions = create<{ revisions: Record<string, number> }>(() => ({ revisions: {} }));
/** The plugin's view content changed: rendered views fetch it again. */
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more