дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-17 23:25:45 +02:00
Порівняти коміти
10
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
c1782f01eb | ||
|
|
9cfe667b6a | ||
|
|
318f4a2d82 | ||
|
|
31466f2834 | ||
|
|
9f9beaa27c | ||
|
|
182285647e | ||
|
|
ba4bf0ce1d | ||
|
|
76c75b0f7f | ||
|
|
c8a91e5b0f | ||
|
|
a430d4ace7 |
No files matched your search
@@ -9,6 +9,7 @@
|
||||
"dist",
|
||||
"target",
|
||||
"src/bindings.ts",
|
||||
"docs/snippets/plugin-catalog.jsx",
|
||||
"evals/*/golden",
|
||||
"src/editor/core/cm/angular/parser*.ts",
|
||||
"src/editor/core/cm/jsp/parser*.ts",
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
//! Codex's asynchronous questions are answered by a user message, not a permission response.
|
||||
|
||||
use crate::AgentQuestion;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The wire reply and its readable record. Question ids, not wording, associate each answer.
|
||||
pub(crate) fn reply(questions: &[AgentQuestion], answers: &str) -> IdeResult<(String, String)> {
|
||||
let answers: BTreeMap<String, Vec<String>> =
|
||||
serde_json::from_str(answers).map_err(|_| IdeError::invalid("invalid question answers"))?;
|
||||
if questions.is_empty() || answers.len() != questions.len() {
|
||||
return Err(IdeError::invalid("answer every question"));
|
||||
}
|
||||
let mut replies = Vec::new();
|
||||
let mut record = Vec::new();
|
||||
for question in questions {
|
||||
let key = question.answer_key.as_deref().ok_or_else(|| IdeError::invalid("missing question id"))?;
|
||||
let values = answers.get(key).ok_or_else(|| IdeError::invalid("missing question answer"))?;
|
||||
if values.is_empty()
|
||||
|| (!question.multi_select && values.len() != 1)
|
||||
|| values.iter().any(|v| v.trim().is_empty())
|
||||
{
|
||||
return Err(IdeError::invalid("empty or invalid question answer"));
|
||||
}
|
||||
let answer = values.iter().map(|v| v.trim()).collect::<Vec<_>>().join(", ");
|
||||
let mut title = question.question.clone();
|
||||
let mut end = title.len().min(512);
|
||||
while !title.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
title.truncate(end);
|
||||
title = title.replace(['\n', '\r'], " ");
|
||||
replies.push(json!({ "questionItemId": key, "question": title, "answer": answer }));
|
||||
record.push(format!("{}: {}", question.question, answer));
|
||||
}
|
||||
Ok((
|
||||
format!("<send_user_message_question_reply>\n{}\n</send_user_message_question_reply>", json!(replies)),
|
||||
record.join("\n"),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn question(key: &str) -> AgentQuestion {
|
||||
AgentQuestion {
|
||||
answer_key: Some(key.into()),
|
||||
header: String::new(),
|
||||
question: "Which?".into(),
|
||||
multi_select: false,
|
||||
options: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identical_wording_keeps_answers_associated_with_ids() {
|
||||
let (wire, record) =
|
||||
reply(&[question("first"), question("second")], r#"{"first":[" One "],"second":["Two"]}"#).unwrap();
|
||||
let body = wire
|
||||
.strip_prefix("<send_user_message_question_reply>\n")
|
||||
.unwrap()
|
||||
.strip_suffix("\n</send_user_message_question_reply>")
|
||||
.unwrap();
|
||||
let replies: serde_json::Value = serde_json::from_str(body).unwrap();
|
||||
assert_eq!(replies[0], json!({"questionItemId":"first","question":"Which?","answer":"One"}));
|
||||
assert_eq!(replies[1]["answer"], "Two");
|
||||
assert_eq!(record, "Which?: One\nWhich?: Two");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_missing_and_empty_answers_are_rejected() {
|
||||
for answers in
|
||||
["no", "{}", r#"{"other":["One"]}"#, r#"{"first":[]}"#, r#"{"first":[" "]}"#, r#"{"first":["One","Two"]}"#]
|
||||
{
|
||||
assert!(reply(&[question("first")], answers).is_err(), "{answers}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
//! next prompt when the agent supports `session/load`.
|
||||
|
||||
mod acp;
|
||||
mod async_questions;
|
||||
mod catalogs;
|
||||
mod config;
|
||||
mod conversation;
|
||||
@@ -415,6 +416,8 @@ struct Task {
|
||||
live: Mutex<Option<Live>>,
|
||||
/// Serializes starting the agent.
|
||||
connecting: tokio::sync::Mutex<()>,
|
||||
/// Serializes replies from multiple windows to the same async question.
|
||||
answering_questions: tokio::sync::Mutex<()>,
|
||||
/// Unanswered permission requests: where to send the chosen option id.
|
||||
permissions: Mutex<HashMap<u32, std::sync::mpsc::Sender<Option<String>>>>,
|
||||
next_permission: AtomicU32,
|
||||
@@ -1409,6 +1412,53 @@ impl AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Replies to a non-blocking question without interrupting the agent's current turn.
|
||||
pub async fn answer_question(&self, id: &str, question: &str, answer: Option<String>) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
let _answering = task.answering_questions.lock().await;
|
||||
let questions = {
|
||||
let s = task.state.lock();
|
||||
s.conversation
|
||||
.main
|
||||
.entries
|
||||
.iter()
|
||||
.find_map(|entry| match entry {
|
||||
AgentEntry::Question { id, questions, chosen: None, .. } if id == question => {
|
||||
Some(questions.clone())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.ok_or_else(|| IdeError::not_found("the question was already answered"))?
|
||||
};
|
||||
let chosen = match answer {
|
||||
None => "Skipped".to_owned(),
|
||||
Some(answer) => {
|
||||
let (text, record) = async_questions::reply(&questions, &answer)?;
|
||||
let prompt = AgentPrompt { text, files: Vec::new(), images: Vec::new() };
|
||||
if let Err(prompt) = task.steer(prompt).await {
|
||||
if task.state.lock().busy {
|
||||
return Err(IdeError::unavailable("the reply could not join the running turn; try again"));
|
||||
}
|
||||
self.prompt(id, prompt, false).await?;
|
||||
}
|
||||
record
|
||||
}
|
||||
};
|
||||
let changed = {
|
||||
let mut s = task.state.lock();
|
||||
s.conversation.main.entries.iter_mut().enumerate().find_map(|(index, entry)| match entry {
|
||||
AgentEntry::Question { id, chosen: current, .. } if id == question => {
|
||||
*current = Some(chosen.clone());
|
||||
Some((None, index))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
task.mark_dirty(changed);
|
||||
task.persist();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stops the agent and moves the task to Archived; its worktree stays.
|
||||
pub fn archive(&self, id: &str) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
@@ -1707,6 +1757,7 @@ impl Task {
|
||||
}),
|
||||
live: Mutex::new(None),
|
||||
connecting: tokio::sync::Mutex::new(()),
|
||||
answering_questions: tokio::sync::Mutex::new(()),
|
||||
permissions: Mutex::new(HashMap::new()),
|
||||
next_permission: AtomicU32::new(1),
|
||||
replaying: AtomicBool::new(false),
|
||||
@@ -2655,7 +2706,7 @@ impl Task {
|
||||
let applied = self.state.lock().conversation.apply(session, update, now_ms());
|
||||
self.mark_dirty(applied);
|
||||
// A subagent can start or finish after the turn that started it: saved right away.
|
||||
if kind == "subagent_update" {
|
||||
if matches!(kind, "subagent_update" | "user_question") {
|
||||
self.persist();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -469,6 +469,14 @@ pub enum AgentEntry {
|
||||
Agent {
|
||||
text: String,
|
||||
},
|
||||
/// A question that can be answered while the agent keeps working, or after the turn ends.
|
||||
Question {
|
||||
id: String,
|
||||
title: String,
|
||||
questions: Vec<AgentQuestion>,
|
||||
/// The submitted answers, or `Skipped`; `None` while unanswered.
|
||||
chosen: Option<String>,
|
||||
},
|
||||
Thought {
|
||||
text: String,
|
||||
},
|
||||
|
||||
@@ -1028,6 +1028,11 @@ impl CodexShim {
|
||||
}
|
||||
Some(t.chunk(kind, &id, &text))
|
||||
});
|
||||
if ty == "agentMessage"
|
||||
&& let Some(update) = translate::question_update(item)
|
||||
{
|
||||
self.emit(thread, update);
|
||||
}
|
||||
}
|
||||
"subAgentActivity" => {
|
||||
let child = item.get("agentThreadId").and_then(Value::as_str).unwrap_or_default();
|
||||
|
||||
@@ -473,6 +473,56 @@ fn history_replays_turns() {
|
||||
assert_eq!(updates[4]["status"], "completed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_preserves_async_questions_with_stable_answer_ids() {
|
||||
let updates = history(
|
||||
&json!({"turns": [{"items": [{
|
||||
"type": "agentMessage", "id": "call-1", "text": "Which?",
|
||||
"questions": [{"title": "Which?", "options": ["One", "Two"]}, {"title": "Why?"}]
|
||||
}]}]}),
|
||||
None,
|
||||
);
|
||||
let asked = updates.iter().find(|u| u["sessionUpdate"] == "user_question").expect("question update");
|
||||
assert_eq!(asked["id"], "call-1");
|
||||
assert_eq!(asked["questions"][0]["answerKey"], r#"["request_user_input_async","call-1",0]"#);
|
||||
assert_eq!(asked["questions"][0]["options"][1]["label"], "Two");
|
||||
assert_eq!(asked["questions"][1]["options"], json!([]));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completing_a_streamed_message_still_delivers_its_async_questions() {
|
||||
let shim = Arc::new(CodexShim {
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
codex: OnceLock::new(),
|
||||
client: OnceLock::new(),
|
||||
state: Mutex::default(),
|
||||
models: tokio::sync::Mutex::new(None),
|
||||
skills: tokio::sync::Mutex::new(()),
|
||||
});
|
||||
shim.state.lock().threads.insert("thread".into(), Thread::default());
|
||||
let client = Arc::new(Client::default());
|
||||
let peer = crate::native::serve(shim.clone(), client.clone());
|
||||
shim.text("thread", &json!({"itemId":"call-1","delta":"Which?"}), "agent_message_chunk", false);
|
||||
shim.item(
|
||||
"thread",
|
||||
&json!({"type":"agentMessage","id":"call-1","text":"Which?",
|
||||
"questions":[{"title":"Which?","options":["One","Two"]}]}),
|
||||
true,
|
||||
);
|
||||
tokio::time::timeout(Duration::from_secs(2), async {
|
||||
while client.of("thread").len() < 2 {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(client.text("thread", "agent_message_chunk"), "Which?");
|
||||
assert!(client.of("thread").iter().any(|u| u["sessionUpdate"] == "user_question"));
|
||||
assert!(client.asked.lock().is_empty(), "an asynchronous question must not block on a permission response");
|
||||
peer.kill();
|
||||
shim.client.get().unwrap().kill();
|
||||
}
|
||||
|
||||
// ---- Transcripts ---------------------------------------------------------------------
|
||||
|
||||
/// The ACP client: records updates and answers permission requests in order.
|
||||
|
||||
@@ -871,6 +871,7 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec<Value> {
|
||||
if !text.is_empty() {
|
||||
out.push(chunk("agent_message_chunk", text));
|
||||
}
|
||||
out.extend(question_update(item));
|
||||
}
|
||||
Some("reasoning") => {
|
||||
let text = reasoning_text(item);
|
||||
@@ -890,6 +891,36 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec<Value> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Structured async questions accompany a completed message, even when its text streamed already.
|
||||
pub(super) fn question_update(item: &Value) -> Option<Value> {
|
||||
let id = item.get("id")?.as_str().filter(|id| !id.is_empty())?;
|
||||
let questions: Vec<Value> = item
|
||||
.get("questions")?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, q)| {
|
||||
let title = q.get("title")?.as_str().filter(|title| !title.trim().is_empty())?;
|
||||
let options: Vec<Value> = q
|
||||
.get("options")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.filter(|label| !label.trim().is_empty())
|
||||
.map(|label| json!({ "label": label, "description": "" }))
|
||||
.collect();
|
||||
Some(json!({ "answerKey": json!(["request_user_input_async", id, index]).to_string(),
|
||||
"question": title, "header": "", "multiSelect": false, "options": options }))
|
||||
})
|
||||
.collect();
|
||||
if questions.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(json!({ "sessionUpdate": "user_question", "id": id,
|
||||
"title": questions[0]["question"], "questions": questions }))
|
||||
}
|
||||
|
||||
/// A reasoning item's summary (or, without one, its raw text).
|
||||
pub(super) fn reasoning_text(item: &Value) -> String {
|
||||
let parts = |k: &str| -> Vec<String> {
|
||||
|
||||
@@ -245,6 +245,10 @@ impl Handler for FakeAgent {
|
||||
}
|
||||
"session/prompt" => {
|
||||
let text = params.pointer("/prompt/0/text").and_then(Value::as_str).unwrap_or_default().to_owned();
|
||||
if text.starts_with("<send_user_message_question_reply>") {
|
||||
self.say(&session, "answer received");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "again" {
|
||||
self.say(&session, "second turn");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
@@ -1154,6 +1158,83 @@ fn text(t: &str) -> AgentPrompt {
|
||||
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
|
||||
}
|
||||
|
||||
fn asynchronous_question() -> Value {
|
||||
json!({"sessionUpdate":"user_question","id":"call-1","title":"Which?",
|
||||
"questions":[{"answerKey":"q1","question":"Which?","options":[]}]})
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn async_question_answers_join_the_turn_and_skipping_does_not_cancel_it() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent { session_steering: true, ..Default::default() });
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
handle.on_update(Some("s1"), &asynchronous_question());
|
||||
assert!(mgr.answer_question(&task.id, "call-1", Some("{}".into())).await.is_err());
|
||||
handle.live.lock().as_mut().unwrap().capabilities.steer = false;
|
||||
assert!(mgr.answer_question(&task.id, "call-1", Some(r#"{"q1":["One"]}"#.into())).await.is_err());
|
||||
assert!(handle.state.lock().task.queue.is_empty());
|
||||
assert_eq!(handle.state.lock().task.status, AgentStatus::Running);
|
||||
handle.live.lock().as_mut().unwrap().capabilities.steer = true;
|
||||
mgr.answer_question(&task.id, "call-1", Some(r#"{"q1":["One"]}"#.into())).await.unwrap();
|
||||
assert_eq!(handle.state.lock().task.status, AgentStatus::Running);
|
||||
assert!(
|
||||
agent.calls.lock().iter().any(|call| call.starts_with("_session/steering ") && call.contains("questionItemId"))
|
||||
);
|
||||
assert!(!agent.calls.lock().iter().any(|call| call == "session/cancel"));
|
||||
assert!(mgr.answer_question(&task.id, "call-1", None).await.is_err());
|
||||
let mut question = asynchronous_question();
|
||||
question["id"] = json!("call-2");
|
||||
handle.on_update(Some("s1"), &question);
|
||||
mgr.answer_question(&task.id, "call-2", None).await.unwrap();
|
||||
assert!(
|
||||
matches!(mgr.entries(&task.id, None).unwrap().last(), Some(AgentEntry::Question { chosen: Some(chosen), .. }) if chosen == "Skipped")
|
||||
);
|
||||
assert_eq!(handle.state.lock().task.status, AgentStatus::Running);
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn async_questions_can_be_answered_after_the_turn_ends() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.task(&task.id).unwrap().on_update(Some("s1"), &asynchronous_question());
|
||||
mgr.answer_question(&task.id, "call-1", Some(r#"{"q1":["One"]}"#.into())).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(
|
||||
mgr.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|entry| matches!(entry, AgentEntry::Question { chosen: Some(answer), .. } if answer == "Which?: One"))
|
||||
);
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert!(
|
||||
entries.iter().any(|entry| matches!(entry, AgentEntry::User { text, .. } if text.contains("questionItemId")))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn steers_through_session_steering() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -54,6 +54,23 @@ impl Timeline {
|
||||
let mut out = Applied::default();
|
||||
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
|
||||
match kind {
|
||||
"user_question" => {
|
||||
let id = str_field(update, "id");
|
||||
let Ok(questions) = serde_json::from_value::<Vec<crate::model::AgentQuestion>>(
|
||||
update.get("questions").cloned().unwrap_or(Value::Null),
|
||||
) else {
|
||||
return out;
|
||||
};
|
||||
if id.is_empty()
|
||||
|| questions.is_empty()
|
||||
|| self.entries.iter().any(|e| matches!(e, AgentEntry::Question { id: known, .. } if known == &id))
|
||||
{
|
||||
return out;
|
||||
}
|
||||
let index =
|
||||
self.push(AgentEntry::Question { id, title: str_field(update, "title"), questions, chosen: None });
|
||||
out.changed.push(index);
|
||||
}
|
||||
"agent_message_chunk" | "agent_thought_chunk" => {
|
||||
let Some(text) = content_text(update.get("content")) else { return out };
|
||||
out.changed.push(self.append_text(kind == "agent_thought_chunk", &text));
|
||||
@@ -388,6 +405,25 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn asynchronous_questions_survive_turn_end_restart_and_duplicate_notifications() {
|
||||
let mut t = Timeline::default();
|
||||
let update = json!({"sessionUpdate":"user_question","id":"call-1","title":"Which?",
|
||||
"questions":[{"answerKey":"q1","question":"Which?","options":[]}]});
|
||||
assert_eq!(t.apply(&update).changed, vec![0]);
|
||||
assert!(t.end_turn(None).is_empty());
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: None, .. }));
|
||||
let saved = serde_json::to_string(&t.entries).unwrap();
|
||||
let mut t = Timeline::from_entries(serde_json::from_str(&saved).unwrap());
|
||||
assert!(t.apply(&update).changed.is_empty());
|
||||
assert_eq!(t.entries.len(), 1);
|
||||
if let AgentEntry::Question { chosen, .. } = &mut t.entries[0] {
|
||||
*chosen = Some("One".into());
|
||||
}
|
||||
assert!(t.apply(&update).changed.is_empty());
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunks_merge_into_one_message_until_another_entry_comes() {
|
||||
let mut t = Timeline::default();
|
||||
|
||||
@@ -783,6 +783,35 @@ pub struct AppearanceSettings {
|
||||
pub main_toolbar: Option<MainToolbarSettings>,
|
||||
/// Appearance › Background Image: an image shown through the IDE window.
|
||||
pub background_image: BackgroundImageSettings,
|
||||
/// Appearance › Presentation Assistant: the name and shortcut of each action run.
|
||||
pub presentation_assistant: PresentationAssistantSettings,
|
||||
}
|
||||
|
||||
/// Appearance › Presentation Assistant: shows the name and shortcut of each action the user runs.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct PresentationAssistantSettings {
|
||||
pub enabled: bool,
|
||||
/// `small` | `medium` | `large`.
|
||||
pub size: String,
|
||||
/// How long each popup stays, in seconds.
|
||||
pub duration_seconds: u32,
|
||||
/// `top-left`, `top`, `top-right`, `bottom-left`, `bottom` or `bottom-right` of the window.
|
||||
pub position: String,
|
||||
/// Also show the shortcut of the other platform's keymap (macOS ⇄ Windows/Linux).
|
||||
pub alternate_keymap: bool,
|
||||
}
|
||||
|
||||
impl Default for PresentationAssistantSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
size: "medium".into(),
|
||||
duration_seconds: 4,
|
||||
position: "bottom".into(),
|
||||
alternate_keymap: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Appearance › Background Image. An empty `path` shows no image.
|
||||
@@ -875,6 +904,7 @@ impl Default for AppearanceSettings {
|
||||
status_bar_widgets: BTreeMap::new(),
|
||||
main_toolbar: None,
|
||||
background_image: BackgroundImageSettings::default(),
|
||||
presentation_assistant: PresentationAssistantSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -812,16 +812,16 @@ impl DbManager {
|
||||
let password = self.password(&source).await;
|
||||
// Holding the tunnel keeps it open while the tool runs, even if the tree disconnects.
|
||||
let (target, _tunnel) = self.endpoint(&source, None, true).await?;
|
||||
let prepared = tools::prepare(job, &target, password.as_deref());
|
||||
tools::run(executable, &prepared.args, &prepared.env, cancel, on_output).await
|
||||
let prepared = tools::prepare(job, executable, &target, password.as_deref())?;
|
||||
tools::run(executable, &prepared.args, &prepared.env, prepared.input.as_deref(), cancel, on_output).await
|
||||
}
|
||||
|
||||
/// The command [`DbManager::run_tool`] would run, for the dialogs' preview: the data source's
|
||||
/// own host and port (not a tunnel's local end), and no password.
|
||||
pub fn tool_preview(&self, id: &str, executable: &std::path::Path, job: &tools::DbToolJob) -> IdeResult<String> {
|
||||
let source = self.source(id)?;
|
||||
let prepared = tools::prepare(job, &source, None);
|
||||
Ok(tools::command_line(executable, &prepared.args))
|
||||
let prepared = tools::prepare(job, executable, &source, None)?;
|
||||
Ok(tools::command_line(executable, &prepared.args, job.input()))
|
||||
}
|
||||
|
||||
/// The PostgreSQL server's `server_version_num` (`150013` for 15.13).
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! The connection arguments come from [`super::connection`]; these are the rest.
|
||||
|
||||
use super::DbTool;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::Path;
|
||||
@@ -58,6 +59,8 @@ pub struct DbPgDumpOptions {
|
||||
pub struct DbPgRestoreOptions {
|
||||
pub content: DbDumpContent,
|
||||
pub schemas: Vec<String>,
|
||||
/// Creates the database the archive names; the target is only connected to.
|
||||
pub create: bool,
|
||||
pub clean: bool,
|
||||
pub if_exists: bool,
|
||||
pub no_owner: bool,
|
||||
@@ -75,6 +78,40 @@ pub struct DbPsqlOptions {
|
||||
pub stop_on_error: bool,
|
||||
}
|
||||
|
||||
/// Switches that `mysqldump` turns on by default (`--opt`) only take a flag when turned off.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DbMysqldumpOptions {
|
||||
/// Empty: every database.
|
||||
pub databases: Vec<String>,
|
||||
/// Only with exactly one database.
|
||||
pub tables: Vec<String>,
|
||||
pub add_drop_table: bool,
|
||||
pub disable_keys: bool,
|
||||
pub add_locks: bool,
|
||||
pub add_drop_trigger: bool,
|
||||
pub no_data: bool,
|
||||
pub complete_insert: bool,
|
||||
pub create_options: bool,
|
||||
pub routines: bool,
|
||||
pub events: bool,
|
||||
/// A consistent InnoDB snapshot without locks; needs no RELOAD privilege.
|
||||
pub single_transaction: bool,
|
||||
/// Wins over `single_transaction`.
|
||||
pub lock_all_tables: bool,
|
||||
/// `None`: the client has no `--masking-policies`.
|
||||
pub masking_policies: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DbMysqlOptions {
|
||||
/// Empty: the databases the dump names.
|
||||
pub database: String,
|
||||
/// Runs the remaining statements after an error.
|
||||
pub force: bool,
|
||||
}
|
||||
|
||||
/// A run of a client tool: which one, the file it writes or reads, and its options.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "tool", rename_all = "camelCase")]
|
||||
@@ -92,6 +129,15 @@ pub enum DbToolJob {
|
||||
file: String,
|
||||
options: DbPsqlOptions,
|
||||
},
|
||||
Mysqldump {
|
||||
file: String,
|
||||
options: DbMysqldumpOptions,
|
||||
},
|
||||
/// `file` goes to the standard input.
|
||||
Mysql {
|
||||
file: String,
|
||||
options: DbMysqlOptions,
|
||||
},
|
||||
}
|
||||
|
||||
impl DbToolJob {
|
||||
@@ -100,15 +146,38 @@ impl DbToolJob {
|
||||
DbToolJob::PgDump { .. } => DbTool::PgDump,
|
||||
DbToolJob::PgRestore { .. } => DbTool::PgRestore,
|
||||
DbToolJob::Psql { .. } => DbTool::Psql,
|
||||
DbToolJob::Mysqldump { .. } => DbTool::Mysqldump,
|
||||
DbToolJob::Mysql { .. } => DbTool::Mysql,
|
||||
}
|
||||
}
|
||||
|
||||
/// The file piped to the tool's standard input.
|
||||
pub fn input(&self) -> Option<&str> {
|
||||
match self {
|
||||
DbToolJob::Mysql { file, .. } if !file.is_empty() => Some(file),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuses names that the tool would read as options: `mysqldump` takes databases and tables
|
||||
/// as plain arguments.
|
||||
pub fn check(&self) -> IdeResult<()> {
|
||||
if let DbToolJob::Mysqldump { options, .. } = self
|
||||
&& let Some(name) = options.databases.iter().chain(&options.tables).find(|n| n.trim().starts_with('-'))
|
||||
{
|
||||
return Err(IdeError::invalid(format!("mysqldump cannot dump a database or table named {name}")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The arguments after the connection ones.
|
||||
pub fn args(&self) -> Vec<String> {
|
||||
match self {
|
||||
DbToolJob::PgDump { file, options } => pg_dump(options, file),
|
||||
DbToolJob::PgRestore { file, options } => pg_restore(options, file),
|
||||
DbToolJob::Psql { file, options } => psql(options, file),
|
||||
DbToolJob::Mysqldump { file, options } => mysqldump(options, file),
|
||||
DbToolJob::Mysql { options, .. } => mysql(options),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -162,6 +231,7 @@ fn pg_dump(o: &DbPgDumpOptions, file: &str) -> Vec<String> {
|
||||
fn pg_restore(o: &DbPgRestoreOptions, file: &str) -> Vec<String> {
|
||||
let mut args: Vec<String> = content(o.content).into_iter().collect();
|
||||
args.extend(each(&o.schemas, "schema"));
|
||||
args.extend(flag(o.create, "--create"));
|
||||
args.extend(flag(o.clean, "--clean"));
|
||||
args.extend(flag(o.clean && o.if_exists, "--if-exists"));
|
||||
args.extend(flag(o.no_owner, "--no-owner"));
|
||||
@@ -187,8 +257,53 @@ fn psql(o: &DbPsqlOptions, file: &str) -> Vec<String> {
|
||||
args
|
||||
}
|
||||
|
||||
/// The command as a shell would need it typed: the dialogs' preview.
|
||||
pub fn command_line(program: &Path, args: &[String]) -> String {
|
||||
fn names(list: &[String]) -> impl Iterator<Item = String> {
|
||||
list.iter().map(|n| n.trim()).filter(|n| !n.is_empty()).map(str::to_owned)
|
||||
}
|
||||
|
||||
fn mysqldump(o: &DbMysqldumpOptions, file: &str) -> Vec<String> {
|
||||
let skip = |on: bool, option: &str| (!on).then(|| format!("--skip-{option}"));
|
||||
let mut args = vec![format!("--result-file={file}")];
|
||||
args.extend(skip(o.add_drop_table, "add-drop-table"));
|
||||
args.extend(skip(o.disable_keys, "disable-keys"));
|
||||
args.extend(skip(o.add_locks, "add-locks"));
|
||||
args.extend(skip(o.create_options, "create-options"));
|
||||
args.extend(flag(o.add_drop_trigger, "--add-drop-trigger"));
|
||||
args.extend(flag(o.no_data, "--no-data"));
|
||||
args.extend(flag(o.complete_insert, "--complete-insert"));
|
||||
args.extend(flag(o.routines, "--routines"));
|
||||
args.extend(flag(o.events, "--events"));
|
||||
args.extend(flag(o.lock_all_tables, "--lock-all-tables"));
|
||||
args.extend(flag(!o.lock_all_tables && o.single_transaction, "--single-transaction"));
|
||||
// On by default where it exists; reading the policies needs privileges most users lack.
|
||||
args.extend(flag(o.masking_policies == Some(false), "--skip-masking-policies"));
|
||||
// Tablespace statements need the PROCESS privilege and rarely matter in a dump.
|
||||
args.push("--no-tablespaces".into());
|
||||
args.push("--verbose".into());
|
||||
let databases: Vec<String> = names(&o.databases).collect();
|
||||
match databases.as_slice() {
|
||||
[] => args.push("--all-databases".into()),
|
||||
[one] => {
|
||||
args.push(one.clone());
|
||||
args.extend(names(&o.tables));
|
||||
}
|
||||
_ => {
|
||||
args.push("--databases".into());
|
||||
args.extend(databases);
|
||||
}
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
fn mysql(o: &DbMysqlOptions) -> Vec<String> {
|
||||
let database = o.database.trim();
|
||||
let mut args: Vec<String> = (!database.is_empty()).then(|| format!("--database={database}")).into_iter().collect();
|
||||
args.extend(flag(o.force, "--force"));
|
||||
args
|
||||
}
|
||||
|
||||
/// The command as a shell would need it typed: the dialogs' preview. `input` is piped in.
|
||||
pub fn command_line(program: &Path, args: &[String], input: Option<&str>) -> String {
|
||||
let quote = |s: &str| {
|
||||
if !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "@%+=:,./-_".contains(c)) {
|
||||
s.to_owned()
|
||||
@@ -196,11 +311,15 @@ pub fn command_line(program: &Path, args: &[String]) -> String {
|
||||
format!("'{}'", s.replace('\'', "'\\''"))
|
||||
}
|
||||
};
|
||||
std::iter::once(program.to_string_lossy().into_owned())
|
||||
let line = std::iter::once(program.to_string_lossy().into_owned())
|
||||
.chain(args.iter().cloned())
|
||||
.map(|a| quote(&a))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
.join(" ");
|
||||
match input {
|
||||
Some(file) => format!("{line} < {}", quote(file)),
|
||||
None => line,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -228,6 +347,7 @@ mod tests {
|
||||
DbPgRestoreOptions {
|
||||
content: DbDumpContent::All,
|
||||
schemas: vec![],
|
||||
create: false,
|
||||
clean: false,
|
||||
if_exists: false,
|
||||
no_owner: false,
|
||||
@@ -308,6 +428,13 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creates_the_database_of_the_archive_when_asked() {
|
||||
let options = DbPgRestoreOptions { create: true, ..restore() };
|
||||
let a = args(DbToolJob::PgRestore { file: "/tmp/shop.dump".into(), options });
|
||||
assert_eq!(a, ["--create", "--exit-on-error", "--verbose", "/tmp/shop.dump"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_out_an_archive_not_chosen_yet() {
|
||||
let a = args(DbToolJob::PgRestore { file: String::new(), options: restore() });
|
||||
@@ -328,8 +455,92 @@ mod tests {
|
||||
let line = command_line(
|
||||
Path::new("/usr/bin/pg_dump"),
|
||||
&["--port=5432".into(), "--file=/tmp/my dump.sql".into(), "--table=it's".into()],
|
||||
None,
|
||||
);
|
||||
assert_eq!(line, r#"/usr/bin/pg_dump --port=5432 '--file=/tmp/my dump.sql' '--table=it'\''s'"#);
|
||||
let line = command_line(Path::new("mysql"), &["--force".into()], Some("/tmp/my dump.sql"));
|
||||
assert_eq!(line, "mysql --force < '/tmp/my dump.sql'");
|
||||
}
|
||||
|
||||
fn mysqldump_options() -> DbMysqldumpOptions {
|
||||
DbMysqldumpOptions {
|
||||
databases: vec!["shop".into()],
|
||||
tables: vec![],
|
||||
add_drop_table: true,
|
||||
disable_keys: true,
|
||||
add_locks: true,
|
||||
add_drop_trigger: false,
|
||||
no_data: false,
|
||||
complete_insert: false,
|
||||
create_options: true,
|
||||
routines: false,
|
||||
events: false,
|
||||
single_transaction: true,
|
||||
lock_all_tables: false,
|
||||
masking_policies: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysqldump_flags_only_what_differs_from_its_defaults() {
|
||||
let job = DbToolJob::Mysqldump { file: "/tmp/shop.sql".into(), options: mysqldump_options() };
|
||||
assert_eq!(
|
||||
args(job),
|
||||
["--result-file=/tmp/shop.sql", "--single-transaction", "--no-tablespaces", "--verbose", "shop"]
|
||||
);
|
||||
let options = DbMysqldumpOptions {
|
||||
add_drop_table: false,
|
||||
create_options: false,
|
||||
routines: true,
|
||||
lock_all_tables: true,
|
||||
masking_policies: Some(false),
|
||||
..mysqldump_options()
|
||||
};
|
||||
let a = args(DbToolJob::Mysqldump { file: "/tmp/x.sql".into(), options });
|
||||
for expected in ["--skip-add-drop-table", "--skip-create-options", "--routines", "--lock-all-tables"] {
|
||||
assert!(a.contains(&expected.to_owned()), "{expected} missing from {a:?}");
|
||||
}
|
||||
assert!(a.contains(&"--skip-masking-policies".to_owned()), "{a:?}");
|
||||
assert!(!a.contains(&"--single-transaction".to_owned()), "{a:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysqldump_names_tables_only_of_a_single_database() {
|
||||
let tables = vec!["orders".to_owned(), "items".to_owned()];
|
||||
let one = DbMysqldumpOptions { tables: tables.clone(), ..mysqldump_options() };
|
||||
assert!(args(DbToolJob::Mysqldump { file: "f".into(), options: one }).ends_with(&[
|
||||
"shop".into(),
|
||||
"orders".into(),
|
||||
"items".into()
|
||||
]));
|
||||
let two = DbMysqldumpOptions { databases: vec!["a".into(), "b".into()], tables, ..mysqldump_options() };
|
||||
assert!(args(DbToolJob::Mysqldump { file: "f".into(), options: two }).ends_with(&[
|
||||
"--databases".into(),
|
||||
"a".into(),
|
||||
"b".into()
|
||||
]));
|
||||
let all = DbMysqldumpOptions { databases: vec![], ..mysqldump_options() };
|
||||
assert_eq!(args(DbToolJob::Mysqldump { file: "f".into(), options: all }).last().unwrap(), "--all-databases");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysqldump_refuses_names_it_would_read_as_options() {
|
||||
let options = DbMysqldumpOptions { tables: vec!["--result-file=/etc/x".into()], ..mysqldump_options() };
|
||||
assert!(DbToolJob::Mysqldump { file: "f".into(), options }.check().is_err());
|
||||
assert!(DbToolJob::Mysqldump { file: "f".into(), options: mysqldump_options() }.check().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_reads_the_dump_from_its_standard_input() {
|
||||
let job = DbToolJob::Mysql {
|
||||
file: "/tmp/shop.sql".into(),
|
||||
options: DbMysqlOptions { database: " shop ".into(), force: true },
|
||||
};
|
||||
assert_eq!(args(job.clone()), ["--database=shop", "--force"]);
|
||||
assert_eq!(job.input(), Some("/tmp/shop.sql"));
|
||||
let none =
|
||||
DbToolJob::Mysql { file: String::new(), options: DbMysqlOptions { database: String::new(), force: false } };
|
||||
assert!(args(none.clone()).is_empty() && none.input().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Client tools of a database (`pg_dump`, `pg_restore`, `psql`): finding installed copies, the
|
||||
//! arguments and environment that connect them like the data source, and running them.
|
||||
//! Client tools of a database (`pg_dump`, `pg_restore`, `psql`, `mysqldump`, `mysql`): finding
|
||||
//! installed copies, the arguments and environment that connect them like the data source, and
|
||||
//! running them.
|
||||
|
||||
mod jobs;
|
||||
pub use jobs::*;
|
||||
@@ -20,6 +21,8 @@ pub enum DbTool {
|
||||
PgDump,
|
||||
PgRestore,
|
||||
Psql,
|
||||
Mysqldump,
|
||||
Mysql,
|
||||
}
|
||||
|
||||
impl DbTool {
|
||||
@@ -27,20 +30,25 @@ impl DbTool {
|
||||
self.programs()[0]
|
||||
}
|
||||
|
||||
/// Executable names.
|
||||
/// Executable names, MariaDB's own after MySQL's.
|
||||
pub fn programs(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
DbTool::PgDump => &["pg_dump"],
|
||||
DbTool::PgRestore => &["pg_restore"],
|
||||
DbTool::Psql => &["psql"],
|
||||
DbTool::Mysqldump => &["mysqldump", "mariadb-dump"],
|
||||
DbTool::Mysql => &["mysql", "mariadb"],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn driver(self) -> DbDriver {
|
||||
DbDriver::Postgres
|
||||
match self {
|
||||
DbTool::PgDump | DbTool::PgRestore | DbTool::Psql => DbDriver::Postgres,
|
||||
DbTool::Mysqldump | DbTool::Mysql => DbDriver::Mysql,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` names this tool (`pg_dump`, `pg_dump.exe`, `pg_dump-17`…).
|
||||
/// Whether `path` names this tool (`pg_dump`, `pg_dump.exe`, `pg_dump-17`, `mariadb-dump`…).
|
||||
/// The data source's password is handed only to such a program.
|
||||
pub fn is_program(self, path: &Path) -> bool {
|
||||
let Some(stem) = path.file_stem().and_then(OsStr::to_str) else { return false };
|
||||
@@ -53,6 +61,12 @@ impl DbTool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `executable` is MariaDB's client (`mariadb`, `mariadb-dump`), whose SSL options differ
|
||||
/// from MySQL's.
|
||||
fn is_mariadb(executable: &Path) -> bool {
|
||||
executable.file_stem().and_then(OsStr::to_str).is_some_and(|s| s.starts_with("mariadb"))
|
||||
}
|
||||
|
||||
/// An installed copy of a tool.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", rename = "DbToolInstall")]
|
||||
@@ -70,28 +84,41 @@ pub struct ToolLine {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// Directories holding the tools that are often missing from `PATH`, by platform.
|
||||
fn known_dirs() -> Vec<PathBuf> {
|
||||
/// Directories holding the tools of `driver` that are often missing from `PATH`, by platform.
|
||||
fn known_dirs(driver: DbDriver) -> Vec<PathBuf> {
|
||||
let mysql = driver == DbDriver::Mysql;
|
||||
let mut dirs = Vec::new();
|
||||
if cfg!(target_os = "macos") {
|
||||
for prefix in ["/opt/homebrew", "/usr/local"] {
|
||||
dirs.push(PathBuf::from(format!("{prefix}/bin")));
|
||||
let opt = PathBuf::from(format!("{prefix}/opt"));
|
||||
for keg in ["libpq", "postgresql"] {
|
||||
let kegs: &[&str] = if mysql { &["mysql-client", "mysql", "mariadb"] } else { &["libpq", "postgresql"] };
|
||||
for keg in kegs {
|
||||
dirs.extend(children(&opt, keg).into_iter().map(|d| d.join("bin")));
|
||||
}
|
||||
}
|
||||
dirs.extend(
|
||||
children(Path::new("/Applications/Postgres.app/Contents/Versions"), "").into_iter().map(|d| d.join("bin")),
|
||||
);
|
||||
if mysql {
|
||||
dirs.push(PathBuf::from("/usr/local/mysql/bin"));
|
||||
} else {
|
||||
dirs.extend(
|
||||
children(Path::new("/Applications/Postgres.app/Contents/Versions"), "")
|
||||
.into_iter()
|
||||
.map(|d| d.join("bin")),
|
||||
);
|
||||
}
|
||||
} else if cfg!(windows) {
|
||||
for var in ["ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = std::env::var_os(var) {
|
||||
let root = PathBuf::from(base).join("PostgreSQL");
|
||||
dirs.extend(children(&root, "").into_iter().map(|d| d.join("bin")));
|
||||
let base = PathBuf::from(base);
|
||||
// MySQL installs to `MySQL\MySQL Server 8.4`, MariaDB to `MariaDB 11.4`.
|
||||
let roots: &[(&str, &str)] =
|
||||
if mysql { &[("MySQL", "MySQL"), ("", "MariaDB")] } else { &[("PostgreSQL", "")] };
|
||||
for (dir, prefix) in roots {
|
||||
dirs.extend(children(&base.join(dir), prefix).into_iter().map(|d| d.join("bin")));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
} else if !mysql {
|
||||
dirs.extend(children(Path::new("/usr/lib/postgresql"), "").into_iter().map(|d| d.join("bin")));
|
||||
dirs.extend(children(Path::new("/usr"), "pgsql-").into_iter().map(|d| d.join("bin")));
|
||||
}
|
||||
@@ -121,7 +148,7 @@ fn version_key(text: &str) -> Vec<u32> {
|
||||
pub fn find_installs(tool: DbTool) -> Vec<ToolInstall> {
|
||||
let path = ide_core::process::host_var_os("PATH").unwrap_or_default();
|
||||
let mut dirs: Vec<PathBuf> = std::env::split_paths(&path).collect();
|
||||
dirs.extend(known_dirs());
|
||||
dirs.extend(known_dirs(tool.driver()));
|
||||
let mut seen = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
for dir in dirs {
|
||||
@@ -150,6 +177,29 @@ pub fn version_of(path: &Path) -> IdeResult<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The long options `path --help` lists (`masking-policies` for `--masking-policies`), so a
|
||||
/// dialog offers only options this copy knows. Blocking.
|
||||
pub fn options_of(path: &Path) -> IdeResult<Vec<String>> {
|
||||
let (_, text) = capture(path, "--help")?;
|
||||
Ok(help_options(&text))
|
||||
}
|
||||
|
||||
fn help_options(help: &str) -> Vec<String> {
|
||||
let mut out: Vec<String> = help
|
||||
.lines()
|
||||
.filter(|l| l.starts_with(' ') && l.trim_start().starts_with('-'))
|
||||
.filter_map(|l| {
|
||||
let at = l.find("--")?;
|
||||
let name: String =
|
||||
l[at + 2..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').collect();
|
||||
(!name.is_empty()).then_some(name)
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// Runs `path arg` for at most five seconds; whether it succeeded, and its standard output.
|
||||
fn capture(path: &Path, arg: &str) -> IdeResult<(bool, String)> {
|
||||
if !path.is_file() {
|
||||
@@ -189,23 +239,41 @@ pub enum DbDumpKind {
|
||||
PostgresArchive,
|
||||
/// Plain SQL from `pg_dump`: `psql`.
|
||||
PostgresSql,
|
||||
/// `mysqldump` / `mariadb-dump`: not for the PostgreSQL tools.
|
||||
/// `mysqldump` / `mariadb-dump`: `mysql`.
|
||||
MysqlSql,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Blocking: reads at most the first 4 KiB.
|
||||
pub fn dump_kind(path: &Path) -> IdeResult<DbDumpKind> {
|
||||
/// What a restore needs to know about a dump before it runs.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", rename = "DbDumpInfo")]
|
||||
pub struct DumpInfo {
|
||||
pub kind: DbDumpKind,
|
||||
/// An SQL dump that runs `CREATE DATABASE` itself: `mysqldump --databases` / `--all-databases`,
|
||||
/// or `pg_dump --create`. Archives say `false`; `pg_restore --create` decides for them.
|
||||
pub creates_database: bool,
|
||||
}
|
||||
|
||||
/// Blocking: reads at most the first 64 KiB, where both tools write their `CREATE DATABASE`.
|
||||
pub fn dump_info(path: &Path) -> IdeResult<DumpInfo> {
|
||||
use std::io::Read;
|
||||
if path.is_dir() {
|
||||
return Ok(if path.join("toc.dat").is_file() { DbDumpKind::PostgresArchive } else { DbDumpKind::Unknown });
|
||||
let kind = if path.join("toc.dat").is_file() { DbDumpKind::PostgresArchive } else { DbDumpKind::Unknown };
|
||||
return Ok(DumpInfo { kind, creates_database: false });
|
||||
}
|
||||
let mut head = Vec::with_capacity(4096);
|
||||
let mut head = Vec::with_capacity(64 * 1024);
|
||||
std::fs::File::open(path)
|
||||
.map_err(|e| IdeError::not_found(format!("cannot read {}: {e}", path.display())))?
|
||||
.take(4096)
|
||||
.take(64 * 1024)
|
||||
.read_to_end(&mut head)?;
|
||||
Ok(kind_of(&head))
|
||||
Ok(info_of(&head))
|
||||
}
|
||||
|
||||
fn info_of(head: &[u8]) -> DumpInfo {
|
||||
let kind = kind_of(head);
|
||||
let sql = matches!(kind, DbDumpKind::PostgresSql | DbDumpKind::MysqlSql);
|
||||
let creates_database = sql && String::from_utf8_lossy(head).lines().any(|l| l.starts_with("CREATE DATABASE "));
|
||||
DumpInfo { kind, creates_database }
|
||||
}
|
||||
|
||||
fn kind_of(head: &[u8]) -> DbDumpKind {
|
||||
@@ -224,9 +292,12 @@ fn kind_of(head: &[u8]) -> DbDumpKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// Arguments and environment that connect `tool` to `source` (already resolved, through its
|
||||
/// tunnel when it has one). The password is left to [`prepare`].
|
||||
pub fn connection(tool: DbTool, source: &DataSource) -> (Vec<String>, Vec<(String, String)>) {
|
||||
/// Arguments and environment that connect `tool` at `executable` to `source` (already resolved,
|
||||
/// through its tunnel when it has one). The password is left to [`prepare`].
|
||||
pub fn connection(tool: DbTool, executable: &Path, source: &DataSource) -> (Vec<String>, Vec<(String, String)>) {
|
||||
if tool.driver() == DbDriver::Mysql {
|
||||
return (mysql_connection(tool, executable, source), Vec::new());
|
||||
}
|
||||
let mut args = Vec::new();
|
||||
let host = source.host.trim();
|
||||
if !host.is_empty() {
|
||||
@@ -271,6 +342,50 @@ pub fn connection(tool: DbTool, source: &DataSource) -> (Vec<String>, Vec<(Strin
|
||||
(args, env)
|
||||
}
|
||||
|
||||
/// The database is the job's: a dump may name several.
|
||||
fn mysql_connection(tool: DbTool, executable: &Path, source: &DataSource) -> Vec<String> {
|
||||
let mut args = Vec::new();
|
||||
let host = source.host.trim();
|
||||
if !host.is_empty() {
|
||||
args.push(format!("--host={host}"));
|
||||
}
|
||||
args.push(format!("--port={}", source.port.or(source.driver.default_port()).unwrap_or(3306)));
|
||||
if !source.user.trim().is_empty() {
|
||||
args.push(format!("--user={}", source.user.trim()));
|
||||
}
|
||||
// `localhost` would otherwise mean the Unix socket, not the port or the tunnel.
|
||||
args.push("--protocol=TCP".into());
|
||||
if is_mariadb(executable) {
|
||||
let flags: &[&str] = match source.ssl {
|
||||
DbSslMode::Disable => &["--skip-ssl"],
|
||||
DbSslMode::Prefer => &["--skip-ssl-verify-server-cert"],
|
||||
DbSslMode::Require => &["--ssl", "--skip-ssl-verify-server-cert"],
|
||||
DbSslMode::VerifyCa | DbSslMode::VerifyFull => &["--ssl", "--ssl-verify-server-cert"],
|
||||
};
|
||||
args.extend(flags.iter().map(|f| f.to_string()));
|
||||
} else {
|
||||
let mode = match source.ssl {
|
||||
DbSslMode::Disable => "DISABLED",
|
||||
DbSslMode::Prefer => "PREFERRED",
|
||||
DbSslMode::Require => "REQUIRED",
|
||||
DbSslMode::VerifyCa => "VERIFY_CA",
|
||||
DbSslMode::VerifyFull => "VERIFY_IDENTITY",
|
||||
};
|
||||
args.push(format!("--ssl-mode={mode}"));
|
||||
}
|
||||
for (flag, file) in
|
||||
[("--ssl-ca", &source.ssl_ca_file), ("--ssl-cert", &source.ssl_cert_file), ("--ssl-key", &source.ssl_key_file)]
|
||||
{
|
||||
if !file.trim().is_empty() {
|
||||
args.push(format!("{flag}={}", ide_ssh::expand(file.trim()).to_string_lossy()));
|
||||
}
|
||||
}
|
||||
if tool == DbTool::Mysql && source.read_only {
|
||||
args.push("--init-command=SET SESSION TRANSACTION READ ONLY".into());
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
/// `--dbname` reads a connection string or URI as connection parameters: such a database name
|
||||
/// goes in quoted as the string's `dbname`, so it cannot pick another host or credentials.
|
||||
fn dbname_arg(name: &str) -> String {
|
||||
@@ -281,36 +396,88 @@ fn dbname_arg(name: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// How a tool is started: connection arguments, then the job's, and the environment.
|
||||
/// A MySQL client option file holding the password, readable by the user only; deleted on drop.
|
||||
struct SecretFile(PathBuf);
|
||||
|
||||
impl SecretFile {
|
||||
fn mysql_password(password: &str) -> IdeResult<Self> {
|
||||
use std::io::Write;
|
||||
let path = std::env::temp_dir().join(format!("openidea-mysql-{}.cnf", uuid::Uuid::new_v4()));
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
|
||||
let mut file = options.open(&path)?;
|
||||
let secret = SecretFile(path);
|
||||
let escaped = password.replace('\\', "\\\\").replace('"', "\\\"");
|
||||
writeln!(file, "[client]\npassword=\"{escaped}\"")?;
|
||||
Ok(secret)
|
||||
}
|
||||
|
||||
/// `mysqldump` / `mysql` accept it only as their first argument.
|
||||
fn arg(&self) -> String {
|
||||
format!("--defaults-extra-file={}", self.0.display())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SecretFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// How a tool is started: connection arguments, then the job's, the environment, and the file
|
||||
/// piped to its standard input. Keep it until the tool exits: it owns the password file.
|
||||
pub struct Prepared {
|
||||
pub args: Vec<String>,
|
||||
pub env: Vec<(String, String)>,
|
||||
pub input: Option<PathBuf>,
|
||||
_secret: Option<SecretFile>,
|
||||
}
|
||||
|
||||
/// The command for `job` against `source`. The password goes in `PGPASSWORD`, never in the
|
||||
/// arguments, which other users of the machine can read in the process list.
|
||||
pub fn prepare(job: &DbToolJob, source: &DataSource, password: Option<&str>) -> Prepared {
|
||||
let (mut args, mut env) = connection(job.tool(), source);
|
||||
/// The command for `job` at `executable` against `source`. The password goes in `PGPASSWORD` or
|
||||
/// a MySQL option file, never in the arguments, which other users of the machine can read in the
|
||||
/// process list.
|
||||
pub fn prepare(job: &DbToolJob, executable: &Path, source: &DataSource, password: Option<&str>) -> IdeResult<Prepared> {
|
||||
job.check()?;
|
||||
let tool = job.tool();
|
||||
let (mut args, mut env) = connection(tool, executable, source);
|
||||
args.extend(job.args());
|
||||
if let Some(p) = password.filter(|p| !p.is_empty()) {
|
||||
env.push(("PGPASSWORD".into(), p.to_owned()));
|
||||
let mut secret = None;
|
||||
match password.filter(|p| !p.is_empty()) {
|
||||
Some(p) if tool.driver() == DbDriver::Mysql => {
|
||||
let file = SecretFile::mysql_password(p)?;
|
||||
args.insert(0, file.arg());
|
||||
secret = Some(file);
|
||||
}
|
||||
Some(p) => env.push(("PGPASSWORD".into(), p.to_owned())),
|
||||
None => {}
|
||||
}
|
||||
Prepared { args, env }
|
||||
Ok(Prepared { args, env, input: job.input().map(PathBuf::from), _secret: secret })
|
||||
}
|
||||
|
||||
/// Runs `program` until it exits, passing its output in batches. Returns the exit code
|
||||
/// (`None`: ended by a signal). Cancelling kills it and everything it started.
|
||||
/// Runs `program` until it exits, passing its output in batches; `input` is piped to its standard
|
||||
/// input. Returns the exit code (`None`: ended by a signal). Cancelling kills it and everything it
|
||||
/// started.
|
||||
pub async fn run(
|
||||
program: &Path,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
input: Option<&Path>,
|
||||
cancel: &CancellationToken,
|
||||
mut on_output: impl FnMut(Vec<ToolLine>),
|
||||
) -> IdeResult<Option<i32>> {
|
||||
let stdin = match input {
|
||||
Some(path) => Stdio::from(
|
||||
std::fs::File::open(path)
|
||||
.map_err(|e| IdeError::not_found(format!("cannot read {}: {e}", path.display())))?,
|
||||
),
|
||||
None => Stdio::null(),
|
||||
};
|
||||
let mut cmd = tokio::process::Command::new(program);
|
||||
cmd.args(args)
|
||||
.envs(env.iter().map(|(k, v)| (k, v)))
|
||||
.stdin(Stdio::null())
|
||||
.stdin(stdin)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
@@ -408,7 +575,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn connects_like_the_data_source_without_prompting() {
|
||||
let (args, env) = connection(DbTool::PgDump, &pg());
|
||||
let (args, env) = connection(DbTool::PgDump, Path::new("pg_dump"), &pg());
|
||||
assert_eq!(args, ["--host=db.example.test", "--port=6543", "--username=app", "--dbname=shop", "--no-password"]);
|
||||
assert!(env.contains(&("PGSSLMODE".into(), "prefer".into())));
|
||||
assert!(!env.iter().any(|(k, _)| k == "PGPASSWORD" || k == "PGOPTIONS"));
|
||||
@@ -421,7 +588,8 @@ mod tests {
|
||||
(r"it's=\x", r"--dbname=dbname='it\'s=\\x'"),
|
||||
("postgresql://evil.example/p", "--dbname=dbname='postgresql://evil.example/p'"),
|
||||
] {
|
||||
let (args, _) = connection(DbTool::PgDump, &DataSource { database: name.into(), ..pg() });
|
||||
let (args, _) =
|
||||
connection(DbTool::PgDump, Path::new("pg_dump"), &DataSource { database: name.into(), ..pg() });
|
||||
assert!(args.contains(&arg.to_owned()), "{args:?}");
|
||||
}
|
||||
}
|
||||
@@ -429,14 +597,14 @@ mod tests {
|
||||
#[test]
|
||||
fn default_port_and_optional_fields() {
|
||||
let source = DataSource { port: None, user: String::new(), database: String::new(), ..pg() };
|
||||
let (args, _) = connection(DbTool::Psql, &source);
|
||||
let (args, _) = connection(DbTool::Psql, Path::new("psql"), &source);
|
||||
assert_eq!(args, ["--host=db.example.test", "--port=5432", "--no-password"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_only_sources_refuse_writes() {
|
||||
let source = DataSource { read_only: true, ssl: DbSslMode::VerifyFull, ..pg() };
|
||||
let (_, env) = connection(DbTool::PgRestore, &source);
|
||||
let (_, env) = connection(DbTool::PgRestore, Path::new("pg_restore"), &source);
|
||||
assert!(env.contains(&("PGOPTIONS".into(), "-c default_transaction_read_only=on".into())));
|
||||
assert!(env.contains(&("PGSSLMODE".into(), "verify-full".into())));
|
||||
}
|
||||
@@ -451,6 +619,77 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_tools_accept_mariadb_names_only_for_themselves() {
|
||||
assert!(DbTool::Mysqldump.is_program(Path::new("/usr/bin/mariadb-dump")));
|
||||
assert!(DbTool::Mysql.is_program(Path::new("/opt/homebrew/opt/mysql-client/bin/mysql")));
|
||||
assert!(!DbTool::Mysql.is_program(Path::new("/usr/bin/mysqldump")));
|
||||
assert!(!DbTool::Mysql.is_program(Path::new("/usr/bin/mariadb-dump")));
|
||||
assert!(!DbTool::Mysqldump.is_program(Path::new("/usr/bin/mysqlpump")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_connects_over_tcp_with_the_ssl_flags_of_its_client() {
|
||||
let source = DataSource {
|
||||
driver: DbDriver::Mysql,
|
||||
host: "localhost".into(),
|
||||
port: None,
|
||||
user: "app".into(),
|
||||
read_only: true,
|
||||
..DataSource::default()
|
||||
};
|
||||
let (args, env) = connection(DbTool::Mysql, Path::new("/usr/bin/mysql"), &source);
|
||||
assert_eq!(
|
||||
args,
|
||||
[
|
||||
"--host=localhost",
|
||||
"--port=3306",
|
||||
"--user=app",
|
||||
"--protocol=TCP",
|
||||
"--ssl-mode=PREFERRED",
|
||||
"--init-command=SET SESSION TRANSACTION READ ONLY"
|
||||
]
|
||||
);
|
||||
assert!(env.is_empty());
|
||||
let (args, _) = connection(DbTool::Mysqldump, Path::new("/usr/bin/mariadb-dump"), &source);
|
||||
assert!(args.contains(&"--skip-ssl-verify-server-cert".to_owned()));
|
||||
assert!(!args.iter().any(|a| a.starts_with("--ssl-mode") || a.starts_with("--init-command")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_password_file_is_private_and_removed() {
|
||||
let file = SecretFile::mysql_password(r#"p"a\ss"#).unwrap();
|
||||
let path = file.arg().trim_start_matches("--defaults-extra-file=").to_owned();
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
assert_eq!(text, "[client]\npassword=\"p\\\"a\\\\ss\"\n");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
drop(file);
|
||||
assert!(!Path::new(&path).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_long_options_from_help() {
|
||||
let help = "Usage: mysqldump [OPTIONS]\n -A, --all-databases Dump all.\n --masking-policies Dump masking\n policies (--not-an-option).\n -y, --no-tablespaces \n -f, --file=FILENAME output file\n";
|
||||
assert_eq!(help_options(help), ["all-databases", "file", "masking-policies", "no-tablespaces"]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn pipes_the_input_file() {
|
||||
let file = std::env::temp_dir().join(format!("openidea-input-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::write(&file, "from the file\n").unwrap();
|
||||
let mut lines = Vec::new();
|
||||
run(Path::new("/bin/cat"), &[], &[], Some(&file), &CancellationToken::new(), |b| lines.extend(b))
|
||||
.await
|
||||
.unwrap();
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
assert_eq!(lines, [ToolLine { stderr: false, text: "from the file".into() }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tells_dumps_apart_by_their_header() {
|
||||
assert_eq!(kind_of(b"PGDMP\x01\x0f"), DbDumpKind::PostgresArchive);
|
||||
@@ -461,6 +700,17 @@ mod tests {
|
||||
assert_eq!(kind_of(b"CREATE TABLE t (id int);\n"), DbDumpKind::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sees_a_dump_that_creates_its_own_database() {
|
||||
let one = b"-- MySQL dump 10.13\n--\n-- Host: localhost Database: shop\nCREATE TABLE `items` (id int);\n";
|
||||
assert!(!info_of(one).creates_database);
|
||||
let several = b"-- MySQL dump 10.13\n--\n-- Current Database: `shop`\n--\n\nCREATE DATABASE /*!32312 IF NOT EXISTS*/ `shop`;\nUSE `shop`;\n";
|
||||
assert!(info_of(several).creates_database);
|
||||
let pg = b"--\n-- PostgreSQL database dump\n--\nSET client_encoding = 'UTF8';\nCREATE DATABASE shop WITH TEMPLATE = template0;\n\\connect shop\n";
|
||||
assert_eq!(info_of(pg), DumpInfo { kind: DbDumpKind::PostgresSql, creates_database: true });
|
||||
assert!(!info_of(b"CREATE DATABASE x;\n").creates_database, "only for a dump the tools wrote");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newer_versions_sort_first() {
|
||||
assert!(version_key("pg_dump (PostgreSQL) 17.2") > version_key("pg_dump (PostgreSQL) 9.6.24"));
|
||||
@@ -474,6 +724,7 @@ mod tests {
|
||||
Path::new("/bin/sh"),
|
||||
&["-c".into(), "echo out; echo err >&2; exit 3".into()],
|
||||
&[],
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
|batch| lines.extend(batch),
|
||||
)
|
||||
@@ -493,19 +744,25 @@ mod tests {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
stop.cancel();
|
||||
});
|
||||
let result = run(Path::new("/bin/sh"), &["-c".into(), "sleep 30".into()], &[], &cancel, |_| {}).await;
|
||||
let result = run(Path::new("/bin/sh"), &["-c".into(), "sleep 30".into()], &[], None, &cancel, |_| {}).await;
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
/// A stand-in for `tool` that prints each argument on a line, then whether `PGPASSWORD`
|
||||
/// holds the expected password.
|
||||
/// A stand-in for `tool` that prints each argument on a line, then whether it got a password
|
||||
/// from `PGPASSWORD` or a MySQL option file.
|
||||
#[cfg(unix)]
|
||||
fn echo_tool(dir: &Path, tool: DbTool) -> PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let path = dir.join(tool.program());
|
||||
std::fs::write(
|
||||
&path,
|
||||
"#!/bin/sh\nfor a in \"$@\"; do echo \"arg:$a\"; done\necho \"env:${PGPASSWORD:+set}\"\n",
|
||||
concat!(
|
||||
"#!/bin/sh\n",
|
||||
"for a in \"$@\"; do echo \"arg:$a\"; case \"$a\" in --defaults-extra-file=*)\n",
|
||||
" grep -q '^password=' \"${a#*=}\" && echo env:set;; esac; done\n",
|
||||
"[ -n \"$PGPASSWORD\" ] && echo env:set\n",
|
||||
"exit 0\n",
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
@@ -541,17 +798,48 @@ mod tests {
|
||||
file: file.clone(),
|
||||
options: DbPsqlOptions { single_transaction: true, stop_on_error: true },
|
||||
},
|
||||
DbToolJob::Mysqldump {
|
||||
file: file.clone(),
|
||||
options: DbMysqldumpOptions {
|
||||
databases: vec!["shop".into()],
|
||||
tables: vec![],
|
||||
add_drop_table: true,
|
||||
disable_keys: true,
|
||||
add_locks: true,
|
||||
add_drop_trigger: false,
|
||||
no_data: false,
|
||||
complete_insert: false,
|
||||
create_options: true,
|
||||
routines: false,
|
||||
events: false,
|
||||
single_transaction: true,
|
||||
lock_all_tables: false,
|
||||
masking_policies: None,
|
||||
},
|
||||
},
|
||||
DbToolJob::Mysql { file: String::new(), options: DbMysqlOptions { database: "shop".into(), force: false } },
|
||||
];
|
||||
for job in jobs {
|
||||
let mysql = job.tool().driver() == DbDriver::Mysql;
|
||||
let source = if mysql { DataSource { driver: DbDriver::Mysql, ..pg() } } else { pg() };
|
||||
let program = echo_tool(&dir, job.tool());
|
||||
let prepared = prepare(&job, &pg(), Some(SECRET));
|
||||
let prepared = prepare(&job, &program, &source, Some(SECRET)).unwrap();
|
||||
assert!(!prepared.args.iter().any(|a| a.contains(SECRET)), "{:?}", prepared.args);
|
||||
assert!(!mysql || prepared.env.is_empty(), "{:?}", prepared.env);
|
||||
let mut lines = Vec::new();
|
||||
run(&program, &prepared.args, &prepared.env, &CancellationToken::new(), |b| lines.extend(b)).await.unwrap();
|
||||
run(&program, &prepared.args, &prepared.env, None, &CancellationToken::new(), |b| lines.extend(b))
|
||||
.await
|
||||
.unwrap();
|
||||
let text: Vec<&str> = lines.iter().map(|l| l.text.as_str()).collect();
|
||||
assert!(text.contains(&"arg:--dbname=shop"), "{text:?}");
|
||||
let database = if mysql { "shop" } else { "--dbname=shop" };
|
||||
assert!(text.iter().any(|l| l.strip_prefix("arg:").is_some_and(|a| a.ends_with(database))), "{text:?}");
|
||||
assert!(!text.iter().any(|l| l.contains(SECRET)), "{text:?}");
|
||||
assert!(text.contains(&"env:set"), "the tool gets the password from PGPASSWORD: {text:?}");
|
||||
assert!(text.contains(&"env:set"), "the tool gets the password: {text:?}");
|
||||
if mysql {
|
||||
let file = prepared.args[0].trim_start_matches("--defaults-extra-file=").to_owned();
|
||||
drop(prepared);
|
||||
assert!(!Path::new(&file).exists(), "the password file outlives the run");
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
@@ -231,3 +231,70 @@ async fn servers_that_advertise_deprecate_eof_but_send_legacy_eof_packets() -> I
|
||||
assert_eq!(r.rows, vec![vec![Some("a".into())], vec![Some("b".into())]]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `mysqldump` into a file and `mysql` reading it back, with the data source's password.
|
||||
#[tokio::test]
|
||||
async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> {
|
||||
use ide_db::tools::{DbMysqlOptions, DbMysqldumpOptions, DbTool, DbToolJob, find_installs};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
|
||||
let (Some(dump), Some(client)) =
|
||||
(find_installs(DbTool::Mysqldump).into_iter().next(), find_installs(DbTool::Mysql).into_iter().next())
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let c = CancellationToken::new();
|
||||
for stmt in [
|
||||
"DROP DATABASE IF EXISTS oi_dump_src",
|
||||
"DROP DATABASE IF EXISTS oi_dump_dst",
|
||||
"CREATE DATABASE oi_dump_src",
|
||||
"CREATE DATABASE oi_dump_dst",
|
||||
"CREATE TABLE oi_dump_src.items (id INT PRIMARY KEY, tag VARCHAR(20))",
|
||||
"INSERT INTO oi_dump_src.items VALUES (1, 'dumped')",
|
||||
] {
|
||||
db.execute("m", stmt, 1, &c).await?;
|
||||
}
|
||||
let file = tmp.path().join("src.sql").to_string_lossy().into_owned();
|
||||
let run = |executable: String, job: DbToolJob| {
|
||||
let db = &db;
|
||||
async move {
|
||||
let mut lines = Vec::new();
|
||||
let code =
|
||||
db.run_tool("m", executable.as_ref(), &job, &CancellationToken::new(), |b| lines.extend(b)).await?;
|
||||
assert_eq!(code, Some(0), "{} failed: {lines:?}", job.tool().program());
|
||||
IdeResult::Ok(())
|
||||
}
|
||||
};
|
||||
let masking = ide_db::tools::options_of(dump.path.as_ref())?.iter().any(|o| o == "masking-policies");
|
||||
let options = DbMysqldumpOptions {
|
||||
databases: vec!["oi_dump_src".into()],
|
||||
tables: vec![],
|
||||
add_drop_table: true,
|
||||
disable_keys: true,
|
||||
add_locks: true,
|
||||
add_drop_trigger: false,
|
||||
no_data: false,
|
||||
complete_insert: false,
|
||||
create_options: true,
|
||||
routines: false,
|
||||
events: false,
|
||||
single_transaction: true,
|
||||
lock_all_tables: false,
|
||||
masking_policies: masking.then_some(false),
|
||||
};
|
||||
run(dump.path.clone(), DbToolJob::Mysqldump { file: file.clone(), options: options.clone() }).await?;
|
||||
assert!(!ide_db::tools::dump_info(file.as_ref())?.creates_database, "one database: restored into a chosen one");
|
||||
let both = tmp.path().join("both.sql").to_string_lossy().into_owned();
|
||||
let two = DbMysqldumpOptions { databases: vec!["oi_dump_src".into(), "oi_dump_dst".into()], ..options };
|
||||
run(dump.path, DbToolJob::Mysqldump { file: both.clone(), options: two }).await?;
|
||||
assert!(ide_db::tools::dump_info(both.as_ref())?.creates_database, "several databases: created by the dump");
|
||||
let restore = DbMysqlOptions { database: "oi_dump_dst".into(), force: false };
|
||||
run(client.path, DbToolJob::Mysql { file, options: restore }).await?;
|
||||
|
||||
let r = db.execute("m", "SELECT tag FROM oi_dump_dst.items", 1, &c).await?;
|
||||
assert_eq!(r.rows[0][0].as_deref(), Some("dumped"));
|
||||
for stmt in ["DROP DATABASE oi_dump_src", "DROP DATABASE oi_dump_dst"] {
|
||||
db.execute("m", stmt, 1, &c).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -282,6 +282,7 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> {
|
||||
let restore = DbPgRestoreOptions {
|
||||
content: DbDumpContent::All,
|
||||
schemas: vec![],
|
||||
create: false,
|
||||
clean: false,
|
||||
if_exists: false,
|
||||
no_owner: false,
|
||||
|
||||
@@ -40,6 +40,7 @@ fn tools() -> Vec<tool::Tool> {
|
||||
tools.push(check::check_files());
|
||||
tools.push(symbols::get_symbol_info());
|
||||
tools.push(symbols::find_references());
|
||||
tools.push(symbols::get_call_hierarchy());
|
||||
tools.extend(edit::tools());
|
||||
tools.extend(run::tools());
|
||||
tools.extend(vcs::tools());
|
||||
|
||||
@@ -280,7 +280,7 @@ fn context(call: &Call) -> IdeResult<(u32, u32)> {
|
||||
|
||||
/// `line`, or when longer than [`MAX_LINE_TEXT`] UTF-16 units, the part from [`SNIPPET_AROUND`]
|
||||
/// units before 0-based UTF-16 column `start` to as many after `end`, with `…` where it was cut.
|
||||
fn snippet(line: &str, start: usize, end: usize) -> String {
|
||||
pub(super) fn snippet(line: &str, start: usize, end: usize) -> String {
|
||||
let units: usize = line.chars().map(char::len_utf16).sum();
|
||||
if units <= MAX_LINE_TEXT {
|
||||
return line.to_owned();
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
//! Quick Documentation through the project's language services.
|
||||
use super::tool::{Call, Output, Param, ParamType, Tool};
|
||||
use ide_core::{IdeError, IdeResult, Pos, Range};
|
||||
use ide_lsp::types::GotoKind;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{DocId, IdeError, IdeResult, OutlineItem, Pos, Range, RequestId, SymbolKind};
|
||||
use ide_lsp::types::{CallHierarchy, GotoKind, HierarchyDirection, HierarchyItem, ReferencesIncomplete};
|
||||
use serde::Serialize;
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
pub fn get_symbol_info() -> Tool {
|
||||
Tool::new("get_symbol_info", "Retrieves information about the symbol at the specified position in the specified file.
|
||||
@@ -212,26 +215,10 @@ pub fn find_references() -> Tool {
|
||||
let path = call.resolve_readable(&call.str("filePath")?).await?;
|
||||
let page = super::page::Page::of(&call, REFERENCES_LIMIT)?;
|
||||
let dir = super::scope::Scope::of(&call)?;
|
||||
let line = call.opt_i64("line")?.ok_or_else(|| IdeError::invalid("missing line"))?;
|
||||
let column = call.opt_i64("column")?.ok_or_else(|| IdeError::invalid("missing column"))?;
|
||||
let project = call.project.clone();
|
||||
let (doc, text) = call.host.blocking(move || {
|
||||
let text = project.text_of(&path)?;
|
||||
let doc = project.documents.open(&path)?;
|
||||
Ok((doc.id, text))
|
||||
}).await?;
|
||||
struct Close(std::sync::Arc<crate::Project>, ide_core::DocId);
|
||||
impl Drop for Close { fn drop(&mut self) { self.0.documents.close(self.1); } }
|
||||
let _close = Close(call.project.clone(), doc);
|
||||
let pos = mcp_position(&text, line, column)?;
|
||||
let opened = open_at(&call, path).await?;
|
||||
let request = super::tool::request_id();
|
||||
let work = crate::ops::lsp::lsp_references(&call.host, &call.window, request, doc, pos, call.flag("includeDeclaration", true)?, true, false, crate::ops::Channel::new(|_| {}));
|
||||
tokio::pin!(work);
|
||||
let result = tokio::select! {
|
||||
result = &mut work => result?,
|
||||
_ = call.cancel.cancelled() => { call.host.cancel_request(request); let _ = work.await; return Err(IdeError::cancelled()); }
|
||||
_ = tokio::time::sleep(std::time::Duration::from_secs(60)) => { call.host.cancel_request(request); let _ = work.await; return Err(IdeError::unavailable("references timed out; retry when analysis finishes")); }
|
||||
};
|
||||
let work = crate::ops::lsp::lsp_references(&call.host, &call.window, request, opened.doc, opened.pos, call.flag("includeDeclaration", true)?, true, false, crate::ops::Channel::new(|_| {}));
|
||||
let result = race(&call, request, work, "references timed out; retry when analysis finishes").await?;
|
||||
let mut value = serde_json::to_value(&result).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
// Convert every Location range at this boundary, including declarations.
|
||||
fn positions(value: &mut serde_json::Value) {
|
||||
@@ -274,6 +261,266 @@ pub fn find_references() -> Tool {
|
||||
/// References `find_references` lists by default.
|
||||
const REFERENCES_LIMIT: usize = 100;
|
||||
|
||||
/// A document a tool opened for the language services and the position it asked about;
|
||||
/// dropping it closes the document.
|
||||
#[must_use]
|
||||
struct Opened {
|
||||
project: Arc<crate::Project>,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
}
|
||||
|
||||
impl Drop for Opened {
|
||||
fn drop(&mut self) {
|
||||
self.project.documents.close(self.doc);
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens `path` at the call's 1-based `line` and `column`.
|
||||
async fn open_at(call: &Call, path: PathBuf) -> IdeResult<Opened> {
|
||||
let line = call.opt_i64("line")?.ok_or_else(|| IdeError::invalid("missing line"))?;
|
||||
let column = call.opt_i64("column")?.ok_or_else(|| IdeError::invalid("missing column"))?;
|
||||
let project = call.project.clone();
|
||||
let (doc, text) = call
|
||||
.host
|
||||
.blocking(move || {
|
||||
let text = project.text_of(&path)?;
|
||||
let doc = project.documents.open(&path)?;
|
||||
Ok((doc.id, text))
|
||||
})
|
||||
.await?;
|
||||
let mut opened = Opened { project: call.project.clone(), doc, pos: Pos::default() };
|
||||
opened.pos = mcp_position(&text, line, column)?;
|
||||
Ok(opened)
|
||||
}
|
||||
|
||||
/// How long a tool waits for a language service request.
|
||||
const LANGUAGE_SERVICE_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// `work`, the language service `request`, until it ends; when the client cancels or
|
||||
/// [`LANGUAGE_SERVICE_TIMEOUT`] passes first, the request is cancelled and `work` runs to its end.
|
||||
async fn race<T>(
|
||||
call: &Call,
|
||||
request: RequestId,
|
||||
work: impl Future<Output = IdeResult<T>>,
|
||||
timed_out: &'static str,
|
||||
) -> IdeResult<T> {
|
||||
tokio::pin!(work);
|
||||
tokio::select! {
|
||||
result = &mut work => result,
|
||||
_ = call.cancel.cancelled() => {
|
||||
call.host.cancel_request(request);
|
||||
let _ = work.await;
|
||||
Err(IdeError::cancelled())
|
||||
}
|
||||
_ = tokio::time::sleep(LANGUAGE_SERVICE_TIMEOUT) => {
|
||||
call.host.cancel_request(request);
|
||||
let _ = work.await;
|
||||
Err(IdeError::unavailable(timed_out))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_call_hierarchy() -> Tool {
|
||||
Tool::new(
|
||||
"get_call_hierarchy",
|
||||
"Callers (incoming) or callees (outgoing) of the function or method at the position, from \
|
||||
the language server's call hierarchy. A position inside a function body means that function. \
|
||||
One level per call: to go deeper, call again with an item's filePath, startLine and startColumn \
|
||||
(items in libraries show a URI as filePath and cannot be expanded). \
|
||||
Positions are 1-based UTF-16. `root` is the symbol the hierarchy is for; each item's callSites \
|
||||
are where the call happens. Reports incomplete results when analysis is still running.",
|
||||
call_hierarchy,
|
||||
)
|
||||
.param(Param::required("filePath", ParamType::String, "Path relative to the project root"))
|
||||
.param(Param::required("line", ParamType::Integer, "1-based line"))
|
||||
.param(Param::required("column", ParamType::Integer, "1-based UTF-16 column"))
|
||||
.param(Param::optional("direction", ParamType::String, "incoming (callers, default) or outgoing (callees)"))
|
||||
.param(super::scope::param())
|
||||
.param(Param::optional("limit", ParamType::Integer, "Items to return at most (default 100)"))
|
||||
.param(Param::optional("offset", ParamType::Integer, super::page::OFFSET))
|
||||
}
|
||||
|
||||
/// Items `get_call_hierarchy` lists by default.
|
||||
const CALLS_LIMIT: usize = 100;
|
||||
/// Call sites shown per item; `callSiteCount` gives the total when there are more.
|
||||
const MAX_CALL_SITES: usize = 20;
|
||||
const CALLS_TIMED_OUT: &str = "call hierarchy timed out; retry when analysis finishes";
|
||||
|
||||
async fn call_hierarchy(call: Call) -> IdeResult<Output> {
|
||||
let direction = match call.opt_str("direction")?.as_deref() {
|
||||
None | Some("incoming") => HierarchyDirection::Incoming,
|
||||
Some("outgoing") => HierarchyDirection::Outgoing,
|
||||
Some(_) => return Err(IdeError::invalid("direction must be incoming or outgoing")),
|
||||
};
|
||||
let page = super::page::Page::of(&call, CALLS_LIMIT)?;
|
||||
let scope = super::scope::Scope::of(&call)?;
|
||||
let path = call.resolve_readable(&call.str("filePath")?).await?;
|
||||
let opened = open_at(&call, path).await?;
|
||||
let hierarchy_at = |pos| {
|
||||
let request = super::tool::request_id();
|
||||
let work = crate::ops::lsp::lsp_call_hierarchy(&call.host, &call.window, request, opened.doc, pos, direction);
|
||||
race(&call, request, work, CALLS_TIMED_OUT)
|
||||
};
|
||||
let mut found = match hierarchy_at(opened.pos).await {
|
||||
// IDEA: inside a function body the hierarchy is the enclosing function's.
|
||||
Err(e) if e.kind == ErrorKind::NotFound => {
|
||||
let outline = tokio::select! {
|
||||
outline = crate::ops::doc::doc_outline(&call.host, &call.window, opened.doc) => outline?,
|
||||
_ = call.cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
};
|
||||
let at = enclosing_callable(&outline, opened.pos).map(|f| f.selection_range.start);
|
||||
let Some(at) = at.filter(|at| *at != opened.pos) else {
|
||||
let Pos { line, col } = opened.pos;
|
||||
return Err(IdeError::not_found(format!("no function or method at {}:{}", line + 1, col + 1)));
|
||||
};
|
||||
hierarchy_at(at).await?
|
||||
}
|
||||
result => result?,
|
||||
};
|
||||
if scope.dir().is_some() {
|
||||
found.items.retain(|i| i.uri.is_none() && scope.contains(&i.path.0));
|
||||
}
|
||||
let incomplete = found.incomplete;
|
||||
let (mut root, items) = call_items(found, |p| call.display(p));
|
||||
let mut out = serde_json::Map::new();
|
||||
let mut items = page.take(items, &mut out);
|
||||
// One file in memory at a time, as `search::fill_lines` reads them.
|
||||
let mut places: Vec<&mut Place> = root
|
||||
.iter_mut()
|
||||
.chain(&mut items)
|
||||
.flat_map(|i| std::iter::once(&mut i.at).chain(&mut i.call_sites))
|
||||
.filter(|place| place.file.is_some())
|
||||
.collect();
|
||||
places.sort_by(|a, b| a.file.cmp(&b.file));
|
||||
for in_file in places.chunk_by_mut(|a, b| a.file == b.file) {
|
||||
if call.cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let Some(path) = in_file[0].file.clone() else { continue };
|
||||
if let Ok(text) = crate::ops::fs::fs_read_text(&call.host, call.window(), path).await {
|
||||
fill_line_texts(in_file, &text);
|
||||
}
|
||||
}
|
||||
Output::json(CallHierarchyOutput { root, items, page: out, incomplete })
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct CallHierarchyOutput {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
root: Option<CallItem>,
|
||||
items: Vec<CallItem>,
|
||||
/// `total`, and `more` and `nextOffset` when items follow.
|
||||
#[serde(flatten)]
|
||||
page: serde_json::Map<String, serde_json::Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
incomplete: Option<ReferencesIncomplete>,
|
||||
}
|
||||
|
||||
/// A function or method in the call hierarchy, at its name.
|
||||
#[derive(Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct CallItem {
|
||||
name: String,
|
||||
kind: SymbolKind,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
detail: Option<String>,
|
||||
#[serde(flatten)]
|
||||
at: Place,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
call_sites: Vec<Place>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
call_site_count: Option<usize>,
|
||||
}
|
||||
|
||||
/// A range as the tools show it: 1-based UTF-16, with the text of its first line.
|
||||
#[derive(Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Place {
|
||||
file_path: String,
|
||||
start_line: u32,
|
||||
start_column: u32,
|
||||
end_line: u32,
|
||||
end_column: u32,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
line_text: Option<String>,
|
||||
/// The file `line_text` is read from; none in a library.
|
||||
#[serde(skip)]
|
||||
file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// The root and the items of `h`, sorted by file and position, with call sites in source
|
||||
/// order, at most [`MAX_CALL_SITES`] per item. Library items show their URI.
|
||||
fn call_items(h: CallHierarchy, display: impl Fn(&Path) -> String) -> (Option<CallItem>, Vec<CallItem>) {
|
||||
let CallHierarchy { root, items, .. } = h;
|
||||
// A file path, or the URI of a virtual document, which has no lines to read here.
|
||||
let target = |path: &Path, uri: Option<&String>| match uri {
|
||||
Some(uri) => (None, uri.clone()),
|
||||
None => (Some(path.to_path_buf()), display(path)),
|
||||
};
|
||||
let place = |(file, file_path): (Option<PathBuf>, String), r: Range| Place {
|
||||
file_path,
|
||||
start_line: r.start.line + 1,
|
||||
start_column: r.start.col + 1,
|
||||
end_line: r.end.line + 1,
|
||||
end_column: r.end.col + 1,
|
||||
line_text: None,
|
||||
file,
|
||||
};
|
||||
let convert = |i: HierarchyItem| {
|
||||
let at = target(&i.path.0, i.uri.as_ref());
|
||||
let sites_in = match &i.from_path {
|
||||
Some(p) => {
|
||||
let shown = p.0.to_string_lossy();
|
||||
target(&p.0, ide_core::is_virtual_uri(&shown).then(|| shown.into_owned()).as_ref())
|
||||
}
|
||||
None => at.clone(),
|
||||
};
|
||||
let mut sites = i.from_ranges;
|
||||
sites.sort();
|
||||
sites.dedup();
|
||||
let count = sites.len();
|
||||
CallItem {
|
||||
call_sites: sites.into_iter().take(MAX_CALL_SITES).map(|r| place(sites_in.clone(), r)).collect(),
|
||||
call_site_count: (count > MAX_CALL_SITES).then_some(count),
|
||||
at: place(at, i.selection_range),
|
||||
name: i.name,
|
||||
kind: i.kind,
|
||||
detail: i.detail,
|
||||
}
|
||||
};
|
||||
let mut items: Vec<CallItem> = items.into_iter().map(&convert).collect();
|
||||
items.sort_by(|a, b| {
|
||||
(&a.at.file_path, a.at.start_line, a.at.start_column).cmp(&(
|
||||
&b.at.file_path,
|
||||
b.at.start_line,
|
||||
b.at.start_column,
|
||||
))
|
||||
});
|
||||
(root.map(convert), items)
|
||||
}
|
||||
|
||||
/// Fills `lineText` of `places`, which are all in the file whose text is `text`.
|
||||
fn fill_line_texts(places: &mut [&mut Place], text: &str) {
|
||||
let lines: Vec<&str> = text.split('\n').collect();
|
||||
for place in places {
|
||||
let Some(line) = lines.get(place.start_line as usize - 1) else { continue };
|
||||
let line = line.strip_suffix('\r').unwrap_or(line);
|
||||
let start = place.start_column as usize - 1;
|
||||
let end = if place.end_line == place.start_line { place.end_column as usize - 1 } else { start };
|
||||
place.line_text = Some(super::search::snippet(line, start, end));
|
||||
}
|
||||
}
|
||||
|
||||
/// The innermost function, method or constructor of `outline` whose extent holds `pos`,
|
||||
/// as the IDE's Call Hierarchy finds it.
|
||||
fn enclosing_callable(outline: &[OutlineItem], pos: Pos) -> Option<&OutlineItem> {
|
||||
let item = outline.iter().find(|i| i.range.start <= pos && pos <= i.range.end)?;
|
||||
enclosing_callable(&item.children, pos).or_else(|| {
|
||||
matches!(item.kind, SymbolKind::Function | SymbolKind::Method | SymbolKind::Constructor).then_some(item)
|
||||
})
|
||||
}
|
||||
|
||||
fn mcp_position(text: &str, line: i64, column: i64) -> IdeResult<Pos> {
|
||||
if line < 1 || line > u32::MAX as i64 || column < 1 || column > u32::MAX as i64 {
|
||||
return Err(IdeError::invalid("line and column must be positive 1-based positions"));
|
||||
@@ -284,3 +531,156 @@ fn mcp_position(text: &str, line: i64, column: i64) -> IdeResult<Pos> {
|
||||
}
|
||||
Ok(Pos::new((line - 1) as u32, (column - 1) as u32))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn range(line: u32, col: u32, end_line: u32, end_col: u32) -> Range {
|
||||
Range::new(Pos::new(line, col), Pos::new(end_line, end_col))
|
||||
}
|
||||
|
||||
fn item(name: &str, path: &str, line: u32, from_ranges: Vec<Range>) -> HierarchyItem {
|
||||
HierarchyItem {
|
||||
name: name.into(),
|
||||
kind: SymbolKind::Function,
|
||||
detail: Some(format!("fn {name}()")),
|
||||
path: PathBuf::from(path).into(),
|
||||
uri: None,
|
||||
range: range(line, 0, line + 2, 1),
|
||||
selection_range: range(line, 3, line, 3 + name.len() as u32),
|
||||
from_ranges,
|
||||
from_path: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn shown(path: &Path) -> String {
|
||||
path.strip_prefix("/p").unwrap_or(path).to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn hierarchy(root: HierarchyItem, items: Vec<HierarchyItem>) -> CallHierarchy {
|
||||
CallHierarchy { root: Some(root), items, incomplete: None }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incoming_call_sites_are_in_the_callers_file_one_based() {
|
||||
let h = hierarchy(
|
||||
item("price", "/p/src/lib.rs", 10, Vec::new()),
|
||||
vec![item("main", "/p/src/main.rs", 2, vec![range(4, 8, 4, 13)])],
|
||||
);
|
||||
let (root, items) = call_items(h, shown);
|
||||
let root = serde_json::to_value(root.unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
root,
|
||||
json!({"name":"price","kind":"function","detail":"fn price()","filePath":"src/lib.rs",
|
||||
"startLine":11,"startColumn":4,"endLine":11,"endColumn":9})
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(&items).unwrap(),
|
||||
json!([{"name":"main","kind":"function","detail":"fn main()","filePath":"src/main.rs",
|
||||
"startLine":3,"startColumn":4,"endLine":3,"endColumn":8,
|
||||
"callSites":[{"filePath":"src/main.rs","startLine":5,"startColumn":9,"endLine":5,"endColumn":14}]}])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outgoing_call_sites_are_in_the_file_ide_lsp_names() {
|
||||
let mut price = item("price", "/p/src/lib.rs", 10, vec![range(4, 8, 4, 13)]);
|
||||
price.from_path = Some(PathBuf::from("/p/src/main.rs").into());
|
||||
let (_, items) = call_items(hierarchy(item("main", "/p/src/main.rs", 2, Vec::new()), vec![price]), shown);
|
||||
assert_eq!(items[0].at.file_path, "src/lib.rs");
|
||||
assert_eq!(items[0].call_sites[0].file_path, "src/main.rs");
|
||||
assert_eq!(items[0].call_sites[0].file.as_deref(), Some(Path::new("/p/src/main.rs")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_items_show_their_uri() {
|
||||
let mut library = item("len", "/virtual", 0, vec![range(4, 8, 4, 11)]);
|
||||
library.uri = Some("jar:file:///lib.jar!/Str.class".into());
|
||||
library.from_path = Some(PathBuf::from("/p/src/main.rs").into());
|
||||
let mut called_from_library = item("parse", "/p/src/a.rs", 3, vec![range(1, 0, 1, 4)]);
|
||||
called_from_library.from_path = Some(PathBuf::from("jdt://contents/lib.jar/Caller.class").into());
|
||||
let h = hierarchy(item("main", "/p/src/main.rs", 2, Vec::new()), vec![library, called_from_library]);
|
||||
let (_, items) = call_items(h, shown);
|
||||
assert_eq!(items[0].at.file_path, "jar:file:///lib.jar!/Str.class");
|
||||
assert_eq!(items[0].at.file, None, "no line text for a library item");
|
||||
assert_eq!(items[0].call_sites[0].file_path, "src/main.rs");
|
||||
assert_eq!(items[1].call_sites[0].file_path, "jdt://contents/lib.jar/Caller.class");
|
||||
assert_eq!(items[1].call_sites[0].file, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_items_are_sorted_by_file_and_line() {
|
||||
let h = hierarchy(
|
||||
item("price", "/p/src/lib.rs", 10, Vec::new()),
|
||||
vec![
|
||||
item("c", "/p/src/main.rs", 9, Vec::new()),
|
||||
item("b", "/p/src/main.rs", 2, Vec::new()),
|
||||
item("a", "/p/src/a.rs", 5, Vec::new()),
|
||||
],
|
||||
);
|
||||
let (_, items) = call_items(h, shown);
|
||||
assert_eq!(items.iter().map(|i| i.name.as_str()).collect::<Vec<_>>(), ["a", "b", "c"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_sites_are_capped_with_their_count() {
|
||||
let sites = (0..MAX_CALL_SITES as u32 + 5).map(|l| range(l, 0, l, 1)).collect();
|
||||
let h = hierarchy(item("price", "/p/src/lib.rs", 10, Vec::new()), vec![item("main", "/p/a.rs", 0, sites)]);
|
||||
let (_, items) = call_items(h, shown);
|
||||
assert_eq!(items[0].call_sites.len(), MAX_CALL_SITES);
|
||||
assert_eq!(items[0].call_site_count, Some(MAX_CALL_SITES + 5));
|
||||
let one = hierarchy(
|
||||
item("price", "/p/src/lib.rs", 10, Vec::new()),
|
||||
vec![item("main", "/p/a.rs", 0, vec![range(1, 0, 1, 1)])],
|
||||
);
|
||||
assert_eq!(call_items(one, shown).1[0].call_site_count, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_sites_are_in_source_order_without_duplicates() {
|
||||
let sites = vec![range(5, 0, 5, 1), range(1, 4, 1, 5), range(5, 0, 5, 1), range(1, 2, 1, 3)];
|
||||
let h = hierarchy(item("price", "/p/src/lib.rs", 10, Vec::new()), vec![item("main", "/p/a.rs", 0, sites)]);
|
||||
let (_, items) = call_items(h, shown);
|
||||
let at: Vec<_> = items[0].call_sites.iter().map(|s| (s.start_line, s.start_column)).collect();
|
||||
assert_eq!(at, [(2, 3), (2, 5), (6, 1)]);
|
||||
assert_eq!(items[0].call_site_count, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_text_is_cut_from_the_line_of_each_place() {
|
||||
let h = hierarchy(item("price", "/p/src/lib.rs", 3, vec![range(0, 4, 0, 9), range(1, 0, 3, 1)]), Vec::new());
|
||||
let mut root = call_items(h, shown).0.unwrap();
|
||||
let mut places: Vec<&mut Place> = std::iter::once(&mut root.at).chain(&mut root.call_sites).collect();
|
||||
fill_line_texts(&mut places, " price();\r\nfn other() {\n\nfn price() {}");
|
||||
assert_eq!(root.at.line_text.as_deref(), Some("fn price() {}"));
|
||||
assert_eq!(root.call_sites[0].line_text.as_deref(), Some(" price();"));
|
||||
assert_eq!(root.call_sites[1].line_text.as_deref(), Some("fn other() {"), "a range over lines");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enclosing_callable_is_the_innermost_function() {
|
||||
let outline = |name: &str, kind, range, children| OutlineItem {
|
||||
name: name.into(),
|
||||
detail: None,
|
||||
kind,
|
||||
range,
|
||||
selection_range: Range::new(range.start, range.start),
|
||||
children,
|
||||
visibility: None,
|
||||
};
|
||||
let method = outline(
|
||||
"total",
|
||||
SymbolKind::Method,
|
||||
range(2, 4, 8, 5),
|
||||
vec![outline("add", SymbolKind::Function, range(3, 8, 5, 9), Vec::new())],
|
||||
);
|
||||
let items = vec![outline("Cart", SymbolKind::Struct, range(0, 0, 9, 1), vec![method])];
|
||||
let name = |pos| enclosing_callable(&items, pos).map(|i| i.name.as_str());
|
||||
assert_eq!(name(Pos::new(4, 0)), Some("add"));
|
||||
assert_eq!(name(Pos::new(5, 9)), Some("add"), "the end is inside");
|
||||
assert_eq!(name(Pos::new(7, 0)), Some("total"));
|
||||
assert_eq!(name(Pos::new(0, 3)), None, "a struct is not callable");
|
||||
assert_eq!(name(Pos::new(12, 0)), None);
|
||||
}
|
||||
}
|
||||
@@ -268,6 +268,19 @@ pub async fn agent_prompt(host: &Host, window: &str, task: String, prompt: Agent
|
||||
host.project(window)?.agents.prompt(&task, prompt, now).await
|
||||
}
|
||||
|
||||
/// Answers a non-blocking question, without cancelling the current turn.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_answer_question(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
task: String,
|
||||
question: String,
|
||||
answer: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.answer_question(&task, &question, answer).await
|
||||
}
|
||||
|
||||
/// Drops a queued message and returns it (to edit it).
|
||||
#[command(trust = always)]
|
||||
pub fn agent_unqueue(host: &Host, window: &str, task: String, queued: String) -> IdeResult<AgentQueued> {
|
||||
@@ -1015,6 +1028,7 @@ mod tests {
|
||||
ide_command::domain!(
|
||||
agent:
|
||||
agent_accept_changes,
|
||||
agent_answer_question,
|
||||
agent_archive,
|
||||
agent_base_text,
|
||||
agent_cancel,
|
||||
|
||||
@@ -5,7 +5,7 @@ use ide_extension::Capability;
|
||||
use ide_plugin::{EventKind, HostError, WorkbenchEvent};
|
||||
use std::{
|
||||
collections::{BTreeSet, HashMap},
|
||||
path::Path,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
@@ -136,32 +136,14 @@ impl PluginHost {
|
||||
if !path.is_absolute() {
|
||||
return None;
|
||||
}
|
||||
let workspace = workspace.as_ref()?;
|
||||
let real = ide_plugin::resolve_real(path);
|
||||
// The file's own project, not the invoking window's: annotations follow
|
||||
// the file, so a plugin hears about a file another window has open.
|
||||
let root = match client {
|
||||
Some(client) => workspace
|
||||
.project_of(client)
|
||||
.filter(|r| real.starts_with(ide_plugin::resolve_real(r)))
|
||||
.or_else(|| {
|
||||
workspace
|
||||
.projects()
|
||||
.into_iter()
|
||||
.filter(|r| real.starts_with(ide_plugin::resolve_real(r)))
|
||||
.max_by_key(|r| r.components().count())
|
||||
}),
|
||||
None => workspace
|
||||
.projects()
|
||||
.into_iter()
|
||||
.filter(|r| real.starts_with(ide_plugin::resolve_real(r)))
|
||||
.max_by_key(|r| r.components().count()),
|
||||
}?;
|
||||
let root = file_project(workspace.as_deref()?, client, path)?;
|
||||
if plugin.dev_root.as_deref().is_some_and(|r| r != root) {
|
||||
return None;
|
||||
}
|
||||
if let WorkbenchEvent::DocumentChanged(change) = event {
|
||||
if let WorkbenchEvent::DocumentChanged(_) = event {
|
||||
// Typed text: only for plugins that may read editors, and only for paths they named.
|
||||
// The path stays absolute until delivery (`relativize_documents`): the batch is
|
||||
// filtered again then, against the grants and subscriptions of that moment.
|
||||
let filter = filters.and_then(|filters| filters.get(event.kind().name()))?;
|
||||
let granted = &plugin.meta.lock().granted;
|
||||
if !granted.contains(&Capability::ProjectRead)
|
||||
@@ -170,11 +152,7 @@ impl PluginHost {
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let real = ide_plugin::resolve_real(path);
|
||||
let relative = real.strip_prefix(ide_plugin::resolve_real(&root)).ok()?;
|
||||
let mut change = change.clone();
|
||||
change.path = relative.to_string_lossy().replace('\\', "/");
|
||||
return Some(WorkbenchEvent::DocumentChanged(change));
|
||||
return Some(event.clone());
|
||||
}
|
||||
filters
|
||||
.and_then(|filters| filters.get(event.kind().name()))
|
||||
@@ -183,6 +161,41 @@ impl PluginHost {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What a plugin receives for `document-changed`: the path relative to the file's own project.
|
||||
pub(super) fn relativize_documents(
|
||||
shared: &super::api::Shared,
|
||||
client: Option<&str>,
|
||||
events: Vec<WorkbenchEvent>,
|
||||
) -> Vec<WorkbenchEvent> {
|
||||
let workspace = shared.workspace();
|
||||
events
|
||||
.into_iter()
|
||||
.filter_map(|event| {
|
||||
let WorkbenchEvent::DocumentChanged(mut change) = event else { return Some(event) };
|
||||
let path = Path::new(&change.path);
|
||||
let root = file_project(workspace.as_deref()?, client, path)?;
|
||||
let relative = ide_plugin::resolve_real(path)
|
||||
.strip_prefix(ide_plugin::resolve_real(&root))
|
||||
.ok()?
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
change.path = relative;
|
||||
Some(WorkbenchEvent::DocumentChanged(change))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The open project an absolute `path` belongs to: the invoking window's when the file is in
|
||||
/// it, else the innermost open project containing it. Annotations follow the file, so a
|
||||
/// plugin hears about a file another window has open.
|
||||
fn file_project(workspace: &dyn super::api::PluginWorkspace, client: Option<&str>, path: &Path) -> Option<PathBuf> {
|
||||
let real = ide_plugin::resolve_real(path);
|
||||
let contains = |r: &PathBuf| real.starts_with(ide_plugin::resolve_real(r));
|
||||
client
|
||||
.and_then(|client| workspace.project_of(client).filter(contains))
|
||||
.or_else(|| workspace.projects().into_iter().filter(contains).max_by_key(|r| r.components().count()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -2214,6 +2214,7 @@ impl PluginHost {
|
||||
if events.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let events = Self::relativize_documents(&shared, invocation.client.as_deref(), events);
|
||||
rt.handle_events(events, invocation)
|
||||
},
|
||||
move |result| {
|
||||
|
||||
@@ -662,6 +662,34 @@ async fn rust_references_and_rename_through_mcp() {
|
||||
assert!(std::time::Instant::now() < deadline, "language server did not find format_price references");
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
}
|
||||
// Its callers, the callees of one of them, and the hierarchy at a call.
|
||||
let callers = h.json("get_call_hierarchy", args.clone()).await;
|
||||
assert_eq!(callers["root"]["name"], "format_price", "{callers}");
|
||||
let main = callers["items"].as_array().unwrap().iter().find(|i| i["name"] == "main").expect("main calls it");
|
||||
assert_eq!(main["filePath"], "src/main.rs");
|
||||
let call = main["callSites"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|s| s["lineText"].as_str().unwrap().contains("format_price("))
|
||||
.expect("the call in main");
|
||||
assert_eq!(call["filePath"], "src/main.rs");
|
||||
let callees = h
|
||||
.json("get_call_hierarchy", json!({"filePath":"src/main.rs", "line":main["startLine"], "column":main["startColumn"], "direction":"outgoing"}))
|
||||
.await;
|
||||
// rust-analyzer leaves out the calls inside macro arguments, such as `format_price` in `println!`.
|
||||
let parse = callees["items"].as_array().unwrap().iter().find(|i| i["name"] == "parse").expect("main calls parse");
|
||||
assert_eq!(
|
||||
(&parse["filePath"], &parse["callSites"][0]["filePath"]),
|
||||
(&json!("src/parser.rs"), &json!("src/main.rs"))
|
||||
);
|
||||
let at_call = h
|
||||
.json("get_call_hierarchy", json!({"filePath":"src/main.rs", "line":call["startLine"], "column":call["startColumn"], "direction":"outgoing"}))
|
||||
.await;
|
||||
assert_eq!(
|
||||
(&at_call["root"]["name"], &at_call["root"]["filePath"]),
|
||||
(&json!("format_price"), &json!("src/lib.rs"))
|
||||
);
|
||||
let result = h.json("rename_refactoring", json!({"pathInProject":"src/lib.rs", "symbolName":"format_price", "newName":"format_amount", "line":line + 1, "column":column})).await;
|
||||
assert_eq!(result["applied"], true, "{result}");
|
||||
assert!(project.documents.text_snapshot(doc.id).unwrap().text.contains("format_amount"));
|
||||
@@ -979,3 +1007,218 @@ async fn http_list_and_run_require_confirmation() {
|
||||
assert!(result.get("headers").is_none(), "{result}");
|
||||
assert!(result.get("request").is_none(), "{result}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn call_hierarchy_is_listed_for_untrusted_projects() {
|
||||
let h = Harness::new();
|
||||
let tools = Registry::new(h.host.clone()).tools(&h.root).unwrap();
|
||||
assert!(tools.iter().any(|t| t.name == "get_call_hierarchy"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn call_hierarchy_without_a_language_server_says_it_is_unsupported() {
|
||||
let h = Harness::new();
|
||||
let error = h.error("get_call_hierarchy", json!({"filePath":"src/a.txt","line":1,"column":1})).await;
|
||||
assert!(error.contains("call hierarchy"), "{error}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn call_hierarchy_rejects_an_unknown_direction() {
|
||||
let h = Harness::new();
|
||||
let args = json!({"filePath":"src/a.txt","line":1,"column":1,"direction":"up"});
|
||||
assert_eq!(h.error("get_call_hierarchy", args).await, "direction must be incoming or outgoing");
|
||||
}
|
||||
|
||||
/// `src/lib.rs`: `price` calls `double`; `src/main.rs`: `main` calls `price` and `show`;
|
||||
/// `other/c.rs`: `helper` calls `price`; a library class calls it too.
|
||||
const LIB_RS: &str = "pub fn price(cents: u64) -> u64 {\n double(cents)\n}\nfn double(v: u64) -> u64 { v * 2 }\n";
|
||||
const MAIN_RS: &str = "fn main() {\n let a = price(1);\n show(a);\n}\nfn show(v: u64) {}\n";
|
||||
const C_RS: &str = "fn helper() {\n price(2);\n}\n";
|
||||
const LIBRARY_URI: &str = "jar:file:///lib.jar!/Caller.class";
|
||||
|
||||
/// A language server for `rust` that knows the call hierarchy of the files above.
|
||||
struct CallServer {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
impl CallServer {
|
||||
fn uri(&self, path: &str) -> String {
|
||||
ide_lsp::path_to_uri_string(&self.root.join(path))
|
||||
}
|
||||
fn item(&self, name: &str) -> Value {
|
||||
let r = |l, c, l2, c2| json!({"start":{"line":l,"character":c},"end":{"line":l2,"character":c2}});
|
||||
let (uri, range, selection) = match name {
|
||||
"price" => (self.uri("src/lib.rs"), r(0, 0, 2, 1), r(0, 7, 0, 12)),
|
||||
"double" => (self.uri("src/lib.rs"), r(3, 0, 3, 34), r(3, 3, 3, 9)),
|
||||
"main" => (self.uri("src/main.rs"), r(0, 0, 3, 1), r(0, 3, 0, 7)),
|
||||
"show" => (self.uri("src/main.rs"), r(4, 0, 4, 18), r(4, 3, 4, 7)),
|
||||
"helper" => (self.uri("other/c.rs"), r(0, 0, 2, 1), r(0, 3, 0, 9)),
|
||||
_ => (LIBRARY_URI.to_owned(), r(0, 0, 9, 1), r(2, 4, 2, 10)),
|
||||
};
|
||||
json!({"name":name,"kind":12,"uri":uri,"range":range,"selectionRange":selection})
|
||||
}
|
||||
fn call(&self, name: &str, key: &str, sites: &[(u32, u32, u32)]) -> Value {
|
||||
let sites: Vec<Value> = sites
|
||||
.iter()
|
||||
.map(|(l, c, c2)| json!({"start":{"line":l,"character":c},"end":{"line":l,"character":c2}}))
|
||||
.collect();
|
||||
json!({key: self.item(name), "fromRanges": sites})
|
||||
}
|
||||
/// The item named at `p`: on a declaration's name or on a call.
|
||||
fn prepare(&self, p: &Value) -> Value {
|
||||
let uri = p["textDocument"]["uri"].as_str().unwrap();
|
||||
let (line, col) = (p["position"]["line"].as_u64().unwrap(), p["position"]["character"].as_u64().unwrap());
|
||||
let on =
|
||||
|path: &str, l: u64, from: u64, to: u64| uri == self.uri(path) && line == l && (from..=to).contains(&col);
|
||||
let name = if on("src/lib.rs", 0, 7, 12) || on("src/main.rs", 1, 12, 17) {
|
||||
"price"
|
||||
} else if on("src/main.rs", 0, 3, 7) {
|
||||
"main"
|
||||
} else {
|
||||
return Value::Null;
|
||||
};
|
||||
json!([self.item(name)])
|
||||
}
|
||||
}
|
||||
|
||||
impl ide_jsonrpc::Handler for CallServer {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
fn on_request(&self, method: &str, p: Value) -> Result<Value, (i64, String)> {
|
||||
let item = p["item"]["name"].as_str().unwrap_or_default();
|
||||
Ok(match method {
|
||||
"initialize" => json!({"capabilities": {
|
||||
"textDocumentSync": {"openClose": true, "change": 1},
|
||||
"callHierarchyProvider": true,
|
||||
"documentSymbolProvider": true,
|
||||
}}),
|
||||
"textDocument/prepareCallHierarchy" => self.prepare(&p),
|
||||
"callHierarchy/incomingCalls" if item == "price" => json!([
|
||||
self.call("main", "from", &[(1, 12, 17)]),
|
||||
self.call("helper", "from", &[(1, 4, 9)]),
|
||||
self.call("Caller", "from", &[(2, 8, 13)]),
|
||||
]),
|
||||
"callHierarchy/outgoingCalls" if item == "price" => json!([self.call("double", "to", &[(1, 4, 10)])]),
|
||||
"callHierarchy/outgoingCalls" if item == "main" => {
|
||||
json!([self.call("show", "to", &[(2, 4, 8)]), self.call("price", "to", &[(1, 12, 17)])])
|
||||
}
|
||||
"textDocument/documentSymbol" if p["textDocument"]["uri"] == self.uri("src/main.rs") => {
|
||||
let symbol = |name| {
|
||||
let item = self.item(name);
|
||||
json!({"name":name,"kind":12,"range":item["range"],"selectionRange":item["selectionRange"]})
|
||||
};
|
||||
json!([symbol("main"), symbol("show")])
|
||||
}
|
||||
"callHierarchy/incomingCalls" | "callHierarchy/outgoingCalls" | "textDocument/documentSymbol" => json!([]),
|
||||
_ => Value::Null,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The harness with the files above and [`CallServer`] serving them.
|
||||
async fn call_hierarchy_harness() -> (Harness, tokio::task::JoinHandle<()>) {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
for (path, text) in [("src/lib.rs", LIB_RS), ("src/main.rs", MAIN_RS), ("other/c.rs", C_RS)] {
|
||||
std::fs::create_dir_all(h.root.join(path).parent().unwrap()).unwrap();
|
||||
std::fs::write(h.root.join(path), text).unwrap();
|
||||
}
|
||||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = Arc::new(CallServer { root: h.root.clone() });
|
||||
let accept = tokio::spawn(async move {
|
||||
let mut peers = Vec::new();
|
||||
while let Ok((stream, _)) = listener.accept().await {
|
||||
let (r, w) = stream.into_split();
|
||||
peers.push(ide_jsonrpc::Peer::connect(r, w, server.clone()));
|
||||
}
|
||||
});
|
||||
let cfg: ide_language::LanguageServerConfig =
|
||||
toml::from_str(&format!("name='calls'\ncommand='no-process-required'\nconnect='127.0.0.1:{port}'")).unwrap();
|
||||
h.host.project("main").unwrap().lsp.set_servers_hook(Box::new(move |language, _| {
|
||||
if language.as_str() == "rust" { vec![cfg.clone()] } else { Vec::new() }
|
||||
}));
|
||||
(h, accept)
|
||||
}
|
||||
|
||||
fn names(result: &Value) -> Vec<&str> {
|
||||
result["items"].as_array().unwrap().iter().map(|i| i["name"].as_str().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn call_hierarchy_lists_callers_with_their_call_sites() {
|
||||
let (h, _server) = call_hierarchy_harness().await;
|
||||
let callers = h.json("get_call_hierarchy", json!({"filePath":"src/lib.rs","line":1,"column":9})).await;
|
||||
assert_eq!(callers["root"]["name"], "price");
|
||||
assert_eq!(callers["root"]["filePath"], "src/lib.rs");
|
||||
assert_eq!(callers["root"]["lineText"], "pub fn price(cents: u64) -> u64 {");
|
||||
assert_eq!(callers["total"], 3);
|
||||
let main = callers["items"].as_array().unwrap().iter().find(|i| i["name"] == "main").unwrap();
|
||||
assert_eq!(
|
||||
main,
|
||||
&json!({"name":"main","kind":"function","filePath":"src/main.rs",
|
||||
"startLine":1,"startColumn":4,"endLine":1,"endColumn":8,"lineText":"fn main() {",
|
||||
"callSites":[{"filePath":"src/main.rs","startLine":2,"startColumn":13,"endLine":2,"endColumn":18,
|
||||
"lineText":" let a = price(1);"}]})
|
||||
);
|
||||
// An item's position is a valid input for the next level.
|
||||
let main_calls = h
|
||||
.json(
|
||||
"get_call_hierarchy",
|
||||
json!({"filePath":"src/main.rs","line":main["startLine"],"column":main["startColumn"],"direction":"outgoing"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(names(&main_calls), ["price", "show"]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn outgoing_call_sites_are_in_the_file_of_the_root() {
|
||||
let (h, _server) = call_hierarchy_harness().await;
|
||||
// On the call `price(1)` in main.rs: the hierarchy of `price`, declared in lib.rs.
|
||||
let callees = h
|
||||
.json("get_call_hierarchy", json!({"filePath":"src/main.rs","line":2,"column":14,"direction":"outgoing"}))
|
||||
.await;
|
||||
assert_eq!(callees["root"]["filePath"], "src/lib.rs");
|
||||
assert_eq!(names(&callees), ["double"]);
|
||||
assert_eq!(
|
||||
callees["items"][0]["callSites"],
|
||||
json!([{"filePath":"src/lib.rs","startLine":2,"startColumn":5,"endLine":2,"endColumn":11,"lineText":" double(cents)"}])
|
||||
);
|
||||
let from_main = h
|
||||
.json("get_call_hierarchy", json!({"filePath":"src/main.rs","line":1,"column":4,"direction":"outgoing"}))
|
||||
.await;
|
||||
let price = &from_main["items"][0];
|
||||
assert_eq!((&price["filePath"], &price["callSites"][0]["filePath"]), (&json!("src/lib.rs"), &json!("src/main.rs")));
|
||||
assert_eq!(price["callSites"][0]["lineText"], " let a = price(1);");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_position_in_a_function_body_means_that_function() {
|
||||
let (h, _server) = call_hierarchy_harness().await;
|
||||
let body = json!({"filePath":"src/main.rs","line":2,"column":5,"direction":"outgoing"});
|
||||
let callees = h.json("get_call_hierarchy", body).await;
|
||||
assert_eq!(callees["root"]["name"], "main");
|
||||
assert_eq!(names(&callees), ["price", "show"]);
|
||||
let outside = h.error("get_call_hierarchy", json!({"filePath":"src/main.rs","line":6,"column":1})).await;
|
||||
assert_eq!(outside, "no function or method at 6:1");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn call_hierarchy_pages_are_sorted_and_scoped() {
|
||||
let (h, _server) = call_hierarchy_harness().await;
|
||||
let at = |extra: Value| {
|
||||
let mut args = json!({"filePath":"src/lib.rs","line":1,"column":9});
|
||||
args.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
args
|
||||
};
|
||||
let first = h.json("get_call_hierarchy", at(json!({"limit":2}))).await;
|
||||
assert_eq!(names(&first), ["Caller", "helper"]);
|
||||
assert_eq!(first["items"][0]["filePath"], LIBRARY_URI);
|
||||
assert!(first["items"][0].get("lineText").is_none(), "{first}");
|
||||
assert_eq!((&first["more"], &first["nextOffset"]), (&json!(true), &json!(2)));
|
||||
let next = h.json("get_call_hierarchy", at(json!({"limit":2,"offset":2}))).await;
|
||||
assert_eq!(names(&next), ["main"]);
|
||||
let scoped = h.json("get_call_hierarchy", at(json!({"scope":"src"}))).await;
|
||||
assert_eq!(names(&scoped), ["main"]);
|
||||
assert_eq!(scoped["total"], 1);
|
||||
assert_eq!(scoped["root"]["name"], "price", "the root is shown whatever the scope");
|
||||
}
|
||||
@@ -5284,6 +5284,29 @@ fn plugin_readonly_fields_and_table_row_extensions_round_trip() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_changes_reach_plugins_relative_to_the_project() {
|
||||
let f = fixture(Limits::default());
|
||||
f.install(&sample("path-events"));
|
||||
f.run("test.path-events", "count", None).unwrap();
|
||||
let deliver = |path: &str| {
|
||||
let change = ide_plugin::DocumentChanged {
|
||||
path: to_ipc(&f.project.join(path)),
|
||||
base_version: 1,
|
||||
version: 2,
|
||||
changes: Vec::new(),
|
||||
};
|
||||
f.host.post_events(Some("main"), vec![WorkbenchEvent::DocumentChanged(change)]);
|
||||
f.host.flush_events_at(Instant::now() + Duration::from_secs(3));
|
||||
assert!(f.host.wait_events(Duration::from_secs(10)));
|
||||
};
|
||||
deliver("src/main.rs");
|
||||
assert_eq!(f.run("test.path-events", "document", None).unwrap(), None, "outside the subscribed paths");
|
||||
// Queued with the absolute path, filtered again at delivery, handed over project-relative.
|
||||
deliver("config/app.yaml");
|
||||
assert_eq!(f.run("test.path-events", "document", None).unwrap().as_deref(), Some("config/app.yaml"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_filtered_events_do_not_wake_idle_plugins_and_recheck_queued_filters() {
|
||||
let f = fixture(Limits { idle_timeout: Some(Duration::from_millis(100)), ..Limits::default() });
|
||||
|
||||
@@ -1032,6 +1032,7 @@ pub fn call_item(conv: &Conv, item: &lsp::CallHierarchyItem, from_ranges: Vec<Ra
|
||||
path: path.into(),
|
||||
uri,
|
||||
from_ranges,
|
||||
from_path: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1056,6 +1057,7 @@ pub fn type_item(conv: &Conv, item: &lsp::TypeHierarchyItem) -> Option<Hierarchy
|
||||
path: path.into(),
|
||||
uri,
|
||||
from_ranges: Vec::new(),
|
||||
from_path: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -3241,6 +3241,7 @@ impl LspManager {
|
||||
.call(t, "textDocument/prepareCallHierarchy", snap.pos_params(t, pos), Some(cancel), DEFAULT_TIMEOUT)
|
||||
.await?;
|
||||
let items = items.filter(|i| !i.is_empty()).ok_or_else(no_hierarchy_target)?;
|
||||
let root = convert::call_item(&self.conv(t.enc()), &items[0], Vec::new());
|
||||
let query = || async {
|
||||
let mut out = Vec::new();
|
||||
for item in &items {
|
||||
@@ -3263,7 +3264,10 @@ impl LspManager {
|
||||
let (src, _) = uri_target(item.uri.as_str());
|
||||
for c in calls.unwrap_or_default() {
|
||||
let ranges = c.from_ranges.iter().map(|r| conv.range(&src, *r)).collect();
|
||||
out.extend(convert::call_item(&conv, &c.to, ranges));
|
||||
out.extend(
|
||||
convert::call_item(&conv, &c.to, ranges)
|
||||
.map(|to| HierarchyItem { from_path: Some(src.clone().into()), ..to }),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3293,8 +3297,8 @@ impl LspManager {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
self.note_virtual(&t.server, out.iter().map(|i| i.uri.as_deref()));
|
||||
Ok(CallHierarchy { items: out, incomplete })
|
||||
self.note_virtual(&t.server, out.iter().chain(&root).map(|i| i.uri.as_deref()));
|
||||
Ok(CallHierarchy { root, items: out, incomplete })
|
||||
}
|
||||
|
||||
/// The type at `pos` as the server's type hierarchy names it (with its `detail`, the
|
||||
|
||||
@@ -397,6 +397,7 @@ impl LspManager {
|
||||
range: *r,
|
||||
selection_range: *selection,
|
||||
from_ranges: vec![*call],
|
||||
from_path: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,6 +329,11 @@ pub struct HierarchyItem {
|
||||
pub selection_range: Range,
|
||||
/// Call sites, for call hierarchy.
|
||||
pub from_ranges: Vec<Range>,
|
||||
/// The file of `from_ranges` when it is not the item's own: for an outgoing call, the
|
||||
/// file of the prepared item that makes it (a path, or the URI of a virtual document).
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub from_path: Option<ide_core::IpcPath>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
@@ -575,6 +580,10 @@ pub struct ServerRefactored {
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CallHierarchy {
|
||||
/// The symbol the hierarchy is for: the first item the server prepared at the position.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub root: Option<HierarchyItem>,
|
||||
pub items: Vec<HierarchyItem>,
|
||||
pub incomplete: Option<ReferencesIncomplete>,
|
||||
}
|
||||
|
||||
@@ -3934,17 +3934,32 @@ async fn navigation_rename_format_and_decorations() {
|
||||
let item = json!({ "name": "foo", "kind": 12, "uri": uri, "range": r(0,0,0,11), "selectionRange": r(0,3,0,6), "data": "id" });
|
||||
s.respond("textDocument/prepareCallHierarchy", json!([item]));
|
||||
s.respond("callHierarchy/incomingCalls", json!([{ "from": { "name": "main", "kind": 12, "uri": uri, "range": r(1,0,1,6), "selectionRange": r(1,0,1,3) }, "fromRanges": [r(1,0,1,3)] }]));
|
||||
let calls = h
|
||||
.mgr
|
||||
.call_hierarchy(doc, Pos::new(0, 4), HierarchyDirection::Incoming, Default::default())
|
||||
.await
|
||||
.unwrap()
|
||||
.items;
|
||||
let hierarchy =
|
||||
h.mgr.call_hierarchy(doc, Pos::new(0, 4), HierarchyDirection::Incoming, Default::default()).await.unwrap();
|
||||
let root = hierarchy.root.expect("the prepared item");
|
||||
assert_eq!((root.name.as_str(), root.selection_range), ("foo", rng(0, 3, 0, 6)));
|
||||
assert_eq!(root.path.to_path_buf(), path);
|
||||
let calls = hierarchy.items;
|
||||
assert_eq!(calls.len(), 1);
|
||||
assert_eq!(calls[0].name, "main");
|
||||
assert_eq!(calls[0].from_ranges, vec![rng(1, 0, 1, 3)]);
|
||||
assert_eq!(s.requested("callHierarchy/incomingCalls")[0]["item"]["data"], "id");
|
||||
|
||||
// Outgoing calls of each prepared item are in that item's file.
|
||||
let other = path.with_file_name("b.mk");
|
||||
let second =
|
||||
json!({ "name": "foo", "kind": 12, "uri": uri_of(&other), "range": r(4,0,4,11), "selectionRange": r(4,3,4,6) });
|
||||
s.respond("textDocument/prepareCallHierarchy", json!([item, second]));
|
||||
s.respond("callHierarchy/outgoingCalls", json!([{ "to": { "name": "bar", "kind": 12, "uri": uri, "range": r(2,0,2,6), "selectionRange": r(2,0,2,3) }, "fromRanges": [r(0,8,0,11)] }]));
|
||||
let callees = h
|
||||
.mgr
|
||||
.call_hierarchy(doc, Pos::new(0, 4), HierarchyDirection::Outgoing, Default::default())
|
||||
.await
|
||||
.unwrap()
|
||||
.items;
|
||||
let from: Vec<_> = callees.iter().map(|c| c.from_path.clone().map(|p| p.into_path_buf())).collect();
|
||||
assert_eq!(from, [Some(path.clone()), Some(other)]);
|
||||
|
||||
// No documentSymbolProvider → None so callers fall back to tree-sitter.
|
||||
assert_eq!(h.mgr.document_symbols(doc).await.unwrap(), None);
|
||||
}
|
||||
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
f9c0cb4fca66ede5adcb1951dd05c3938c218224cb61e63a574ba08a93f4a041
|
||||
872f94f4bbc441457f36ed7b44b3a2fb6b87021f2f0a66104caf5c807b524147
|
||||
@@ -1,13 +1,13 @@
|
||||
id = "test.path-events"
|
||||
name = "Path event fixture"
|
||||
version = "0.1.0"
|
||||
engines.openidea = "^1.3"
|
||||
engines.openidea = "^1.6"
|
||||
wasm = "dist/plugin.wasm"
|
||||
activation = ["on-command:*"]
|
||||
|
||||
[capabilities]
|
||||
required = ["storage"]
|
||||
optional = ["events", "project.read"]
|
||||
optional = ["events", "project.read", "editor.read"]
|
||||
|
||||
[[contributes.providers]]
|
||||
kinds = ["hover"]
|
||||
@@ -29,6 +29,10 @@ title = "all"
|
||||
id = "off"
|
||||
title = "off"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "document"
|
||||
title = "document"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "count"
|
||||
title = "count"
|
||||
@@ -11,6 +11,7 @@ impl Plugin for Fixture {
|
||||
let globs: Vec<_> = glob.lines().collect();
|
||||
let _ = host::subscribe_paths("file-opened", &globs);
|
||||
let _ = host::subscribe_paths("file-saved", &["config/*.yaml"]);
|
||||
let _ = host::subscribe_paths("document-changed", &["config/*.yaml"]);
|
||||
Ok(())
|
||||
}
|
||||
fn run_command(&mut self, id: &str, _: &Invocation, arg: Option<&str>) -> Result<Option<String>, Error> {
|
||||
@@ -31,12 +32,18 @@ impl Plugin for Fixture {
|
||||
Ok(None)
|
||||
}
|
||||
"count" => Ok(host::storage::get("count")?),
|
||||
"document" => Ok(host::storage::get("document")?),
|
||||
_ => Err(Error::NotFound(id.into())),
|
||||
}
|
||||
}
|
||||
fn handle_events(&mut self, events: &[Event], _: &Invocation) {
|
||||
let count = host::storage::get("count").ok().flatten().and_then(|n| n.parse::<usize>().ok()).unwrap_or(0);
|
||||
host::storage::set("count", &(count + events.len()).to_string()).unwrap();
|
||||
for event in events {
|
||||
if let Event::DocumentChanged(change) = event {
|
||||
host::storage::set("document", &change.path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl HoverProvider for Fixture {
|
||||
|
||||
@@ -329,6 +329,9 @@ impl Http {
|
||||
}
|
||||
own_group(ide_core::process::prepare(&mut cmd));
|
||||
cmd.args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-A", "openidea"]);
|
||||
// A connection that stops delivering (a stalled proxy or mirror) fails and is retried
|
||||
// instead of leaving the request waiting forever.
|
||||
cmd.args(["--speed-limit", "1", "--speed-time", "30"]);
|
||||
// System Settings › HTTP Proxy (a manual proxy comes in through `prepare`'s environment).
|
||||
cmd.args(ide_core::proxy_settings::proxy().curl_args(url));
|
||||
if self.https_only {
|
||||
@@ -918,6 +921,14 @@ mod github_auth_tests {
|
||||
assert_eq!(fs::read_to_string(f.path("headers")).unwrap(), "Authorization: Bearer gho_fake_second\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stalled_transfer_times_out_instead_of_hanging() {
|
||||
let f = Fixture::new();
|
||||
f.get(API).unwrap();
|
||||
let args = fs::read_to_string(f.path("curl-args")).unwrap();
|
||||
assert!(args.contains("--speed-limit\n1\n--speed-time\n30\n"), "{args}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_token_avoids_gh_and_non_github_urls_receive_no_credentials() {
|
||||
let mut f = Fixture::new();
|
||||
|
||||
@@ -425,7 +425,7 @@ fn release_install_end_to_end_without_network() {
|
||||
"curl",
|
||||
&format!(
|
||||
r#"out=""; url=""
|
||||
while [ $# -gt 0 ]; do case "$1" in -o) out="$2"; shift 2;; -A|-H|--retry|--connect-timeout) shift 2;; -*) shift;; *) url="$1"; shift;; esac; done
|
||||
while [ $# -gt 0 ]; do case "$1" in -o) out="$2"; shift 2;; -A|-H|--retry|--connect-timeout|--speed-limit|--speed-time) shift 2;; -*) shift;; *) url="$1"; shift;; esac; done
|
||||
case "$url" in
|
||||
https://api.github.com/*) /bin/cat '{json}';;
|
||||
*) /bin/cp '{archive}' "$out";;
|
||||
@@ -485,7 +485,7 @@ fn phar_release_installs_with_a_php_launcher() {
|
||||
"curl",
|
||||
&format!(
|
||||
r#"out=""; url=""
|
||||
while [ $# -gt 0 ]; do case "$1" in -o) out="$2"; shift 2;; -A|-H|--retry|--connect-timeout) shift 2;; -*) shift;; *) url="$1"; shift;; esac; done
|
||||
while [ $# -gt 0 ]; do case "$1" in -o) out="$2"; shift 2;; -A|-H|--retry|--connect-timeout|--speed-limit|--speed-time) shift 2;; -*) shift;; *) url="$1"; shift;; esac; done
|
||||
case "$url" in
|
||||
https://api.github.com/*) /bin/cat '{json}';;
|
||||
*) /bin/cp '{phar}' "$out";;
|
||||
|
||||
+41
-2
@@ -18,6 +18,10 @@
|
||||
},
|
||||
"navbar": {
|
||||
"links": [
|
||||
{
|
||||
"label": "Marketplace",
|
||||
"href": "/plugins"
|
||||
},
|
||||
{
|
||||
"label": "GitHub",
|
||||
"href": "https://github.com/l0ng-ai/openidea"
|
||||
@@ -40,7 +44,14 @@
|
||||
"groups": [
|
||||
{
|
||||
"group": "Get started",
|
||||
"pages": ["en/index", "en/guide/install", "en/guide/quickstart", "en/guide/migrate", "en/roadmap"]
|
||||
"pages": [
|
||||
"en/index",
|
||||
"en/introduction",
|
||||
"en/guide/install",
|
||||
"en/guide/quickstart",
|
||||
"en/guide/migrate",
|
||||
"en/roadmap"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Editing",
|
||||
@@ -234,13 +245,37 @@
|
||||
},
|
||||
{
|
||||
"language": "zh",
|
||||
"navbar": {
|
||||
"links": [
|
||||
{
|
||||
"label": "插件市场",
|
||||
"href": "/zh/plugins"
|
||||
},
|
||||
{
|
||||
"label": "GitHub",
|
||||
"href": "https://github.com/l0ng-ai/openidea"
|
||||
}
|
||||
],
|
||||
"primary": {
|
||||
"type": "button",
|
||||
"label": "下载",
|
||||
"href": "https://github.com/l0ng-ai/openidea/releases/latest"
|
||||
}
|
||||
},
|
||||
"tabs": [
|
||||
{
|
||||
"tab": "指南",
|
||||
"groups": [
|
||||
{
|
||||
"group": "开始",
|
||||
"pages": ["zh/index", "zh/guide/install", "zh/guide/quickstart", "zh/guide/migrate", "zh/roadmap"]
|
||||
"pages": [
|
||||
"zh/index",
|
||||
"zh/introduction",
|
||||
"zh/guide/install",
|
||||
"zh/guide/quickstart",
|
||||
"zh/guide/migrate",
|
||||
"zh/roadmap"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "编辑",
|
||||
@@ -434,6 +469,10 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"redirects": [
|
||||
{ "source": "/en/plugins", "destination": "/plugins" },
|
||||
{ "source": "/zh/home", "destination": "/zh" }
|
||||
],
|
||||
"footer": {
|
||||
"socials": {
|
||||
"github": "https://github.com/l0ng-ai/openidea",
|
||||
|
||||
@@ -83,25 +83,26 @@ While the server runs, OpenIDEA writes its port and token to `mcp/server.json` i
|
||||
|
||||
## Tools
|
||||
|
||||
| Area | Tools |
|
||||
| ------------- | --------------------------------------------------------------------------- |
|
||||
| Files | `read_file`, `list_directory_tree`, `create_new_file`, `apply_patch` |
|
||||
| Search | `search_text`, `search_regex`, `search_symbol`, `search_file` |
|
||||
| Editors | `get_all_open_file_paths`, `get_current_file`, `open_file_in_editor` |
|
||||
| Code | `get_symbol_info`, `find_references`, `rename_refactoring`, `reformat_file` |
|
||||
| Problems | `get_file_problems`, `get_project_problems`, `check_files` |
|
||||
| Run and build | `get_run_configurations`, `execute_run_configuration`, `build_project` |
|
||||
| Commands | `run_command`, `wait_for_run`, `send_run_input`, `stop_run` |
|
||||
| Command state | `get_run_status`, `read_run_output`, `list_runs` |
|
||||
| Git | `get_repositories`, `git_status`, `git_diff` |
|
||||
| HTTP Client | `http_list_requests`, `http_run_request` |
|
||||
| Area | Tools |
|
||||
| ------------- | ------------------------------------------------------------------------------------------------- |
|
||||
| Files | `read_file`, `list_directory_tree`, `create_new_file`, `apply_patch` |
|
||||
| Search | `search_text`, `search_regex`, `search_symbol`, `search_file` |
|
||||
| Editors | `get_all_open_file_paths`, `get_current_file`, `open_file_in_editor` |
|
||||
| Code | `get_symbol_info`, `find_references`, `get_call_hierarchy`, `rename_refactoring`, `reformat_file` |
|
||||
| Problems | `get_file_problems`, `get_project_problems`, `check_files` |
|
||||
| Run and build | `get_run_configurations`, `execute_run_configuration`, `build_project` |
|
||||
| Commands | `run_command`, `wait_for_run`, `send_run_input`, `stop_run` |
|
||||
| Command state | `get_run_status`, `read_run_output`, `list_runs` |
|
||||
| Git | `get_repositories`, `git_status`, `git_diff` |
|
||||
| HTTP Client | `http_list_requests`, `http_run_request` |
|
||||
|
||||
Notes on what they do:
|
||||
|
||||
- `read_file` also reads sources of dependencies and files inside jar and zip archives.
|
||||
- The tools that list things return one page: `limit` items (100 by default; 50 for `search_symbol`, 10 for `list_runs`), from `offset`. `total` (where counting is cheap), `more` and `nextOffset` say what follows. `list_runs` filters by `state` (`running`, `idle`, `error` or one state), `get_run_configurations` by `query`, and `get_project_problems` lists errors only unless `errorsOnly` is false.
|
||||
- The query tools (the searches, `find_references`, `get_project_problems`, `git_status`, `get_all_open_file_paths`, `get_run_configurations`, `list_runs`) take `scope`: a directory, relative to the project root or absolute, that limits their results to the files in it, such as an attached project or one module.
|
||||
- The query tools (the searches, `find_references`, `get_call_hierarchy`, `get_project_problems`, `git_status`, `get_all_open_file_paths`, `get_run_configurations`, `list_runs`) take `scope`: a directory, relative to the project root or absolute, that limits their results to the files in it, such as an attached project or one module.
|
||||
- `search_symbol` and `find_references` use the IDE's index and the language servers; `get_symbol_info` returns what Quick Documentation shows.
|
||||
- `get_call_hierarchy` lists the callers of the function or method at a position, or with `direction` `outgoing` the functions it calls, one level per call. A position inside a function body means that function. To go one level deeper, call it again with an item's `filePath`, `startLine` and `startColumn`. Items in libraries show a URI as `filePath` and cannot be expanded.
|
||||
- `get_file_problems` and `get_project_problems` return what the Problems tool window shows, after your inspection profile is applied, rather than a fresh analysis.
|
||||
- `check_files` is the fresh analysis, for after an edit made by any tool: it syncs each file from disk, tells its language servers it was saved (so on-save checks such as `cargo check` run) and waits until they answered and finished. Each file gets a `status` that says whether the problems are complete, or why it could not be checked: no language server for it, or one that is not installed, misconfigured or crashed.
|
||||
- `rename_refactoring` renames through the language server, so references that a text search would miss are updated too. It can preview without writing.
|
||||
|
||||
+246
-45
@@ -1,58 +1,259 @@
|
||||
---
|
||||
title: "Introduction"
|
||||
description: "OpenIDEA is an open-source IDE with the IntelliJ IDEA way of working, built as a native app with a Rust core."
|
||||
title: "OpenIDEA"
|
||||
sidebarTitle: "Home"
|
||||
description: "The IDE you know, rebuilt in Rust. Open source, native, and fast on macOS, Windows and Linux."
|
||||
mode: "custom"
|
||||
---
|
||||
|
||||
OpenIDEA brings the IntelliJ IDEA way of working (its keymap, its tool windows, its search-everything habits) to a native desktop app with a Rust core. It runs on macOS, Windows and Linux and is licensed under Apache 2.0.
|
||||
import { pluginCatalog } from "/snippets/plugin-catalog.jsx";
|
||||
import { FeaturedPlugins } from "/snippets/marketplace.jsx";
|
||||
|
||||
If you have used IntelliJ IDEA, PyCharm or another JetBrains IDE, most of what you know carries over: pressing <kbd>Shift</kbd> twice opens Search Everywhere, `⌥↵` / `Alt+Enter` shows context actions, and the default keymap matches IDEA's. Coming from VS Code or Eclipse? Their keymaps are built in too.
|
||||
export const Kbd = ({ children }) => <span className="oi-kbd">{children}</span>;
|
||||
|
||||
## Highlights
|
||||
<div className="oi-home">
|
||||
|
||||
- **One IDE for many languages.** Editor and code insight for 60+ languages, and a one-click install of the language servers a project needs. See [Languages](/en/languages/index).
|
||||
- **The tools you expect.** Debugger, Git, terminal, database client, HTTP client, test runner, coverage and profiler, each in its own tool window.
|
||||
- **Search everything.** Search Everywhere, Find Action, Go to Class / File / Symbol and Find in Files across the indexed project.
|
||||
- **Refactorings and inspections.** Rename, extract, inline, change signature, safe delete, quick fixes and Inspect Code.
|
||||
- **Remote development.** Work on a machine over SSH or in a dev container with the `openidea-server` backend.
|
||||
- **AI agents.** Run coding agents in a tool window, and give them the IDE's own tools through the built-in MCP server.
|
||||
- **Plugins.** Plugins add actions, completion, quick fixes, tool windows, custom editors, themes, file icons and languages. They run as sandboxed WebAssembly components; themes, icon themes and languages need no code. The plugin API is still a preview.
|
||||
<section className="oi-hero">
|
||||
<div className="oi-hero-glow" aria-hidden="true" />
|
||||
<div className="oi-grid-bg" aria-hidden="true" />
|
||||
<div className="oi-wrap oi-hero-inner">
|
||||
<a className="oi-pill" href="https://github.com/l0ng-ai/openidea">
|
||||
<span className="oi-pill-dot" />
|
||||
Open source · Apache 2.0
|
||||
<span className="oi-pill-arrow">→</span>
|
||||
</a>
|
||||
<h1 className="oi-title">
|
||||
The IDE you know,
|
||||
<br />
|
||||
<span className="oi-title-accent">rebuilt in Rust.</span>
|
||||
</h1>
|
||||
<p className="oi-lead">
|
||||
Keymap, tool windows and search-everything habits you already have, in a native desktop app that opens in
|
||||
under a second and idles at a fraction of the memory.
|
||||
</p>
|
||||
<div className="oi-actions">
|
||||
<a className="oi-btn oi-btn-primary" href="https://github.com/l0ng-ai/openidea/releases/latest">
|
||||
Download
|
||||
</a>
|
||||
<a className="oi-btn oi-btn-ghost" href="/en/introduction">
|
||||
Read the docs
|
||||
</a>
|
||||
</div>
|
||||
<p className="oi-platforms">macOS · Windows · Linux</p>
|
||||
</div>
|
||||
|
||||
## Benchmark
|
||||
<div className="oi-wrap">
|
||||
<img
|
||||
className="oi-shot"
|
||||
src="/images/ide-dark.webp"
|
||||
alt="OpenIDEA in the dark theme: a Java project with the project tree and the editor"
|
||||
width="2880"
|
||||
height="1800"
|
||||
noZoom
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, about 770 files) with warm caches, median of 5 runs:
|
||||
<section className="oi-section">
|
||||
<div className="oi-wrap">
|
||||
<div className="oi-eyebrow">Benchmark</div>
|
||||
<h2 className="oi-h2">Native speed, measured from the outside.</h2>
|
||||
<p className="oi-sub">
|
||||
Opening freqtrade (Python, ~770 files) with warm caches, median of 5 runs, against IntelliJ IDEA 2026.2.3 with
|
||||
default settings.
|
||||
</p>
|
||||
<div className="oi-stats">
|
||||
<div className="oi-stat">
|
||||
<div className="oi-stat-num">
|
||||
0.9<small>s</small>
|
||||
</div>
|
||||
<div className="oi-stat-label">Window with the project</div>
|
||||
<div className="oi-bar">
|
||||
<span style={{ width: "29%" }} />
|
||||
</div>
|
||||
<div className="oi-stat-vs">3.1 s in IntelliJ IDEA</div>
|
||||
</div>
|
||||
<div className="oi-stat">
|
||||
<div className="oi-stat-num">
|
||||
1.1<small>s</small>
|
||||
</div>
|
||||
<div className="oi-stat-label">Ready, CPU settled</div>
|
||||
<div className="oi-bar">
|
||||
<span style={{ width: "8%" }} />
|
||||
</div>
|
||||
<div className="oi-stat-vs">13.2 s in IntelliJ IDEA</div>
|
||||
</div>
|
||||
<div className="oi-stat">
|
||||
<div className="oi-stat-num">
|
||||
169<small>MB</small>
|
||||
</div>
|
||||
<div className="oi-stat-label">Memory, all processes</div>
|
||||
<div className="oi-bar">
|
||||
<span style={{ width: "8%" }} />
|
||||
</div>
|
||||
<div className="oi-stat-vs">2011 MB in IntelliJ IDEA</div>
|
||||
</div>
|
||||
<div className="oi-stat">
|
||||
<div className="oi-stat-num">
|
||||
0.3<small>s</small>
|
||||
</div>
|
||||
<div className="oi-stat-label">Quit</div>
|
||||
<div className="oi-bar">
|
||||
<span style={{ width: "5%" }} />
|
||||
</div>
|
||||
<div className="oi-stat-vs">5.9 s in IntelliJ IDEA</div>
|
||||
</div>
|
||||
</div>
|
||||
<p className="oi-footnote">
|
||||
Windows 11, 32-core AMD, 62 GB RAM. IDEA analyses Python more deeply, so "ready" isn't the same work on both
|
||||
sides. Reproduce it with <a href="https://github.com/l0ng-ai/openidea/blob/main/perf/compare">perf/compare</a>.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|
||||
| --------------------------- | ----------------- | ---------------------- |
|
||||
| Window with the project | **0.9 s** | 3.1 s |
|
||||
| Ready (CPU settled) | **1.1 s** | 13.2 s |
|
||||
| Memory (USS, all processes) | **169 MB** | 2011 MB |
|
||||
| CPU time until ready | **2.4 s** | 47.9 s |
|
||||
| Idle CPU | **4 %** of a core | 7 % of a core |
|
||||
| Quit | **0.3 s** | 5.9 s |
|
||||
<section className="oi-section">
|
||||
<div className="oi-wrap">
|
||||
<div className="oi-eyebrow">Everything in one window</div>
|
||||
<h2 className="oi-h2">A full IDE, not an editor with extensions.</h2>
|
||||
<div className="oi-features">
|
||||
<a className="oi-feature" href="/en/languages/index">
|
||||
<Icon icon="code" size={18} />
|
||||
<h3>60+ languages</h3>
|
||||
<p>
|
||||
Editor and code insight for every language, with one-click install of the language servers a project needs.
|
||||
</p>
|
||||
</a>
|
||||
<a className="oi-feature" href="/en/guide/search">
|
||||
<Icon icon="magnifying-glass" size={18} />
|
||||
<h3>Search everything</h3>
|
||||
<p>Search Everywhere, Find Action, Go to Class / File / Symbol and Find in Files across the indexed project.</p>
|
||||
</a>
|
||||
<a className="oi-feature" href="/en/guide/refactoring">
|
||||
<Icon icon="wand-magic-sparkles" size={18} />
|
||||
<h3>Refactor with confidence</h3>
|
||||
<p>Rename, extract, inline, change signature and safe delete, plus inspections with quick fixes.</p>
|
||||
</a>
|
||||
<a className="oi-feature" href="/en/guide/debugging">
|
||||
<Icon icon="bug" size={18} />
|
||||
<h3>Run, test, debug</h3>
|
||||
<p>Debugger, test runner, coverage and profiler, each in its own tool window.</p>
|
||||
</a>
|
||||
<a className="oi-feature" href="/en/guide/vcs">
|
||||
<Icon icon="code-branch" size={18} />
|
||||
<h3>Git, terminal, database</h3>
|
||||
<p>Commit, log and branches, a real terminal, a database client and an HTTP client built in.</p>
|
||||
</a>
|
||||
<a className="oi-feature" href="/en/guide/remote/ssh">
|
||||
<Icon icon="server" size={18} />
|
||||
<h3>Remote development</h3>
|
||||
<p>
|
||||
Work on a machine over SSH or in a dev container, backed by <code>openidea-server</code>.
|
||||
</p>
|
||||
</a>
|
||||
<a className="oi-feature" href="/en/guide/agents">
|
||||
<Icon icon="sparkles" size={18} />
|
||||
<h3>AI agents</h3>
|
||||
<p>Run coding agents in a tool window and give them the IDE's own tools through the built-in MCP server.</p>
|
||||
</a>
|
||||
<a className="oi-feature" href="/en/plugins/index">
|
||||
<Icon icon="puzzle-piece" size={18} />
|
||||
<h3>WebAssembly plugins</h3>
|
||||
<p>Sandboxed plugins add actions, completion, tool windows and editors. Themes and languages need no code.</p>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
Measured with a release build of OpenIDEA from `main` and IDEA with default settings and plugins, on Windows 11, 32-core AMD, 62 GB RAM. IDEA analyses Python more deeply, so "ready" doesn't mean the same work on both sides. Both are measured from the outside, the same way: see [`perf/compare`](https://github.com/l0ng-ai/openidea/blob/main/perf/compare) to run the comparison on your own machine and projects.
|
||||
<section className="oi-section">
|
||||
<div className="oi-wrap">
|
||||
<div className="oi-plug-head">
|
||||
<div>
|
||||
<div className="oi-eyebrow">Plugin Marketplace</div>
|
||||
<h2 className="oi-h2">{pluginCatalog.plugins.length} plugins and counting.</h2>
|
||||
<p className="oi-sub">
|
||||
Spring, Laravel, Symfony, Kubernetes, AI commit messages, themes and more, from {pluginCatalog.publishers}{" "}
|
||||
publishers. Every package is signed and runs in a WebAssembly sandbox.
|
||||
</p>
|
||||
</div>
|
||||
<a className="oi-btn oi-btn-ghost" href="/plugins">
|
||||
Browse the marketplace →
|
||||
</a>
|
||||
</div>
|
||||
<FeaturedPlugins catalog={pluginCatalog} href="/plugins" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## Where to go next
|
||||
<section className="oi-section">
|
||||
<div className="oi-wrap oi-split">
|
||||
<div>
|
||||
<div className="oi-eyebrow">Muscle memory included</div>
|
||||
<h2 className="oi-h2">Your shortcuts already work.</h2>
|
||||
<p className="oi-sub">
|
||||
The default keymap matches IntelliJ IDEA, and VS Code and Eclipse keymaps are built in. Settings import brings
|
||||
the rest.
|
||||
</p>
|
||||
<a className="oi-link" href="/en/guide/migrate">
|
||||
Coming from another IDE →
|
||||
</a>
|
||||
</div>
|
||||
<div className="oi-keys">
|
||||
<div className="oi-key-row">
|
||||
<span>
|
||||
<Kbd>⇧</Kbd>
|
||||
<Kbd>⇧</Kbd>
|
||||
</span>
|
||||
Search Everywhere
|
||||
</div>
|
||||
<div className="oi-key-row">
|
||||
<span>
|
||||
<Kbd>⌥</Kbd>
|
||||
<Kbd>↵</Kbd>
|
||||
</span>
|
||||
Show context actions
|
||||
</div>
|
||||
<div className="oi-key-row">
|
||||
<span>
|
||||
<Kbd>⌘</Kbd>
|
||||
<Kbd>⇧</Kbd>
|
||||
<Kbd>A</Kbd>
|
||||
</span>
|
||||
Find Action
|
||||
</div>
|
||||
<div className="oi-key-row">
|
||||
<span>
|
||||
<Kbd>⇧</Kbd>
|
||||
<Kbd>F6</Kbd>
|
||||
</span>
|
||||
Rename
|
||||
</div>
|
||||
<div className="oi-key-row">
|
||||
<span>
|
||||
<Kbd>⌃</Kbd>
|
||||
<Kbd>⇧</Kbd>
|
||||
<Kbd>D</Kbd>
|
||||
</span>
|
||||
Debug
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Install" icon="download" href="/en/guide/install">
|
||||
Download OpenIDEA for macOS, Windows or Linux.
|
||||
</Card>
|
||||
<Card title="Quickstart" icon="rocket" href="/en/guide/quickstart">
|
||||
Open a project, find your way around, run and debug.
|
||||
</Card>
|
||||
<Card title="Coming from another IDE" icon="right-left" href="/en/guide/migrate">
|
||||
Keymaps, settings import and concepts for IntelliJ IDEA, VS Code and Eclipse users.
|
||||
</Card>
|
||||
<Card title="Languages" icon="code" href="/en/languages/index">
|
||||
What each language supports and what it needs installed.
|
||||
</Card>
|
||||
<Card title="Plugins" icon="puzzle-piece" href="/en/plugins/index">
|
||||
Write themes, languages and WebAssembly plugins.
|
||||
</Card>
|
||||
<Card title="Contribute" icon="code-branch" href="/en/contribute/setup">
|
||||
Build OpenIDEA from source and send a pull request.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
<section className="oi-cta">
|
||||
<div className="oi-hero-glow oi-cta-glow" aria-hidden="true" />
|
||||
<div className="oi-wrap oi-cta-inner">
|
||||
<h2 className="oi-h2">Open a project in under a second.</h2>
|
||||
<p className="oi-sub">Free and open source, for macOS, Windows and Linux.</p>
|
||||
<div className="oi-actions">
|
||||
<a className="oi-btn oi-btn-primary" href="https://github.com/l0ng-ai/openidea/releases/latest">
|
||||
Download
|
||||
</a>
|
||||
<a className="oi-btn oi-btn-ghost" href="/en/guide/quickstart">
|
||||
Quickstart
|
||||
</a>
|
||||
</div>
|
||||
<p className="oi-disclaimer">
|
||||
OpenIDEA is not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<Note>OpenIDEA is not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.</Note>
|
||||
</div>
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
title: "Introduction"
|
||||
description: "OpenIDEA is an open-source IDE with the IntelliJ IDEA way of working, built as a native app with a Rust core."
|
||||
---
|
||||
|
||||
OpenIDEA brings the IntelliJ IDEA way of working (its keymap, its tool windows, its search-everything habits) to a native desktop app with a Rust core. It runs on macOS, Windows and Linux and is licensed under Apache 2.0.
|
||||
|
||||
If you have used IntelliJ IDEA, PyCharm or another JetBrains IDE, most of what you know carries over: pressing <kbd>Shift</kbd> twice opens Search Everywhere, `⌥↵` / `Alt+Enter` shows context actions, and the default keymap matches IDEA's. Coming from VS Code or Eclipse? Their keymaps are built in too.
|
||||
|
||||
## Highlights
|
||||
|
||||
- **One IDE for many languages.** Editor and code insight for 60+ languages, and a one-click install of the language servers a project needs. See [Languages](/en/languages/index).
|
||||
- **The tools you expect.** Debugger, Git, terminal, database client, HTTP client, test runner, coverage and profiler, each in its own tool window.
|
||||
- **Search everything.** Search Everywhere, Find Action, Go to Class / File / Symbol and Find in Files across the indexed project.
|
||||
- **Refactorings and inspections.** Rename, extract, inline, change signature, safe delete, quick fixes and Inspect Code.
|
||||
- **Remote development.** Work on a machine over SSH or in a dev container with the `openidea-server` backend.
|
||||
- **AI agents.** Run coding agents in a tool window, and give them the IDE's own tools through the built-in MCP server.
|
||||
- **Plugins.** Plugins add actions, completion, quick fixes, tool windows, custom editors, themes, file icons and languages. They run as sandboxed WebAssembly components; themes, icon themes and languages need no code. The plugin API is still a preview.
|
||||
|
||||
## Benchmark
|
||||
|
||||
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, about 770 files) with warm caches, median of 5 runs:
|
||||
|
||||
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|
||||
| --------------------------- | ----------------- | ---------------------- |
|
||||
| Window with the project | **0.9 s** | 3.1 s |
|
||||
| Ready (CPU settled) | **1.1 s** | 13.2 s |
|
||||
| Memory (USS, all processes) | **169 MB** | 2011 MB |
|
||||
| CPU time until ready | **2.4 s** | 47.9 s |
|
||||
| Idle CPU | **4 %** of a core | 7 % of a core |
|
||||
| Quit | **0.3 s** | 5.9 s |
|
||||
|
||||
Measured with a release build of OpenIDEA from `main` and IDEA with default settings and plugins, on Windows 11, 32-core AMD, 62 GB RAM. IDEA analyses Python more deeply, so "ready" doesn't mean the same work on both sides. Both are measured from the outside, the same way: see [`perf/compare`](https://github.com/l0ng-ai/openidea/blob/main/perf/compare) to run the comparison on your own machine and projects.
|
||||
|
||||
## Where to go next
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Install" icon="download" href="/en/guide/install">
|
||||
Download OpenIDEA for macOS, Windows or Linux.
|
||||
</Card>
|
||||
<Card title="Quickstart" icon="rocket" href="/en/guide/quickstart">
|
||||
Open a project, find your way around, run and debug.
|
||||
</Card>
|
||||
<Card title="Coming from another IDE" icon="right-left" href="/en/guide/migrate">
|
||||
Keymaps, settings import and concepts for IntelliJ IDEA, VS Code and Eclipse users.
|
||||
</Card>
|
||||
<Card title="Languages" icon="code" href="/en/languages/index">
|
||||
What each language supports and what it needs installed.
|
||||
</Card>
|
||||
<Card title="Plugins" icon="puzzle-piece" href="/en/plugins/index">
|
||||
Write themes, languages and WebAssembly plugins.
|
||||
</Card>
|
||||
<Card title="Contribute" icon="code-branch" href="/en/contribute/setup">
|
||||
Build OpenIDEA from source and send a pull request.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>OpenIDEA is not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.</Note>
|
||||
File diff suppressed because it is too large.
Load diff
Бінарний файл не відображається.
|
Після Ширина: | Висота: | Розмір: 192 KiB |
@@ -0,0 +1,10 @@
|
||||
---
|
||||
title: "Plugin Marketplace"
|
||||
description: "Browse OpenIDEA plugins: languages, frameworks, linters, themes, AI and tools from the community and the OpenIDEA team."
|
||||
mode: "custom"
|
||||
---
|
||||
|
||||
import { pluginCatalog } from "/snippets/plugin-catalog.jsx";
|
||||
import { Marketplace } from "/snippets/marketplace.jsx";
|
||||
|
||||
<Marketplace catalog={pluginCatalog} lang="en" />
|
||||
@@ -0,0 +1,411 @@
|
||||
// Pages import the catalog (`/snippets/plugin-catalog.jsx`) and pass it in. Mintlify takes each imported
|
||||
// export on its own, so every component here is self-contained: no imports, no shared top-level helpers.
|
||||
|
||||
export const Marketplace = ({ catalog: pluginCatalog, lang = "en" }) => {
|
||||
const TEXT = {
|
||||
en: {
|
||||
eyebrow: "Plugin Marketplace",
|
||||
title: "Make OpenIDEA yours.",
|
||||
lead: "Languages, frameworks, linters, themes and tools, signed by their publishers and installed in one click from",
|
||||
path: "Settings › Plugins › Marketplace",
|
||||
leadEnd: ".",
|
||||
plugins: "plugins",
|
||||
publishers: "publishers",
|
||||
downloads: "downloads",
|
||||
downloadsLabel: "Downloads",
|
||||
listSep: ", ",
|
||||
search: "Search plugins",
|
||||
sort: "Sort",
|
||||
popular: "Popular",
|
||||
az: "A–Z",
|
||||
category: "Category",
|
||||
official: "Official",
|
||||
empty: (q) => `No plugins match “${q}”.`,
|
||||
buildEyebrow: "Build a plugin",
|
||||
buildTitle: "Ship your plugin to every OpenIDEA user.",
|
||||
buildLead:
|
||||
"Plugins are sandboxed WebAssembly components with a typed API. Themes, icon themes and languages need no code at all. Scaffold one in a minute, then list it through the community registry.",
|
||||
quickstart: "Plugin quickstart",
|
||||
publish: "Publish to the marketplace",
|
||||
term1: "# attach the .oiplugin to a release, then open a",
|
||||
term2: "# pull request in l0ng-ai/openidea-plugins",
|
||||
note: (d) =>
|
||||
`Snapshot of the marketplace index from ${d}. The IDE always shows the current list. Community plugins are built and signed by their authors.`,
|
||||
close: "Close",
|
||||
version: "Version",
|
||||
categoriesLabel: "Categories",
|
||||
pluginId: "Plugin id",
|
||||
install: (name) => (
|
||||
<>
|
||||
<b>Install</b> In OpenIDEA, open <b>Settings › Plugins › Marketplace</b>, search for “{name}” and click{" "}
|
||||
<b>Install</b>.
|
||||
</>
|
||||
),
|
||||
source: "Source and docs",
|
||||
categories: {
|
||||
all: "All",
|
||||
frameworks: "Frameworks",
|
||||
languages: "Languages",
|
||||
tools: "Tools",
|
||||
linters: "Linters",
|
||||
vcs: "Version control",
|
||||
ai: "AI",
|
||||
themes: "Themes",
|
||||
"icon-themes": "Icon themes",
|
||||
other: "Other",
|
||||
},
|
||||
},
|
||||
zh: {
|
||||
eyebrow: "插件市场",
|
||||
title: "让 OpenIDEA 成为你的 IDE。",
|
||||
lead: "语言、框架、代码检查、主题和工具,均由发布者签名,在",
|
||||
path: "设置 › 插件 › 插件市场",
|
||||
leadEnd: "中一键安装。",
|
||||
plugins: "个插件",
|
||||
publishers: "位发布者",
|
||||
downloads: "次下载",
|
||||
downloadsLabel: "下载量",
|
||||
listSep: "、",
|
||||
search: "搜索插件",
|
||||
sort: "排序",
|
||||
popular: "最热门",
|
||||
az: "按名称",
|
||||
category: "分类",
|
||||
official: "官方",
|
||||
empty: (q) => `没有与“${q}”匹配的插件。`,
|
||||
buildEyebrow: "开发插件",
|
||||
buildTitle: "把你的插件交到每一位 OpenIDEA 用户手中。",
|
||||
buildLead:
|
||||
"插件是运行在沙箱中的 WebAssembly 组件,API 有完整类型。主题、图标主题和语言完全不用写代码。一分钟搭好脚手架,再通过社区登记仓库上架。",
|
||||
quickstart: "插件快速开始",
|
||||
publish: "发布到插件市场",
|
||||
term1: "# 把 .oiplugin 附加到 release,然后向",
|
||||
term2: "# l0ng-ai/openidea-plugins 提交 pull request",
|
||||
note: (d) => `插件市场索引快照,生成于 ${d}。IDE 中显示的始终是最新列表。社区插件由作者自行构建和签名。`,
|
||||
close: "关闭",
|
||||
version: "版本",
|
||||
categoriesLabel: "分类",
|
||||
pluginId: "插件 id",
|
||||
install: (name) => (
|
||||
<>
|
||||
<b>安装</b> 在 OpenIDEA 中打开 <b>设置 › 插件 › 插件市场</b>,搜索“
|
||||
{name}”,点击 <b>安装</b>。
|
||||
</>
|
||||
),
|
||||
source: "源码与文档",
|
||||
categories: {
|
||||
all: "全部",
|
||||
frameworks: "框架",
|
||||
languages: "语言",
|
||||
tools: "工具",
|
||||
linters: "代码检查",
|
||||
vcs: "版本控制",
|
||||
ai: "AI",
|
||||
themes: "主题",
|
||||
"icon-themes": "图标主题",
|
||||
other: "其他",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const CATEGORY_IDS = [
|
||||
"all",
|
||||
"frameworks",
|
||||
"languages",
|
||||
"tools",
|
||||
"linters",
|
||||
"vcs",
|
||||
"ai",
|
||||
"themes",
|
||||
"icon-themes",
|
||||
"other",
|
||||
];
|
||||
|
||||
const formatCount = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k` : `${n}`);
|
||||
|
||||
// Called as a function: snippet components cannot use each other as JSX tags.
|
||||
|
||||
const pluginIcon = (plugin, size) =>
|
||||
plugin.icon ? (
|
||||
<span className="oi-mk-icon" style={{ width: size, height: size }}>
|
||||
<img className="oi-mk-icon-light" src={plugin.icon.light} alt="" />
|
||||
<img className="oi-mk-icon-dark" src={plugin.icon.dark || plugin.icon.light} alt="" />
|
||||
</span>
|
||||
) : (
|
||||
<span className="oi-mk-icon oi-mk-icon-fallback" style={{ width: size, height: size }}>
|
||||
{plugin.name
|
||||
.replace(/^[^A-Za-z0-9]+/, "")
|
||||
.slice(0, 1)
|
||||
.toUpperCase()}
|
||||
</span>
|
||||
);
|
||||
|
||||
const t = TEXT[lang] || TEXT.en;
|
||||
const categoryLabel = (id) => t.categories[id] || id;
|
||||
const all = pluginCatalog.plugins;
|
||||
const [query, setQuery] = useState("");
|
||||
const [category, setCategory] = useState("all");
|
||||
const [sort, setSort] = useState("popular");
|
||||
const [open, setOpen] = useState(null);
|
||||
|
||||
const counts = {};
|
||||
for (const p of all) for (const c of p.categories) counts[c] = (counts[c] || 0) + 1;
|
||||
const totalDownloads = all.reduce((s, p) => s + p.downloads, 0);
|
||||
|
||||
const q = query.trim().toLowerCase();
|
||||
const shown = all
|
||||
.filter((p) => category === "all" || p.categories.includes(category))
|
||||
.filter(
|
||||
(p) =>
|
||||
!q ||
|
||||
p.name.toLowerCase().includes(q) ||
|
||||
p.description.toLowerCase().includes(q) ||
|
||||
p.publisher.toLowerCase().includes(q) ||
|
||||
p.id.toLowerCase().includes(q),
|
||||
)
|
||||
.slice()
|
||||
.sort((a, b) => (sort === "name" ? a.name.localeCompare(b.name) : b.downloads - a.downloads));
|
||||
|
||||
const current = open && all.find((p) => p.id === open);
|
||||
|
||||
useEffect(() => {
|
||||
if (!current) return;
|
||||
const onKey = (e) => e.key === "Escape" && setOpen(null);
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [current]);
|
||||
|
||||
return (
|
||||
<div className="oi-home oi-mk">
|
||||
<section className="oi-mk-hero">
|
||||
<div className="oi-hero-glow" aria-hidden="true" />
|
||||
<div className="oi-grid-bg" aria-hidden="true" />
|
||||
<div className="oi-wrap">
|
||||
<div className="oi-eyebrow">{t.eyebrow}</div>
|
||||
<h1 className="oi-mk-title">{t.title}</h1>
|
||||
<p className="oi-sub">
|
||||
{t.lead} <b>{t.path}</b>
|
||||
{t.leadEnd}
|
||||
</p>
|
||||
<div className="oi-mk-metrics">
|
||||
<div>
|
||||
<strong>{all.length}</strong>
|
||||
<span>{t.plugins}</span>
|
||||
</div>
|
||||
<div>
|
||||
<strong>{pluginCatalog.publishers}</strong>
|
||||
<span>{t.publishers}</span>
|
||||
</div>
|
||||
<div>
|
||||
<strong>{formatCount(totalDownloads)}</strong>
|
||||
<span>{t.downloads}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="oi-wrap">
|
||||
<div className="oi-mk-toolbar">
|
||||
<label className="oi-mk-search">
|
||||
<svg viewBox="0 0 16 16" width="15" height="15" aria-hidden="true">
|
||||
<circle cx="7" cy="7" r="4.75" fill="none" stroke="currentColor" strokeWidth="1.5" />
|
||||
<path d="M10.5 10.5 14 14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
|
||||
</svg>
|
||||
<input
|
||||
type="search"
|
||||
placeholder={t.search}
|
||||
aria-label={t.search}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<div className="oi-mk-sort" role="group" aria-label={t.sort}>
|
||||
<button type="button" className={sort === "popular" ? "is-on" : ""} onClick={() => setSort("popular")}>
|
||||
{t.popular}
|
||||
</button>
|
||||
<button type="button" className={sort === "name" ? "is-on" : ""} onClick={() => setSort("name")}>
|
||||
{t.az}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="oi-mk-chips" role="group" aria-label={t.category}>
|
||||
{CATEGORY_IDS.filter((id) => id === "all" || counts[id]).map((id) => (
|
||||
<button type="button" key={id} className={category === id ? "is-on" : ""} onClick={() => setCategory(id)}>
|
||||
{categoryLabel(id)}
|
||||
<em>{id === "all" ? all.length : counts[id]}</em>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="oi-mk-grid">
|
||||
{shown.map((p) => (
|
||||
<button type="button" key={p.id} className="oi-mk-card" onClick={() => setOpen(p.id)}>
|
||||
<div className="oi-mk-card-head">
|
||||
{pluginIcon(p, 44)}
|
||||
<div className="oi-mk-card-title">
|
||||
<h3>{p.name}</h3>
|
||||
<span>
|
||||
{p.publisher}
|
||||
{p.official && <b className="oi-mk-badge">{t.official}</b>}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p>{p.description}</p>
|
||||
<div className="oi-mk-card-foot">
|
||||
<span className="oi-mk-tag">{categoryLabel(p.categories[0])}</span>
|
||||
{p.downloads > 0 && (
|
||||
<span className="oi-mk-dl">
|
||||
<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">
|
||||
<path
|
||||
d="M8 2v8m0 0 3-3m-3 3L5 7M3 13h10"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
{formatCount(p.downloads)}
|
||||
</span>
|
||||
)}
|
||||
<span className="oi-mk-ver">v{p.version}</span>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{shown.length === 0 && <p className="oi-mk-empty">{t.empty(query)}</p>}
|
||||
|
||||
<section className="oi-mk-build">
|
||||
<div>
|
||||
<div className="oi-eyebrow">{t.buildEyebrow}</div>
|
||||
<h2 className="oi-h2">{t.buildTitle}</h2>
|
||||
<p className="oi-sub">{t.buildLead}</p>
|
||||
<div className="oi-mk-build-actions">
|
||||
<a className="oi-btn oi-btn-primary" href={`/${lang}/plugins/quickstart`}>
|
||||
{t.quickstart}
|
||||
</a>
|
||||
<a className="oi-btn oi-btn-ghost" href={`/${lang}/plugins/publishing/marketplace`}>
|
||||
{t.publish}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div className="oi-mk-term" aria-hidden="true">
|
||||
<div className="oi-mk-term-bar">
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
</div>
|
||||
<div className="oi-mk-term-body">
|
||||
<div>
|
||||
<b>$</b> openidea-plugin new hello --id acme.hello
|
||||
</div>
|
||||
<div>
|
||||
<b>$</b> cd hello && cargo test
|
||||
</div>
|
||||
<div>
|
||||
<b>$</b> openidea-plugin build
|
||||
</div>
|
||||
<div>
|
||||
<b>$</b> openidea-plugin pack . --key acme.key --publisher acme
|
||||
</div>
|
||||
<div className="dim">{t.term1}</div>
|
||||
<div className="dim">{t.term2}</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<p className="oi-mk-note">{t.note(pluginCatalog.generatedAt)}</p>
|
||||
</div>
|
||||
|
||||
{current && (
|
||||
<div className="oi-mk-overlay" onClick={() => setOpen(null)}>
|
||||
<div
|
||||
className="oi-mk-dialog"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={current.name}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<button type="button" className="oi-mk-close" aria-label={t.close} onClick={() => setOpen(null)}>
|
||||
<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
|
||||
<path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
|
||||
</svg>
|
||||
</button>
|
||||
<div className="oi-mk-card-head">
|
||||
{pluginIcon(current, 64)}
|
||||
<div className="oi-mk-card-title">
|
||||
<h3>{current.name}</h3>
|
||||
<span>
|
||||
{current.publisher}
|
||||
{current.official && <b className="oi-mk-badge">{t.official}</b>}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="oi-mk-dialog-desc">{current.description}</p>
|
||||
<dl className="oi-mk-facts">
|
||||
<div>
|
||||
<dt>{t.version}</dt>
|
||||
<dd>{current.version}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{t.downloadsLabel}</dt>
|
||||
<dd>{current.downloads ? current.downloads.toLocaleString(lang === "zh" ? "zh-CN" : "en-US") : "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{t.categoriesLabel}</dt>
|
||||
<dd>{current.categories.map(categoryLabel).join(t.listSep)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{t.pluginId}</dt>
|
||||
<dd>
|
||||
<code>{current.id}</code>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div className="oi-mk-install">{t.install(current.name)}</div>
|
||||
{current.homepage && (
|
||||
<a className="oi-btn oi-btn-ghost oi-mk-home" href={current.homepage} target="_blank" rel="noreferrer">
|
||||
{t.source} ↗
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const FeaturedPlugins = ({ catalog: pluginCatalog, href }) => {
|
||||
const pluginIcon = (plugin, size) =>
|
||||
plugin.icon ? (
|
||||
<span className="oi-mk-icon" style={{ width: size, height: size }}>
|
||||
<img className="oi-mk-icon-light" src={plugin.icon.light} alt="" />
|
||||
<img className="oi-mk-icon-dark" src={plugin.icon.dark || plugin.icon.light} alt="" />
|
||||
</span>
|
||||
) : (
|
||||
<span className="oi-mk-icon oi-mk-icon-fallback" style={{ width: size, height: size }}>
|
||||
{plugin.name
|
||||
.replace(/^[^A-Za-z0-9]+/, "")
|
||||
.slice(0, 1)
|
||||
.toUpperCase()}
|
||||
</span>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="oi-plug-grid">
|
||||
{pluginCatalog.plugins
|
||||
.filter((p) => p.icon)
|
||||
.slice(0, 12)
|
||||
.map((p) => (
|
||||
<a key={p.id} className="oi-plug" href={href}>
|
||||
{pluginIcon(p, 36)}
|
||||
<span className="oi-plug-text">
|
||||
<b>{p.name}</b>
|
||||
<em>{p.publisher}</em>
|
||||
</span>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,2 @@
|
||||
// Generated by scripts/gen-plugin-catalog.ts. Do not edit.
|
||||
export const pluginCatalog = {"generatedAt":"2026-11-17","publishers":43,"plugins":[{"id":"aritti.ignore","name":".ignore","version":"0.3.0","description":"Support for ignore files (.gitignore, .dockerignore, .npmignore, .hgignore and 30 more). Reports duplicate, redundant, relative and malformed entries and invalid `syntax:` values, with quick fixes. Completes `syntax:` in .hgignore, opens the file an entry names on Ctrl-click and highlights ignore files the IDE does not recognise. A tool window adds github/gitignore and user templates. The status bar shows Ignored while you edit an ignored file, a notification warns about a Git project without a .gitignore, and any file gets an Add to .gitignore quick fix. Templates from github/gitignore (CC0-1.0).","publisher":"aritti","official":false,"categories":["linters","vcs"],"downloads":1430,"homepage":"https://github.com/arnaud-ritti/openidea-plugins/tree/main/plugins/ignore","icon":{"light":"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIgdmlld0JveD0iMCAwIDY0IDY0Ij48cmVjdCB4PSIyIiB5PSIyIiB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHJ4PSIxNCIgZmlsbD0iI0ZGRkZGRiIgc3Ryb2tlPSIjRDBEM0RCIiBzdHJva2Utd2lkdGg9IjIiLz48ZyB0cmFuc2Zvcm09InRyYW5zbGF0ZSg4LjAwIDguMDApIHNjYWxlKDAuMTQ4NCkiPjxwYXRoIGZpbGw9IiNkZTRjMzYiIGQ9Ik0yNTEuMTcyIDExNi41OTRMMTM5LjQgNC44MjhjLTYuNDMzLTYuNDM3LTE2Ljg3My02LjQzNy0yMy4zMTQgMGwtMjMuMjEgMjMuMjFsMjkuNDQzIDI5LjQ0M2M2Ljg0Mi0yLjMxMiAxNC42ODgtLjc2MSAyMC4xNDIgNC42OTNjNS40OCA1LjQ4OSA3LjAyIDEzLjQwMiA0LjY1MiAyMC4yNjZsMjguMzc1IDI4LjM3NmM2Ljg2NS0yLjM2NSAxNC43ODYtLjgzNSAyMC4yNjkgNC42NTdjNy42NjMgNy42NiA3LjY2MyAyMC4wNzUgMCAyNy43NGMtNy42NjUgNy42NjYtMjAuMDggNy42NjYtMjcuNzQ5IDBjLTUuNzY0LTUuNzctNy4xODgtMTQuMjM1LTQuMjctMjEuMzM2bC0yNi40NjItMjYuNDYybC0uMDAzIDY5LjYzN2ExOS44IDE5LjggMCAwIDEgNS4xODggMy43MWM3LjY2MyA3LjY2IDcuNjYzIDIwLjA3NiAwIDI3Ljc0N2MtNy42NjUgNy42NjItMjAuMDg2IDcuNjYyLTI3Ljc0IDBjLTcuNjYzLTcuNjcxLTcuNjYzLTIwLjA4NiAwLTI3Ljc0NmExOS43IDE5LjcgMCAwIDEgNi40MjEtNC4yODFWOTQuMTk2YTE5LjQgMTkuNCAwIDAgMS02LjQyMS00LjI4MWMtNS44MDYtNS43OTgtNy4yMDItMTQuMzE3LTQuMjI3LTIxLjQ0Nkw4MS40NyAzOS40NDJMNC44MyAxMTYuMDc3Yy02LjQ0IDYuNDQzLTYuNDQgMTYuODg0IDAgMjMuMzIybDExMS43NzQgMTExLjc2OGM2LjQzNSA2LjQzOCAxNi44NzMgNi40MzggMjMuMzE2IDBsMTExLjI1MS0xMTEuMjQ5YzYuNDM4LTYuNDQgNi40MzgtMTYuODg3IDAtMjMuMzI0Ii8+PC9nPjxjaXJjbGUgY3g9IjQ2IiBjeT0iNDYiIHI9IjEzIiBmaWxsPSIjMUYyMDI0IiBzdHJva2U9IiNGRkZGRkYiIHN0cm9rZS13aWR0aD0iMiIvPjxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKDM4LjggMzguOCkgc2NhbGUoLjYpIj48Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSI4IiBzdHJva2U9IiNGRkZGRkYiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIiBmaWxsPSJub25lIi8+PHBhdGggZD0iTTYuMyA2LjNsMTEuNCAxMS40IiBzdHJva2U9IiNGRkZGRkYiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIiBmaWxsPSJub25lIi8+PC9nPjwvc3ZnPg=="}},{"id":"aritti.dotenv","name":".env files","version":"0.3.0","description":".env file support: highlighting, inspections with quick fixes and ${VARIABLE} completion. Environment variables in code (getenv, os.environ, process.env, ENV[…], env::var, PHPUnit <env>, …) get completion and go to declaration in .env files, Dockerfiles and docker-compose files. Go to declaration on a key in a .env file lists its usages, and a confirmed source-only action can update current-file interpolation tokens after a key edit.","publisher":"aritti","official":false,"categories":["languages","linters"],"downloads":1267,"homepage":"https://github.com/arnaud-ritti/openidea-plugins","icon":{"light":"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIgdmlld0JveD0iMCAwIDY0IDY0Ij48cmVjdCB4PSIyIiB5PSIyIiB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHJ4PSIxNCIgZmlsbD0iI0ZGRkZGRiIgc3Ryb2tlPSIjRDBEM0RCIiBzdHJva2Utd2lkdGg9IjIiLz48ZyB0cmFuc2Zvcm09InRyYW5zbGF0ZSg5LjAwIDkuMDApIHNjYWxlKDEuOTE2NykiPjxwYXRoIGZpbGw9IiMwOTA5MGIiIGQ9Ik0wIDBoMjR2MjRIMHoiLz48cGF0aCBmaWxsPSIjZWNkNTNmIiBkPSJNMjQgMHYyNEgwVjB6TTEwLjkzMyAxNS44OUg2Ljg0djUuNTJoNC4xOTh2LS45M0g3Ljk1NXYtMS41MDNoMi43N3YtLjkzaC0yLjc3di0xLjIyNGgyLjk3OHptMi4xNDYgMGgtMS4wODR2NS41MmgxLjAzNXYtMy42bDIuMjI2IDMuNmgxLjExOHYtNS41MmgtMS4wMzZ2My42ODZ6bTUuMTE3IDBoLTEuMjA4bDEuOTczIDUuNTJoMS4xOWwxLjk3Ni01LjUyaC0xLjE4MmwtMS4zNTIgNC4wODV6TTUuNCAxOS42OEgzLjcydjEuNjhINS40eiIvPjwvZz48L3N2Zz4="}},{"id":"aritti.spring-boot","name":"Spring Boot Tools","version":"0.3.0","description":"Completion and checks for Spring Boot configuration files. Completes keys and values in application*.properties and application*.yml from a bundled Spring Boot fallback snapshot, explicitly selected version-qualified dependency JAR metadata, the project's configuration metadata files and its @ConfigurationProperties classes. Warns about deprecated keys (with a quick fix) and unknown keys in known groups, and checks cron expressions in @Scheduled(cron) and *.cron keys.","publisher":"aritti","official":false,"categories":["frameworks"],"downloads":1198,"homepage":"https://github.com/arnaud-ritti/openidea-plugins","icon":{Line truncated
|
||||
@@ -82,25 +82,26 @@ stdio 配置大致如下(路径以你机器上的为准):
|
||||
|
||||
## 工具
|
||||
|
||||
| 类别 | 工具 |
|
||||
| ----------- | --------------------------------------------------------------------------- |
|
||||
| 文件 | `read_file`、`list_directory_tree`、`create_new_file`、`apply_patch` |
|
||||
| 搜索 | `search_text`、`search_regex`、`search_symbol`、`search_file` |
|
||||
| 编辑器 | `get_all_open_file_paths`、`get_current_file`、`open_file_in_editor` |
|
||||
| 代码 | `get_symbol_info`、`find_references`、`rename_refactoring`、`reformat_file` |
|
||||
| 问题 | `get_file_problems`、`get_project_problems`、`check_files` |
|
||||
| 运行与构建 | `get_run_configurations`、`execute_run_configuration`、`build_project` |
|
||||
| 命令 | `run_command`、`wait_for_run`、`send_run_input`、`stop_run` |
|
||||
| 命令状态 | `get_run_status`、`read_run_output`、`list_runs` |
|
||||
| Git | `get_repositories`、`git_status`、`git_diff` |
|
||||
| HTTP 客户端 | `http_list_requests`、`http_run_request` |
|
||||
| 类别 | 工具 |
|
||||
| ----------- | ------------------------------------------------------------------------------------------------- |
|
||||
| 文件 | `read_file`、`list_directory_tree`、`create_new_file`、`apply_patch` |
|
||||
| 搜索 | `search_text`、`search_regex`、`search_symbol`、`search_file` |
|
||||
| 编辑器 | `get_all_open_file_paths`、`get_current_file`、`open_file_in_editor` |
|
||||
| 代码 | `get_symbol_info`、`find_references`、`get_call_hierarchy`、`rename_refactoring`、`reformat_file` |
|
||||
| 问题 | `get_file_problems`、`get_project_problems`、`check_files` |
|
||||
| 运行与构建 | `get_run_configurations`、`execute_run_configuration`、`build_project` |
|
||||
| 命令 | `run_command`、`wait_for_run`、`send_run_input`、`stop_run` |
|
||||
| 命令状态 | `get_run_status`、`read_run_output`、`list_runs` |
|
||||
| Git | `get_repositories`、`git_status`、`git_diff` |
|
||||
| HTTP 客户端 | `http_list_requests`、`http_run_request` |
|
||||
|
||||
几点说明:
|
||||
|
||||
- `read_file` 还能读取依赖的源代码,以及 jar 和 zip 压缩包中的文件。
|
||||
- `search_symbol` 和 `find_references` 使用 IDE 的索引和语言服务器;`get_symbol_info` 返回的内容与快速文档相同。
|
||||
- `get_call_hierarchy` 列出某个位置上函数或方法的调用方,`direction` 为 `outgoing` 时列出它调用的函数,每次一层。位置在函数体内时,指的就是这个函数。要再深入一层,用某一项的 `filePath`、`startLine` 和 `startColumn` 再调用一次。库中的项以 URI 作为 `filePath`,不能继续展开。
|
||||
- 列表类工具每次返回一页:从 `offset` 开始的 `limit` 项(默认 100;`search_symbol` 为 50,`list_runs` 为 10)。`total`(计数代价低的工具才有)、`more` 和 `nextOffset` 说明后面还有多少。`list_runs` 可按 `state` 过滤(`running`、`idle`、`error` 或某个具体状态),`get_run_configurations` 可按 `query` 过滤,`get_project_problems` 默认只列错误,`errorsOnly` 传 false 时也列警告。
|
||||
- 查询类工具(各搜索工具、`find_references`、`get_project_problems`、`git_status`、`get_all_open_file_paths`、`get_run_configurations`、`list_runs`)接受 `scope`:一个目录(相对项目根目录或绝对路径),只返回其中文件的结果,比如某个附加项目或某个模块。
|
||||
- 查询类工具(各搜索工具、`find_references`、`get_call_hierarchy`、`get_project_problems`、`git_status`、`get_all_open_file_paths`、`get_run_configurations`、`list_runs`)接受 `scope`:一个目录(相对项目根目录或绝对路径),只返回其中文件的结果,比如某个附加项目或某个模块。
|
||||
- `get_file_problems` 和 `get_project_problems` 返回的是问题工具窗口当前显示的内容(已应用你的检查配置文件),而不是重新分析的结果。
|
||||
- `check_files` 才是重新分析,适合在任何工具修改文件之后调用:它从磁盘同步每个文件,通知语言服务器文件已保存(这样 `cargo check` 等保存时检查也会运行),并等到服务器答复且分析完成。每个文件都有一个 `status`,说明问题列表是否完整,或者为什么无法检查:没有对应的语言服务器,或者服务器未安装、配置错误、已崩溃。
|
||||
- `rename_refactoring` 通过语言服务器重命名,文本搜索找不到的引用也会一并更新;也可以只预览不写入。
|
||||
|
||||
+239
-45
@@ -1,58 +1,252 @@
|
||||
---
|
||||
title: "介绍"
|
||||
description: "OpenIDEA 是一款开源 IDE,沿用 IntelliJ IDEA 的使用方式,以 Rust 为核心构建成原生应用。"
|
||||
title: "OpenIDEA"
|
||||
sidebarTitle: "首页"
|
||||
description: "熟悉的 IDE,用 Rust 重新打造。开源、原生,在 macOS、Windows 和 Linux 上都很快。"
|
||||
mode: "custom"
|
||||
---
|
||||
|
||||
OpenIDEA 把 IntelliJ IDEA 的使用方式(快捷键、工具窗口、随处搜索的习惯)带到一个以 Rust 为核心的原生桌面应用里。支持 macOS、Windows 和 Linux,采用 Apache 2.0 许可证。
|
||||
import { pluginCatalog } from "/snippets/plugin-catalog.jsx";
|
||||
import { FeaturedPlugins } from "/snippets/marketplace.jsx";
|
||||
|
||||
用过 IntelliJ IDEA、PyCharm 或其他 JetBrains IDE 的话,大部分经验可以直接沿用:连按两下 <kbd>Shift</kbd> 打开随处搜索,`⌥↵` / `Alt+Enter` 显示上下文操作,默认快捷键方案与 IDEA 一致。从 VS Code 或 Eclipse 过来,也有对应的内置快捷键方案。
|
||||
export const Kbd = ({ children }) => <span className="oi-kbd">{children}</span>;
|
||||
|
||||
## 亮点
|
||||
<div className="oi-home">
|
||||
|
||||
- **一个 IDE 覆盖多种语言。** 为 60 多种语言提供编辑和代码洞察,项目需要的语言服务器可一键安装。参见[语言](/zh/languages/index)。
|
||||
- **常用工具齐全。** 调试器、Git、终端、数据库客户端、HTTP 客户端、测试运行器、覆盖率和性能分析器,各有自己的工具窗口。
|
||||
- **随处搜索。** 在已建立索引的项目中使用随处搜索、查找操作、转到类 / 文件 / 符号以及在文件中查找。
|
||||
- **重构与检查。** 重命名、提取、内联、更改签名、安全删除、快速修复和代码检查。
|
||||
- **远程开发。** 通过 SSH 或在开发容器中工作,后端是 `openidea-server`。
|
||||
- **AI 智能体。** 在工具窗口中运行编码智能体,并通过内置 MCP 服务器把 IDE 自身的工具提供给它们。
|
||||
- **插件。** 插件可以添加操作、补全、快速修复、工具窗口、自定义编辑器、主题、文件图标和语言。插件以沙箱化的 WebAssembly 组件运行;主题、图标主题和语言无需编写代码。插件 API 目前仍是预览版。
|
||||
<section className="oi-hero">
|
||||
<div className="oi-hero-glow" aria-hidden="true" />
|
||||
<div className="oi-grid-bg" aria-hidden="true" />
|
||||
<div className="oi-wrap oi-hero-inner">
|
||||
<a className="oi-pill" href="https://github.com/l0ng-ai/openidea">
|
||||
<span className="oi-pill-dot" />
|
||||
开源 · Apache 2.0
|
||||
<span className="oi-pill-arrow">→</span>
|
||||
</a>
|
||||
<h1 className="oi-title">
|
||||
熟悉的 IDE,
|
||||
<br />
|
||||
<span className="oi-title-accent">用 Rust 重新打造。</span>
|
||||
</h1>
|
||||
<p className="oi-lead">
|
||||
你熟悉的快捷键、工具窗口和随处搜索,装进一个原生桌面应用:不到一秒打开项目,内存只占一小部分。
|
||||
</p>
|
||||
<div className="oi-actions">
|
||||
<a className="oi-btn oi-btn-primary" href="https://github.com/l0ng-ai/openidea/releases/latest">
|
||||
下载
|
||||
</a>
|
||||
<a className="oi-btn oi-btn-ghost" href="/zh/introduction">
|
||||
阅读文档
|
||||
</a>
|
||||
</div>
|
||||
<p className="oi-platforms">macOS · Windows · Linux</p>
|
||||
</div>
|
||||
|
||||
## 性能对比
|
||||
<div className="oi-wrap">
|
||||
<img
|
||||
className="oi-shot"
|
||||
src="/images/ide-dark.webp"
|
||||
alt="深色主题下的 OpenIDEA:一个 Java 项目,包含项目树和编辑器"
|
||||
width="2880"
|
||||
height="1800"
|
||||
noZoom
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
在缓存已预热的情况下打开 [freqtrade](https://github.com/freqtrade/freqtrade)(Python,约 770 个文件),取 5 次运行的中位数:
|
||||
<section className="oi-section">
|
||||
<div className="oi-wrap">
|
||||
<div className="oi-eyebrow">性能对比</div>
|
||||
<h2 className="oi-h2">原生的速度,从外部实测。</h2>
|
||||
<p className="oi-sub">
|
||||
打开 freqtrade(Python,约 770 个文件),缓存已预热,取 5 次运行的中位数,对比默认设置的 IntelliJ IDEA 2026.2.3。
|
||||
</p>
|
||||
<div className="oi-stats">
|
||||
<div className="oi-stat">
|
||||
<div className="oi-stat-num">
|
||||
0.9<small>s</small>
|
||||
</div>
|
||||
<div className="oi-stat-label">项目窗口出现</div>
|
||||
<div className="oi-bar">
|
||||
<span style={{ width: "29%" }} />
|
||||
</div>
|
||||
<div className="oi-stat-vs">IntelliJ IDEA:3.1 s</div>
|
||||
</div>
|
||||
<div className="oi-stat">
|
||||
<div className="oi-stat-num">
|
||||
1.1<small>s</small>
|
||||
</div>
|
||||
<div className="oi-stat-label">就绪(CPU 平稳)</div>
|
||||
<div className="oi-bar">
|
||||
<span style={{ width: "8%" }} />
|
||||
</div>
|
||||
<div className="oi-stat-vs">IntelliJ IDEA:13.2 s</div>
|
||||
</div>
|
||||
<div className="oi-stat">
|
||||
<div className="oi-stat-num">
|
||||
169<small>MB</small>
|
||||
</div>
|
||||
<div className="oi-stat-label">内存(全部进程)</div>
|
||||
<div className="oi-bar">
|
||||
<span style={{ width: "8%" }} />
|
||||
</div>
|
||||
<div className="oi-stat-vs">IntelliJ IDEA:2011 MB</div>
|
||||
</div>
|
||||
<div className="oi-stat">
|
||||
<div className="oi-stat-num">
|
||||
0.3<small>s</small>
|
||||
</div>
|
||||
<div className="oi-stat-label">退出</div>
|
||||
<div className="oi-bar">
|
||||
<span style={{ width: "5%" }} />
|
||||
</div>
|
||||
<div className="oi-stat-vs">IntelliJ IDEA:5.9 s</div>
|
||||
</div>
|
||||
</div>
|
||||
<p className="oi-footnote">
|
||||
Windows 11,32 核 AMD,62 GB 内存。IDEA 对 Python 的分析更深入,所以两边的“就绪”并不是同样的工作量。可以用{" "}
|
||||
<a href="https://github.com/l0ng-ai/openidea/blob/main/perf/compare">perf/compare</a> 在自己的机器上复现。
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|
||||
| --------------------- | -------------- | ---------------------- |
|
||||
| 显示项目窗口 | **0.9 s** | 3.1 s |
|
||||
| 就绪(CPU 平稳) | **1.1 s** | 13.2 s |
|
||||
| 内存(USS,所有进程) | **169 MB** | 2011 MB |
|
||||
| 就绪前消耗的 CPU 时间 | **2.4 s** | 47.9 s |
|
||||
| 空闲 CPU | 单核的 **4 %** | 单核的 7 % |
|
||||
| 退出 | **0.3 s** | 5.9 s |
|
||||
<section className="oi-section">
|
||||
<div className="oi-wrap">
|
||||
<div className="oi-eyebrow">一个窗口,应有尽有</div>
|
||||
<h2 className="oi-h2">完整的 IDE,而不是装满扩展的编辑器。</h2>
|
||||
<div className="oi-features">
|
||||
<a className="oi-feature" href="/zh/languages/index">
|
||||
<Icon icon="code" size={18} />
|
||||
<h3>60 多种语言</h3>
|
||||
<p>每种语言都有编辑和代码洞察,项目需要的语言服务器一键安装。</p>
|
||||
</a>
|
||||
<a className="oi-feature" href="/zh/guide/search">
|
||||
<Icon icon="magnifying-glass" size={18} />
|
||||
<h3>随处搜索</h3>
|
||||
<p>随处搜索、查找操作、转到类 / 文件 / 符号,以及在整个已索引项目中查找。</p>
|
||||
</a>
|
||||
<a className="oi-feature" href="/zh/guide/refactoring">
|
||||
<Icon icon="wand-magic-sparkles" size={18} />
|
||||
<h3>放心重构</h3>
|
||||
<p>重命名、提取、内联、更改签名和安全删除,还有带快速修复的代码检查。</p>
|
||||
</a>
|
||||
<a className="oi-feature" href="/zh/guide/debugging">
|
||||
<Icon icon="bug" size={18} />
|
||||
<h3>运行、测试、调试</h3>
|
||||
<p>调试器、测试运行器、覆盖率和性能分析器,各有自己的工具窗口。</p>
|
||||
</a>
|
||||
<a className="oi-feature" href="/zh/guide/vcs">
|
||||
<Icon icon="code-branch" size={18} />
|
||||
<h3>Git、终端、数据库</h3>
|
||||
<p>提交、日志和分支,真正的终端,内置数据库客户端和 HTTP 客户端。</p>
|
||||
</a>
|
||||
<a className="oi-feature" href="/zh/guide/remote/ssh">
|
||||
<Icon icon="server" size={18} />
|
||||
<h3>远程开发</h3>
|
||||
<p>
|
||||
通过 SSH 连到远程机器,或在开发容器中工作,后端是 <code>openidea-server</code>。
|
||||
</p>
|
||||
</a>
|
||||
<a className="oi-feature" href="/zh/guide/agents">
|
||||
<Icon icon="sparkles" size={18} />
|
||||
<h3>AI 智能体</h3>
|
||||
<p>在工具窗口中运行编码智能体,并通过内置 MCP 服务器把 IDE 自身的工具交给它们。</p>
|
||||
</a>
|
||||
<a className="oi-feature" href="/zh/plugins/index">
|
||||
<Icon icon="puzzle-piece" size={18} />
|
||||
<h3>WebAssembly 插件</h3>
|
||||
<p>沙箱化的插件可以添加操作、补全、工具窗口和编辑器。主题和语言无需写代码。</p>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
测试使用 `main` 分支的 OpenIDEA release 构建,以及默认设置和插件的 IDEA,环境为 Windows 11、32 核 AMD、62 GB 内存。IDEA 对 Python 的分析更深入,所以两边的“就绪”并不代表完成了同样多的工作。两者都以相同方式从外部测量:可以用 [`perf/compare`](https://github.com/l0ng-ai/openidea/blob/main/perf/compare) 在自己的机器和项目上复现。
|
||||
<section className="oi-section">
|
||||
<div className="oi-wrap">
|
||||
<div className="oi-plug-head">
|
||||
<div>
|
||||
<div className="oi-eyebrow">插件市场</div>
|
||||
<h2 className="oi-h2">{pluginCatalog.plugins.length} 个插件,还在增加。</h2>
|
||||
<p className="oi-sub">
|
||||
Spring、Laravel、Symfony、Kubernetes、AI 提交信息、主题等等,来自 {pluginCatalog.publishers}{" "}
|
||||
位发布者。每个插件包都经过签名,运行在 WebAssembly 沙箱中。
|
||||
</p>
|
||||
</div>
|
||||
<a className="oi-btn oi-btn-ghost" href="/plugins">
|
||||
浏览插件市场 →
|
||||
</a>
|
||||
</div>
|
||||
<FeaturedPlugins catalog={pluginCatalog} href="/zh/plugins" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
## 下一步
|
||||
<section className="oi-section">
|
||||
<div className="oi-wrap oi-split">
|
||||
<div>
|
||||
<div className="oi-eyebrow">肌肉记忆照样好用</div>
|
||||
<h2 className="oi-h2">你的快捷键,直接就能用。</h2>
|
||||
<p className="oi-sub">
|
||||
默认快捷键方案与 IntelliJ IDEA 一致,也内置了 VS Code 和 Eclipse 方案。其余设置可以直接导入。
|
||||
</p>
|
||||
<a className="oi-link" href="/zh/guide/migrate">
|
||||
从其他 IDE 迁移 →
|
||||
</a>
|
||||
</div>
|
||||
<div className="oi-keys">
|
||||
<div className="oi-key-row">
|
||||
<span>
|
||||
<Kbd>⇧</Kbd>
|
||||
<Kbd>⇧</Kbd>
|
||||
</span>
|
||||
随处搜索
|
||||
</div>
|
||||
<div className="oi-key-row">
|
||||
<span>
|
||||
<Kbd>⌥</Kbd>
|
||||
<Kbd>↵</Kbd>
|
||||
</span>
|
||||
显示上下文操作
|
||||
</div>
|
||||
<div className="oi-key-row">
|
||||
<span>
|
||||
<Kbd>⌘</Kbd>
|
||||
<Kbd>⇧</Kbd>
|
||||
<Kbd>A</Kbd>
|
||||
</span>
|
||||
查找操作
|
||||
</div>
|
||||
<div className="oi-key-row">
|
||||
<span>
|
||||
<Kbd>⇧</Kbd>
|
||||
<Kbd>F6</Kbd>
|
||||
</span>
|
||||
重命名
|
||||
</div>
|
||||
<div className="oi-key-row">
|
||||
<span>
|
||||
<Kbd>⌃</Kbd>
|
||||
<Kbd>⇧</Kbd>
|
||||
<Kbd>D</Kbd>
|
||||
</span>
|
||||
调试
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="安装" icon="download" href="/zh/guide/install">
|
||||
下载 macOS、Windows 或 Linux 版 OpenIDEA。
|
||||
</Card>
|
||||
<Card title="快速上手" icon="rocket" href="/zh/guide/quickstart">
|
||||
打开项目、熟悉界面、运行和调试。
|
||||
</Card>
|
||||
<Card title="从其他 IDE 迁移" icon="right-left" href="/zh/guide/migrate">
|
||||
面向 IntelliJ IDEA、VS Code 和 Eclipse 用户的快捷键、设置导入和概念对照。
|
||||
</Card>
|
||||
<Card title="语言" icon="code" href="/zh/languages/index">
|
||||
各语言支持哪些功能、需要安装什么。
|
||||
</Card>
|
||||
<Card title="插件" icon="puzzle-piece" href="/zh/plugins/index">
|
||||
编写主题、语言和 WebAssembly 插件。
|
||||
</Card>
|
||||
<Card title="参与贡献" icon="code-branch" href="/zh/contribute/setup">
|
||||
从源码构建 OpenIDEA 并提交 Pull Request。
|
||||
</Card>
|
||||
</CardGroup>
|
||||
<section className="oi-cta">
|
||||
<div className="oi-hero-glow oi-cta-glow" aria-hidden="true" />
|
||||
<div className="oi-wrap oi-cta-inner">
|
||||
<h2 className="oi-h2">不到一秒,打开项目。</h2>
|
||||
<p className="oi-sub">免费开源,支持 macOS、Windows 和 Linux。</p>
|
||||
<div className="oi-actions">
|
||||
<a className="oi-btn oi-btn-primary" href="https://github.com/l0ng-ai/openidea/releases/latest">
|
||||
下载
|
||||
</a>
|
||||
<a className="oi-btn oi-btn-ghost" href="/zh/guide/quickstart">
|
||||
快速开始
|
||||
</a>
|
||||
</div>
|
||||
<p className="oi-disclaimer">OpenIDEA 与 JetBrains 无关联。IntelliJ IDEA 是 JetBrains s.r.o. 的商标。</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<Note>OpenIDEA 与 JetBrains 无关联。IntelliJ IDEA 是 JetBrains s.r.o. 的商标。</Note>
|
||||
</div>
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
title: "介绍"
|
||||
description: "OpenIDEA 是一款开源 IDE,沿用 IntelliJ IDEA 的使用方式,以 Rust 为核心构建成原生应用。"
|
||||
---
|
||||
|
||||
OpenIDEA 把 IntelliJ IDEA 的使用方式(快捷键、工具窗口、随处搜索的习惯)带到一个以 Rust 为核心的原生桌面应用里。支持 macOS、Windows 和 Linux,采用 Apache 2.0 许可证。
|
||||
|
||||
用过 IntelliJ IDEA、PyCharm 或其他 JetBrains IDE 的话,大部分经验可以直接沿用:连按两下 <kbd>Shift</kbd> 打开随处搜索,`⌥↵` / `Alt+Enter` 显示上下文操作,默认快捷键方案与 IDEA 一致。从 VS Code 或 Eclipse 过来,也有对应的内置快捷键方案。
|
||||
|
||||
## 亮点
|
||||
|
||||
- **一个 IDE 覆盖多种语言。** 为 60 多种语言提供编辑和代码洞察,项目需要的语言服务器可一键安装。参见[语言](/zh/languages/index)。
|
||||
- **常用工具齐全。** 调试器、Git、终端、数据库客户端、HTTP 客户端、测试运行器、覆盖率和性能分析器,各有自己的工具窗口。
|
||||
- **随处搜索。** 在已建立索引的项目中使用随处搜索、查找操作、转到类 / 文件 / 符号以及在文件中查找。
|
||||
- **重构与检查。** 重命名、提取、内联、更改签名、安全删除、快速修复和代码检查。
|
||||
- **远程开发。** 通过 SSH 或在开发容器中工作,后端是 `openidea-server`。
|
||||
- **AI 智能体。** 在工具窗口中运行编码智能体,并通过内置 MCP 服务器把 IDE 自身的工具提供给它们。
|
||||
- **插件。** 插件可以添加操作、补全、快速修复、工具窗口、自定义编辑器、主题、文件图标和语言。插件以沙箱化的 WebAssembly 组件运行;主题、图标主题和语言无需编写代码。插件 API 目前仍是预览版。
|
||||
|
||||
## 性能对比
|
||||
|
||||
在缓存已预热的情况下打开 [freqtrade](https://github.com/freqtrade/freqtrade)(Python,约 770 个文件),取 5 次运行的中位数:
|
||||
|
||||
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|
||||
| --------------------- | -------------- | ---------------------- |
|
||||
| 显示项目窗口 | **0.9 s** | 3.1 s |
|
||||
| 就绪(CPU 平稳) | **1.1 s** | 13.2 s |
|
||||
| 内存(USS,所有进程) | **169 MB** | 2011 MB |
|
||||
| 就绪前消耗的 CPU 时间 | **2.4 s** | 47.9 s |
|
||||
| 空闲 CPU | 单核的 **4 %** | 单核的 7 % |
|
||||
| 退出 | **0.3 s** | 5.9 s |
|
||||
|
||||
测试使用 `main` 分支的 OpenIDEA release 构建,以及默认设置和插件的 IDEA,环境为 Windows 11、32 核 AMD、62 GB 内存。IDEA 对 Python 的分析更深入,所以两边的“就绪”并不代表完成了同样多的工作。两者都以相同方式从外部测量:可以用 [`perf/compare`](https://github.com/l0ng-ai/openidea/blob/main/perf/compare) 在自己的机器和项目上复现。
|
||||
|
||||
## 下一步
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="安装" icon="download" href="/zh/guide/install">
|
||||
下载 macOS、Windows 或 Linux 版 OpenIDEA。
|
||||
</Card>
|
||||
<Card title="快速上手" icon="rocket" href="/zh/guide/quickstart">
|
||||
打开项目、熟悉界面、运行和调试。
|
||||
</Card>
|
||||
<Card title="从其他 IDE 迁移" icon="right-left" href="/zh/guide/migrate">
|
||||
面向 IntelliJ IDEA、VS Code 和 Eclipse 用户的快捷键、设置导入和概念对照。
|
||||
</Card>
|
||||
<Card title="语言" icon="code" href="/zh/languages/index">
|
||||
各语言支持哪些功能、需要安装什么。
|
||||
</Card>
|
||||
<Card title="插件" icon="puzzle-piece" href="/zh/plugins/index">
|
||||
编写主题、语言和 WebAssembly 插件。
|
||||
</Card>
|
||||
<Card title="参与贡献" icon="code-branch" href="/zh/contribute/setup">
|
||||
从源码构建 OpenIDEA 并提交 Pull Request。
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>OpenIDEA 与 JetBrains 无关联。IntelliJ IDEA 是 JetBrains s.r.o. 的商标。</Note>
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
title: "插件市场"
|
||||
description: "浏览 OpenIDEA 插件:来自社区和 OpenIDEA 团队的语言、框架、代码检查、主题、AI 和工具插件。"
|
||||
mode: "custom"
|
||||
---
|
||||
|
||||
import { pluginCatalog } from "/snippets/plugin-catalog.jsx";
|
||||
import { Marketplace } from "/snippets/marketplace.jsx";
|
||||
|
||||
<Marketplace catalog={pluginCatalog} lang="zh" />
|
||||
@@ -44,6 +44,91 @@ const questions: AgentQuestion[] = [
|
||||
},
|
||||
];
|
||||
|
||||
for (const status of ["running", "ready"] as const) {
|
||||
test(`answers an asynchronous Codex question when ${status}`, async ({ workbench: page }) => {
|
||||
const key = JSON.stringify(["request_user_input_async", "call-1", 0]);
|
||||
await page.evaluate(
|
||||
async ({ task, status, key }) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const store = await import(storePath);
|
||||
(await import(ipcPath)).commands.agentAnswerQuestion = async (
|
||||
id: string,
|
||||
question: string,
|
||||
answer: string | null,
|
||||
) => {
|
||||
document.documentElement.dataset.asyncAnswer = JSON.stringify({ id, question, answer });
|
||||
const entries = store.useAgents.getState().entries.get(id)!;
|
||||
store.useAgents.setState({
|
||||
entries: new Map([
|
||||
[
|
||||
id,
|
||||
entries.map((entry) =>
|
||||
entry.type === "question" ? { ...entry, chosen: "Read latest content" } : entry,
|
||||
),
|
||||
],
|
||||
]),
|
||||
});
|
||||
return { status: "ok", data: null };
|
||||
};
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
tasks: new Map([[task.id, { ...task, status }]]),
|
||||
entries: new Map([
|
||||
[
|
||||
task.id,
|
||||
[
|
||||
{ type: "agent", text: "I can keep working while you decide." },
|
||||
{
|
||||
type: "question",
|
||||
id: "call-1",
|
||||
title: "Should Retry read the latest content?",
|
||||
chosen: null,
|
||||
questions: [
|
||||
{
|
||||
answerKey: key,
|
||||
header: "",
|
||||
question: "Should Retry read the latest content?",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Read latest content (Recommended)", description: "", preview: null },
|
||||
{ label: "Keep the original snapshot", description: "", preview: null },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
],
|
||||
]),
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
},
|
||||
{ task, status, key },
|
||||
);
|
||||
const card = page.getByRole("form", { name: "Should Retry read the latest content?" });
|
||||
await expect(card).toBeVisible();
|
||||
await card.getByRole("radio", { name: /^Read latest content/ }).check();
|
||||
if (status === "running") {
|
||||
await page.evaluate(async (id) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const { useAgents } = await import(storePath);
|
||||
useAgents.setState((s) => ({ tasks: new Map(s.tasks).set(id, { ...s.tasks.get(id)!, status: "ready" }) }));
|
||||
}, task.id);
|
||||
await expect(card.getByRole("radio", { name: /^Read latest content/ })).toBeChecked();
|
||||
}
|
||||
await card.getByRole("button", { name: "Submit", exact: true }).click();
|
||||
await expect(page.locator("html")).toHaveAttribute(
|
||||
"data-async-answer",
|
||||
JSON.stringify({
|
||||
id: task.id,
|
||||
question: "call-1",
|
||||
answer: JSON.stringify({ [key]: ["Read latest content (Recommended)"] }),
|
||||
}),
|
||||
);
|
||||
await expect(card).toHaveCount(0);
|
||||
});
|
||||
}
|
||||
|
||||
for (const theme of ["dark", "light"] as const) {
|
||||
for (const width of [760, 1400]) {
|
||||
for (const count of [1, 3]) {
|
||||
|
||||
@@ -39,3 +39,44 @@ for (const activation of ["double-click", "Enter"] as const) {
|
||||
await expect(page.getByRole("menuitem", { name: "Add Mouse Shortcut", exact: true })).toBeVisible();
|
||||
});
|
||||
}
|
||||
|
||||
test("rectangular drag remains configurable after removal and saves a middle mouse binding", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const title = "Create Rectangular Selection on Mouse Drag";
|
||||
await page.keyboard.press("Meta+,");
|
||||
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
|
||||
await settings.getByRole("textbox", { name: "Search actions", exact: true }).fill(title);
|
||||
const row = settings.getByRole("tree", { name: "Actions" }).getByRole("treeitem", { name: new RegExp(title) });
|
||||
for (let i = 0; i < 2; i++) {
|
||||
await row.click({ button: "right" });
|
||||
await page
|
||||
.getByRole("menuitem", { name: /^Remove / })
|
||||
.first()
|
||||
.click();
|
||||
}
|
||||
await expect(row).toBeVisible();
|
||||
await row.click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Add Mouse Shortcut", exact: true }).click();
|
||||
const recorder = page.getByRole("dialog", { name: `Mouse Shortcut: ${title}`, exact: true });
|
||||
await recorder.getByRole("textbox", { name: "Mouse shortcut" }).click({ button: "middle", modifiers: ["Alt"] });
|
||||
await expect(recorder.getByRole("textbox", { name: "Mouse shortcut" })).toContainText("Middle Click");
|
||||
await recorder.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await settings.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await expect(settings).toBeHidden();
|
||||
await expect
|
||||
.poll(() =>
|
||||
page.evaluate(async () => {
|
||||
const keymapModule = "/src/platform/keymap.ts";
|
||||
const { bindingsFor } = await import(/* @vite-ignore */ keymapModule);
|
||||
return bindingsFor("editor.createRectangularSelectionOnMouseDrag");
|
||||
}),
|
||||
)
|
||||
.toEqual(["Alt+Button2"]);
|
||||
await page.keyboard.press("Meta+,");
|
||||
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
|
||||
await settings.getByRole("textbox", { name: "Search actions", exact: true }).fill(title);
|
||||
await expect(row).toContainText("Middle Click");
|
||||
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import { expect, openFromTree, test } from "./fixtures";
|
||||
|
||||
test("middle and Alt drags create editable rectangles without changing ordinary selection", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await openFromTree(page, "build.gradle.kts");
|
||||
const text = "alpha = 111;\nbravo = 222;\ncharl = 333;\ndelta = 444;";
|
||||
const prepare = () =>
|
||||
page.evaluate(async (text) => {
|
||||
const controllerModule = "/src/editor/core/controller.ts";
|
||||
const columnModule = "/src/editor/core/cm/columnMode.ts";
|
||||
const { editorController } = await import(/* @vite-ignore */ controllerModule);
|
||||
const { setColumnMode } = await import(/* @vite-ignore */ columnModule);
|
||||
const view = editorController().activeSlot.view;
|
||||
view.dispatch({
|
||||
changes: { from: 0, to: view.state.doc.length, insert: text },
|
||||
selection: { anchor: 0 },
|
||||
effects: setColumnMode.of(false),
|
||||
});
|
||||
view.focus();
|
||||
const a = view.coordsAtPos(0);
|
||||
const b = view.coordsAtPos(view.state.doc.line(4).from + 5);
|
||||
return {
|
||||
from: { x: a.left + 0.5, y: (a.top + a.bottom) / 2 },
|
||||
to: { x: b.left + 0.5, y: (b.top + b.bottom) / 2 },
|
||||
};
|
||||
}, text);
|
||||
const selection = () =>
|
||||
page.evaluate(async () => {
|
||||
const controllerModule = "/src/editor/core/controller.ts";
|
||||
const columnModule = "/src/editor/core/cm/columnMode.ts";
|
||||
const { editorController } = await import(/* @vite-ignore */ controllerModule);
|
||||
const { isColumnMode } = await import(/* @vite-ignore */ columnModule);
|
||||
const view = editorController().activeSlot.view;
|
||||
return {
|
||||
ranges: view.state.selection.ranges.map((r: { from: number; to: number }) => view.state.sliceDoc(r.from, r.to)),
|
||||
columnMode: isColumnMode(view.state),
|
||||
text: view.state.doc.toString(),
|
||||
};
|
||||
});
|
||||
for (const button of ["middle", "left"] as const) {
|
||||
const points = await prepare();
|
||||
if (button === "left") await page.keyboard.down("Alt");
|
||||
await page.mouse.move(points.from.x, points.from.y);
|
||||
await page.mouse.down({ button });
|
||||
await page.mouse.move(points.to.x, points.to.y, { steps: 5 });
|
||||
await page.mouse.up({ button });
|
||||
if (button === "left") await page.keyboard.up("Alt");
|
||||
await expect.poll(async () => (await selection()).ranges).toEqual(["alpha", "bravo", "charl", "delta"]);
|
||||
expect((await selection()).columnMode).toBe(false);
|
||||
}
|
||||
await page.keyboard.insertText("name");
|
||||
await expect.poll(async () => (await selection()).text).toBe("name = 111;\nname = 222;\nname = 333;\nname = 444;");
|
||||
const points = await prepare();
|
||||
await page.mouse.move(points.from.x, points.from.y);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(points.to.x, points.to.y, { steps: 5 });
|
||||
await page.mouse.up();
|
||||
await expect.poll(async () => (await selection()).ranges).toEqual([text.slice(0, text.lastIndexOf("delta") + 5)]);
|
||||
});
|
||||
@@ -25,6 +25,7 @@
|
||||
"gen:django-grammar": "lezer-generator src/editor/core/cm/django/django.grammar --typeScript -o src/editor/core/cm/django/parser.ts",
|
||||
"gen:astro-grammar": "lezer-generator src/editor/core/cm/astro/astro.grammar --typeScript -o src/editor/core/cm/astro/parser.ts",
|
||||
"gen:theme-docs": "node scripts/theme/gen-docs.ts",
|
||||
"gen:plugin-catalog": "node scripts/gen-plugin-catalog.ts",
|
||||
"theme:import-intellij": "node scripts/theme/import-intellij-theme.ts",
|
||||
"dev:app": "node scripts/tauri.ts dev --config src-tauri/tauri.dev.conf.json",
|
||||
"dev:status": "node scripts/dev-status.ts",
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
// Writes docs/snippets/plugin-catalog.jsx, the snapshot of the plugin marketplace the
|
||||
// documentation site shows, from the release's plugins-index.json (or a local file).
|
||||
//
|
||||
// node scripts/gen-plugin-catalog.ts [index.json | url]
|
||||
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const OFFICIAL_INDEX = "https://github.com/l0ng-ai/openidea/releases/latest/download/plugins-index.json";
|
||||
const OUT = fileURLToPath(new URL("../docs/snippets/plugin-catalog.jsx", import.meta.url));
|
||||
|
||||
interface IndexPlugin {
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
description: string;
|
||||
publisher: string;
|
||||
categories?: string[];
|
||||
icon?: { light: string | null; dark: string | null } | null;
|
||||
homepage?: string | null;
|
||||
downloads?: number | null;
|
||||
}
|
||||
|
||||
interface Index {
|
||||
publishers: { id: string; name: string }[];
|
||||
plugins: IndexPlugin[];
|
||||
}
|
||||
|
||||
async function load(source: string): Promise<Index> {
|
||||
if (/^https?:\/\//.test(source)) {
|
||||
const res = await fetch(source);
|
||||
if (!res.ok) throw new Error(`${source}: HTTP ${res.status}`);
|
||||
return (await res.json()) as Index;
|
||||
}
|
||||
return JSON.parse(readFileSync(source, "utf8")) as Index;
|
||||
}
|
||||
|
||||
function compareVersions(a: string, b: string): number {
|
||||
const pa = a.split(/[.-]/).map(Number);
|
||||
const pb = b.split(/[.-]/).map(Number);
|
||||
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
||||
const d = (pa[i] || 0) - (pb[i] || 0);
|
||||
if (d) return d;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
const svgUri = (svg: string) => `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`;
|
||||
|
||||
function icon(p: IndexPlugin) {
|
||||
const light = p.icon?.light ?? p.icon?.dark;
|
||||
const dark = p.icon?.dark ?? p.icon?.light;
|
||||
if (!light || !dark) return null;
|
||||
return light === dark ? { light: svgUri(light) } : { light: svgUri(light), dark: svgUri(dark) };
|
||||
}
|
||||
|
||||
const index = await load(process.argv[2] ?? OFFICIAL_INDEX);
|
||||
const publishers = new Map(index.publishers.map((p) => [p.id, p.name]));
|
||||
|
||||
const latest = new Map<string, IndexPlugin>();
|
||||
for (const plugin of index.plugins) {
|
||||
const seen = latest.get(plugin.id);
|
||||
if (!seen || compareVersions(plugin.version, seen.version) > 0) latest.set(plugin.id, plugin);
|
||||
}
|
||||
|
||||
const plugins = [...latest.values()]
|
||||
// API examples document the plugin API; they are not offered to users here.
|
||||
.filter((p) => !/\(API Example\)$/.test(p.name))
|
||||
.map((p) => ({
|
||||
id: p.id,
|
||||
name: p.name,
|
||||
version: p.version,
|
||||
description: p.description,
|
||||
publisher: publishers.get(p.publisher) ?? p.publisher,
|
||||
official: p.publisher === "openidea",
|
||||
categories: p.categories?.length ? p.categories : ["other"],
|
||||
downloads: p.downloads ?? 0,
|
||||
homepage: p.homepage ?? null,
|
||||
icon: icon(p),
|
||||
}))
|
||||
.sort((a, b) => b.downloads - a.downloads || a.name.localeCompare(b.name));
|
||||
|
||||
const catalog = {
|
||||
generatedAt: new Date().toISOString().slice(0, 10),
|
||||
publishers: new Set(plugins.map((p) => p.publisher)).size,
|
||||
plugins,
|
||||
};
|
||||
|
||||
writeFileSync(
|
||||
OUT,
|
||||
`// Generated by scripts/gen-plugin-catalog.ts. Do not edit.\nexport const pluginCatalog = ${JSON.stringify(catalog)};\n`,
|
||||
);
|
||||
console.log(`${OUT}: ${plugins.length} plugins from ${catalog.publishers} publishers`);
|
||||
@@ -1,11 +1,11 @@
|
||||
//! The OS clipboard's file list, so the project view and Explorer exchange files.
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
|
||||
use crate::commands::doc::blocking;
|
||||
use ide_command::desktop_command;
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
use ide_core::IdeError;
|
||||
use ide_core::IdeResult;
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
|
||||
use ide_host::ops::doc::blocking;
|
||||
use std::path::{Path, PathBuf};
|
||||
use tauri::{AppHandle, WebviewWindow};
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::state::AppState;
|
||||
use ide_command::desktop_command;
|
||||
use ide_core::{IdeResult, RequestId};
|
||||
use ide_db::tools::{DbDumpKind, DbTool, DbToolJob, ToolInstall, ToolLine};
|
||||
use ide_db::tools::{DbTool, DbToolJob, DumpInfo, ToolInstall, ToolLine};
|
||||
use tauri::ipc::Channel;
|
||||
use tauri::{State, Window};
|
||||
|
||||
@@ -37,12 +37,20 @@ pub async fn db_tool_version(path: std::path::PathBuf) -> IdeResult<String> {
|
||||
ide_host::ops::doc::blocking(move || ide_db::tools::version_of(&path)).await
|
||||
}
|
||||
|
||||
/// What made the dump at `path` (from its first bytes), so a restore picks the right tool.
|
||||
/// The long options the executable at `path` lists in its `--help` (`masking-policies`…).
|
||||
#[desktop_command(trust = trusted)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn db_dump_kind(path: std::path::PathBuf) -> IdeResult<DbDumpKind> {
|
||||
ide_host::ops::doc::blocking(move || ide_db::tools::dump_kind(&path)).await
|
||||
pub async fn db_tool_options(path: std::path::PathBuf) -> IdeResult<Vec<String>> {
|
||||
ide_host::ops::doc::blocking(move || ide_db::tools::options_of(&path)).await
|
||||
}
|
||||
|
||||
/// What made the dump at `path` and whether it creates its own database (from its first bytes).
|
||||
#[desktop_command(trust = trusted)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn db_dump_info(path: std::path::PathBuf) -> IdeResult<DumpInfo> {
|
||||
ide_host::ops::doc::blocking(move || ide_db::tools::dump_info(&path)).await
|
||||
}
|
||||
|
||||
/// The command line `db_run_tool` would run, without the password.
|
||||
@@ -88,11 +96,12 @@ pub async fn db_server_version(window: Window, state: State<'_, AppState>, id: S
|
||||
}
|
||||
|
||||
ide_command::desktop_domain!(
|
||||
db_dump_kind,
|
||||
db_dump_info,
|
||||
db_export_file,
|
||||
db_run_tool,
|
||||
db_server_version,
|
||||
db_tool_installs,
|
||||
db_tool_options,
|
||||
db_tool_preview,
|
||||
db_tool_version,
|
||||
);
|
||||
@@ -396,6 +396,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("editor.toggleZen", "Enter Distraction Free Mode"),
|
||||
act("window.toggleFullScreen", "Toggle Full Screen"),
|
||||
toggle("view.toggleCompactMode", "Compact Mode"),
|
||||
toggle("view.togglePresentationAssistant", "Presentation Assistant"),
|
||||
SEP,
|
||||
act("view.zoomIn", "Zoom In IDE"),
|
||||
act("view.zoomOut", "Zoom Out IDE"),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# Generated by `pnpm gen:bindings`; do not edit. One line per command:
|
||||
# name, trust class, placement in a remote window, in bindings.ts, how Tauri runs it.
|
||||
agent_accept_changes trusted project_host bindings async
|
||||
agent_answer_question trusted project_host bindings async
|
||||
agent_archive always project_host bindings sync
|
||||
agent_base_text trusted project_host bindings async
|
||||
agent_cancel always project_host bindings sync
|
||||
@@ -96,7 +97,7 @@ db_database_catalog trusted project_host bin
|
||||
db_databases trusted project_host bindings async
|
||||
db_ddl trusted project_host bindings async
|
||||
db_disconnect trusted project_host bindings async
|
||||
db_dump_kind trusted desktop bindings async
|
||||
db_dump_info trusted desktop bindings async
|
||||
db_execute trusted project_host bindings async
|
||||
db_explain trusted project_host bindings async
|
||||
db_export_file always desktop bindings async
|
||||
@@ -123,6 +124,7 @@ db_tables trusted project_host bin
|
||||
db_test trusted project_host bindings async
|
||||
db_test_tunnel trusted project_host bindings async
|
||||
db_tool_installs trusted desktop bindings async
|
||||
db_tool_options trusted desktop bindings async
|
||||
db_tool_preview trusted desktop bindings sync
|
||||
db_tool_version trusted desktop bindings async
|
||||
db_trust_ssh_host trusted project_host bindings async
|
||||
|
||||
+87
-6
@@ -12,6 +12,8 @@ export const commands = {
|
||||
* local checkout, uncommitted; files the checkout changed itself are left alone and reported.
|
||||
*/
|
||||
agentAcceptChanges: (task: string, paths: string[] | null) => typedError<AgentAcceptOutcome, IdeError>(__TAURI_INVOKE("agent_accept_changes", { task, paths })),
|
||||
/** Answers a non-blocking question, without cancelling the current turn. */
|
||||
agentAnswerQuestion: (task: string, question: string, answer: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_answer_question", { task, question, answer })),
|
||||
agentArchive: (task: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_archive", { task })),
|
||||
/** Content of `path` when the task started (left side of its diff). */
|
||||
agentBaseText: (task: string, path: IpcPath) => typedError<string | null, IdeError>(__TAURI_INVOKE("agent_base_text", { task, path })),
|
||||
@@ -274,8 +276,8 @@ export const commands = {
|
||||
dbDatabases: (id: string) => typedError<DbDatabases, IdeError>(__TAURI_INVOKE("db_databases", { id })),
|
||||
dbDdl: (id: string, schema: string, table: string) => typedError<string, IdeError>(__TAURI_INVOKE("db_ddl", { id, schema, table })),
|
||||
dbDisconnect: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_disconnect", { id })),
|
||||
/** What made the dump at `path` (from its first bytes), so a restore picks the right tool. */
|
||||
dbDumpKind: (path: string) => typedError<DbDumpKind, IdeError>(__TAURI_INVOKE("db_dump_kind", { path })),
|
||||
/** What made the dump at `path` and whether it creates its own database (from its first bytes). */
|
||||
dbDumpInfo: (path: string) => typedError<DbDumpInfo, IdeError>(__TAURI_INVOKE("db_dump_info", { path })),
|
||||
dbExecute: (request: RequestId, id: string, statements: SqlStatement[], skip: number, maxRows: number, schema: string | null) => typedError<DbStatementOutcome[], IdeError>(__TAURI_INVOKE("db_execute", { request, id, statements, skip, maxRows, schema })),
|
||||
dbExplain: (request: RequestId, id: string, statement: string, schema: string | null) => typedError<DbPlanNode[], IdeError>(__TAURI_INVOKE("db_explain", { request, id, statement, schema })),
|
||||
/**
|
||||
@@ -316,6 +318,8 @@ export const commands = {
|
||||
dbTestTunnel: (source: DataSource_Deserialize, sshSecret: string | null) => typedError<string, IdeError>(__TAURI_INVOKE("db_test_tunnel", { source, sshSecret })),
|
||||
/** Installed copies of `tool`, newest first. */
|
||||
dbToolInstalls: (tool: DbTool) => typedError<DbToolInstall[], IdeError>(__TAURI_INVOKE("db_tool_installs", { tool })),
|
||||
/** The long options the executable at `path` lists in its `--help` (`masking-policies`…). */
|
||||
dbToolOptions: (path: string) => typedError<string[], IdeError>(__TAURI_INVOKE("db_tool_options", { path })),
|
||||
/** The command line `db_run_tool` would run, without the password. */
|
||||
dbToolPreview: (id: string, executable: string, job: DbToolJob) => typedError<string, IdeError>(__TAURI_INVOKE("db_tool_preview", { id, executable, job })),
|
||||
/** The version line of the executable at `path`. */
|
||||
@@ -811,6 +815,11 @@ export const commands = {
|
||||
selectionRange: Range,
|
||||
/** Call sites, for call hierarchy. */
|
||||
fromRanges: Range[],
|
||||
/**
|
||||
* The file of `from_ranges` when it is not the item's own: for an outgoing call, the
|
||||
* file of the prepared item that makes it (a path, or the URI of a virtual document).
|
||||
*/
|
||||
fromPath?: IpcPath | null,
|
||||
} | null, IdeError>(__TAURI_INVOKE("lsp_prepare_type_hierarchy", { doc, pos })),
|
||||
/**
|
||||
* References of the symbol at `pos`. `project_wide` also searches project files
|
||||
@@ -2130,7 +2139,11 @@ sentMs?: number | null;
|
||||
/** When the turn it started ended; `None` while it runs or when it was cut off. */
|
||||
doneMs?: number | null;
|
||||
/** Sent into a running turn rather than starting one. */
|
||||
steered?: boolean } | { type: "agent"; text: string } | { type: "thought"; text: string } | { type: "tool"; id: string; title: string;
|
||||
steered?: boolean } | { type: "agent"; text: string } |
|
||||
/** A question that can be answered while the agent keeps working, or after the turn ends. */
|
||||
{ type: "question"; id: string; title: string; questions: AgentQuestion[];
|
||||
/** The submitted answers, or `Skipped`; `None` while unanswered. */
|
||||
chosen: string | null } | { type: "thought"; text: string } | { type: "tool"; id: string; title: string;
|
||||
/** ACP tool kind: `read`, `edit`, `execute`, `search`, `fetch`, `think`… */
|
||||
kind: string; status: AgentToolStatus; locations: IpcPath[];
|
||||
/** Text the tool reported (command output…), truncated. */
|
||||
@@ -2812,6 +2825,8 @@ export type AppearanceSettings_Deserialize = {
|
||||
mainToolbar?: MainToolbarSettings | null,
|
||||
/** Appearance › Background Image: an image shown through the IDE window. */
|
||||
backgroundImage?: BackgroundImageSettings,
|
||||
/** Appearance › Presentation Assistant: the name and shortcut of each action run. */
|
||||
presentationAssistant?: PresentationAssistantSettings,
|
||||
};
|
||||
|
||||
export type AppearanceSettings_Serialize = {
|
||||
@@ -2881,6 +2896,8 @@ export type AppearanceSettings_Serialize = {
|
||||
mainToolbar: MainToolbarSettings | null,
|
||||
/** Appearance › Background Image: an image shown through the IDE window. */
|
||||
backgroundImage: BackgroundImageSettings,
|
||||
/** Appearance › Presentation Assistant: the name and shortcut of each action run. */
|
||||
presentationAssistant: PresentationAssistantSettings,
|
||||
};
|
||||
|
||||
export type ApplyOutcome = {
|
||||
@@ -3183,6 +3200,8 @@ export type CMakeSettings_Serialize = {
|
||||
};
|
||||
|
||||
export type CallHierarchy = {
|
||||
/** The symbol the hierarchy is for: the first item the server prepared at the position. */
|
||||
root?: HierarchyItem | null,
|
||||
items: HierarchyItem[],
|
||||
incomplete: ReferencesIncomplete | null,
|
||||
};
|
||||
@@ -4170,13 +4189,23 @@ export type DbDumpFormat =
|
||||
/** A directory of files; the only format `pg_dump` writes in parallel. */
|
||||
"directory" | "tar";
|
||||
|
||||
/** What a restore needs to know about a dump before it runs. */
|
||||
export type DbDumpInfo = {
|
||||
kind: DbDumpKind,
|
||||
/**
|
||||
* An SQL dump that runs `CREATE DATABASE` itself: `mysqldump --databases` / `--all-databases`,
|
||||
* or `pg_dump --create`. Archives say `false`; `pg_restore --create` decides for them.
|
||||
*/
|
||||
createsDatabase: boolean,
|
||||
};
|
||||
|
||||
/** What made a dump, read from its first bytes (a directory: its `toc.dat`). */
|
||||
export type DbDumpKind =
|
||||
/** `pg_dump` custom or tar archive, or a directory archive: `pg_restore`. */
|
||||
"postgresArchive" |
|
||||
/** Plain SQL from `pg_dump`: `psql`. */
|
||||
"postgresSql" |
|
||||
/** `mysqldump` / `mariadb-dump`: not for the PostgreSQL tools. */
|
||||
/** `mysqldump` / `mariadb-dump`: `mysql`. */
|
||||
"mysqlSql" | "unknown";
|
||||
|
||||
export type DbDumpStatements = "copy" | "inserts" | "columnInserts";
|
||||
@@ -4220,6 +4249,36 @@ export type DbIntrospection = {
|
||||
objectFilter?: string,
|
||||
};
|
||||
|
||||
export type DbMysqlOptions = {
|
||||
/** Empty: the databases the dump names. */
|
||||
database: string,
|
||||
/** Runs the remaining statements after an error. */
|
||||
force: boolean,
|
||||
};
|
||||
|
||||
/** Switches that `mysqldump` turns on by default (`--opt`) only take a flag when turned off. */
|
||||
export type DbMysqldumpOptions = {
|
||||
/** Empty: every database. */
|
||||
databases: string[],
|
||||
/** Only with exactly one database. */
|
||||
tables: string[],
|
||||
addDropTable: boolean,
|
||||
disableKeys: boolean,
|
||||
addLocks: boolean,
|
||||
addDropTrigger: boolean,
|
||||
noData: boolean,
|
||||
completeInsert: boolean,
|
||||
createOptions: boolean,
|
||||
routines: boolean,
|
||||
events: boolean,
|
||||
/** A consistent InnoDB snapshot without locks; needs no RELOAD privilege. */
|
||||
singleTransaction: boolean,
|
||||
/** Wins over `single_transaction`. */
|
||||
lockAllTables: boolean,
|
||||
/** `None`: the client has no `--masking-policies`. */
|
||||
maskingPolicies: boolean | null,
|
||||
};
|
||||
|
||||
/** Schema objects other than tables and columns (Go to DDL, Drop). */
|
||||
export type DbObjectKind = "function" | "procedure" | "package" | "trigger" | "sequence";
|
||||
|
||||
@@ -4266,6 +4325,8 @@ export type DbPgDumpOptions = {
|
||||
export type DbPgRestoreOptions = {
|
||||
content: DbDumpContent,
|
||||
schemas: string[],
|
||||
/** Creates the database the archive names; the target is only connected to. */
|
||||
create: boolean,
|
||||
clean: boolean,
|
||||
ifExists: boolean,
|
||||
noOwner: boolean,
|
||||
@@ -4462,7 +4523,7 @@ export type DbTablePage = {
|
||||
offset: number | null,
|
||||
};
|
||||
|
||||
export type DbTool = "pgDump" | "pgRestore" | "psql";
|
||||
export type DbTool = "pgDump" | "pgRestore" | "psql" | "mysqldump" | "mysql";
|
||||
|
||||
/** An installed copy of a tool. */
|
||||
export type DbToolInstall = {
|
||||
@@ -4474,7 +4535,9 @@ export type DbToolInstall = {
|
||||
/** A run of a client tool: which one, the file it writes or reads, and its options. */
|
||||
export type DbToolJob = { tool: "pgDump"; file: string; options: DbPgDumpOptions } |
|
||||
/** `file`: an archive, or a directory archive. */
|
||||
{ tool: "pgRestore"; file: string; options: DbPgRestoreOptions } | { tool: "psql"; file: string; options: DbPsqlOptions };
|
||||
{ tool: "pgRestore"; file: string; options: DbPgRestoreOptions } | { tool: "psql"; file: string; options: DbPsqlOptions } | { tool: "mysqldump"; file: string; options: DbMysqldumpOptions } |
|
||||
/** `file` goes to the standard input. */
|
||||
{ tool: "mysql"; file: string; options: DbMysqlOptions };
|
||||
|
||||
/** A line the tool wrote. */
|
||||
export type DbToolLine = {
|
||||
@@ -6416,6 +6479,11 @@ export type HierarchyItem = {
|
||||
selectionRange: Range,
|
||||
/** Call sites, for call hierarchy. */
|
||||
fromRanges: Range[],
|
||||
/**
|
||||
* The file of `from_ranges` when it is not the item's own: for an outgoing call, the
|
||||
* file of the prepared item that makes it (a path, or the URI of a virtual document).
|
||||
*/
|
||||
fromPath?: IpcPath | null,
|
||||
};
|
||||
|
||||
export type HierarchyMember = {
|
||||
@@ -9213,6 +9281,19 @@ export type PreparedRequest = {
|
||||
body: string | null,
|
||||
};
|
||||
|
||||
/** Appearance › Presentation Assistant: shows the name and shortcut of each action the user runs. */
|
||||
export type PresentationAssistantSettings = {
|
||||
enabled?: boolean,
|
||||
/** `small` | `medium` | `large`. */
|
||||
size?: string,
|
||||
/** How long each popup stays, in seconds. */
|
||||
durationSeconds?: number,
|
||||
/** `top-left`, `top`, `top-right`, `bottom-left`, `bottom` or `bottom-right` of the window. */
|
||||
position?: string,
|
||||
/** Also show the shortcut of the other platform's keymap (macOS ⇄ Windows/Linux). */
|
||||
alternateKeymap?: boolean,
|
||||
};
|
||||
|
||||
export type ProblemSeverity = "info" | "warning" | "error" |
|
||||
/** The refactoring can't run at all; there is no edit. */
|
||||
"fatal";
|
||||
|
||||
@@ -917,6 +917,16 @@ export function registerEditorActions(): () => void {
|
||||
// The mouse selection style handles the pointer position and dragging.
|
||||
run: () => {},
|
||||
},
|
||||
{
|
||||
id: "editor.createRectangularSelectionOnMouseDrag",
|
||||
title: "Create Rectangular Selection on Mouse Drag",
|
||||
category: "Editor Actions",
|
||||
when: "textEditorActive",
|
||||
hidden: true,
|
||||
keymap: true,
|
||||
// The mouse selection style owns the drag; invoking the action alone is harmless.
|
||||
run: () => {},
|
||||
},
|
||||
text("editor.cloneCaretAbove", "Clone Caret Above", (v) => cloneCaretAbove(v), { category: "Editor Actions" }),
|
||||
text("editor.cloneCaretBelow", "Clone Caret Below", (v) => cloneCaretBelow(v), { category: "Editor Actions" }),
|
||||
text("editor.matchBrace", "Move Caret to Matching Brace", (v) => cursorMatchBrace(v), {
|
||||
|
||||
@@ -82,3 +82,52 @@ describe("caret mouse bindings", () => {
|
||||
expect(styles(event({ button: 1, altKey: false }))[1]).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("rectangular mouse bindings", () => {
|
||||
const id = "editor.createRectangularSelectionOnMouseDrag";
|
||||
|
||||
it.each(Object.keys(PRESETS))("%s exposes both default gestures", (preset) => {
|
||||
useKeymap.setState({ preset });
|
||||
expect(PRESETS[preset]![id]).toEqual(["Alt+Button1", "Button2"]);
|
||||
expect(styles(event())[1]).not.toBeNull();
|
||||
expect(styles(event({ button: 1, altKey: false }))[1]).not.toBeNull();
|
||||
});
|
||||
|
||||
it("uses the full rebound stroke immediately instead of the old defaults", () => {
|
||||
useKeymap.setState({ overrides: { [id]: ["ctrl+alt+shift+button1"] } });
|
||||
expect(styles(event())[1]).toBeNull();
|
||||
expect(styles(event({ button: 1, altKey: false }))[1]).toBeNull();
|
||||
expect(styles(event({ ctrlKey: true, shiftKey: true }))[1]).not.toBeNull();
|
||||
expect(styles(event({ ctrlKey: true, shiftKey: true, metaKey: true }))[1]).toBeNull();
|
||||
});
|
||||
|
||||
it("honours removal and restoration without changing the column mode", () => {
|
||||
useKeymap.setState({ overrides: { [id]: [] } });
|
||||
expect(styles(event())[1]).toBeNull();
|
||||
expect(styles(event({ button: 1, altKey: false }))[1]).toBeNull();
|
||||
useKeymap.setState({ overrides: {} });
|
||||
expect(styles(event())[1]).not.toBeNull();
|
||||
});
|
||||
|
||||
it("keeps Linux middle paste by default but accepts an explicit middle binding", () => {
|
||||
usePlatform.setState({ os: "linux" });
|
||||
expect(styles(event())[1]).not.toBeNull();
|
||||
expect(styles(event({ button: 1, altKey: false }))[1]).toBeNull();
|
||||
useKeymap.setState({ overrides: { [id]: ["Button2"] } });
|
||||
expect(styles(event({ button: 1, altKey: false }))[1]).not.toBeNull();
|
||||
expect(styles(event())[1]).toBeNull();
|
||||
});
|
||||
|
||||
it("leaves a shared stroke to the add-caret gesture", () => {
|
||||
useKeymap.setState({ overrides: { [id]: ["Alt+Shift+Button1"] } });
|
||||
const [caret, rectangle] = styles(event({ shiftKey: true }));
|
||||
expect(caret).not.toBeNull();
|
||||
expect(rectangle).toBeNull();
|
||||
});
|
||||
|
||||
it("does not claim right or side buttons", () => {
|
||||
useKeymap.setState({ overrides: { [id]: ["Alt+Button3", "Alt+Button4"] } });
|
||||
expect(styles(event({ button: 2 }))[1]).toBeNull();
|
||||
expect(styles(event({ button: 3 }))[1]).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,7 @@
|
||||
/** Mouse caret gestures follow the keymap; Alt and middle-button drags select columns. */
|
||||
/** Mouse caret and rectangular selection gestures follow the keymap. */
|
||||
import { EditorSelection, type Extension } from "@codemirror/state";
|
||||
import { EditorView, type MouseSelectionStyle } from "@codemirror/view";
|
||||
import { bindingsFor, mouseStrokeOf, normalizeBinding } from "@/platform/keymap";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { blockMouseSelection } from "./columnMode";
|
||||
|
||||
/** The selection after a caret click / drag from `anchor` to `head` on top of `start`. */
|
||||
@@ -25,6 +24,15 @@ export function isAddCaretGesture(event: MouseEvent): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
export function isRectangularSelectionGesture(event: MouseEvent): boolean {
|
||||
if ((event.button !== 0 && event.button !== 1) || isAddCaretGesture(event)) return false;
|
||||
const stroke = mouseStrokeOf(event);
|
||||
return (
|
||||
stroke !== null &&
|
||||
bindingsFor("editor.createRectangularSelectionOnMouseDrag").some((binding) => normalizeBinding(binding) === stroke)
|
||||
);
|
||||
}
|
||||
|
||||
const addCaretStyle = EditorView.mouseSelectionStyle.of((view, event): MouseSelectionStyle | null => {
|
||||
if (!isAddCaretGesture(event)) return null;
|
||||
let start = view.state.selection;
|
||||
@@ -44,9 +52,5 @@ export const multiCaretMouse: Extension = [
|
||||
addCaretStyle,
|
||||
// CodeMirror's default (⌘click) would clash with ⌘click navigation.
|
||||
EditorView.clickAddsSelectionRange.of(() => false),
|
||||
blockMouseSelection((e) => {
|
||||
if (isAddCaretGesture(e) || e.shiftKey || e.metaKey || e.ctrlKey) return false;
|
||||
if (e.button === 0) return e.altKey;
|
||||
return e.button === 1 && !e.altKey && usePlatform.getState().os !== "linux";
|
||||
}),
|
||||
blockMouseSelection(isRectangularSelectionGesture),
|
||||
];
|
||||
@@ -290,11 +290,14 @@
|
||||
.docBody {
|
||||
padding: 10px 14px;
|
||||
}
|
||||
/* Go signatures: a type name opens its documentation (`linkSignatureTypes` in docs.ts). */
|
||||
.docBody :global(.cm-lsp-markdown > pre:first-of-type > code.language-go .tok-typeName) {
|
||||
/* Signatures: a type name opens its documentation (`linkSignatureTypes` in docs.ts); other
|
||||
languages' names look like links once they are found to lead somewhere. */
|
||||
.docBody :global(.cm-lsp-markdown > pre:first-of-type > code.language-go .tok-typeName),
|
||||
.docBody :global(.cm-lsp-markdown [data-doc-ref]) {
|
||||
cursor: pointer;
|
||||
}
|
||||
.docBody :global(.cm-lsp-markdown > pre:first-of-type > code.language-go .tok-typeName:hover) {
|
||||
.docBody :global(.cm-lsp-markdown > pre:first-of-type > code.language-go .tok-typeName:hover),
|
||||
.docBody :global(.cm-lsp-markdown [data-doc-ref]:hover) {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.defPopup {
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { Location, Pos } from "@/bindings";
|
||||
|
||||
const at = (path: string, line: number, col = 0): Location => ({
|
||||
path,
|
||||
range: { start: { line, col }, end: { line, col } },
|
||||
});
|
||||
|
||||
const LIB = "/w/src/lib.rs";
|
||||
const files: Record<string, string[]> = {
|
||||
[LIB]: [
|
||||
"use crate::model::Item;",
|
||||
"",
|
||||
"/// Takes the items.",
|
||||
"pub fn take(items: Vec<Item>,",
|
||||
" on: Clock) -> Inventory { // an Order list",
|
||||
" Order::all(items)",
|
||||
"}",
|
||||
],
|
||||
"/w/src/c.ts": ["/** Note: Item is re-read. */", "export function f(x: Item): void {}"],
|
||||
};
|
||||
// What the server answers per `path:line:col`.
|
||||
const defs: Record<string, Location[]> = {
|
||||
[`${LIB}:3:7`]: [at(LIB, 3, 7)], // take
|
||||
[`${LIB}:3:12`]: [at(LIB, 3, 12)], // items: the parameter
|
||||
[`${LIB}:3:19`]: [at("/rust/library/alloc/src/vec/mod.rs", 396, 11)], // Vec
|
||||
[`${LIB}:3:23`]: [at("/w/src/model.rs", 4, 11)], // Item
|
||||
[`${LIB}:4:8`]: [at("/w/src/clock.rs", 1, 11), at("/w/src/clock2.rs", 1, 11)], // Clock: two places
|
||||
[`${LIB}:4:18`]: [at("/w/src/inventory.rs", 2, 11)], // Inventory
|
||||
[`${LIB}:5:4`]: [at("/w/src/order.rs", 2, 11)], // Order, in the body
|
||||
"/w/src/c.ts:1:21": [at("/w/src/item.ts", 0, 17)], // Item; the comment's has no definition
|
||||
};
|
||||
|
||||
let file = "";
|
||||
vi.mock("../files", () => ({
|
||||
readFileLines: async (p: string) => files[p] ?? null,
|
||||
withDocument: async <T>(p: string, fn: (doc: number) => Promise<T>) => ((file = p), fn(1)),
|
||||
}));
|
||||
vi.mock("../lsp", () => ({ lspRequest: <T>(run: () => Promise<T>) => run() }));
|
||||
vi.mock("@/platform/ipc", () => ({
|
||||
commands: { lspGoto: async (_doc: number, pos: Pos) => defs[`${file}:${pos.line}:${pos.col}`] ?? [] },
|
||||
}));
|
||||
|
||||
const { signatureNameTarget } = await import("./signature");
|
||||
|
||||
describe("names in a signature", () => {
|
||||
it.each([
|
||||
["a type from another file", "Item", { path: "/w/src/model.rs", line: 4, col: 11 }],
|
||||
["a library type", "Vec", { path: "/rust/library/alloc/src/vec/mod.rs", line: 396, col: 11 }],
|
||||
["a wrapped parameter's type", "Inventory", { path: "/w/src/inventory.rs", line: 2, col: 11 }],
|
||||
["a parameter", "items", null],
|
||||
["the symbol itself", "take", null],
|
||||
["defined in two places", "Clock", null],
|
||||
["inferred: not in the source", "Option", null],
|
||||
["not a name", "a.b", null],
|
||||
])("%s", async (_, name, want) => {
|
||||
expect(await signatureNameTarget(at(LIB, 3, 7), name, 1)).toEqual(want);
|
||||
});
|
||||
|
||||
it("asks only near the declaration", async () => {
|
||||
expect(await signatureNameTarget(at(LIB, 3, 7), "Order", 1)).toEqual({ path: "/w/src/order.rs", line: 2, col: 11 });
|
||||
expect(await signatureNameTarget(at(LIB, 0, 0), "Order", -9)).toBeNull();
|
||||
});
|
||||
|
||||
it("skips an occurrence the server has no definition for (a comment)", async () => {
|
||||
expect(await signatureNameTarget(at("/w/src/c.ts", 0), "Item", 1)).toEqual({
|
||||
path: "/w/src/item.ts",
|
||||
line: 0,
|
||||
col: 17,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Names in a signature, for languages without their own rule (Go has `go.ts`): the name is
|
||||
* looked up in the documented symbol's declaration, in its source, and the language server's
|
||||
* definition of it there is the target. A name the source doesn't spell (an inferred type)
|
||||
* or one declared by the declaration itself (a parameter, a type parameter, the symbol's own
|
||||
* name) leads nowhere; so does a definition the server finds in several places.
|
||||
*/
|
||||
import { commands, type Location } from "@/platform/ipc";
|
||||
import { readFileLines, withDocument } from "../files";
|
||||
import { lspRequest } from "../lsp";
|
||||
import { unique, type DocTarget } from "./symbols";
|
||||
|
||||
const NAME = /^[\p{L}_$][\p{L}\p{N}_$]*$/u;
|
||||
/** Lines the declaration may take in its source beyond the signature's own (wrapped parameters, attributes). */
|
||||
const SLACK = 10;
|
||||
|
||||
/** Where `name`, written in the signature (`lines` long) of the symbol declared at `decl`, is declared. */
|
||||
export async function signatureNameTarget(decl: Location, name: string, lines: number): Promise<DocTarget | null> {
|
||||
if (!NAME.test(name)) return null;
|
||||
const text = await readFileLines(decl.path).catch(() => null);
|
||||
if (!text) return null;
|
||||
const first = decl.range.start.line;
|
||||
const last = Math.min(text.length, first + lines + SLACK);
|
||||
// A preceding non-name character, not a lookbehind: WebKit before 16.4 can't parse one.
|
||||
const word = new RegExp(`(^|[^\\p{L}\\p{N}_$])${name.replace(/\$/g, "\\$")}(?![\\p{L}\\p{N}_$])`, "gu");
|
||||
const inside = (l: Location) => l.path === decl.path && l.range.start.line >= first && l.range.start.line < last;
|
||||
return withDocument(decl.path, async (doc) => {
|
||||
for (let line = first; line < last; line++) {
|
||||
for (const m of text[line]!.matchAll(word)) {
|
||||
const locs = await lspRequest(() =>
|
||||
commands.lspGoto(doc, { line, col: m.index + m[1]!.length }, "definition"),
|
||||
).catch(() => []);
|
||||
// Nothing here: a comment or a string; the next occurrence may be the name itself.
|
||||
if (!locs.length) continue;
|
||||
return locs.some(inside) ? null : unique(locs.map((location) => ({ location })));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/** `workspace/symbol` lookups shared by the per-language documentation link rules. */
|
||||
import { call, commands, nextRequestId, type WorkspaceSymbol } from "@/platform/ipc";
|
||||
import { call, commands, nextRequestId, type Location, type WorkspaceSymbol } from "@/platform/ipc";
|
||||
|
||||
export interface DocTarget {
|
||||
path: string;
|
||||
@@ -12,7 +12,7 @@ export async function symbols(query: string): Promise<WorkspaceSymbol[]> {
|
||||
}
|
||||
|
||||
/** The one place `hits` name (the same place listed twice counts once); null when none or several. */
|
||||
export function unique(hits: WorkspaceSymbol[]): DocTarget | null {
|
||||
export function unique(hits: { location: Location }[]): DocTarget | null {
|
||||
const places = new Map(
|
||||
hits.map((s) => {
|
||||
const { path, range } = s.location;
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent } from "@testing-library/react";
|
||||
|
||||
const signatureNameTarget = vi.fn(async (_decl: unknown, name: string, _lines: number) =>
|
||||
name === "Item" ? { path: "/w/src/model.rs", line: 4, col: 11 } : null,
|
||||
);
|
||||
vi.mock("./docLinks/signature", () => ({ signatureNameTarget }));
|
||||
|
||||
const { linkSignatureTypes } = await import("./docs");
|
||||
|
||||
describe("signature names", () => {
|
||||
it("resolve in the signature blocks only, and look like links once they lead somewhere", async () => {
|
||||
const dom = document.createElement("div");
|
||||
// rust-analyzer: module path, signature, rule, docs with an example.
|
||||
dom.innerHTML =
|
||||
'<pre><code class="language-rust">inventory</code></pre>' +
|
||||
'<pre><code class="language-rust">pub fn take(<span class="tok-variableName tok-definition">items</span>: ' +
|
||||
'<span class="tok-typeName">Vec</span><<span class="tok-typeName">Item</span>>)</code></pre>' +
|
||||
'<hr><p>Takes them.</p><pre><code class="language-rust"><span class="tok-typeName">Item</span></code></pre>';
|
||||
const decl = { path: "/w/src/lib.rs", range: { start: { line: 3, col: 7 }, end: { line: 3, col: 11 } } };
|
||||
linkSignatureTypes(dom, "window", {
|
||||
markup: { kind: "markdown", value: "" },
|
||||
language: null,
|
||||
source: async () => decl,
|
||||
});
|
||||
const [items, vec, item, example] = [...dom.querySelectorAll("span")];
|
||||
for (const el of [items!, vec!, item!, example!]) fireEvent.mouseOver(el);
|
||||
await vi.waitFor(() => expect(item!.hasAttribute("data-doc-ref")).toBe(true));
|
||||
expect(vec!.hasAttribute("data-doc-ref")).toBe(false);
|
||||
expect(signatureNameTarget.mock.calls.map((c) => c[1])).toEqual(["Vec", "Item"]);
|
||||
expect(signatureNameTarget).toHaveBeenCalledWith(decl, "Item", 1);
|
||||
});
|
||||
|
||||
it("include the block closing the documentation after a rule (clangd)", async () => {
|
||||
signatureNameTarget.mockClear();
|
||||
const dom = document.createElement("div");
|
||||
dom.innerHTML =
|
||||
"<h3>function take</h3><hr><p>Takes them.</p><hr>" +
|
||||
'<pre><code class="language-cpp">void take(<span class="tok-typeName">Item</span> i)</code></pre>';
|
||||
const decl = { path: "/w/take.cpp", range: { start: { line: 1, col: 5 }, end: { line: 1, col: 9 } } };
|
||||
linkSignatureTypes(dom, "window", {
|
||||
markup: { kind: "markdown", value: "" },
|
||||
language: null,
|
||||
source: async () => decl,
|
||||
});
|
||||
fireEvent.mouseOver(dom.querySelector("span")!);
|
||||
await vi.waitFor(() => expect(dom.querySelector("[data-doc-ref]")?.textContent).toBe("Item"));
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,7 @@ import { closePopup, updatePopup, useLspPopup, type DocEntry } from "./popupStor
|
||||
import { isEmptyMarkup, languageForPath, openDocLink, sourceLink, type DocLinkHandler } from "./markdown";
|
||||
import { resolveGoRef, signatureRef } from "./docLinks/go";
|
||||
import { docUrlResolver } from "./docLinks";
|
||||
import { signatureNameTarget } from "./docLinks/signature";
|
||||
import type { DocTarget } from "./docLinks/symbols";
|
||||
import { lspRequest } from "./lsp";
|
||||
import { readFileLines, withDocument } from "./files";
|
||||
@@ -231,16 +232,64 @@ export function docLinkHandler(host: DocHost): DocLinkHandler {
|
||||
|
||||
/** The signature block of gopls documentation, whose type names `linkSignatureTypes` follows. */
|
||||
const GO_SIGNATURE = ":scope > pre:first-of-type > code.language-go";
|
||||
/** Names in other languages' signatures worth asking about (grammars without type names tag them as variables). */
|
||||
const SIGNATURE_NAME = ".tok-typeName, .tok-className, .tok-variableName:not(.tok-definition), .tok-name";
|
||||
|
||||
/**
|
||||
* Go: a click on a type name in the signature shows that type's documentation
|
||||
* in the same view, when the name resolves to exactly one declaration.
|
||||
* The signature code block `el` is in: the code blocks that open the documentation
|
||||
* (rust-analyzer's module path and signature, others' signature) or the one closing it
|
||||
* after a rule (clangd); not the examples in between.
|
||||
*/
|
||||
function signatureBlock(dom: HTMLElement, el: Element): HTMLElement | null {
|
||||
const pre = el.closest("pre");
|
||||
if (!pre || pre.parentElement !== dom) return null;
|
||||
const blocks = [...dom.children];
|
||||
const i = blocks.indexOf(pre);
|
||||
const leading = blocks.slice(0, i).every((b) => b.tagName === "PRE");
|
||||
const closing = i === blocks.length - 1 && blocks[i - 1]?.tagName === "HR";
|
||||
return leading || closing ? pre : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A click on a type name in the signature shows that type's documentation in the same view,
|
||||
* when the name resolves to exactly one declaration. Go resolves by its imports; other
|
||||
* languages ask the server where the name is declared, resolving a name once the pointer is
|
||||
* over it so only the names that lead somewhere look like links.
|
||||
*/
|
||||
export function linkSignatureTypes(dom: HTMLElement, host: DocHost, entry: DocEntry) {
|
||||
const refs = new WeakMap<Element, Promise<DocTarget | null>>();
|
||||
const nameAt = (e: Event) => {
|
||||
const name = (e.target as Element | null)?.closest?.(SIGNATURE_NAME);
|
||||
const block = name && signatureBlock(dom, name);
|
||||
return name && block && !block.querySelector("code.language-go") ? { name, block } : null;
|
||||
};
|
||||
const resolve = (name: Element, block: HTMLElement) => {
|
||||
let ref = refs.get(name);
|
||||
if (!ref) {
|
||||
ref = (async () => {
|
||||
const decl = await entry.source?.().catch(() => null);
|
||||
const lines = (block.textContent ?? "").trimEnd().split("\n").length;
|
||||
return decl ? signatureNameTarget(decl, name.textContent ?? "", lines) : null;
|
||||
})().catch(() => null);
|
||||
refs.set(name, ref);
|
||||
void ref.then((t) => t && name.setAttribute("data-doc-ref", ""));
|
||||
}
|
||||
return ref;
|
||||
};
|
||||
dom.addEventListener("mouseover", (e) => {
|
||||
const at = nameAt(e);
|
||||
if (at) void resolve(at.name, at.block);
|
||||
});
|
||||
dom.addEventListener("click", (e) => {
|
||||
if (!document.getSelection()?.isCollapsed) return;
|
||||
const at = nameAt(e);
|
||||
if (at) {
|
||||
void resolve(at.name, at.block).then((t) => t && followTo(host, t));
|
||||
return;
|
||||
}
|
||||
const name = (e.target as Element | null)?.closest?.(".tok-typeName");
|
||||
const code = dom.querySelector(GO_SIGNATURE);
|
||||
if (!name || !code?.contains(name) || !document.getSelection()?.isCollapsed) return;
|
||||
if (!name || !code?.contains(name)) return;
|
||||
const before = document.createRange();
|
||||
before.setStart(code, 0);
|
||||
before.setEndBefore(name);
|
||||
|
||||
@@ -52,6 +52,17 @@ describe("markdown rendering", () => {
|
||||
expect(el.querySelector("img")?.getAttribute("onerror")).toBeNull();
|
||||
});
|
||||
|
||||
it("puts the names a grammar can't parse in spans too (signature links find them)", async () => {
|
||||
const md = await freshMarkdown();
|
||||
await md.loadMarkdown();
|
||||
const el = md.renderMarkup({
|
||||
kind: "markdown",
|
||||
value: "```typescript\n(method) Cart.add(product: Product, quantity?: number): Cart\n```",
|
||||
});
|
||||
await vi.waitFor(() => expect(el.querySelector(".tok-name")?.textContent).toBe("Product"));
|
||||
expect(el.querySelector("code")?.textContent).toBe("(method) Cart.add(product: Product, quantity?: number): Cart");
|
||||
});
|
||||
|
||||
it("renders synchronously once loaded", async () => {
|
||||
const md = await freshMarkdown();
|
||||
await md.loadMarkdown();
|
||||
|
||||
@@ -192,10 +192,28 @@ function highlightBlocks(root: HTMLElement, fallback: string | null) {
|
||||
const lang = cls ? cls.slice("language-".length) : fallback;
|
||||
const text = (code.textContent ?? "").replace(/\n+$/, "");
|
||||
code.textContent = text;
|
||||
void highlightInto(code, text, lang);
|
||||
void highlightInto(code, text, lang).then(() => wrapPlainNames(code));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the names a grammar left as plain text in spans (`.tok-name`), as the ones it
|
||||
* recognised are, so a signature's names can be followed (`linkSignatureTypes` in docs.ts):
|
||||
* signatures aren't always code a grammar parses (`(method) Cart.add(product: Product)`).
|
||||
*/
|
||||
function wrapPlainNames(code: HTMLElement) {
|
||||
for (const node of [...code.childNodes]) {
|
||||
if (node.nodeType !== Node.TEXT_NODE) continue;
|
||||
const parts = (node.textContent ?? "").split(/([\p{L}_$][\p{L}\p{N}_$]*)/u);
|
||||
if (parts.length < 2) continue;
|
||||
node.replaceWith(
|
||||
...parts.map((p, i) =>
|
||||
i % 2 ? Object.assign(document.createElement("span"), { className: "tok-name", textContent: p }) : p,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** A documentation link to a source position (`file://…#L12,5`, `jdt://…#L42`); null for web links. */
|
||||
export function sourceLink(href: string): { path: string; line: number; col: number } | null {
|
||||
if (href.startsWith("file://")) {
|
||||
|
||||
@@ -57,7 +57,7 @@ import { executeAction } from "@/platform/actions";
|
||||
import { basename, relativePath, useProject } from "@/platform/project";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { fileIconName } from "@/ui";
|
||||
import { NO_SERVER, debounce, docOf, isUnavailable, lspRequest, reportLspError } from "./lsp";
|
||||
import { NO_SERVER, debounce, docOf, isUnavailable, lspDoc, lspRequest, reportLspError } from "./lsp";
|
||||
import { offsetToPos, rangeContains, rangeToOffsets } from "./positions";
|
||||
import {
|
||||
SYNTAX_NOTE,
|
||||
@@ -89,7 +89,7 @@ import { projectPythonHierarchy, pythonImplementationTargets } from "@/editor/na
|
||||
import { importBindings } from "@/editor/navigation/inheritanceGraph";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { isVirtualUri, virtualContainer } from "@/platform/virtualDocs";
|
||||
import { isAddCaretGesture } from "@/editor/core/cm/multiCaret";
|
||||
import { isAddCaretGesture, isRectangularSelectionGesture } from "@/editor/core/cm/multiCaret";
|
||||
import { dispatchMouseShortcut, shortcutLabel } from "@/platform/keymap";
|
||||
import { isNavigationGesture, onNavigationModifier, navigationModifierHeld } from "@/platform/navigationModifier";
|
||||
import { create } from "zustand";
|
||||
@@ -921,6 +921,8 @@ const linkPlugin = ViewPlugin.fromClass(
|
||||
private hovered: string | null = null;
|
||||
private probeVersion = 0;
|
||||
private probeTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
private middleClickVersion = 0;
|
||||
private stopMiddleClick: (() => void) | null = null;
|
||||
constructor(readonly view: EditorView) {
|
||||
// Window-wide, so ⌘/Ctrl over an unfocused editor underlines too; released anywhere clears it.
|
||||
const offModifier = onNavigationModifier((held) => {
|
||||
@@ -949,12 +951,87 @@ const linkPlugin = ViewPlugin.fromClass(
|
||||
};
|
||||
}
|
||||
destroy() {
|
||||
this.cancelMiddleClick();
|
||||
this.off();
|
||||
this.offProviders();
|
||||
this.disposed = true;
|
||||
this.probeVersion++;
|
||||
clearTimeout(this.probeTimer);
|
||||
}
|
||||
update(update: ViewUpdate) {
|
||||
if (update.docChanged || update.startState.facet(lspDoc) !== update.state.facet(lspDoc)) this.cancelMiddleClick();
|
||||
}
|
||||
cancelMiddleClick() {
|
||||
this.middleClickVersion++;
|
||||
this.stopMiddleClick?.();
|
||||
}
|
||||
startMiddleClick(event: MouseEvent) {
|
||||
const view = this.view;
|
||||
const pos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
|
||||
if (pos == null) return;
|
||||
const source = view.state.doc;
|
||||
const context = docOf(view);
|
||||
const selection = view.state.selection;
|
||||
const version = this.middleClickVersion;
|
||||
const doc = view.contentDOM.ownerDocument;
|
||||
const win = doc.defaultView!;
|
||||
let dragged = false;
|
||||
// Tolerate click jitter, but a real selection must never turn into navigation.
|
||||
const moved = (e: MouseEvent) =>
|
||||
Math.max(Math.abs(e.clientX - event.clientX), Math.abs(e.clientY - event.clientY)) >= 4 ||
|
||||
(view.state.selection !== selection &&
|
||||
(view.state.selection.ranges.length > 1 || !view.state.selection.main.empty));
|
||||
const cancel = () => this.cancelMiddleClick();
|
||||
const stop = () => {
|
||||
doc.removeEventListener("mousemove", move);
|
||||
doc.removeEventListener("mouseup", up);
|
||||
doc.removeEventListener("keydown", cancel, true);
|
||||
win.removeEventListener("mousedown", cancel, true);
|
||||
win.removeEventListener("blur", cancel);
|
||||
if (this.stopMiddleClick === stop) this.stopMiddleClick = null;
|
||||
};
|
||||
const move = (e: MouseEvent) => {
|
||||
if (!(e.buttons & 4)) return cancel();
|
||||
dragged ||= moved(e);
|
||||
};
|
||||
const up = (e: MouseEvent) => {
|
||||
if (e.button !== 1) return;
|
||||
dragged ||= moved(e);
|
||||
doc.removeEventListener("mousemove", move);
|
||||
doc.removeEventListener("mouseup", up);
|
||||
if (
|
||||
dragged ||
|
||||
e.altKey !== event.altKey ||
|
||||
e.ctrlKey !== event.ctrlKey ||
|
||||
e.metaKey !== event.metaKey ||
|
||||
e.shiftKey !== event.shiftKey ||
|
||||
!view.contentDOM.contains(e.target as Node)
|
||||
) {
|
||||
stop();
|
||||
return;
|
||||
}
|
||||
// CodeMirror's document mouseup handler must finish before we replace its selection.
|
||||
queueMicrotask(() => {
|
||||
stop();
|
||||
if (
|
||||
version !== this.middleClickVersion ||
|
||||
this.disposed ||
|
||||
view.state.doc !== source ||
|
||||
docOf(view) !== context
|
||||
)
|
||||
return;
|
||||
view.dispatch({ selection: EditorSelection.cursor(pos), effects: setLink.of(null) });
|
||||
view.focus();
|
||||
void gotoTargets(view, "definition", pos);
|
||||
});
|
||||
};
|
||||
this.stopMiddleClick = stop;
|
||||
doc.addEventListener("mousemove", move);
|
||||
doc.addEventListener("mouseup", up);
|
||||
doc.addEventListener("keydown", cancel, true);
|
||||
win.addEventListener("mousedown", cancel, true);
|
||||
win.addEventListener("blur", cancel);
|
||||
}
|
||||
private set(value: LinkState | null) {
|
||||
const current = this.view.state.field(linkField);
|
||||
if (
|
||||
@@ -1093,10 +1170,17 @@ const linkPlugin = ViewPlugin.fromClass(
|
||||
this.show(false);
|
||||
},
|
||||
mousedown(e, view) {
|
||||
this.cancelMiddleClick();
|
||||
if (e.button !== 0 && e.button !== 1) return false;
|
||||
if (isAddCaretGesture(e)) return false;
|
||||
const rectangle = isRectangularSelectionGesture(e);
|
||||
let middleDeclaration = false;
|
||||
if (
|
||||
dispatchMouseShortcut(e, () => {
|
||||
dispatchMouseShortcut(e, (id) => {
|
||||
if (e.button === 1 && id === "navigate.declaration") {
|
||||
middleDeclaration = true;
|
||||
return false;
|
||||
}
|
||||
const pos = view.posAtCoords({ x: e.clientX, y: e.clientY }, false);
|
||||
if (pos == null) return false;
|
||||
view.dispatch({ selection: EditorSelection.cursor(pos), effects: setLink.of(null) });
|
||||
@@ -1107,8 +1191,12 @@ const linkPlugin = ViewPlugin.fromClass(
|
||||
e.preventDefault();
|
||||
return true;
|
||||
}
|
||||
// IDEA parity: middle button navigates on a plain click, without the modifier.
|
||||
if (e.button === 1 ? e.metaKey || e.ctrlKey || e.altKey || e.shiftKey : !isNavigationGesture(e)) return false;
|
||||
if (e.button === 1) {
|
||||
if (middleDeclaration || (!e.metaKey && !e.ctrlKey && !e.altKey && !e.shiftKey)) this.startMiddleClick(e);
|
||||
// Do not preventDefault here: CodeMirror still needs the press to start a rectangle.
|
||||
return false;
|
||||
}
|
||||
if (rectangle || !isNavigationGesture(e)) return false;
|
||||
if (!navigateFromPointer(view, e)) return false;
|
||||
e.preventDefault();
|
||||
return true;
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { registerNavigationProvider } from "../navigationProviders";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorState, StateEffect } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { commands } from "@/platform/ipc";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { resetNavigationModifier } from "@/platform/navigationModifier";
|
||||
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
|
||||
import { registerAction } from "@/platform/actions";
|
||||
import { multiCaretMouse } from "@/editor/core/cm/multiCaret";
|
||||
import { columnModeExtension, isColumnMode } from "@/editor/core/cm/columnMode";
|
||||
|
||||
const lspGoto = vi.hoisted(() => vi.fn<typeof commands.lspGoto>());
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
@@ -14,7 +16,16 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
// Go to Implementation streams (`lspGotoImplementation`); here it answers all at once.
|
||||
const lspGotoImplementation: typeof commands.lspGotoImplementation = (_request, doc, pos) =>
|
||||
lspGoto(doc, pos, "implementation");
|
||||
return { ...real, isTauri: () => true, commands: { ...real.commands, lspGoto, lspGotoImplementation } };
|
||||
return {
|
||||
...real,
|
||||
isTauri: () => true,
|
||||
commands: {
|
||||
...real.commands,
|
||||
lspGoto,
|
||||
lspGotoImplementation,
|
||||
lspHighlights: vi.fn(async () => ({ status: "ok", data: [] })),
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@tauri-apps/api/core", async (orig) => ({
|
||||
...(await orig<object>()),
|
||||
@@ -123,12 +134,159 @@ describe("mouse navigation", () => {
|
||||
expect(lspGoto).toHaveBeenCalledExactlyOnceWith(1, { line: 0, col: 9 }, "definition");
|
||||
});
|
||||
|
||||
it("opens the definition from a plain middle-button click", async () => {
|
||||
it("opens the definition only after a plain middle-button click is released", async () => {
|
||||
const event = click({ button: 1 });
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(lspGoto).not.toHaveBeenCalled();
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mouseup", { button: 1, bubbles: true }));
|
||||
await vi.waitFor(() => expect(openFile).toHaveBeenCalledOnce());
|
||||
expect(lspGoto).toHaveBeenCalledExactlyOnceWith(1, { line: 0, col: 9 }, "definition");
|
||||
expect(view.state.selection.main.head).toBe(9);
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
expect(event.defaultPrevented).toBe(false);
|
||||
});
|
||||
|
||||
it.each([false, true])("does not navigate after a middle drag (returns to start: %s)", async (back) => {
|
||||
click({ button: 1, clientX: 10, clientY: 10 });
|
||||
document.dispatchEvent(new MouseEvent("mousemove", { buttons: 4, clientX: 30, clientY: 40 }));
|
||||
view.contentDOM.dispatchEvent(
|
||||
new MouseEvent("mouseup", { button: 1, bubbles: true, clientX: back ? 10 : 30, clientY: back ? 10 : 40 }),
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(lspGoto).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("detects a drag from the release even if no move event arrived", async () => {
|
||||
click({ button: 1, clientX: 10 });
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mouseup", { button: 1, bubbles: true, clientX: 40 }));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(lspGoto).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("tolerates a small click movement without navigating twice", async () => {
|
||||
click({ button: 1, clientX: 10 });
|
||||
document.dispatchEvent(new MouseEvent("mousemove", { buttons: 4, clientX: 11 }));
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mouseup", { button: 1, bubbles: true, clientX: 11 }));
|
||||
await vi.waitFor(() => expect(openFile).toHaveBeenCalledOnce());
|
||||
expect(lspGoto).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it.each([
|
||||
"blur",
|
||||
"edit",
|
||||
"context",
|
||||
"destroy",
|
||||
"outside",
|
||||
"lost-button",
|
||||
"keydown",
|
||||
"new-gesture",
|
||||
"other-component",
|
||||
"side-button",
|
||||
])("cancels pending middle navigation on %s", async (cancel) => {
|
||||
click({ button: 1 });
|
||||
if (cancel === "blur") window.dispatchEvent(new Event("blur"));
|
||||
if (cancel === "edit") view.dispatch({ changes: { from: 0, insert: " " } });
|
||||
if (cancel === "context")
|
||||
view.dispatch({
|
||||
effects: StateEffect.reconfigure.of([
|
||||
lspDoc.of({ doc: 2, path: "/p/Other.java", language: "java", uiMode: "Java", readOnly: false }),
|
||||
navigationExtension(),
|
||||
]),
|
||||
});
|
||||
if (cancel === "destroy") view.destroy();
|
||||
if (cancel === "lost-button") document.dispatchEvent(new MouseEvent("mousemove", { buttons: 0 }));
|
||||
if (cancel === "keydown") document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
|
||||
if (cancel === "new-gesture") click({});
|
||||
if (cancel === "other-component")
|
||||
document.body.dispatchEvent(new MouseEvent("mousedown", { button: 0, bubbles: true }));
|
||||
if (cancel === "side-button")
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mousedown", { button: 3, bubbles: true }));
|
||||
const target = cancel === "outside" ? document.body : view.contentDOM;
|
||||
target.dispatchEvent(new MouseEvent("mouseup", { button: 1, bubbles: true }));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(lspGoto).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cancels a released click if another gesture starts before its deferred navigation", async () => {
|
||||
click({ button: 1 });
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mouseup", { button: 1, bubbles: true }));
|
||||
click({});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(lspGoto).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["middle", "short-middle", "alt", "rebound", "shared-middle", "shared-modified-middle"])(
|
||||
"keeps real rectangular ranges with navigation installed: %s",
|
||||
async (gesture) => {
|
||||
const id = "editor.createRectangularSelectionOnMouseDrag";
|
||||
const remove = registerAction({ id, title: "Create Rectangular Selection on Mouse Drag", run: () => {} });
|
||||
const removeDeclaration = registerAction({
|
||||
id: "navigate.declaration",
|
||||
title: "Go to Declaration",
|
||||
run: () => gotoTargets(view, "definition"),
|
||||
});
|
||||
try {
|
||||
if (gesture === "rebound") useKeymap.setState({ overrides: { [id]: ["Ctrl+Alt+Button1"] } });
|
||||
if (gesture.startsWith("shared-")) {
|
||||
const binding = gesture === "shared-middle" ? "Button2" : "Alt+Button2";
|
||||
useKeymap.setState({ overrides: { [id]: [binding], "navigate.declaration": [binding] } });
|
||||
}
|
||||
view.setState(
|
||||
EditorState.create({
|
||||
doc: "first\nsecond\nthird",
|
||||
extensions: [
|
||||
EditorState.allowMultipleSelections.of(true),
|
||||
lspDoc.of({ doc: 1, path: "/p/Main.java", language: "java", uiMode: "Java", readOnly: false }),
|
||||
multiCaretMouse,
|
||||
columnModeExtension,
|
||||
navigationExtension(),
|
||||
],
|
||||
}),
|
||||
);
|
||||
vi.mocked(view.posAtCoords).mockImplementation((coords) => coords.x);
|
||||
vi.spyOn(view, "coordsAtPos").mockReturnValue(null);
|
||||
const mods = gesture.endsWith("middle")
|
||||
? { button: 1, buttons: 4, altKey: gesture === "shared-modified-middle" }
|
||||
: { button: 0, buttons: 1, ctrlKey: gesture === "rebound", altKey: true };
|
||||
const end = gesture === "short-middle" ? 2 : 9;
|
||||
click({ ...mods, clientX: 1, detail: 1 });
|
||||
document.dispatchEvent(new MouseEvent("mousemove", { ...mods, clientX: end, bubbles: true }));
|
||||
document.dispatchEvent(new MouseEvent("mouseup", { ...mods, buttons: 0, clientX: end, bubbles: true }));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(view.state.selection.ranges.map((r) => [r.from, r.to])).toEqual(
|
||||
gesture === "short-middle"
|
||||
? [[1, 2]]
|
||||
: [
|
||||
[1, 3],
|
||||
[7, 9],
|
||||
],
|
||||
);
|
||||
expect(isColumnMode(view.state)).toBe(false);
|
||||
expect(lspGoto).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
remove();
|
||||
removeDeclaration();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([false, true])("delays an explicitly bound middle declaration click (Alt: %s)", async (altKey) => {
|
||||
const binding = altKey ? "Alt+Button2" : "Button2";
|
||||
const remove = registerAction({
|
||||
id: "navigate.declaration",
|
||||
title: "Go to Declaration",
|
||||
run: () => gotoTargets(view, "definition"),
|
||||
});
|
||||
useKeymap.setState({ overrides: { "navigate.declaration": [binding] } });
|
||||
try {
|
||||
click({ button: 1, altKey });
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(lspGoto).not.toHaveBeenCalled();
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mouseup", { button: 1, altKey, bubbles: true }));
|
||||
await vi.waitFor(() => expect(openFile).toHaveBeenCalledOnce());
|
||||
expect(lspGoto).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
remove();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
|
||||
@@ -82,7 +82,7 @@ import { ConfigPickers } from "./ConfigPickers";
|
||||
import { McpPicker } from "./McpPicker";
|
||||
import { useEffortFocus } from "./effortFocus";
|
||||
import { useAgentFontZoomSurface } from "./fontZoom";
|
||||
import { findRanges, formatDuration, formatSentAt, isFindRangeShown } from "./conversation";
|
||||
import { findRanges, formatDuration, formatSentAt, isFindRangeShown, userMessageText } from "./conversation";
|
||||
import { ImagePreview, imageSrc } from "./ImagePreview";
|
||||
import { useAgentSettings } from "./agentSettings";
|
||||
import { foldedTurns, summarizeWork, workParts, type FoldedTurn, type WorkSummary } from "./timeline";
|
||||
@@ -143,6 +143,7 @@ import {
|
||||
removeQueued,
|
||||
resendMessage,
|
||||
respond,
|
||||
answerQuestion,
|
||||
sendMessage,
|
||||
sendQueuedNow,
|
||||
setTaskConfig,
|
||||
@@ -1526,6 +1527,20 @@ const Entry = memo(function Entry({
|
||||
case "permission":
|
||||
// Waiting for an answer, it is asked above the composer; the conversation keeps the record.
|
||||
return entry.chosen || entry.questions?.length ? <PermissionLine task={task} entry={entry} /> : null;
|
||||
case "question":
|
||||
return (
|
||||
<div className={clsx(styles.permissionLine, entry.chosen ? styles.permissionDone : styles.permissionAsking)}>
|
||||
<Icon name={!entry.chosen ? "warning" : entry.chosen === "Skipped" ? "minus" : "check"} size={14} />
|
||||
<div className={styles.permissionBody}>
|
||||
<span className={styles.permissionTitle}>{entry.title}</span>
|
||||
{entry.chosen && (
|
||||
<span className={styles.permissionRecord}>
|
||||
{entry.chosen === "Skipped" ? <T>Skipped</T> : entry.chosen}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
case "error":
|
||||
return (
|
||||
<div className={styles.error} role="alert">
|
||||
@@ -1561,10 +1576,11 @@ function UserMessage({
|
||||
const inPlace = !archived && rollback && turn !== null;
|
||||
// A copy up to an earlier turn drops the later ones from the copied session.
|
||||
const canFork = idle && fork && (rollback || turn === turnCount - 1);
|
||||
const text = userMessageText(entry.text);
|
||||
if (editing && turn !== null) {
|
||||
return (
|
||||
<MessageEditor
|
||||
initial={entry.text}
|
||||
initial={text}
|
||||
initialImages={entry.images ?? []}
|
||||
later={turn < turnCount - 1}
|
||||
onCancel={() => setEditing(false)}
|
||||
@@ -1578,7 +1594,7 @@ function UserMessage({
|
||||
// Images are listed after the files in `attachments` and shown as thumbnails instead.
|
||||
// Files mentioned in the text are chips there already.
|
||||
const mentioned = new Set(
|
||||
messageTokens(entry.text).flatMap((t) => {
|
||||
messageTokens(text).flatMap((t) => {
|
||||
const m = t.kind === "file" ? parseMention(t.value) : null;
|
||||
return m ? [basename(m.rel.replace(/\/$/, ""))] : [];
|
||||
}),
|
||||
@@ -1589,7 +1605,7 @@ function UserMessage({
|
||||
{/* Actions and the time sit beside the author on hover: the reply under it has the turn's duration. */}
|
||||
<div className={styles.messageHead}>
|
||||
<MessageActions>
|
||||
<IconButton size="small" icon="copy" title="Copy" onClick={() => void copyText(entry.text)} />
|
||||
<IconButton size="small" icon="copy" title="Copy" onClick={() => void copyText(text)} />
|
||||
{inPlace && entry.text && (
|
||||
<IconButton size="small" icon="edit" title="Edit" onClick={() => setEditing(true)} />
|
||||
)}
|
||||
@@ -1630,7 +1646,7 @@ function UserMessage({
|
||||
</span>
|
||||
</div>
|
||||
<div className={styles.user}>
|
||||
<ReferencedText text={entry.text} cwd={task.cwd} />
|
||||
<ReferencedText text={text} cwd={task.cwd} />
|
||||
<ImageStrip images={images} />
|
||||
{files.length > 0 && (
|
||||
<div className={styles.attachments}>
|
||||
@@ -2348,15 +2364,39 @@ const isRecommended = (label: string) => label.endsWith(RECOMMENDED_SUFFIX);
|
||||
|
||||
const plainLabel = (label: string) => (isRecommended(label) ? label.slice(0, -RECOMMENDED_SUFFIX.length) : label);
|
||||
|
||||
/** An open `AskUserQuestion` request or agent form, as a card above the composer; one question at a time. */
|
||||
type AsyncQuestionEntry = Extract<AgentEntry, { type: "question" }>;
|
||||
|
||||
/** Blocking requests take priority; async questions stay available after their turn ends. */
|
||||
function QuestionCard({ task, entries }: { task: AgentTask; entries: AgentEntry[] | null }) {
|
||||
const entry = entries?.find(
|
||||
(candidate): candidate is PermissionEntry =>
|
||||
candidate.type === "permission" && !candidate.chosen && asksInCard(candidate),
|
||||
);
|
||||
if (entry?.form) return <FormCard key={entry.id} task={task} entry={entry} form={entry.form} />;
|
||||
const drafts = useRef(new Map<string, QuestionAnswer[]>());
|
||||
useEffect(() => {
|
||||
const open = new Set(
|
||||
entries
|
||||
?.filter(
|
||||
(entry): entry is PermissionEntry | AsyncQuestionEntry =>
|
||||
(entry.type === "question" || entry.type === "permission") && !entry.chosen,
|
||||
)
|
||||
.map((entry) => `${entry.type}:${entry.id}`),
|
||||
);
|
||||
for (const key of drafts.current.keys()) if (!open.has(key)) drafts.current.delete(key);
|
||||
}, [entries]);
|
||||
if (task.status === "archived") return null;
|
||||
const entry =
|
||||
entries?.find(
|
||||
(candidate): candidate is PermissionEntry =>
|
||||
candidate.type === "permission" && !candidate.chosen && asksInCard(candidate),
|
||||
) ??
|
||||
entries?.find((candidate): candidate is AsyncQuestionEntry => candidate.type === "question" && !candidate.chosen);
|
||||
if (entry?.type === "permission" && entry.form)
|
||||
return <FormCard key={entry.id} task={task} entry={entry} form={entry.form} />;
|
||||
return entry?.questions ? (
|
||||
<QuestionForm key={entry.id} task={task} entry={entry} questions={entry.questions} />
|
||||
<QuestionForm
|
||||
key={`${entry.type}:${entry.id}`}
|
||||
task={task}
|
||||
entry={entry}
|
||||
questions={entry.questions}
|
||||
drafts={drafts}
|
||||
/>
|
||||
) : null;
|
||||
}
|
||||
|
||||
@@ -2364,17 +2404,27 @@ function QuestionForm({
|
||||
task,
|
||||
entry,
|
||||
questions,
|
||||
drafts,
|
||||
}: {
|
||||
task: AgentTask;
|
||||
entry: PermissionEntry;
|
||||
entry: PermissionEntry | AsyncQuestionEntry;
|
||||
questions: AgentQuestion[];
|
||||
drafts: RefObject<Map<string, QuestionAnswer[]>>;
|
||||
}) {
|
||||
const [answers, setAnswers] = useState<QuestionAnswer[]>(() =>
|
||||
questions.map((question) => ({ question, picked: [], other: null })),
|
||||
const cacheKey = `${entry.type}:${entry.id}`;
|
||||
const [answers, setAnswers] = useState<QuestionAnswer[]>(
|
||||
() =>
|
||||
drafts.current.get(cacheKey) ??
|
||||
questions.map((question) => ({ question, picked: [], other: question.options.length ? null : "" })),
|
||||
);
|
||||
useLayoutEffect(() => {
|
||||
drafts.current.set(cacheKey, answers);
|
||||
}, [drafts, cacheKey, answers]);
|
||||
const [position, setPosition] = useState(0);
|
||||
const [hovered, setHovered] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const pending = useRef(false);
|
||||
const questionPrefix = useId();
|
||||
const panelsRef = useRef<HTMLDivElement>(null);
|
||||
const panelRef = useRef<HTMLDivElement>(null);
|
||||
@@ -2390,8 +2440,20 @@ function QuestionForm({
|
||||
panelRef.current?.focus();
|
||||
}, [position]);
|
||||
const send = (option: string) => {
|
||||
if (pending.current) return;
|
||||
pending.current = true;
|
||||
setBusy(true);
|
||||
void respond(task.id, entry.id, option).finally(() => setBusy(false));
|
||||
setError(null);
|
||||
const sent =
|
||||
entry.type === "question"
|
||||
? answerQuestion(task.id, entry.id, option === "reject" ? null : option)
|
||||
: respond(task.id, entry.id, option);
|
||||
void sent
|
||||
.catch((error: unknown) => setError(String(error)))
|
||||
.finally(() => {
|
||||
pending.current = false;
|
||||
setBusy(false);
|
||||
});
|
||||
};
|
||||
const submit = () =>
|
||||
send(
|
||||
@@ -2565,7 +2627,7 @@ function QuestionForm({
|
||||
})}
|
||||
{item.other !== null && (
|
||||
<Input
|
||||
autoFocus
|
||||
autoFocus={entry.type === "permission" || item.question.options.length > 0}
|
||||
className={styles.questionOther}
|
||||
value={item.other}
|
||||
placeholder="Type your answer"
|
||||
@@ -2611,6 +2673,11 @@ function QuestionForm({
|
||||
})}
|
||||
</div>
|
||||
<div className={styles.questionActions}>
|
||||
{error && (
|
||||
<span className={styles.error} role="alert">
|
||||
{error}
|
||||
</span>
|
||||
)}
|
||||
<Button variant="ghost" disabled={busy} onClick={() => send("reject")}>
|
||||
Skip
|
||||
</Button>
|
||||
|
||||
@@ -9,8 +9,23 @@ import {
|
||||
quoteText,
|
||||
symbolRef,
|
||||
withQuote,
|
||||
userMessageText,
|
||||
} from "./conversation";
|
||||
|
||||
it("shows async replies as readable question/answer pairs without losing malformed user text", () => {
|
||||
const wire = `<send_user_message_question_reply>\n${JSON.stringify([
|
||||
{ questionItemId: "q1", question: "Which?", answer: "One" },
|
||||
{ questionItemId: "q2", question: "Why?", answer: "Because" },
|
||||
])}\n</send_user_message_question_reply>`;
|
||||
expect(userMessageText(wire)).toBe("Which?\nOne\n\nWhy?\nBecause");
|
||||
for (const text of [
|
||||
"normal",
|
||||
"<send_user_message_question_reply>bad</send_user_message_question_reply>",
|
||||
"<send_user_message_question_reply>[{}]</send_user_message_question_reply>",
|
||||
])
|
||||
expect(userMessageText(text)).toBe(text);
|
||||
});
|
||||
|
||||
describe("quoting", () => {
|
||||
it("quotes each line and leaves a line to type on", () => {
|
||||
expect(quoteText("one\n\ntwo\n")).toBe("> one\n>\n> two\n\n");
|
||||
|
||||
@@ -3,6 +3,31 @@
|
||||
import type { SymbolKind } from "@/platform/ipc";
|
||||
import { opensOtherShare } from "@/platform/paths";
|
||||
|
||||
/** Display a structured async answer as the question and answer, keeping its wire ids out of the UI. */
|
||||
export function userMessageText(text: string): string {
|
||||
const start = "<send_user_message_question_reply>";
|
||||
const end = "</send_user_message_question_reply>";
|
||||
if (!text.startsWith(start) || !text.endsWith(end)) return text;
|
||||
try {
|
||||
const replies: unknown = JSON.parse(text.slice(start.length, -end.length));
|
||||
if (
|
||||
!Array.isArray(replies) ||
|
||||
!replies.length ||
|
||||
!replies.every(
|
||||
(reply) =>
|
||||
reply &&
|
||||
typeof reply.questionItemId === "string" &&
|
||||
typeof reply.question === "string" &&
|
||||
typeof reply.answer === "string",
|
||||
)
|
||||
)
|
||||
return text;
|
||||
return replies.map((reply) => `${reply.question}\n${reply.answer}`).join("\n\n");
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
/** `text` as a Markdown quote for the composer, followed by an empty line to type in. */
|
||||
export function quoteText(text: string): string {
|
||||
const lines = text.replace(/\s+$/, "").split("\n");
|
||||
|
||||
@@ -35,6 +35,8 @@ const backend = vi.hoisted(() => ({
|
||||
groupedCalls: 0,
|
||||
rolledBack: [] as Array<[string, string[] | null, string | null]>,
|
||||
answers: [] as Array<[string, number, string | null]>,
|
||||
questionAnswers: [] as Array<[string, string, string | null]>,
|
||||
questionError: null as string | null,
|
||||
fetched: [] as string[],
|
||||
entryError: null as string | null,
|
||||
entryWait: null as Promise<void> | null,
|
||||
@@ -101,6 +103,11 @@ vi.mock("@/platform/ipc", async (original) => ({
|
||||
backend.answers.push([task, permission, option]);
|
||||
return { status: "ok", data: null };
|
||||
},
|
||||
agentAnswerQuestion: async (task: string, question: string, answer: string | null) => {
|
||||
backend.questionAnswers.push([task, question, answer]);
|
||||
if (backend.questionError) throw new Error(backend.questionError);
|
||||
return { status: "ok", data: null };
|
||||
},
|
||||
agentExternalSessions: async () => {
|
||||
backend.externalCalls += 1;
|
||||
await backend.externalWait;
|
||||
@@ -1280,6 +1287,125 @@ describe("a pending question", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("an asynchronous Codex question", () => {
|
||||
beforeEach(() => {
|
||||
backend.questionAnswers = [];
|
||||
backend.questionError = null;
|
||||
});
|
||||
|
||||
function freeQuestion() {
|
||||
const answerKey = JSON.stringify(["request_user_input_async", "free", 0]);
|
||||
const entry: AgentEntry = {
|
||||
type: "question",
|
||||
id: "free",
|
||||
title: "What deadline?",
|
||||
chosen: null,
|
||||
questions: [{ answerKey, header: "", question: "What deadline?", multiSelect: false, options: [] }],
|
||||
};
|
||||
backend.entries.set("A", [entry]);
|
||||
useAgents.setState({ entries: new Map(backend.entries) });
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
return answerKey;
|
||||
}
|
||||
|
||||
it("accepts a typed answer without suggested choices", async () => {
|
||||
const answerKey = freeQuestion();
|
||||
const card = await screen.findByRole("form", { name: "What deadline?" });
|
||||
const submit = within(card).getByRole("button", { name: "Submit" });
|
||||
expect(submit).toBeDisabled();
|
||||
fireEvent.change(within(card).getByPlaceholderText("Type your answer"), { target: { value: "Tomorrow" } });
|
||||
fireEvent.click(submit);
|
||||
await waitFor(() =>
|
||||
expect(backend.questionAnswers).toEqual([["A", "free", JSON.stringify({ [answerKey]: ["Tomorrow"] })]]),
|
||||
);
|
||||
});
|
||||
|
||||
it("skips without submitting an answer", async () => {
|
||||
freeQuestion();
|
||||
const card = await screen.findByRole("form", { name: "What deadline?" });
|
||||
fireEvent.click(within(card).getByRole("button", { name: "Skip" }));
|
||||
await waitFor(() => expect(backend.questionAnswers).toEqual([["A", "free", null]]));
|
||||
});
|
||||
|
||||
it("preserves a draft while a blocking question takes priority", async () => {
|
||||
freeQuestion();
|
||||
const card = await screen.findByRole("form", { name: "What deadline?" });
|
||||
fireEvent.change(within(card).getByPlaceholderText("Type your answer"), { target: { value: "Tomorrow" } });
|
||||
const asyncEntry = backend.entries.get("A")![0]!;
|
||||
const blocking = {
|
||||
type: "permission",
|
||||
id: 100,
|
||||
title: "Blocking question",
|
||||
options: [],
|
||||
chosen: null,
|
||||
questions: [{ header: "", question: "Blocking question", multiSelect: false, options: [] }],
|
||||
} as AgentEntry;
|
||||
act(() => useAgents.setState({ entries: new Map([["A", [asyncEntry, blocking]]]) }));
|
||||
expect(await screen.findByRole("form", { name: "Blocking question" })).toBeInTheDocument();
|
||||
act(() => useAgents.setState({ entries: new Map([["A", [asyncEntry, { ...blocking, chosen: "Cancelled" }]]]) }));
|
||||
const restored = await screen.findByRole("form", { name: "What deadline?" });
|
||||
expect(within(restored).getByPlaceholderText("Type your answer")).toHaveValue("Tomorrow");
|
||||
});
|
||||
|
||||
it("hides the card while its task is archived", async () => {
|
||||
freeQuestion();
|
||||
await screen.findByRole("form", { name: "What deadline?" });
|
||||
act(() =>
|
||||
useAgents.setState((s) => ({ tasks: new Map(s.tasks).set("A", { ...s.tasks.get("A")!, status: "archived" }) })),
|
||||
);
|
||||
expect(screen.queryByRole("form", { name: "What deadline?" })).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the typed answer after a failed submission and allows retry", async () => {
|
||||
freeQuestion();
|
||||
const card = await screen.findByRole("form", { name: "What deadline?" });
|
||||
fireEvent.change(within(card).getByPlaceholderText("Type your answer"), { target: { value: "Tomorrow" } });
|
||||
backend.questionError = "reply unavailable";
|
||||
fireEvent.click(within(card).getByRole("button", { name: "Submit" }));
|
||||
expect(await within(card).findByRole("alert")).toHaveTextContent("reply unavailable");
|
||||
expect(within(card).getByPlaceholderText("Type your answer")).toHaveValue("Tomorrow");
|
||||
backend.questionError = null;
|
||||
fireEvent.click(within(card).getByRole("button", { name: "Submit" }));
|
||||
await waitFor(() => expect(backend.questionAnswers).toHaveLength(2));
|
||||
expect(within(card).queryByRole("alert")).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["running", "ready"] as const)("offers answers while the task is %s", async (status) => {
|
||||
const answerKey = JSON.stringify(["request_user_input_async", "call-1", 0]);
|
||||
const question: AgentEntry = {
|
||||
type: "question",
|
||||
id: "call-1",
|
||||
title: "Include retries?",
|
||||
chosen: null,
|
||||
questions: [
|
||||
{
|
||||
answerKey,
|
||||
header: "",
|
||||
question: "Include retries?",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Yes", description: "", preview: null },
|
||||
{ label: "No", description: "", preview: null },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
backend.questionAnswers = [];
|
||||
backend.entries.set("A", [{ type: "agent", text: "I can continue while you decide." }, question]);
|
||||
useAgents.setState((s) => ({
|
||||
entries: new Map(backend.entries),
|
||||
tasks: new Map(s.tasks).set("A", { ...s.tasks.get("A")!, status }),
|
||||
}));
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
const card = await screen.findByRole("form", { name: "Include retries?" });
|
||||
fireEvent.click(within(card).getByRole("radio", { name: /^Yes/ }));
|
||||
fireEvent.click(within(card).getByRole("button", { name: "Submit" }));
|
||||
await waitFor(() =>
|
||||
expect(backend.questionAnswers).toEqual([["A", "call-1", JSON.stringify({ [answerKey]: ["Yes"] })]]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a pending AskUserQuestion", () => {
|
||||
it("keeps separate answers for Codex question ids with identical wording", async () => {
|
||||
backend.entries.set("A", [
|
||||
|
||||
@@ -1352,6 +1352,8 @@ export const stopBackgroundTask = (task: string, background: string) =>
|
||||
call(commands.agentStopBackground(task, background));
|
||||
export const respond = (task: string, permission: number, option: string | null) =>
|
||||
call(commands.agentRespond(task, permission, option));
|
||||
export const answerQuestion = (task: string, question: string, answer: string | null) =>
|
||||
call(commands.agentAnswerQuestion(task, question, answer));
|
||||
export const unarchiveTask = (task: string) => call(commands.agentUnarchive(task));
|
||||
export const renameTask = (task: string, title: string) => call(commands.agentRename(task, title));
|
||||
export const archiveTask = (task: string) => call(commands.agentArchive(task));
|
||||
|
||||
@@ -126,11 +126,16 @@ export function foldedTurns(entries: readonly AgentEntry[], from: number, busy:
|
||||
break;
|
||||
}
|
||||
// Something after the reply still wants to be seen (an error, an open question).
|
||||
if (e.type === "error" || (e.type === "permission" && e.chosen === null)) return;
|
||||
if (e.type === "error" || ((e.type === "permission" || e.type === "question") && e.chosen === null)) return;
|
||||
}
|
||||
if (reply < 0 || reply === user + 1) return;
|
||||
// What the user sent into the turn, and an error it ran into, stay in view.
|
||||
if (entries.slice(user + 1, reply).some((e) => e.type === "user" || e.type === "error")) return;
|
||||
if (
|
||||
entries
|
||||
.slice(user + 1, reply)
|
||||
.some((e) => e.type === "user" || e.type === "error" || (e.type === "question" && e.chosen === null))
|
||||
)
|
||||
return;
|
||||
turns.set(user, { user, reply, sentMs: asked.sentMs ?? null, doneMs: asked.doneMs ?? null });
|
||||
});
|
||||
return turns;
|
||||
|
||||
@@ -1425,7 +1425,8 @@
|
||||
}
|
||||
.dumpPreview {
|
||||
grid-column: 1 / -1;
|
||||
max-height: 96px;
|
||||
flex: none;
|
||||
height: 96px;
|
||||
overflow: auto;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--border);
|
||||
|
||||
@@ -16,6 +16,8 @@ const ImportDialog = lazyComponent(() => import("./DataDialogs").then((m) => m.I
|
||||
const SchemaCompareDialog = lazyComponent(() => import("./SchemaCompareDialog").then((m) => m.SchemaCompareDialog));
|
||||
const DumpDialog = lazyComponent(() => import("./DumpDialogs").then((m) => m.DumpDialog));
|
||||
const RestoreDialog = lazyComponent(() => import("./DumpDialogs").then((m) => m.RestoreDialog));
|
||||
const MysqlDumpDialog = lazyComponent(() => import("./MysqlDumpDialogs").then((m) => m.MysqlDumpDialog));
|
||||
const MysqlRestoreDialog = lazyComponent(() => import("./MysqlDumpDialogs").then((m) => m.MysqlRestoreDialog));
|
||||
|
||||
function PasswordDialog({ source, resolve }: { source: DataSource; resolve: (ok: boolean) => void }) {
|
||||
const [password, setPassword] = useState("");
|
||||
@@ -214,6 +216,12 @@ export function DatabaseDialogs() {
|
||||
serverVersion={dialog.serverVersion}
|
||||
/>
|
||||
);
|
||||
if (dialog.kind === "mysqlDump")
|
||||
return (
|
||||
<MysqlDumpDialog key={dialog.target} target={dialog.target} database={dialog.database} tables={dialog.tables} />
|
||||
);
|
||||
if (dialog.kind === "mysqlRestore")
|
||||
return <MysqlRestoreDialog key={dialog.target} target={dialog.target} database={dialog.database} />;
|
||||
if (dialog.kind === "sshSecret")
|
||||
return (
|
||||
<SshSecretDialog key={dialog.source.id} source={dialog.source} prompt={dialog.prompt} resolve={dialog.resolve} />
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
commands,
|
||||
type DbDumpContent,
|
||||
type DbDumpFormat,
|
||||
type DbDumpKind,
|
||||
type DbDumpInfo,
|
||||
type DbDumpStatements,
|
||||
type DbPsqlOptions,
|
||||
type DbTool,
|
||||
@@ -39,15 +39,30 @@ import {
|
||||
outputPath,
|
||||
pickInstall,
|
||||
restoreOptions,
|
||||
nameList,
|
||||
patternName,
|
||||
restoreTargetProblem,
|
||||
restoreToolFor,
|
||||
toggleName,
|
||||
unquoteName,
|
||||
versionFit,
|
||||
withExtension,
|
||||
type DumpForm,
|
||||
type DumpMismatch,
|
||||
type RestoreForm,
|
||||
type TargetProblem,
|
||||
} from "./dumpTools";
|
||||
import { splitTarget } from "./model";
|
||||
import { closeDialog, refresh, sourceById } from "./store";
|
||||
import {
|
||||
closeDialog,
|
||||
loadDatabases,
|
||||
loadSchemas,
|
||||
loadTables,
|
||||
refresh,
|
||||
sourceById,
|
||||
tablesKey,
|
||||
useDatabase,
|
||||
} from "./store";
|
||||
import { TOOL_PROGRAMS, startToolRun, stopToolRun, useToolRuns } from "./toolRuns";
|
||||
import { copySelectionOnKeyDown } from "@/ui/selectableText";
|
||||
import styles from "./Database.module.css";
|
||||
@@ -176,36 +191,184 @@ export function ExecutableField({
|
||||
<span />
|
||||
<span className={clsx(styles.formHint, (current?.error || hint?.warn) && styles.dumpError)}>
|
||||
{installs && !value.trim()
|
||||
? tx`${program} was not found. Install the PostgreSQL client tools or choose the executable.`
|
||||
? tool === "mysqldump" || tool === "mysql"
|
||||
? tx`${program} was not found. Install the MySQL or MariaDB client tools or choose the executable.`
|
||||
: tx`${program} was not found. Install the PostgreSQL client tools or choose the executable.`
|
||||
: (hint?.text ?? current?.error ?? "\u00a0")}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** What made the dump at `path`, read from its header (`null` while unknown). */
|
||||
export function useDumpKind(path: string): DbDumpKind | null {
|
||||
const [known, setKnown] = useState<{ path: string; kind: DbDumpKind } | null>(null);
|
||||
/** What made the dump at `path` and whether it creates its database, from its header (`null` while unknown). */
|
||||
export function useDumpInfo(path: string): DbDumpInfo | null {
|
||||
const [known, setKnown] = useState<{ path: string; info: DbDumpInfo } | null>(null);
|
||||
useEffect(() => {
|
||||
const p = path.trim();
|
||||
if (!p) return;
|
||||
let live = true;
|
||||
const timer = setTimeout(() => {
|
||||
call(commands.dbDumpKind(p))
|
||||
.then((kind) => live && setKnown({ path: p, kind }))
|
||||
.catch(() => live && setKnown({ path: p, kind: "unknown" }));
|
||||
call(commands.dbDumpInfo(p))
|
||||
.then((info) => live && setKnown({ path: p, info }))
|
||||
.catch(() => live && setKnown({ path: p, info: { kind: "unknown", createsDatabase: false } }));
|
||||
}, 250);
|
||||
return () => {
|
||||
live = false;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [path]);
|
||||
return known?.path === path.trim() ? known.kind : null;
|
||||
return known?.path === path.trim() ? known.info : null;
|
||||
}
|
||||
|
||||
/** The databases of the data source of `target` (MySQL: its schemas); `null` while unknown. */
|
||||
export function useDatabaseNames(target: string): { names: string[]; current: string } | null {
|
||||
const { id } = splitTarget(target);
|
||||
const mysql = sourceById(id)?.driver === "mysql";
|
||||
const databases = useDatabase((s) => s.databases[id]);
|
||||
const schemas = useDatabase((s) => s.schemas[id]);
|
||||
const loaded = mysql ? schemas : databases;
|
||||
useEffect(() => {
|
||||
if (!loaded) void (mysql ? loadSchemas(id) : loadDatabases(id));
|
||||
}, [id, mysql, loaded]);
|
||||
if (mysql) return schemas?.status === "ok" ? { names: schemas.value, current: "" } : null;
|
||||
return databases?.status === "ok" ? databases.value : null;
|
||||
}
|
||||
|
||||
/** The schemas on connection target `target` (`null` while unknown). */
|
||||
function useSchemaNames(target: string): string[] | null {
|
||||
const loaded = useDatabase((s) => s.schemas[target]);
|
||||
useEffect(() => {
|
||||
if (!loaded) void loadSchemas(target);
|
||||
}, [target, loaded]);
|
||||
return loaded?.status === "ok" ? loaded.value : null;
|
||||
}
|
||||
|
||||
/** The tables of `schemas` on connection target `id` (`null` while one of them is unknown, or without schemas). */
|
||||
export function useTableNames(
|
||||
id: string,
|
||||
schemas: readonly string[] | null,
|
||||
): { schema: string; name: string }[] | null {
|
||||
const all = useDatabase((s) => s.tables);
|
||||
const keys = (schemas ?? []).join("\u0000");
|
||||
useEffect(() => {
|
||||
for (const schema of schemas ?? []) if (!all[tablesKey(id, schema)]) void loadTables(id, schema);
|
||||
// `keys` stands for `schemas`.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [id, keys, all]);
|
||||
if (!schemas?.length) return null;
|
||||
const out: { schema: string; name: string }[] = [];
|
||||
for (const schema of schemas) {
|
||||
const loaded = all[tablesKey(id, schema)];
|
||||
if (loaded?.status !== "ok") return null;
|
||||
for (const t of loaded.value) if (t.kind === "table") out.push({ schema, name: t.name });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A typed name list with a button that ticks names off a list of the server's. */
|
||||
export function NamesField({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
names,
|
||||
placeholder,
|
||||
disabled,
|
||||
title,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
names: string[] | null;
|
||||
placeholder: string;
|
||||
disabled?: boolean;
|
||||
title?: string;
|
||||
}) {
|
||||
const chosen = nameList(value);
|
||||
return (
|
||||
<div className={styles.formRow}>
|
||||
<Input
|
||||
mono
|
||||
className={styles.dumpPath}
|
||||
aria-label={label}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
title={title}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="list"
|
||||
title="Choose from the server…"
|
||||
disabled={disabled || !names?.length}
|
||||
onClick={(e) =>
|
||||
showContextMenu(
|
||||
e,
|
||||
(names ?? []).map((n) => ({
|
||||
label: n,
|
||||
verbatim: true,
|
||||
checked: chosen.includes(n),
|
||||
run: () => onChange(toggleName(value, n)),
|
||||
})),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The database a restore runs in: the data source's databases to pick from, or a text field
|
||||
* while they are unknown. `empty` labels a choice of no database.
|
||||
*/
|
||||
export function DatabaseField({
|
||||
value,
|
||||
onChange,
|
||||
names,
|
||||
empty,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
names: string[] | null;
|
||||
empty?: string;
|
||||
}) {
|
||||
if (!names) return <Input aria-label="Database" value={value} onChange={(e) => onChange(e.target.value)} />;
|
||||
const options = [
|
||||
...(empty !== undefined ? [{ value: "", label: empty }] : []),
|
||||
...names.map((n) => ({ value: n, label: n, verbatim: true })),
|
||||
];
|
||||
if (value && !names.includes(value)) options.push({ value, label: value, verbatim: true });
|
||||
return <Select aria-label="Database" searchable value={value} options={options} onChange={onChange} />;
|
||||
}
|
||||
|
||||
/** The hint under a restore's database: what is wrong with it, else what happens there. */
|
||||
export function TargetHint({
|
||||
problem,
|
||||
database,
|
||||
note,
|
||||
}: {
|
||||
problem: TargetProblem | null;
|
||||
database: string;
|
||||
note?: string;
|
||||
}) {
|
||||
const text =
|
||||
problem === "missing"
|
||||
? tx`Database ${database} does not exist.`
|
||||
: problem === "noDatabase"
|
||||
? tx("This dump does not create its database. Choose the database to restore into.")
|
||||
: note;
|
||||
return (
|
||||
<>
|
||||
<span />
|
||||
<span className={clsx(styles.formHint, problem && styles.dumpError)}>{text ?? "\u00a0"}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Why the chosen tool cannot restore the chosen dump, as a hint under the path. */
|
||||
export function mismatchText(m: DumpMismatch): string {
|
||||
switch (m) {
|
||||
case "postgresIntoMysql":
|
||||
return tx("This is a PostgreSQL dump: restore it into a PostgreSQL data source.");
|
||||
case "mysqlIntoPostgres":
|
||||
return tx("This is a MySQL dump: restore it into a MySQL data source.");
|
||||
case "archiveIntoPsql":
|
||||
@@ -215,8 +378,8 @@ export function mismatchText(m: DumpMismatch): string {
|
||||
}
|
||||
}
|
||||
|
||||
/** The command line the backend would run for `job` on target `id` (empty while unknown). */
|
||||
function useToolPreview(id: string, executable: string, job: DbToolJob): string {
|
||||
/** The command line the backend would run for `job` on target `id`; the previous one while the next loads. */
|
||||
export function useToolPreview(id: string, executable: string, job: DbToolJob): string {
|
||||
const key = JSON.stringify([id, executable, job]);
|
||||
const [shown, setShown] = useState<{ key: string; line: string } | null>(null);
|
||||
useEffect(() => {
|
||||
@@ -233,10 +396,10 @@ function useToolPreview(id: string, executable: string, job: DbToolJob): string
|
||||
// `key` stands for the three inputs.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [key]);
|
||||
return shown?.key === key ? shown.line : "";
|
||||
return shown?.line ?? "";
|
||||
}
|
||||
|
||||
function Preview({ text }: { text: string }) {
|
||||
export function Preview({ text }: { text: string }) {
|
||||
return (
|
||||
<div className={clsx(styles.dumpPreview, selectableText)} onKeyDown={(e) => void copySelectionOnKeyDown(e)}>
|
||||
<code aria-label="Command line">{text || "\u00a0"}</code>
|
||||
@@ -309,6 +472,9 @@ export function RunOutput({ runKey }: { runKey: number }) {
|
||||
{l.text || " "}
|
||||
</div>
|
||||
))}
|
||||
{run.status === "done" && !run.lines.length && (
|
||||
<div className={styles.formHint}>{tx`${PROGRAM[run.tool]} printed no output.`}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -371,6 +537,16 @@ export function DumpDialog({
|
||||
setOptions((o) => ({ ...o, [k]: v }));
|
||||
const plain = options.format === "plain";
|
||||
const runTarget = targetOf(target, database);
|
||||
const databases = useDatabaseNames(target);
|
||||
const shown = database || (databases?.current ?? "");
|
||||
const schemaNames = useSchemaNames(runTarget);
|
||||
const typedSchemas = nameList(options.schemas)
|
||||
.map(unquoteName)
|
||||
.filter((n) => schemaNames?.includes(n));
|
||||
const tableNames =
|
||||
useTableNames(runTarget, typedSchemas.length ? typedSchemas : schemaNames)?.map(
|
||||
(t) => `${patternName(t.schema)}.${patternName(t.name)}`,
|
||||
) ?? null;
|
||||
const jobFor = (file: string): DbToolJob => ({ tool: "pgDump", file, options: dumpOptions(options) });
|
||||
const preview = useToolPreview(runTarget, executable || "pg_dump", jobFor(output));
|
||||
|
||||
@@ -385,7 +561,7 @@ export function DumpDialog({
|
||||
};
|
||||
|
||||
const run = async () => {
|
||||
const file = outputPath(output, { dataSource: source?.name ?? "", database, now: new Date() });
|
||||
const file = outputPath(output, { dataSource: source?.name ?? "", database: shown, now: new Date() });
|
||||
const job = jobFor(file);
|
||||
localStorage.setItem(pathKey("pgDump"), executable);
|
||||
const commandLine = await call(commands.dbToolPreview(runTarget, executable, job)).catch(() => "");
|
||||
@@ -396,7 +572,7 @@ export function DumpDialog({
|
||||
job,
|
||||
commandLine,
|
||||
output: file,
|
||||
from: database || (source?.name ?? target),
|
||||
from: shown || (source?.name ?? target),
|
||||
to: file,
|
||||
}),
|
||||
);
|
||||
@@ -431,7 +607,7 @@ export function DumpDialog({
|
||||
<span className={styles.formLabel}>
|
||||
<T>Database:</T>
|
||||
</span>
|
||||
<Input aria-label="Database" value={database} onChange={(e) => setDatabase(e.target.value)} />
|
||||
<DatabaseField value={shown} onChange={setDatabase} names={databases?.names ?? null} />
|
||||
<span className={styles.formLabel}>
|
||||
<T>Output result to:</T>
|
||||
</span>
|
||||
@@ -480,20 +656,14 @@ export function DumpDialog({
|
||||
<Select aria-label="Content" value={options.content} options={CONTENT_OPTIONS} onChange={set("content")} />
|
||||
{(
|
||||
[
|
||||
["schemas", "Schemas:"],
|
||||
["tables", "Tables:"],
|
||||
["excludeTables", "Exclude tables:"],
|
||||
["schemas", "Schemas:", schemaNames?.map(patternName) ?? null],
|
||||
["tables", "Tables:", tableNames],
|
||||
["excludeTables", "Exclude tables:", tableNames],
|
||||
] as const
|
||||
).map(([k, label]) => (
|
||||
).map(([k, label, names]) => (
|
||||
<Fragment key={k}>
|
||||
<span className={styles.formLabel}>{tx(label)}</span>
|
||||
<Input
|
||||
mono
|
||||
aria-label={tx(label)}
|
||||
placeholder="All"
|
||||
value={options[k]}
|
||||
onChange={(e) => set(k)(e.target.value)}
|
||||
/>
|
||||
<NamesField label={tx(label)} placeholder="All" value={options[k]} onChange={set(k)} names={names} />
|
||||
</Fragment>
|
||||
))}
|
||||
{options.format === "directory" && (
|
||||
@@ -562,11 +732,15 @@ export function RestoreDialog({
|
||||
const [psql, setPsql] = useState<DbPsqlOptions>(DEFAULT_PSQL);
|
||||
const [runKey, setRunKey] = useState<number | null>(null);
|
||||
const running = useToolRuns((s) => (runKey !== null ? s.runs[runKey]?.status === "running" : false));
|
||||
const kind = useDumpKind(file);
|
||||
const tool = picked ?? restoreToolFor(file, kind);
|
||||
const mismatch = dumpMismatch(tool, kind);
|
||||
const info = useDumpInfo(file);
|
||||
const tool = picked ?? restoreToolFor(file, info?.kind ?? null);
|
||||
const mismatch = dumpMismatch(tool, info?.kind ?? null);
|
||||
const executable = executables[tool];
|
||||
const readOnly = !!source?.readOnly;
|
||||
const databases = useDatabaseNames(target);
|
||||
const shown = database || (databases?.current ?? "");
|
||||
const problem = restoreTargetProblem(shown, databases?.names ?? null, false, false);
|
||||
const creates = tool === "pgRestore" ? restore.create : !!info?.createsDatabase;
|
||||
|
||||
const changeFile = setFile;
|
||||
const browse = async (directory: boolean) => {
|
||||
@@ -602,8 +776,11 @@ export function RestoreDialog({
|
||||
job,
|
||||
commandLine,
|
||||
from: file,
|
||||
to: database || (source?.name ?? target),
|
||||
onSuccess: () => void refresh(runTarget),
|
||||
to: shown || (source?.name ?? target),
|
||||
onSuccess: () => {
|
||||
void refresh(runTarget);
|
||||
if (creates) void refresh(splitTarget(target).id);
|
||||
},
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -616,7 +793,7 @@ export function RestoreDialog({
|
||||
{
|
||||
label: "Run",
|
||||
role: "default",
|
||||
disabled: readOnly || !!mismatch || !executable.trim() || !file.trim(),
|
||||
disabled: readOnly || !!mismatch || !!problem || !executable.trim() || !file.trim(),
|
||||
title: readOnly ? tx`The data source is read-only` : undefined,
|
||||
onClick: () => void run(),
|
||||
},
|
||||
@@ -655,7 +832,18 @@ export function RestoreDialog({
|
||||
<span className={styles.formLabel}>
|
||||
<T>Database:</T>
|
||||
</span>
|
||||
<Input aria-label="Database" value={database} onChange={(e) => setDatabase(e.target.value)} />
|
||||
<DatabaseField value={shown} onChange={setDatabase} names={databases?.names ?? null} />
|
||||
<TargetHint
|
||||
problem={problem}
|
||||
database={shown}
|
||||
note={
|
||||
!creates
|
||||
? undefined
|
||||
: tool === "pgRestore"
|
||||
? tx`pg_restore connects to ${shown} and creates the database the archive names.`
|
||||
: tx`The dump creates its own database. psql connects to ${shown} first.`
|
||||
}
|
||||
/>
|
||||
<span className={styles.formLabel}>
|
||||
<T>Path to dump:</T>
|
||||
</span>
|
||||
@@ -724,6 +912,11 @@ export function RestoreDialog({
|
||||
/>
|
||||
<span />
|
||||
<div className={styles.dumpChecks}>
|
||||
<Checkbox
|
||||
checked={restore.create}
|
||||
onChange={setR("create")}
|
||||
label="Create the database from the archive (--create)"
|
||||
/>
|
||||
<Checkbox
|
||||
checked={restore.clean}
|
||||
onChange={setR("clean")}
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
/** DataGrip's Export with 'mysqldump' and Restore with 'mysql' dialogs. */
|
||||
import { useEffect, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { call, commands, type DbToolJob } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { Checkbox, Dialog, IconButton, Input, T, type DialogButton } from "@/ui";
|
||||
import {
|
||||
DEFAULT_MYSQLDUMP,
|
||||
dumpMismatch,
|
||||
restoreTargetProblem,
|
||||
mysqldumpOptions,
|
||||
nameList,
|
||||
outputPath,
|
||||
type MysqldumpForm,
|
||||
} from "./dumpTools";
|
||||
import {
|
||||
DatabaseField,
|
||||
ExecutableField,
|
||||
NamesField,
|
||||
Preview,
|
||||
RunOutput,
|
||||
joinPath,
|
||||
mismatchText,
|
||||
pathKey,
|
||||
runButtons,
|
||||
TargetHint,
|
||||
useDatabaseNames,
|
||||
useDumpInfo,
|
||||
useHome,
|
||||
useTableNames,
|
||||
useToolPreview,
|
||||
} from "./DumpDialogs";
|
||||
import { splitTarget } from "./model";
|
||||
import { closeDialog, refresh, sourceById } from "./store";
|
||||
import { startToolRun, useToolRuns } from "./toolRuns";
|
||||
import styles from "./Database.module.css";
|
||||
|
||||
/** Whether the executable at `path` lists `option` in its `--help` (`false` while unknown). */
|
||||
function useKnowsOption(path: string, option: string): boolean {
|
||||
const [known, setKnown] = useState<{
|
||||
path: string;
|
||||
options: string[];
|
||||
} | null>(null);
|
||||
useEffect(() => {
|
||||
const p = path.trim();
|
||||
if (!p) return;
|
||||
let live = true;
|
||||
const timer = setTimeout(() => {
|
||||
call(commands.dbToolOptions(p))
|
||||
.then((options) => live && setKnown({ path: p, options }))
|
||||
.catch(() => live && setKnown({ path: p, options: [] }));
|
||||
}, 250);
|
||||
return () => {
|
||||
live = false;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [path]);
|
||||
return known?.path === path.trim() && known.options.includes(option);
|
||||
}
|
||||
|
||||
type Switch = {
|
||||
[K in keyof MysqldumpForm]: MysqldumpForm[K] extends boolean ? K : never;
|
||||
}[keyof MysqldumpForm];
|
||||
|
||||
const CHECKS: readonly [Switch, string][] = [
|
||||
["addDropTable", "Add DROP TABLE before CREATE TABLE"],
|
||||
["completeInsert", "Include column names in each INSERT"],
|
||||
["disableKeys", "Add DISABLE KEYS before each INSERT block"],
|
||||
["createOptions", "Include all table options in CREATE TABLE"],
|
||||
["addLocks", "Add LOCK TABLES around each table"],
|
||||
["routines", "Include stored routines"],
|
||||
["addDropTrigger", "Add DROP TRIGGER before CREATE TRIGGER"],
|
||||
["events", "Include scheduled events"],
|
||||
["noData", "Export schema without data"],
|
||||
];
|
||||
|
||||
export function MysqlDumpDialog({ target, database, tables }: { target: string; database: string; tables?: string }) {
|
||||
const source = sourceById(target);
|
||||
const home = useHome();
|
||||
const [executable, setExecutable] = useState("");
|
||||
const [form, setForm] = useState<MysqldumpForm>({
|
||||
...DEFAULT_MYSQLDUMP,
|
||||
databases: database,
|
||||
tables: tables ?? "",
|
||||
});
|
||||
const [edited, setOutput] = useState<string | null>(null);
|
||||
const output = edited ?? (home ? joinPath(home, "{data_source}-{database}-{timestamp}.sql") : "");
|
||||
const [runKey, setRunKey] = useState<number | null>(null);
|
||||
const running = useToolRuns((s) => (runKey !== null ? s.runs[runKey]?.status === "running" : false));
|
||||
const knowsMasking = useKnowsOption(executable, "masking-policies");
|
||||
const chosenDatabases = nameList(form.databases);
|
||||
const oneDatabase = chosenDatabases.length === 1;
|
||||
const databases = useDatabaseNames(target);
|
||||
const tableNames =
|
||||
useTableNames(splitTarget(target).id, oneDatabase ? chosenDatabases : null)?.map((t) => t.name) ?? null;
|
||||
const set =
|
||||
<K extends keyof MysqldumpForm>(k: K) =>
|
||||
(v: MysqldumpForm[K]) =>
|
||||
setForm((f) => ({ ...f, [k]: v }));
|
||||
const jobFor = (file: string): DbToolJob => ({
|
||||
tool: "mysqldump",
|
||||
file,
|
||||
options: mysqldumpOptions(form, knowsMasking),
|
||||
});
|
||||
const preview = useToolPreview(target, executable || "mysqldump", jobFor(output));
|
||||
|
||||
const browse = async () => {
|
||||
try {
|
||||
const { save } = await import("@/platform/dialog");
|
||||
const path = await save({ defaultPath: output });
|
||||
if (path) setOutput(path);
|
||||
} catch {
|
||||
// No dialog (tests): keep typing the path.
|
||||
}
|
||||
};
|
||||
|
||||
const run = async () => {
|
||||
const databases = nameList(form.databases);
|
||||
const file = outputPath(output, {
|
||||
dataSource: source?.name ?? "",
|
||||
database: databases.join("_"),
|
||||
now: new Date(),
|
||||
});
|
||||
const job = jobFor(file);
|
||||
localStorage.setItem(pathKey("mysqldump"), executable);
|
||||
const commandLine = await call(commands.dbToolPreview(target, executable, job)).catch(() => "");
|
||||
setRunKey(
|
||||
startToolRun({
|
||||
target,
|
||||
executable,
|
||||
job,
|
||||
commandLine,
|
||||
output: file,
|
||||
from: databases.join(", ") || tx("all databases"),
|
||||
to: file,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const buttons: DialogButton[] =
|
||||
runKey !== null
|
||||
? runButtons(runKey, running, () => setRunKey(null))
|
||||
: [
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{
|
||||
label: "Run",
|
||||
role: "default",
|
||||
disabled: !executable.trim() || !output.trim(),
|
||||
onClick: () => void run(),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={closeDialog}
|
||||
title={tx`Export with 'mysqldump' (${source?.name ?? target})`}
|
||||
width={760}
|
||||
buttons={buttons}
|
||||
>
|
||||
{runKey !== null ? (
|
||||
<RunOutput runKey={runKey} />
|
||||
) : (
|
||||
<div className={styles.form}>
|
||||
<ExecutableField tool="mysqldump" value={executable} onChange={setExecutable} serverMajor={null} />
|
||||
<span className={styles.formLabel}>
|
||||
<T>Output result to:</T>
|
||||
</span>
|
||||
<div className={styles.formRow}>
|
||||
<Input
|
||||
mono
|
||||
className={styles.dumpPath}
|
||||
aria-label="Output result to"
|
||||
value={output}
|
||||
onChange={(e) => setOutput(e.target.value)}
|
||||
/>
|
||||
<IconButton icon="folder" title="Browse…" onClick={() => void browse()} />
|
||||
</div>
|
||||
<span />
|
||||
<span className={styles.formHint}>
|
||||
<T>Allowed substitution patterns:</T> {"{timestamp}, {data_source}, {database}"}
|
||||
</span>
|
||||
<span className={styles.formLabel}>
|
||||
<T>Databases to dump:</T>
|
||||
</span>
|
||||
<NamesField
|
||||
label="Databases to dump"
|
||||
placeholder={tx("All databases")}
|
||||
value={form.databases}
|
||||
onChange={set("databases")}
|
||||
names={databases?.names ?? null}
|
||||
/>
|
||||
<span className={styles.formLabel}>
|
||||
<T>Tables to dump:</T>
|
||||
</span>
|
||||
<NamesField
|
||||
label="Tables to dump"
|
||||
placeholder="All"
|
||||
disabled={!oneDatabase}
|
||||
title={oneDatabase ? undefined : tx("Tables can be chosen when one database is dumped")}
|
||||
value={oneDatabase ? form.tables : ""}
|
||||
onChange={set("tables")}
|
||||
names={tableNames}
|
||||
/>
|
||||
<span />
|
||||
<div className={styles.dumpChecks}>
|
||||
{CHECKS.map(([k, label]) => (
|
||||
<Checkbox key={k} checked={form[k]} onChange={set(k)} label={label} />
|
||||
))}
|
||||
<Checkbox
|
||||
checked={form.singleTransaction && !form.lockAllTables}
|
||||
disabled={form.lockAllTables}
|
||||
onChange={set("singleTransaction")}
|
||||
label="Consistent snapshot (--single-transaction)"
|
||||
/>
|
||||
<Checkbox
|
||||
checked={form.lockAllTables}
|
||||
onChange={set("lockAllTables")}
|
||||
label="Lock all tables for the whole export (needs RELOAD)"
|
||||
/>
|
||||
{knowsMasking && (
|
||||
<Checkbox
|
||||
checked={form.maskingPolicies}
|
||||
onChange={set("maskingPolicies")}
|
||||
label="Include masking policies"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<Preview text={preview} />
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function MysqlRestoreDialog({ target, database: initialDatabase }: { target: string; database: string }) {
|
||||
const source = sourceById(target);
|
||||
const [executable, setExecutable] = useState("");
|
||||
const [database, setDatabase] = useState(initialDatabase);
|
||||
const [file, setFile] = useState("");
|
||||
const [force, setForce] = useState(false);
|
||||
const [runKey, setRunKey] = useState<number | null>(null);
|
||||
const running = useToolRuns((s) => (runKey !== null ? s.runs[runKey]?.status === "running" : false));
|
||||
const readOnly = !!source?.readOnly;
|
||||
const info = useDumpInfo(file);
|
||||
const mismatch = dumpMismatch("mysql", info?.kind ?? null);
|
||||
const databases = useDatabaseNames(target);
|
||||
const creates = !!info?.createsDatabase;
|
||||
// Until the dump is read, an empty choice is not yet wrong.
|
||||
const problem = restoreTargetProblem(database, databases?.names ?? null, true, creates || !info);
|
||||
const job: DbToolJob = { tool: "mysql", file, options: { database, force } };
|
||||
const preview = useToolPreview(target, executable || "mysql", job);
|
||||
|
||||
const browse = async () => {
|
||||
try {
|
||||
const { open } = await import("@/platform/dialog");
|
||||
const path = await open({
|
||||
multiple: false,
|
||||
directory: false,
|
||||
title: tx("Path to dump"),
|
||||
});
|
||||
if (typeof path === "string") setFile(path);
|
||||
} catch {
|
||||
// No dialog (tests): keep typing the path.
|
||||
}
|
||||
};
|
||||
|
||||
const run = async () => {
|
||||
localStorage.setItem(pathKey("mysql"), executable);
|
||||
const commandLine = await call(commands.dbToolPreview(target, executable, job)).catch(() => preview);
|
||||
setRunKey(
|
||||
startToolRun({
|
||||
target,
|
||||
executable,
|
||||
job,
|
||||
commandLine,
|
||||
from: file,
|
||||
to: database || (source?.name ?? target),
|
||||
onSuccess: () => void refresh(target),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const buttons: DialogButton[] =
|
||||
runKey !== null
|
||||
? runButtons(runKey, running, () => setRunKey(null))
|
||||
: [
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{
|
||||
label: "Run",
|
||||
role: "default",
|
||||
disabled: readOnly || !!mismatch || !!problem || !info || !executable.trim() || !file.trim(),
|
||||
title: readOnly ? tx`The data source is read-only` : undefined,
|
||||
onClick: () => void run(),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={closeDialog}
|
||||
title={tx`Restore with 'mysql' (${source?.name ?? target})`}
|
||||
width={720}
|
||||
buttons={buttons}
|
||||
>
|
||||
{runKey !== null ? (
|
||||
<RunOutput runKey={runKey} />
|
||||
) : (
|
||||
<div className={styles.form}>
|
||||
<ExecutableField tool="mysql" value={executable} onChange={setExecutable} serverMajor={null} />
|
||||
<span className={styles.formLabel}>
|
||||
<T>Database:</T>
|
||||
</span>
|
||||
<DatabaseField
|
||||
value={database}
|
||||
onChange={setDatabase}
|
||||
names={databases?.names ?? null}
|
||||
empty="As named in the dump"
|
||||
/>
|
||||
<TargetHint
|
||||
problem={problem}
|
||||
database={database}
|
||||
note={creates ? tx("The dump creates the databases it names.") : undefined}
|
||||
/>
|
||||
<span className={styles.formLabel}>
|
||||
<T>Path to dump:</T>
|
||||
</span>
|
||||
<div className={styles.formRow}>
|
||||
<Input
|
||||
mono
|
||||
className={styles.dumpPath}
|
||||
aria-label="Path to dump"
|
||||
value={file}
|
||||
onChange={(e) => setFile(e.target.value)}
|
||||
/>
|
||||
<IconButton icon="folder" title="Browse…" onClick={() => void browse()} />
|
||||
</div>
|
||||
<span />
|
||||
<span className={clsx(styles.formHint, mismatch && styles.dumpError)}>
|
||||
{mismatch ? mismatchText(mismatch) : <T>mysql runs the SQL dump that mysqldump wrote.</T>}
|
||||
</span>
|
||||
<span />
|
||||
<Checkbox checked={force} onChange={setForce} label="Continue after errors (--force)" />
|
||||
{readOnly && (
|
||||
<>
|
||||
<span />
|
||||
<span className={clsx(styles.formHint, styles.dumpError)}>
|
||||
<T>The data source is read-only.</T>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
<Preview text={preview} />
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import type { DataSource, DbTableInfo } from "@/platform/ipc";
|
||||
import {
|
||||
DEFAULT_DUMP,
|
||||
DEFAULT_MYSQLDUMP,
|
||||
DEFAULT_RESTORE,
|
||||
baseName,
|
||||
dumpMismatch,
|
||||
@@ -9,7 +10,13 @@ import {
|
||||
dumpScope,
|
||||
formatElapsed,
|
||||
majorOf,
|
||||
mysqlDumpScope,
|
||||
mysqldumpOptions,
|
||||
outputPath,
|
||||
patternName,
|
||||
unquoteName,
|
||||
restoreTargetProblem,
|
||||
toggleName,
|
||||
pickInstall,
|
||||
restoreOptions,
|
||||
restoreToolFor,
|
||||
@@ -31,6 +38,25 @@ describe("forms", () => {
|
||||
expect(options.tables).toEqual(['public."Order Items"', '"a,""b"".c"']);
|
||||
});
|
||||
|
||||
it("send mysqldump tables only with one database, and masking policies only to a client that knows them", () => {
|
||||
const one = mysqldumpOptions({ ...DEFAULT_MYSQLDUMP, databases: "shop", tables: "orders, items" }, false);
|
||||
expect(one).toMatchObject({ databases: ["shop"], tables: ["orders", "items"], maskingPolicies: null });
|
||||
const two = mysqldumpOptions({ ...DEFAULT_MYSQLDUMP, databases: "a b", tables: "orders" }, true);
|
||||
expect(two).toMatchObject({ databases: ["a", "b"], tables: [], maskingPolicies: false });
|
||||
});
|
||||
|
||||
it("turn names into pg_dump patterns and back", () => {
|
||||
for (const name of ["public", "My Schema", 'a"b', "Orders"]) expect(unquoteName(patternName(name))).toBe(name);
|
||||
expect(patternName("Orders")).toBe('"Orders"');
|
||||
expect(unquoteName("Public")).toBe("public");
|
||||
});
|
||||
|
||||
it("toggle a name chosen from a list", () => {
|
||||
expect(toggleName("", "shop")).toBe("shop");
|
||||
expect(toggleName("shop crm", "audit")).toBe("shop, crm, audit");
|
||||
expect(toggleName("shop, crm", "shop")).toBe("crm");
|
||||
});
|
||||
|
||||
it("send the typed name lists as lists", () => {
|
||||
const options = dumpOptions({
|
||||
...DEFAULT_DUMP,
|
||||
@@ -66,6 +92,26 @@ describe("restore", () => {
|
||||
expect(dumpMismatch("psql", "postgresSql")).toBeNull();
|
||||
expect(dumpMismatch("psql", "unknown")).toBeNull();
|
||||
expect(dumpMismatch("pgRestore", null)).toBeNull();
|
||||
expect(dumpMismatch("mysql", "postgresSql")).toBe("postgresIntoMysql");
|
||||
expect(dumpMismatch("mysql", "postgresArchive")).toBe("postgresIntoMysql");
|
||||
expect(dumpMismatch("mysql", "mysqlSql")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("restore target", () => {
|
||||
const existing = ["postgres", "shop"];
|
||||
|
||||
it("needs an existing database", () => {
|
||||
expect(restoreTargetProblem("shop", existing, false, false)).toBeNull();
|
||||
expect(restoreTargetProblem(" shop ", existing, true, false)).toBeNull();
|
||||
expect(restoreTargetProblem("shop_new", existing, false, true)).toBe("missing");
|
||||
expect(restoreTargetProblem("shop_new", null, false, false)).toBeNull();
|
||||
});
|
||||
|
||||
it("lets MySQL run without a database only for a dump that creates its databases", () => {
|
||||
expect(restoreTargetProblem("", existing, true, false)).toBe("noDatabase");
|
||||
expect(restoreTargetProblem("", existing, true, true)).toBeNull();
|
||||
expect(restoreTargetProblem("", existing, false, false)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -102,6 +148,24 @@ describe("dumpScope", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("applies to MySQL sources, schemas (databases) and tables with mysqlDumpScope", () => {
|
||||
const mysql = { ...pg, driver: "mysql", database: "shop" } as DataSource;
|
||||
expect(mysqlDumpScope({ kind: "source", key: "s1", source: mysql }, mysql)).toEqual({
|
||||
target: "s1",
|
||||
database: "shop",
|
||||
});
|
||||
expect(mysqlDumpScope({ kind: "schema", key: "k", id: "s1", schema: "crm" }, mysql)).toEqual({
|
||||
target: "s1",
|
||||
database: "crm",
|
||||
});
|
||||
expect(mysqlDumpScope({ kind: "table", key: "k", id: "s1", schema: "crm", table }, mysql)).toEqual({
|
||||
target: "s1",
|
||||
database: "crm",
|
||||
tables: "Orders",
|
||||
});
|
||||
expect(mysqlDumpScope({ kind: "source", key: "s1", source: pg }, pg)).toBeNull();
|
||||
});
|
||||
|
||||
it("does not apply to other drivers or views", () => {
|
||||
const mysql = { ...pg, driver: "mysql" } as DataSource;
|
||||
expect(dumpScope({ kind: "source", key: "s1", source: mysql }, mysql)).toBeNull();
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
DataSource,
|
||||
DbDumpFormat,
|
||||
DbDumpKind,
|
||||
DbMysqldumpOptions,
|
||||
DbPgDumpOptions,
|
||||
DbPgRestoreOptions,
|
||||
DbPsqlOptions,
|
||||
@@ -24,6 +25,10 @@ type Typed<T, K extends keyof T> = Omit<T, K> & { [P in K]: string };
|
||||
|
||||
export type DumpForm = Typed<DbPgDumpOptions, "schemas" | "tables" | "excludeTables">;
|
||||
export type RestoreForm = Typed<DbPgRestoreOptions, "schemas">;
|
||||
/** `maskingPolicies` is the checkbox; whether the client knows the option is decided at run time. */
|
||||
export type MysqldumpForm = Typed<Omit<DbMysqldumpOptions, "maskingPolicies">, "databases" | "tables"> & {
|
||||
maskingPolicies: boolean;
|
||||
};
|
||||
|
||||
export const DEFAULT_DUMP: DumpForm = {
|
||||
format: "plain",
|
||||
@@ -43,6 +48,7 @@ export const DEFAULT_DUMP: DumpForm = {
|
||||
export const DEFAULT_RESTORE: RestoreForm = {
|
||||
content: "all",
|
||||
schemas: "",
|
||||
create: false,
|
||||
clean: false,
|
||||
ifExists: false,
|
||||
noOwner: false,
|
||||
@@ -54,6 +60,27 @@ export const DEFAULT_RESTORE: RestoreForm = {
|
||||
|
||||
export const DEFAULT_PSQL: DbPsqlOptions = { singleTransaction: true, stopOnError: true };
|
||||
|
||||
/**
|
||||
* `mysqldump`'s own defaults, except `--single-transaction` instead of DataGrip's
|
||||
* `--lock-all-tables`, which needs the RELOAD privilege.
|
||||
*/
|
||||
export const DEFAULT_MYSQLDUMP: MysqldumpForm = {
|
||||
databases: "",
|
||||
tables: "",
|
||||
addDropTable: true,
|
||||
disableKeys: true,
|
||||
addLocks: true,
|
||||
addDropTrigger: false,
|
||||
noData: false,
|
||||
completeInsert: false,
|
||||
createOptions: true,
|
||||
routines: false,
|
||||
events: false,
|
||||
singleTransaction: true,
|
||||
lockAllTables: false,
|
||||
maskingPolicies: false,
|
||||
};
|
||||
|
||||
/** `a, b c` → `["a", "b", "c"]`; a double-quoted part keeps its spaces and commas: `public."Order Items"`. */
|
||||
export function nameList(text: string): string[] {
|
||||
return text.match(/(?:"(?:[^"]|"")*"|[^\s,"]|")+/g) ?? [];
|
||||
@@ -67,6 +94,23 @@ export function restoreOptions(f: RestoreForm): DbPgRestoreOptions {
|
||||
return { ...f, schemas: nameList(f.schemas) };
|
||||
}
|
||||
|
||||
/** The typed list with `name` added, or taken out when it is there: `a, b` + `c` → `a, b, c`. */
|
||||
export function toggleName(text: string, name: string): string {
|
||||
const names = nameList(text);
|
||||
return (names.includes(name) ? names.filter((n) => n !== name) : [...names, name]).join(", ");
|
||||
}
|
||||
|
||||
/** `knowsMasking`: the chosen `mysqldump` lists `--masking-policies` in its `--help`. */
|
||||
export function mysqldumpOptions(f: MysqldumpForm, knowsMasking: boolean): DbMysqldumpOptions {
|
||||
const databases = nameList(f.databases);
|
||||
return {
|
||||
...f,
|
||||
databases,
|
||||
tables: databases.length === 1 ? nameList(f.tables) : [],
|
||||
maskingPolicies: knowsMasking ? f.maskingPolicies : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The PostgreSQL tool for a dump: from its header when known, else `psql` for a `.sql` file and
|
||||
* `pg_restore` for anything else (archives, directories).
|
||||
@@ -77,17 +121,37 @@ export function restoreToolFor(path: string, kind: DbDumpKind | null = null): Ex
|
||||
return /\.sql$/i.test(path.trim()) ? "psql" : "pgRestore";
|
||||
}
|
||||
|
||||
export type DumpMismatch = "mysqlIntoPostgres" | "archiveIntoPsql" | "sqlIntoPgRestore";
|
||||
export type DumpMismatch = "postgresIntoMysql" | "mysqlIntoPostgres" | "archiveIntoPsql" | "sqlIntoPgRestore";
|
||||
|
||||
/** Why `tool` cannot restore a dump of `kind`; `null` when it can, or the kind is unknown. */
|
||||
export function dumpMismatch(tool: DbTool, kind: DbDumpKind | null): DumpMismatch | null {
|
||||
if (!kind || kind === "unknown") return null;
|
||||
if (tool === "mysql") return kind === "mysqlSql" ? null : "postgresIntoMysql";
|
||||
if (kind === "mysqlSql") return "mysqlIntoPostgres";
|
||||
if (tool === "psql" && kind === "postgresArchive") return "archiveIntoPsql";
|
||||
if (tool === "pgRestore" && kind === "postgresSql") return "sqlIntoPgRestore";
|
||||
return null;
|
||||
}
|
||||
|
||||
export type TargetProblem = "missing" | "noDatabase";
|
||||
|
||||
/**
|
||||
* Why a restore cannot run in or connect to `database`; `null` when it can, or while the
|
||||
* databases are unknown. An empty name is the data source's own for PostgreSQL; MySQL then runs
|
||||
* without a database, which only works for a dump that creates its databases.
|
||||
*/
|
||||
export function restoreTargetProblem(
|
||||
database: string,
|
||||
existing: readonly string[] | null,
|
||||
mysql: boolean,
|
||||
createsDatabase: boolean,
|
||||
): TargetProblem | null {
|
||||
const name = database.trim();
|
||||
if (!name) return mysql && !createsDatabase ? "noDatabase" : null;
|
||||
if (!existing) return null;
|
||||
return existing.includes(name) ? null : "missing";
|
||||
}
|
||||
|
||||
/** `2026-03-07_09-05-02` (local time). */
|
||||
export function timestamp(d: Date): string {
|
||||
const p = (n: number) => String(n).padStart(2, "0");
|
||||
@@ -111,10 +175,15 @@ export function withExtension(pattern: string, format: DbDumpFormat): string {
|
||||
}
|
||||
|
||||
/** A name as a `pg_dump` pattern: quoted unless it is a lower-case identifier. */
|
||||
function patternName(name: string): string {
|
||||
export function patternName(name: string): string {
|
||||
return /^[a-z_][a-z0-9_$]*$/.test(name) ? name : `"${name.replaceAll('"', '""')}"`;
|
||||
}
|
||||
|
||||
/** A typed `pg_dump` name back to the name itself: `"My Schema"` → `My Schema`, `Public` → `public`. */
|
||||
export function unquoteName(pattern: string): string {
|
||||
return /^".*"$/.test(pattern) ? pattern.slice(1, -1).replaceAll('""', '"') : pattern.toLowerCase();
|
||||
}
|
||||
|
||||
export interface DumpScope {
|
||||
target: string;
|
||||
database: string;
|
||||
@@ -134,6 +203,19 @@ export function dumpScope(n: DbNode, source: DataSource | undefined): DumpScope
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What Export with 'mysqldump' / Restore with 'mysql' act on for tree node `n`: a MySQL schema
|
||||
* is a database. `null` when they don't apply.
|
||||
*/
|
||||
export function mysqlDumpScope(n: DbNode, source: DataSource | undefined): DumpScope | null {
|
||||
const target = nodeTarget(n);
|
||||
if (!target || source?.driver !== "mysql") return null;
|
||||
if (n.kind === "source") return { target, database: source.database ?? "" };
|
||||
if (n.kind === "schema") return { target, database: n.schema };
|
||||
if (n.kind === "table" && n.table.kind === "table") return { target, database: n.schema, tables: n.table.name };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The major version in a `--version` line (`pg_dump (PostgreSQL) 17.2` → 17). */
|
||||
export function majorOf(version: string): number | null {
|
||||
const m = /(\d+)(?:\.\d+)?/.exec(version);
|
||||
|
||||
@@ -150,7 +150,11 @@ export type DialogState =
|
||||
/** Export with 'pg_dump' of a database, schema or table. */
|
||||
| { kind: "dump"; target: string; database: string; schemas?: string; tables?: string; serverVersion: number | null }
|
||||
/** Restore with 'pg_restore' / 'psql' into a database. */
|
||||
| { kind: "restore"; target: string; database: string; serverVersion: number | null };
|
||||
| { kind: "restore"; target: string; database: string; serverVersion: number | null }
|
||||
/** Export with 'mysqldump' of a data source, database or table. */
|
||||
| { kind: "mysqlDump"; target: string; database: string; tables?: string }
|
||||
/** Restore with 'mysql' into a database. */
|
||||
| { kind: "mysqlRestore"; target: string; database: string };
|
||||
|
||||
/** The schemas and tables of a data source's databases, as far as introspection has read them. */
|
||||
export interface SourceCatalog {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** Runs of `pg_dump` / `pg_restore` / `psql`: they outlive the dialog that started them. */
|
||||
/** Runs of the database client tools (`pg_dump`, `mysql`…): they outlive the dialog that started them. */
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
import { create } from "zustand";
|
||||
import {
|
||||
@@ -23,6 +23,8 @@ export const TOOL_PROGRAMS: Record<DbTool, string> = {
|
||||
pgDump: "pg_dump",
|
||||
pgRestore: "pg_restore",
|
||||
psql: "psql",
|
||||
mysqldump: "mysqldump",
|
||||
mysql: "mysql",
|
||||
};
|
||||
|
||||
export interface ToolRun {
|
||||
|
||||
@@ -45,7 +45,7 @@ import {
|
||||
removeSource,
|
||||
} from "./store";
|
||||
import { tableInput } from "./tableInput";
|
||||
import { dumpScope } from "./dumpTools";
|
||||
import { dumpScope, mysqlDumpScope } from "./dumpTools";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { chooseItem } from "@/workbench/inputDialogs";
|
||||
import { databaseRequest } from "./requests";
|
||||
@@ -468,6 +468,29 @@ export function registerDatabaseTreeActions(): () => void {
|
||||
openDialog({ kind: "restore", target: scope.target, database: scope.database, serverVersion });
|
||||
},
|
||||
}),
|
||||
tree({
|
||||
id: "db.dumpWithMysqldump",
|
||||
title: "Export with 'mysqldump'…",
|
||||
icon: "export",
|
||||
keywords: ["backup", "dump", "mysql", "mariadb"],
|
||||
run: async ({ arg }) => {
|
||||
const n = nodeFrom(arg);
|
||||
const scope = n && mysqlDumpScope(n, sourceOf(n));
|
||||
if (scope && (await connect(scope.target))) openDialog({ kind: "mysqlDump", ...scope });
|
||||
},
|
||||
}),
|
||||
tree({
|
||||
id: "db.restoreWithMysql",
|
||||
title: "Restore with 'mysql'…",
|
||||
icon: "download",
|
||||
keywords: ["backup", "restore", "load dump", "mysql", "mariadb"],
|
||||
run: async ({ arg }) => {
|
||||
const n = nodeFrom(arg);
|
||||
const scope = n && mysqlDumpScope(n, sourceOf(n));
|
||||
if (scope && (await connect(scope.target)))
|
||||
openDialog({ kind: "mysqlRestore", target: scope.target, database: scope.database });
|
||||
},
|
||||
}),
|
||||
tree({
|
||||
id: "db.copyReference",
|
||||
title: "Copy Reference",
|
||||
|
||||
@@ -8,7 +8,7 @@ import { SCRIPT_LABELS, canDrop, canModifyTable, canRename, type ScriptKind } fr
|
||||
import { connectedTargets, openDialog, openSourceDialog, sourceById, useDatabase } from "./store";
|
||||
import { readClipboardPlainText } from "@/platform/clipboard";
|
||||
import { useRemote } from "@/platform/remote";
|
||||
import { dumpScope } from "./dumpTools";
|
||||
import { dumpScope, mysqlDumpScope } from "./dumpTools";
|
||||
|
||||
const act = (
|
||||
action: string,
|
||||
@@ -83,14 +83,17 @@ function sqlScripts(n: DbNode, table: boolean): MenuItem {
|
||||
return { label: "SQL Scripts", submenu: [act("db.ddlToClipboard", n), act("db.ddlToConsole", n), sep, ...scripts] };
|
||||
}
|
||||
|
||||
/** Export with 'pg_dump' / Restore of a PostgreSQL node; the tools run on this machine, so not in remote windows. */
|
||||
/** Export / Restore with the client tools of a PostgreSQL or MySQL node; they run on this machine, so not in remote windows. */
|
||||
function dumpItems(n: DbNode, restore: boolean): MenuItem[] {
|
||||
const source = sourceById(nodeTarget(n));
|
||||
if (useRemote.getState().session || !dumpScope(n, source)) return [];
|
||||
return [
|
||||
act("db.dumpWithPgDump", n),
|
||||
...(restore ? [act("db.restoreWithPgRestore", n, { disabled: !!source?.readOnly })] : []),
|
||||
];
|
||||
if (useRemote.getState().session) return [];
|
||||
const [dump, load] = dumpScope(n, source)
|
||||
? ["db.dumpWithPgDump", "db.restoreWithPgRestore"]
|
||||
: mysqlDumpScope(n, source)
|
||||
? ["db.dumpWithMysqldump", "db.restoreWithMysql"]
|
||||
: [];
|
||||
if (!dump || !load) return [];
|
||||
return [act(dump, n), ...(restore ? [act(load, n, { disabled: !!source?.readOnly })] : [])];
|
||||
}
|
||||
|
||||
function importExport(items: MenuItem[]): MenuItem[] {
|
||||
|
||||
@@ -232,20 +232,23 @@ describe("conflicts", () => {
|
||||
});
|
||||
|
||||
describe("shortcut search", () => {
|
||||
it.each(Object.keys(PRESETS))("keeps the mouse-only caret action configurable in %s", (preset) => {
|
||||
it.each(Object.keys(PRESETS))("keeps mouse-only selection actions configurable in %s", (preset) => {
|
||||
const dispose = registerEditorActions();
|
||||
const originalKeymap = useKeymap.getState();
|
||||
const id = "editor.addOrRemoveCaret";
|
||||
const title = "Add or Remove Caret";
|
||||
try {
|
||||
expect(matchActions(allActions(), title, { isEnabled: () => true, recent: [id] })).toEqual([]);
|
||||
const variants: KeymapDraft["overrides"][] = [{}, { [id]: ["Alt+Button1"] }, { [id]: [] }];
|
||||
for (const overrides of variants) {
|
||||
useKeymap.setState({ preset, overrides });
|
||||
expect(keymapSearchLabels()).toContain(title);
|
||||
const tree = buildKeymapTree(allActions(), { preset, overrides }, title, "");
|
||||
const group = tree.find((node) => node.key === "grp:Editor Actions");
|
||||
expect(group?.kind === "group" && group.children.map((node) => node.key)).toEqual([id]);
|
||||
for (const [id, title] of [
|
||||
["editor.addOrRemoveCaret", "Add or Remove Caret"],
|
||||
["editor.createRectangularSelectionOnMouseDrag", "Create Rectangular Selection on Mouse Drag"],
|
||||
] as const) {
|
||||
expect(matchActions(allActions(), title, { isEnabled: () => true, recent: [id] })).toEqual([]);
|
||||
const variants: KeymapDraft["overrides"][] = [{}, { [id]: ["Alt+Button1"] }, { [id]: [] }];
|
||||
for (const overrides of variants) {
|
||||
useKeymap.setState({ preset, overrides });
|
||||
expect(keymapSearchLabels()).toContain(title);
|
||||
const tree = buildKeymapTree(allActions(), { preset, overrides }, title, "");
|
||||
const group = tree.find((node) => node.key === "grp:Editor Actions");
|
||||
expect(group?.kind === "group" && group.children.map((node) => node.key)).toEqual([id]);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
useKeymap.setState(originalKeymap);
|
||||
|
||||
@@ -1,12 +1,67 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { RecordShortcutDialog } from "../keymap/RecordShortcutDialog";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
|
||||
afterEach(cleanup);
|
||||
const originalPlatform = usePlatform.getState();
|
||||
afterEach(() => usePlatform.setState(originalPlatform));
|
||||
|
||||
const action = { id: "my.action", title: "My Action", category: "Test" };
|
||||
const rectangular = {
|
||||
id: "editor.createRectangularSelectionOnMouseDrag",
|
||||
title: "Create Rectangular Selection on Mouse Drag",
|
||||
category: "Editor Actions",
|
||||
};
|
||||
|
||||
describe("Mouse Shortcut dialog", () => {
|
||||
it.each(["windows", "macos", "linux"] as const)("records middle drag and explains Linux paste on %s", (os) => {
|
||||
usePlatform.setState({ os });
|
||||
const onSubmit = vi.fn();
|
||||
render(
|
||||
<RecordShortcutDialog
|
||||
mouse
|
||||
action={rectangular}
|
||||
actions={[rectangular]}
|
||||
draft={{ preset: "intellij-windows", overrides: { [rectangular.id]: [] } }}
|
||||
onCancel={() => {}}
|
||||
onSubmit={onSubmit}
|
||||
/>,
|
||||
);
|
||||
fireEvent.mouseDown(screen.getByRole("textbox", { name: "Mouse shortcut" }), { button: 1 });
|
||||
expect(screen.getByRole("textbox", { name: "Mouse shortcut" })).toHaveTextContent("Middle Click");
|
||||
expect(
|
||||
screen.queryByText("On Linux, middle-button rectangular selection conflicts with primary selection paste.") !==
|
||||
null,
|
||||
).toBe(os === "linux");
|
||||
fireEvent.click(screen.getByRole("button", { name: "OK" }));
|
||||
expect(onSubmit).toHaveBeenCalledWith("Button2", [], false);
|
||||
});
|
||||
|
||||
it.each([3, 4])("rejects side button %s for rectangular selection without replacing a valid gesture", (button) => {
|
||||
const onSubmit = vi.fn();
|
||||
render(
|
||||
<RecordShortcutDialog
|
||||
mouse
|
||||
action={rectangular}
|
||||
actions={[rectangular]}
|
||||
draft={{ preset: "intellij-windows", overrides: { [rectangular.id]: [] } }}
|
||||
onCancel={() => {}}
|
||||
onSubmit={onSubmit}
|
||||
/>,
|
||||
);
|
||||
const pad = screen.getByRole("textbox", { name: "Mouse shortcut" });
|
||||
fireEvent.mouseDown(pad, { button, altKey: true });
|
||||
expect(screen.getByRole("button", { name: "OK" })).toBeDisabled();
|
||||
expect(pad).toHaveTextContent("Click here with Ctrl, Alt or Command held, or use the middle mouse button");
|
||||
fireEvent.mouseDown(pad, { button: 0, altKey: true });
|
||||
expect(pad).toHaveTextContent("Left Click");
|
||||
fireEvent.mouseDown(pad, { button });
|
||||
expect(pad).toHaveTextContent("Left Click");
|
||||
fireEvent.click(screen.getByRole("button", { name: "OK" }));
|
||||
expect(onSubmit).toHaveBeenCalledWith("Alt+Button1", [], false);
|
||||
});
|
||||
|
||||
it("records and submits Option+Command+left click", () => {
|
||||
const onSubmit = vi.fn();
|
||||
render(
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { act, cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionContext } from "@/platform/actions";
|
||||
import type { Settings } from "@/platform/ipc";
|
||||
|
||||
const settingsSet = vi.fn();
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
isTauri: () => true,
|
||||
commands: { ...real.commands, settingsSet: (...a: unknown[]) => settingsSet(...a) },
|
||||
};
|
||||
});
|
||||
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
import { useKeymap } from "@/platform/keymap";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { presentationAssistantAction } from "../appearanceRuntime";
|
||||
import { validateAppearanceExtras } from "../model/behaviorSchema";
|
||||
import { PresentationAssistant } from "../presentation/PresentationAssistant";
|
||||
import { alternatePreset, presentAction } from "../presentation/presentation";
|
||||
|
||||
let assistant: Record<string, unknown>;
|
||||
const disposers: Array<() => void> = [];
|
||||
|
||||
function useSettings(patch: Record<string, unknown>) {
|
||||
assistant = { ...assistant, ...patch };
|
||||
useProject.setState({ settings: { appearance: { presentationAssistant: { ...assistant } } } as unknown as Settings });
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
assistant = {};
|
||||
useSettings({});
|
||||
usePlatform.setState({ os: "macos" });
|
||||
useKeymap.setState({ preset: "intellij-macos", overrides: {}, extensions: {} });
|
||||
disposers.push(
|
||||
registerActions([
|
||||
{ id: "file.save", title: "Save All", category: "File", run: () => {} },
|
||||
{ id: "test.unbound", title: "Unbound Action", run: () => {} },
|
||||
{ id: "test.internal", title: "Internal Step", hidden: true, run: () => {} },
|
||||
]),
|
||||
);
|
||||
settingsSet.mockReset().mockImplementation(async (_scope: string, key: string, json: string) => {
|
||||
useSettings({ [key.replace("appearance.presentationAssistant.", "")]: JSON.parse(json) });
|
||||
return { status: "ok", data: useProject.getState().settings };
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.useRealTimers();
|
||||
while (disposers.length) disposers.pop()!();
|
||||
useProject.setState({ settings: null });
|
||||
});
|
||||
|
||||
describe("Presentation Assistant", () => {
|
||||
it("is off by default and keeps its options in range", () => {
|
||||
expect(validateAppearanceExtras({}).presentationAssistant).toEqual({
|
||||
enabled: false,
|
||||
size: "medium",
|
||||
durationSeconds: 4,
|
||||
position: "bottom",
|
||||
alternateKeymap: false,
|
||||
});
|
||||
expect(
|
||||
validateAppearanceExtras({ presentationAssistant: { size: "huge", durationSeconds: 0, position: "middle" } })
|
||||
.presentationAssistant,
|
||||
).toMatchObject({ size: "medium", durationSeconds: 1, position: "bottom" });
|
||||
});
|
||||
|
||||
it("names the action with its shortcut, and the other platform's on request", () => {
|
||||
expect(presentAction("file.save", false)).toEqual({ title: "Save All", shortcut: "⌘S" });
|
||||
expect(presentAction("file.save", true)).toEqual({
|
||||
title: "Save All",
|
||||
shortcut: "⌘S",
|
||||
alternate: { keymap: "Windows/Linux", shortcut: "Ctrl+S" },
|
||||
});
|
||||
expect(presentAction("file.save", true, false)?.alternate).toEqual({ keymap: "macOS", shortcut: "⌘S" });
|
||||
expect(presentAction("test.unbound", true)).toEqual({ title: "Unbound Action", shortcut: undefined });
|
||||
expect(presentAction("test.internal", false)).toBeNull();
|
||||
expect(alternatePreset("vscode-macos", true)).toBe("vscode-windows");
|
||||
expect(alternatePreset("my-custom-keymap", false)).toBe("intellij-macos");
|
||||
});
|
||||
|
||||
it("shows each action run while enabled and hides it after the duration", async () => {
|
||||
vi.useFakeTimers();
|
||||
render(<PresentationAssistant />);
|
||||
await act(async () => void (await executeAction("file.save")));
|
||||
expect(screen.queryByTestId("presentation-assistant")).toBeNull();
|
||||
|
||||
act(() => useSettings({ enabled: true, durationSeconds: 2 }));
|
||||
await act(async () => void (await executeAction("file.save")));
|
||||
expect(screen.getByTestId("presentation-assistant").textContent).toBe("Save All⌘S");
|
||||
|
||||
act(() => vi.advanceTimersByTime(1500));
|
||||
expect(screen.getByTestId("presentation-assistant")).toBeTruthy();
|
||||
act(() => vi.advanceTimersByTime(600));
|
||||
expect(screen.queryByTestId("presentation-assistant")).toBeNull();
|
||||
});
|
||||
|
||||
it("is toggled from View › Appearance", async () => {
|
||||
const action = presentationAssistantAction();
|
||||
expect(action.toggled?.()).toBe(false);
|
||||
await action.run({ ctx: {} } as ActionContext);
|
||||
expect(settingsSet).toHaveBeenCalledWith("global", "appearance.presentationAssistant.enabled", "true");
|
||||
expect(action.toggled?.()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -208,6 +208,26 @@ export function appearanceToggleActions(): Action[] {
|
||||
];
|
||||
}
|
||||
|
||||
/** View › Appearance › Presentation Assistant. */
|
||||
export function presentationAssistantAction(): Action {
|
||||
const enabled = () => validateSettings(useProject.getState().settings).appearance.presentationAssistant.enabled;
|
||||
return {
|
||||
id: "view.togglePresentationAssistant",
|
||||
title: "Presentation Assistant",
|
||||
category: "View",
|
||||
keywords: ["appearance", "show shortcuts", "action names", "screencast", "demo", "key promoter"],
|
||||
toggled: enabled,
|
||||
run: async () => {
|
||||
if (!isTauri()) return;
|
||||
useProject.setState({
|
||||
settings: await call(
|
||||
commands.settingsSet("global", "appearance.presentationAssistant.enabled", JSON.stringify(!enabled())),
|
||||
),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// View › Appearance › Navigation Bar: a radio choice (Top / Status Bar / hidden)
|
||||
|
||||
|
||||
@@ -38,7 +38,13 @@ import {
|
||||
settingsTitle,
|
||||
useSettingsDialog,
|
||||
} from "./model/staging";
|
||||
import { appearanceToggleActions, navigationBarActions, zoomActions } from "./appearanceRuntime";
|
||||
import {
|
||||
appearanceToggleActions,
|
||||
navigationBarActions,
|
||||
presentationAssistantAction,
|
||||
zoomActions,
|
||||
} from "./appearanceRuntime";
|
||||
import { PresentationAssistant } from "./presentation/PresentationAssistant";
|
||||
import { activateFileTypes } from "./fileTypesRuntime";
|
||||
import { trackRuntimeSettings } from "./runtime";
|
||||
import { installActionProxies, installSettingsHost } from "./window/bridge";
|
||||
@@ -129,6 +135,8 @@ export function activate(): () => void {
|
||||
registerOverlay({ id: "settings.projectStructure", component: LazyProjectStructureDialog }),
|
||||
registerActions(zoomActions()),
|
||||
registerActions(appearanceToggleActions()),
|
||||
registerActions([presentationAssistantAction()]),
|
||||
registerOverlay({ id: "settings.presentationAssistant", component: PresentationAssistant }),
|
||||
registerActions(navigationBarActions()),
|
||||
registerActions(settingsActions((page, newProjects) => void showSettings(page, newProjects))),
|
||||
registerActions([
|
||||
|
||||
@@ -15,6 +15,7 @@ import { groupPath } from "./groups";
|
||||
import { StrokeRecorder } from "./StrokeRecorder";
|
||||
import styles from "./Keymap.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
|
||||
export interface RecordShortcutDialogProps {
|
||||
action: Pick<Action, "id" | "title" | "category" | "when">;
|
||||
@@ -23,7 +24,7 @@ export interface RecordShortcutDialogProps {
|
||||
onCancel: () => void;
|
||||
/** `removeConflicts`: also unbind the conflicting assignments. */
|
||||
onSubmit: (binding: string, conflicts: Conflict[], removeConflicts: boolean) => void;
|
||||
/** Record a mouse shortcut (modified left clicks or side buttons) instead of keys. */
|
||||
/** Record a mouse shortcut (modified left clicks, middle or side buttons) instead of keys. */
|
||||
mouse?: boolean;
|
||||
}
|
||||
|
||||
@@ -31,6 +32,8 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi
|
||||
const [first, setFirst] = useState("");
|
||||
const [second, setSecond] = useState("");
|
||||
const [useSecond, setUseSecond] = useState(false);
|
||||
const os = usePlatform((s) => s.os);
|
||||
const rectangularSelection = action.id === "editor.createRectangularSelectionOnMouseDrag";
|
||||
|
||||
const binding =
|
||||
mouse || isPageSwipe(first) ? first : first && useSecond ? (second ? `${first} ${second}` : "") : first;
|
||||
@@ -76,7 +79,7 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi
|
||||
>
|
||||
<div className={styles.recordBody}>
|
||||
{mouse ? (
|
||||
<MouseRecorder value={first} onChange={setFirst} />
|
||||
<MouseRecorder value={first} onChange={setFirst} sideButtons={!rectangularSelection} />
|
||||
) : (
|
||||
<KeyStrokes
|
||||
first={first}
|
||||
@@ -87,6 +90,11 @@ export function RecordShortcutDialog({ action, actions, draft, onCancel, onSubmi
|
||||
setUseSecond={setUseSecond}
|
||||
/>
|
||||
)}
|
||||
{mouse && os === "linux" && rectangularSelection && /(?:^|\+)Button2$/.test(binding) && (
|
||||
<div className={styles.recordHint}>
|
||||
<T>On Linux, middle-button rectangular selection conflicts with primary selection paste.</T>
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.conflictsLabel}>
|
||||
<T>Conflicts:</T>
|
||||
</div>
|
||||
@@ -180,10 +188,20 @@ function KeyStrokes({ first, second, useSecond, setFirst, setSecond, setUseSecon
|
||||
);
|
||||
}
|
||||
|
||||
/** Record modified left clicks and side buttons; shortcuts stay off while the dialog is open. */
|
||||
function MouseRecorder({ value, onChange }: { value: string; onChange: (binding: string) => void }) {
|
||||
/** Shortcuts stay off while the dialog records mouse buttons and modifiers. */
|
||||
function MouseRecorder({
|
||||
value,
|
||||
onChange,
|
||||
sideButtons,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (binding: string) => void;
|
||||
sideButtons: boolean;
|
||||
}) {
|
||||
useEffect(() => suspendKeyboardDispatch(), []);
|
||||
const record = (e: MouseEvent<HTMLDivElement>) => {
|
||||
// Rectangular selection only handles left and middle buttons.
|
||||
if (!sideButtons && e.button > 1) return;
|
||||
const stroke = mouseStrokeOf(e.nativeEvent);
|
||||
if (!stroke) return;
|
||||
e.preventDefault();
|
||||
@@ -204,7 +222,11 @@ function MouseRecorder({ value, onChange }: { value: string; onChange: (binding:
|
||||
<span className={styles.recorded}>{formatBinding(value)}</span>
|
||||
) : (
|
||||
<span className={styles.recorderPlaceholder}>
|
||||
<T>Click here with Ctrl, Alt or Command held, or use a mouse side button</T>
|
||||
{sideButtons ? (
|
||||
<T>Click here with Ctrl, Alt or Command held, or use a middle or side mouse button</T>
|
||||
) : (
|
||||
<T>Click here with Ctrl, Alt or Command held, or use the middle mouse button</T>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -35,6 +35,27 @@ export interface BackgroundImageValid {
|
||||
fill: BackgroundImageFill;
|
||||
anchor: BackgroundImageAnchor;
|
||||
}
|
||||
export type PresentationAssistantSize = "small" | "medium" | "large";
|
||||
export const PRESENTATION_ASSISTANT_POSITIONS = [
|
||||
"top-left",
|
||||
"top",
|
||||
"top-right",
|
||||
"bottom-left",
|
||||
"bottom",
|
||||
"bottom-right",
|
||||
] as const;
|
||||
export type PresentationAssistantPosition = (typeof PRESENTATION_ASSISTANT_POSITIONS)[number];
|
||||
export const PRESENTATION_ASSISTANT_DURATION = { min: 1, max: 60 } as const;
|
||||
|
||||
/** Appearance › Presentation Assistant: the name and shortcut of each action the user runs. */
|
||||
export interface PresentationAssistantValid {
|
||||
enabled: boolean;
|
||||
size: PresentationAssistantSize;
|
||||
durationSeconds: number;
|
||||
position: PresentationAssistantPosition;
|
||||
/** Also show the other platform's shortcut (macOS ⇄ Windows/Linux). */
|
||||
alternateKeymap: boolean;
|
||||
}
|
||||
/** Themes selectable as "preferred" when syncing with the OS. */
|
||||
export type ConcreteTheme = ThemeChoiceId;
|
||||
|
||||
@@ -77,6 +98,7 @@ export interface AppearanceExtras {
|
||||
* the editor, in the status bar, or not at all. */
|
||||
navigationBar: NavigationBarPosition;
|
||||
backgroundImage: BackgroundImageValid;
|
||||
presentationAssistant: PresentationAssistantValid;
|
||||
}
|
||||
|
||||
export interface DateFormatValid {
|
||||
@@ -156,6 +178,13 @@ export const DEFAULT_APPEARANCE_EXTRAS: AppearanceExtras = {
|
||||
showStatusBar: true,
|
||||
navigationBar: "statusBar",
|
||||
backgroundImage: { path: "", opacity: 15, fill: "scale", anchor: "center" },
|
||||
presentationAssistant: {
|
||||
enabled: false,
|
||||
size: "medium",
|
||||
durationSeconds: 4,
|
||||
position: "bottom",
|
||||
alternateKeymap: false,
|
||||
},
|
||||
};
|
||||
|
||||
const NAV_BAR_POSITIONS: readonly NavigationBarPosition[] = ["top", "statusBar", "hidden"];
|
||||
@@ -238,6 +267,19 @@ export function validateAppearanceExtras(raw: unknown): AppearanceExtras {
|
||||
return oneOf(a.navigationBar, NAV_BAR_POSITIONS, d.navigationBar);
|
||||
})(),
|
||||
backgroundImage: validateBackgroundImage(a.backgroundImage),
|
||||
presentationAssistant: validatePresentationAssistant(a.presentationAssistant),
|
||||
};
|
||||
}
|
||||
|
||||
function validatePresentationAssistant(raw: unknown): PresentationAssistantValid {
|
||||
const p = obj(raw);
|
||||
const d = DEFAULT_APPEARANCE_EXTRAS.presentationAssistant;
|
||||
return {
|
||||
enabled: bool(p.enabled, d.enabled),
|
||||
size: oneOf(p.size, ["small", "medium", "large"], d.size),
|
||||
durationSeconds: int(p.durationSeconds, d.durationSeconds, PRESENTATION_ASSISTANT_DURATION),
|
||||
position: oneOf(p.position, PRESENTATION_ASSISTANT_POSITIONS, d.position),
|
||||
alternateKeymap: bool(p.alternateKeymap, d.alternateKeymap),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,9 @@ import {
|
||||
type NotificationGroupValid,
|
||||
type NavigationBarPosition,
|
||||
type OpenProjectIn,
|
||||
PRESENTATION_ASSISTANT_DURATION,
|
||||
type PresentationAssistantPosition,
|
||||
type PresentationAssistantSize,
|
||||
} from "../model/behaviorSchema";
|
||||
import { ACCENT_PRESETS, LIMITS, type ThemeId } from "../model/schema";
|
||||
import type { PageSpec } from "./spec";
|
||||
@@ -393,6 +396,21 @@ const AA_OPTIONS: SelectOption<Antialiasing>[] = [
|
||||
{ value: "none", label: "No antialiasing" },
|
||||
];
|
||||
|
||||
const PRESENTATION_SIZE_OPTIONS: SelectOption<PresentationAssistantSize>[] = [
|
||||
{ value: "small", label: "Small" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "large", label: "Large" },
|
||||
];
|
||||
|
||||
const PRESENTATION_POSITION_OPTIONS: SelectOption<PresentationAssistantPosition>[] = [
|
||||
{ value: "top-left", label: "Top left" },
|
||||
{ value: "top", label: "Top center" },
|
||||
{ value: "top-right", label: "Top right" },
|
||||
{ value: "bottom-left", label: "Bottom left" },
|
||||
{ value: "bottom", label: "Bottom center" },
|
||||
{ value: "bottom-right", label: "Bottom right" },
|
||||
];
|
||||
|
||||
const NAV_BAR_OPTIONS: SelectOption<NavigationBarPosition>[] = [
|
||||
{ value: "top", label: "Top" },
|
||||
{ value: "statusBar", label: "Status Bar" },
|
||||
@@ -966,6 +984,50 @@ export const BEHAVIOR_PAGES: PageSpec[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "appearance.presentationAssistant",
|
||||
title: "Presentation Assistant",
|
||||
order: 0,
|
||||
keywords: ["action names", "shortcuts", "screencast", "demo", "presentation"],
|
||||
sections: [
|
||||
{
|
||||
options: [
|
||||
{
|
||||
kind: "toggle",
|
||||
key: "appearance.presentationAssistant.enabled",
|
||||
label: "Show action names and shortcuts",
|
||||
hint: "Each action you run shows its name and shortcut in a popup, for screencasts and demos.",
|
||||
},
|
||||
{
|
||||
kind: "select",
|
||||
key: "appearance.presentationAssistant.size",
|
||||
label: "Popup size",
|
||||
options: PRESENTATION_SIZE_OPTIONS,
|
||||
},
|
||||
{
|
||||
kind: "number",
|
||||
key: "appearance.presentationAssistant.durationSeconds",
|
||||
label: "Duration",
|
||||
...PRESENTATION_ASSISTANT_DURATION,
|
||||
integer: true,
|
||||
unit: "seconds",
|
||||
},
|
||||
{
|
||||
kind: "select",
|
||||
key: "appearance.presentationAssistant.position",
|
||||
label: "Popup position",
|
||||
options: PRESENTATION_POSITION_OPTIONS,
|
||||
},
|
||||
{
|
||||
kind: "toggle",
|
||||
key: "appearance.presentationAssistant.alternateKeymap",
|
||||
label: "Also show the other platform's shortcut",
|
||||
hint: "macOS shortcuts on Windows and Linux, Windows/Linux shortcuts on macOS.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "general",
|
||||
title: "System Settings",
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
.popup {
|
||||
position: fixed;
|
||||
z-index: var(--z-toast);
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: var(--space-3);
|
||||
max-width: calc(100vw - 32px);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
border: 1px solid var(--border-popup);
|
||||
border-radius: var(--radius-popup-large);
|
||||
background: var(--bg-popup);
|
||||
box-shadow: var(--shadow-popup);
|
||||
color: var(--fg-strong);
|
||||
pointer-events: none;
|
||||
white-space: nowrap;
|
||||
animation: fade-in 120ms ease-out;
|
||||
}
|
||||
|
||||
.leaving {
|
||||
opacity: 0;
|
||||
transition: opacity 300ms ease-in;
|
||||
}
|
||||
|
||||
.top-left,
|
||||
.top,
|
||||
.top-right {
|
||||
top: 56px;
|
||||
}
|
||||
|
||||
.bottom-left,
|
||||
.bottom,
|
||||
.bottom-right {
|
||||
bottom: 48px;
|
||||
}
|
||||
|
||||
.top-left,
|
||||
.bottom-left {
|
||||
left: 24px;
|
||||
}
|
||||
|
||||
.top-right,
|
||||
.bottom-right {
|
||||
right: 24px;
|
||||
}
|
||||
|
||||
.top,
|
||||
.bottom {
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
|
||||
.title {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.shortcut {
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
|
||||
.keymap {
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.small {
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.medium {
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.large {
|
||||
font-size: 32px;
|
||||
}
|
||||
|
||||
.small .shortcut,
|
||||
.small .keymap {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.medium .shortcut,
|
||||
.medium .keymap {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.large .shortcut,
|
||||
.large .keymap {
|
||||
font-size: 26px;
|
||||
}
|
||||
|
||||
@keyframes fade-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.popup {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.leaving {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { onActionExecuted } from "@/platform/actions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { validateSettings } from "../model/schema";
|
||||
import { presentAction, type PresentedAction } from "./presentation";
|
||||
import styles from "./PresentationAssistant.module.css";
|
||||
|
||||
const FADE_MS = 300;
|
||||
|
||||
/** Appearance › Presentation Assistant: the name and shortcut of each action the user runs. */
|
||||
export function PresentationAssistant() {
|
||||
const raw = useProject((s) => s.settings);
|
||||
const settings = useMemo(() => validateSettings(raw).appearance.presentationAssistant, [raw]);
|
||||
const [shown, setShown] = useState<{ action: PresentedAction; key: number; leaving: boolean } | null>(null);
|
||||
const timers = useRef<ReturnType<typeof setTimeout>[]>([]);
|
||||
const { enabled, durationSeconds, alternateKeymap } = settings;
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
let key = 0;
|
||||
const clear = () => {
|
||||
for (const t of timers.current) clearTimeout(t);
|
||||
timers.current = [];
|
||||
};
|
||||
const off = onActionExecuted((id) => {
|
||||
const action = presentAction(id, alternateKeymap);
|
||||
if (!action) return;
|
||||
clear();
|
||||
const current = ++key;
|
||||
setShown({ action, key: current, leaving: false });
|
||||
const hold = Math.max(0, durationSeconds * 1000 - FADE_MS);
|
||||
timers.current.push(
|
||||
setTimeout(() => setShown((s) => (s?.key === current ? { ...s, leaving: true } : s)), hold),
|
||||
setTimeout(() => setShown((s) => (s?.key === current ? null : s)), hold + FADE_MS),
|
||||
);
|
||||
});
|
||||
return () => {
|
||||
off();
|
||||
clear();
|
||||
// A popup whose timers were just cleared would otherwise stay up.
|
||||
setShown(null);
|
||||
};
|
||||
}, [enabled, durationSeconds, alternateKeymap]);
|
||||
|
||||
if (!enabled || !shown) return null;
|
||||
const { action, leaving } = shown;
|
||||
return (
|
||||
<div
|
||||
className={[styles.popup, styles[settings.size], styles[settings.position], leaving && styles.leaving]
|
||||
.filter(Boolean)
|
||||
.join(" ")}
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
data-testid="presentation-assistant"
|
||||
>
|
||||
<span className={styles.title}>{action.title}</span>
|
||||
{action.shortcut && <span className={styles.shortcut}>{action.shortcut}</span>}
|
||||
{action.alternate && (
|
||||
<span className={styles.keymap}>
|
||||
{action.alternate.shortcut} ({action.alternate.keymap})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Presentation Assistant: what to show for an action the user ran, its name and shortcut, and
|
||||
* optionally the shortcut in the other platform's keymap (macOS ⇄ Windows/Linux).
|
||||
*/
|
||||
import { getAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import {
|
||||
formatBinding,
|
||||
isMacHost,
|
||||
isMouseBinding,
|
||||
presetBindings,
|
||||
primaryKeyBinding,
|
||||
PRESETS,
|
||||
useKeymap,
|
||||
} from "@/platform/keymap";
|
||||
|
||||
export interface PresentedAction {
|
||||
title: string;
|
||||
shortcut?: string;
|
||||
/** The shortcut in the other platform's keymap, with that platform's name. */
|
||||
alternate?: { keymap: string; shortcut: string };
|
||||
}
|
||||
|
||||
/** The same keymap family on the other platform (`intellij-macos` ⇄ `intellij-windows`). */
|
||||
export function alternatePreset(preset: string, mac: boolean): string {
|
||||
const swapped = mac ? preset.replace(/-macos$/, "-windows") : preset.replace(/-windows$/, "-macos");
|
||||
if (swapped !== preset && swapped in PRESETS) return swapped;
|
||||
return mac ? "intellij-windows" : "intellij-macos";
|
||||
}
|
||||
|
||||
export function presentAction(id: string, alternateKeymap: boolean, mac = isMacHost()): PresentedAction | null {
|
||||
const action = getAction(id);
|
||||
// Hidden actions are internal steps (accepting a completion, focusing the editor), not commands.
|
||||
if (!action || action.hidden) return null;
|
||||
const title = action.verbatim ? action.title : tx(action.title);
|
||||
const binding = primaryKeyBinding(id);
|
||||
const presented: PresentedAction = { title, shortcut: binding ? formatBinding(binding, mac) : undefined };
|
||||
if (alternateKeymap) {
|
||||
const other = presetBindings(alternatePreset(useKeymap.getState().preset, mac), id).find((b) => !isMouseBinding(b));
|
||||
if (other) presented.alternate = { keymap: mac ? "Windows/Linux" : "macOS", shortcut: formatBinding(other, !mac) };
|
||||
}
|
||||
return presented;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { readdirSync, readFileSync } from "node:fs";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
dispatchForwardedKey,
|
||||
bindingsFor,
|
||||
effectiveBindings,
|
||||
FORWARDABLE_ACTIONS,
|
||||
formatBinding,
|
||||
@@ -11,8 +12,10 @@ import {
|
||||
letterOf,
|
||||
normalizeBinding,
|
||||
parseDoubleModifier,
|
||||
presetBindings,
|
||||
strokeOf,
|
||||
useKeymap,
|
||||
withBindings,
|
||||
} from "./keymap";
|
||||
import { executeAction, registerAction } from "./actions";
|
||||
import { clearContext, setContext } from "./context";
|
||||
@@ -37,6 +40,37 @@ describe("keymap", () => {
|
||||
useKeymap.setState({ overrides: initial.overrides, extensions: initial.extensions });
|
||||
});
|
||||
|
||||
it("uses platform defaults consistently and preserves explicit Linux middle bindings", () => {
|
||||
const keymap = useKeymap.getState();
|
||||
const platform = usePlatform.getState();
|
||||
const id = "editor.createRectangularSelectionOnMouseDrag";
|
||||
try {
|
||||
useKeymap.setState({ preset: "intellij-windows", overrides: {}, extensions: {} });
|
||||
usePlatform.setState({ os: "windows" });
|
||||
const windows = effectiveBindings();
|
||||
expect(bindingsFor(id)).toEqual(["Alt+Button1", "Button2"]);
|
||||
expect(windows).toContainEqual(["Button2", id]);
|
||||
|
||||
usePlatform.setState({ os: "linux" });
|
||||
expect(effectiveBindings()).not.toBe(windows);
|
||||
expect(effectiveBindings()).not.toContainEqual(["Button2", id]);
|
||||
expect(bindingsFor(id)).toEqual(["Alt+Button1"]);
|
||||
expect(presetBindings("intellij-windows", id)).toEqual(["Alt+Button1"]);
|
||||
const overrides = withBindings({ preset: "intellij-windows", overrides: {} }, id, ["Alt+Button1", "Button2"]);
|
||||
expect(overrides[id]).toEqual(["Alt+Button1", "Button2"]);
|
||||
useKeymap.setState({ overrides });
|
||||
expect(bindingsFor(id)).toEqual(["Alt+Button1", "Button2"]);
|
||||
expect(effectiveBindings()).toContainEqual(["Button2", id]);
|
||||
useKeymap.setState({ overrides: { [id]: [] } });
|
||||
expect(bindingsFor(id)).toEqual([]);
|
||||
useKeymap.setState({ overrides: {} });
|
||||
expect(bindingsFor(id)).toEqual(["Alt+Button1"]);
|
||||
} finally {
|
||||
useKeymap.setState(keymap);
|
||||
usePlatform.setState(platform);
|
||||
}
|
||||
});
|
||||
|
||||
it("formats macOS style", () => {
|
||||
expect(formatBinding("Meta+Shift+O")).toBe("⇧⌘O");
|
||||
expect(formatBinding("Alt+Enter")).toBe("⌥↵");
|
||||
|
||||
@@ -20,6 +20,7 @@ import { eclipseWindows } from "./keymaps/eclipse-windows";
|
||||
import { vscodeMacos } from "./keymaps/vscode-macos";
|
||||
import { vscodeWindows } from "./keymaps/vscode-windows";
|
||||
import { usePlatform } from "./platformInfo";
|
||||
import { tx } from "./i18n";
|
||||
import { isImeKey } from "./ime";
|
||||
import { isPageSwipe, PAGE_SWIPE_EVENT } from "./pageSwipe";
|
||||
|
||||
@@ -86,14 +87,14 @@ export function isMouseBinding(binding: string): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* Side buttons, or a left click with Ctrl/Alt/Meta. Plain and Shift-only
|
||||
* left clicks keep selection semantics; middle/right clicks keep their own meaning.
|
||||
* Middle/side buttons, or a left click with Ctrl/Alt/Meta. Plain and Shift-only
|
||||
* left clicks keep selection semantics; right clicks keep the context menu.
|
||||
*/
|
||||
export function mouseStrokeOf(
|
||||
e: Pick<MouseEvent, "button" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">,
|
||||
): string | null {
|
||||
if (!Number.isInteger(e.button) || e.button < 0) return null;
|
||||
if (e.button < 3 && !(e.button === 0 && (e.ctrlKey || e.altKey || e.metaKey))) return null;
|
||||
if (e.button === 2 || (e.button === 0 && !(e.ctrlKey || e.altKey || e.metaKey))) return null;
|
||||
const mods = [e.ctrlKey && "Ctrl", e.altKey && "Alt", e.shiftKey && "Shift", e.metaKey && "Meta"].filter(Boolean);
|
||||
return [...mods, `Button${e.button + 1}`].join("+");
|
||||
}
|
||||
@@ -194,39 +195,50 @@ export function suspendKeyboardDispatch(): () => void {
|
||||
};
|
||||
}
|
||||
|
||||
/** Linux reserves middle paste by default; explicit overrides bypass this filter. */
|
||||
function platformPreset(preset: string): Keymap {
|
||||
const own = PRESETS[preset] ?? {};
|
||||
const id = "editor.createRectangularSelectionOnMouseDrag";
|
||||
if (usePlatform.getState().os !== "linux" || !own[id]) return own;
|
||||
return { ...own, [id]: own[id].filter((binding) => binding !== "Button2") };
|
||||
}
|
||||
|
||||
export function bindingsFor(actionId: string): string[] {
|
||||
const { preset, overrides, extensions } = useKeymap.getState();
|
||||
return overrides[actionId] ?? PRESETS[preset]?.[actionId] ?? usableExtensionBindings(extensions)[actionId] ?? [];
|
||||
return overrides[actionId] ?? platformPreset(preset)[actionId] ?? usableExtensionBindings(extensions)[actionId] ?? [];
|
||||
}
|
||||
|
||||
let bindingsCache: {
|
||||
preset: string;
|
||||
overrides: Keymap;
|
||||
extensions: Keymap;
|
||||
os: string;
|
||||
pairs: Array<[string, string]>;
|
||||
} | null = null;
|
||||
|
||||
/** Every (binding, actionId) pair of the effective keymap. */
|
||||
export function effectiveBindings(): Array<[string, string]> {
|
||||
const { preset, overrides, extensions } = useKeymap.getState();
|
||||
const { os } = usePlatform.getState();
|
||||
// The dispatcher asks for these on every keystroke; merging and normalizing
|
||||
// the whole keymap each time costs more than handling the key. The store
|
||||
// replaces `overrides` / `extensions` wholesale, so identity tracks changes.
|
||||
if (
|
||||
bindingsCache?.preset === preset &&
|
||||
bindingsCache.os === os &&
|
||||
bindingsCache.overrides === overrides &&
|
||||
bindingsCache.extensions === extensions
|
||||
)
|
||||
return bindingsCache.pairs;
|
||||
const merged: Keymap = { ...usableExtensionBindings(extensions), ...PRESETS[preset], ...overrides };
|
||||
const merged: Keymap = { ...usableExtensionBindings(extensions), ...platformPreset(preset), ...overrides };
|
||||
const pairs = Object.entries(merged).flatMap(([id, keys]) =>
|
||||
keys.map((k) => [normalizeBinding(k), id] as [string, string]),
|
||||
);
|
||||
bindingsCache = { preset, overrides, extensions, pairs };
|
||||
bindingsCache = { preset, overrides, extensions, os, pairs };
|
||||
return pairs;
|
||||
}
|
||||
|
||||
let extensionCache: { source: Keymap; preset: string; overrides: Keymap; usable: Keymap } | null = null;
|
||||
let extensionCache: { source: Keymap; preset: string; overrides: Keymap; os: string; usable: Keymap } | null = null;
|
||||
|
||||
/**
|
||||
* Plugin default bindings that stay: those of actions the preset and the
|
||||
@@ -235,13 +247,15 @@ let extensionCache: { source: Keymap; preset: string; overrides: Keymap; usable:
|
||||
*/
|
||||
function usableExtensionBindings(extensions: Keymap | undefined = {}): Keymap {
|
||||
const { preset, overrides } = useKeymap.getState();
|
||||
const { os } = usePlatform.getState();
|
||||
if (
|
||||
extensionCache?.source === extensions &&
|
||||
extensionCache.preset === preset &&
|
||||
extensionCache.os === os &&
|
||||
extensionCache.overrides === overrides
|
||||
)
|
||||
return extensionCache.usable;
|
||||
const builtIn: Keymap = { ...PRESETS[preset], ...overrides };
|
||||
const builtIn: Keymap = { ...platformPreset(preset), ...overrides };
|
||||
const taken = new Set(Object.values(builtIn).flatMap((keys) => keys.map(normalizeBinding)));
|
||||
const usable: Keymap = {};
|
||||
for (const [id, keys] of Object.entries(extensions)) {
|
||||
@@ -250,7 +264,7 @@ function usableExtensionBindings(extensions: Keymap | undefined = {}): Keymap {
|
||||
for (const k of free) taken.add(normalizeBinding(k));
|
||||
if (free.length) usable[id] = free;
|
||||
}
|
||||
extensionCache = { source: extensions, preset, overrides, usable };
|
||||
extensionCache = { source: extensions, preset, overrides, os, usable };
|
||||
return usable;
|
||||
}
|
||||
|
||||
@@ -390,7 +404,7 @@ export function formatBinding(binding: string, mac = isMacHost()): string {
|
||||
if (isMouseBinding(binding)) {
|
||||
const parts = normalizeBinding(binding).split("+");
|
||||
const key = parts.pop();
|
||||
const button = key === "Button1" ? "Left Click" : `${key} Click`;
|
||||
const button = key === "Button1" ? "Left Click" : key === "Button2" ? tx("Middle Click") : `${key} Click`;
|
||||
return mac ? parts.map((p) => SYMBOLS[p] ?? p).join("") + button : [...parts, button].join("+");
|
||||
}
|
||||
if (!mac)
|
||||
@@ -489,6 +503,8 @@ export function dispatchMouseShortcut(e: MouseEvent, prepare?: (id: string) => b
|
||||
for (const id of ids.reverse()) {
|
||||
const action = getAction(id);
|
||||
if (!action || !isActionKeyEnabled(action)) continue;
|
||||
// A rectangular selection needs the drag; do not consume it as an ordinary click.
|
||||
if (id === "editor.createRectangularSelectionOnMouseDrag") return false;
|
||||
if (prepare && !prepare(id)) return false;
|
||||
void executeAction(id, arg);
|
||||
return true;
|
||||
@@ -753,6 +769,8 @@ export function installKeyboardDispatcher(
|
||||
reset();
|
||||
return;
|
||||
}
|
||||
// Editors arbitrate middle click/drag; other components may use middle paste.
|
||||
if (e.button === 1) return;
|
||||
const stroke = mouseStrokeOf(e);
|
||||
if (!stroke) return;
|
||||
if (e.button === 0) {
|
||||
@@ -831,7 +849,7 @@ export interface KeymapDraft {
|
||||
* override like any other.
|
||||
*/
|
||||
export function presetBindings(preset: string, id: string): string[] {
|
||||
const own = PRESETS[preset];
|
||||
const own = platformPreset(preset);
|
||||
const keys = own && id in own ? own[id] : useKeymap.getState().extensions?.[id];
|
||||
return (keys ?? []).map(normalizeBinding);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
} from "./keymap";
|
||||
import { registerAction } from "./actions";
|
||||
import { setContext } from "./context";
|
||||
import { setLocale, useI18n } from "./i18n";
|
||||
|
||||
const noMods = { metaKey: false, ctrlKey: false, altKey: false, shiftKey: false };
|
||||
|
||||
@@ -28,7 +29,9 @@ describe("mouse shortcuts", () => {
|
||||
expect(mouseStrokeOf({ ...noMods, button: 3 })).toBe("Button4");
|
||||
expect(mouseStrokeOf({ ...noMods, button: 4 })).toBe("Button5");
|
||||
expect(mouseStrokeOf({ ...noMods, button: 3, altKey: true, shiftKey: true })).toBe("Alt+Shift+Button4");
|
||||
for (const button of [0, 1, 2]) expect(mouseStrokeOf({ ...noMods, button })).toBeNull();
|
||||
for (const button of [0, 2]) expect(mouseStrokeOf({ ...noMods, button })).toBeNull();
|
||||
expect(mouseStrokeOf({ ...noMods, button: 1 })).toBe("Button2");
|
||||
expect(mouseStrokeOf({ ...noMods, button: 1, altKey: true })).toBe("Alt+Button2");
|
||||
});
|
||||
|
||||
it("parses, normalizes and formats mouse bindings", () => {
|
||||
@@ -41,10 +44,26 @@ describe("mouse shortcuts", () => {
|
||||
expect(formatBinding("Ctrl+Button5", false)).toBe("Ctrl+Button5 Click");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["en", "Middle Click"],
|
||||
["zh", "鼠标中键"],
|
||||
])("formats middle mouse shortcuts in %s", async (locale, label) => {
|
||||
const originalLocale = useI18n.getState().locale;
|
||||
try {
|
||||
await setLocale(locale);
|
||||
expect(formatBinding("Button2", false)).toBe(label);
|
||||
expect(formatBinding("Button2", true)).toBe(label);
|
||||
expect(formatBinding("Ctrl+Alt+Button2", false)).toBe(`Ctrl+Alt+${label}`);
|
||||
expect(formatBinding("Alt+Meta+Button2", true)).toBe(`⌥⌘${label}`);
|
||||
} finally {
|
||||
await setLocale(originalLocale);
|
||||
}
|
||||
});
|
||||
|
||||
it("records modified left clicks without capturing selection and context-menu clicks", () => {
|
||||
expect(mouseStrokeOf({ ...noMods, button: 0, altKey: true, metaKey: true })).toBe("Alt+Meta+Button1");
|
||||
expect(mouseStrokeOf({ ...noMods, button: 0, shiftKey: true })).toBeNull();
|
||||
for (const button of [1, 2]) expect(mouseStrokeOf({ ...noMods, button, metaKey: true })).toBeNull();
|
||||
expect(mouseStrokeOf({ ...noMods, button: 2, metaKey: true })).toBeNull();
|
||||
expect(normalizeBinding("Meta+Alt+Button1")).toBe("Alt+Meta+Button1");
|
||||
expect(formatBinding("Alt+Meta+Button1", true)).toBe("⌥⌘Left Click");
|
||||
expect(formatBinding("Ctrl+Alt+Button1", false)).toBe("Ctrl+Alt+Left Click");
|
||||
@@ -103,6 +122,19 @@ describe("mouse shortcuts", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("does not consume a rectangular gesture or run its action outside the editor", () => {
|
||||
const run = vi.fn();
|
||||
const id = "editor.createRectangularSelectionOnMouseDrag";
|
||||
const remove = registerAction({ id, title: "Create Rectangular Selection on Mouse Drag", run });
|
||||
try {
|
||||
const [down] = click(document.getElementById("tree")!, 0, { altKey: true });
|
||||
expect(down!.defaultPrevented).toBe(false);
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
remove();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["the editor", () => editor],
|
||||
["another component", () => document.getElementById("tree")!],
|
||||
@@ -140,6 +172,26 @@ describe("mouse shortcuts", () => {
|
||||
expect(forward).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("leaves a configured middle gesture to the editor and other components", () => {
|
||||
const run = vi.fn();
|
||||
const remove = registerAction({ id: "test.middle", title: "Middle", run });
|
||||
useKeymap.setState({ overrides: { "test.middle": ["Button2"] } });
|
||||
const reached = vi.fn();
|
||||
editor.addEventListener("mousedown", reached);
|
||||
const tree = document.getElementById("tree")!;
|
||||
tree.addEventListener("mousedown", reached);
|
||||
try {
|
||||
for (const target of [editor, tree]) {
|
||||
const [down] = click(target, 1);
|
||||
expect(down!.defaultPrevented).toBe(false);
|
||||
}
|
||||
expect(reached).toHaveBeenCalledTimes(2);
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("follows keymap overrides and modifiers", async () => {
|
||||
useKeymap.setState({ overrides: { "navigate.back": ["Meta+["], "navigate.forward": ["Shift+Button4"] } });
|
||||
click(editor, 3);
|
||||
|
||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача