дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 08:43:07 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
6f1c3a7b0f |
No files matched your search
@@ -46,8 +46,6 @@ pub enum ErrorData {
|
||||
JavaBuildProblems {
|
||||
problems: Vec<String>,
|
||||
},
|
||||
/// A remote backend of another OpenIDEA build still serves the project and refused to retire.
|
||||
RemoteBackendBusy,
|
||||
}
|
||||
|
||||
/// Git's reported result for each destination ref. A remote with several push URLs can
|
||||
|
||||
@@ -308,14 +308,6 @@ pub struct SessionInfo {
|
||||
pub parent: Option<DebugSessionId>,
|
||||
}
|
||||
|
||||
/// One owner's breakpoints, kept without a session and sent when one of its sessions starts.
|
||||
#[derive(Default)]
|
||||
struct OwnerBreakpoints {
|
||||
lines: BTreeMap<PathBuf, Vec<Breakpoint>>,
|
||||
functions: Vec<FunctionBreakpoint>,
|
||||
data: Vec<DataBreakpoint>,
|
||||
}
|
||||
|
||||
/// Who started a session. Every event of the session, and of the child sessions
|
||||
/// its adapter starts, goes to `sink` only; `key` (e.g. a window label) scopes
|
||||
/// listings such as [`DebugManager::sessions`].
|
||||
@@ -344,12 +336,13 @@ pub struct DebugManager {
|
||||
sessions: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
/// Session start order, for "the first session" semantics.
|
||||
order: Mutex<Vec<DebugSessionId>>,
|
||||
/// Breakpoints by owner (window): each window's sessions get only its own.
|
||||
breakpoints: Mutex<HashMap<String, OwnerBreakpoints>>,
|
||||
breakpoints: Mutex<BTreeMap<PathBuf, Vec<Breakpoint>>>,
|
||||
states: Mutex<HashMap<PathBuf, Vec<BreakpointState>>>,
|
||||
/// Explicit exception filter choices (filter id → enabled); unset filters use the adapter default.
|
||||
exception_choices: Mutex<BTreeMap<String, bool>>,
|
||||
exception_classes: Mutex<Vec<ExceptionClassBreakpoint>>,
|
||||
function_breakpoints: Mutex<Vec<FunctionBreakpoint>>,
|
||||
data_breakpoints: Mutex<Vec<DataBreakpoint>>,
|
||||
/// In-flight stops, by session: a second Stop sets `stop_force`, the waiting one kills.
|
||||
stopping: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
jvm_finder: Mutex<jvm_memory::JvmFinder>,
|
||||
@@ -825,6 +818,8 @@ impl DebugManager {
|
||||
states: Mutex::default(),
|
||||
exception_choices: Mutex::default(),
|
||||
exception_classes: Mutex::default(),
|
||||
function_breakpoints: Mutex::default(),
|
||||
data_breakpoints: Mutex::default(),
|
||||
stopping: Mutex::default(),
|
||||
jvm_finder: Mutex::new(Arc::new(jvm_memory::find_local_jvm)),
|
||||
})
|
||||
@@ -844,24 +839,8 @@ impl DebugManager {
|
||||
self.order.lock().iter().filter_map(|id| sessions.get(id).cloned()).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn stored_breakpoints(&self, owner: &str, path: &Path) -> Vec<Breakpoint> {
|
||||
self.breakpoints.lock().get(owner).and_then(|b| b.lines.get(path).cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn function_breakpoints(&self, owner: &str) -> Vec<FunctionBreakpoint> {
|
||||
self.breakpoints.lock().get(owner).map(|b| b.functions.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn data_breakpoints(&self, owner: &str) -> Vec<DataBreakpoint> {
|
||||
self.breakpoints.lock().get(owner).map(|b| b.data.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `owner`'s sessions that take breakpoint requests.
|
||||
fn configured_sessions(&self, owner: &str) -> Vec<Arc<Session>> {
|
||||
self.live_sessions()
|
||||
.into_iter()
|
||||
.filter(|s| s.owner.key == owner && s.configured.load(Ordering::Acquire) && !s.conn.is_closed())
|
||||
.collect()
|
||||
pub(crate) fn stored_breakpoints(&self, path: &Path) -> Vec<Breakpoint> {
|
||||
self.breakpoints.lock().get(path).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Live sessions of `owner` (all owners when `None`).
|
||||
@@ -1312,10 +1291,8 @@ impl DebugManager {
|
||||
let (files, idle): (Vec<_>, Vec<_>) = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.get(&s.owner.key)
|
||||
.map(|b| b.lines.iter().map(|(p, b)| (p.clone(), b.clone())).collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.iter()
|
||||
.map(|(p, b)| (p.clone(), b.clone()))
|
||||
.partition(|(_, b)| b.iter().any(|b| b.enabled));
|
||||
let sent = join_all(files.iter().map(|(path, bps)| s.send_breakpoints(path, bps, None))).await;
|
||||
// Breakpoint states follow the owner's first session.
|
||||
@@ -1333,14 +1310,14 @@ impl DebugManager {
|
||||
Err(e) => tracing::debug!("setBreakpoints for {} failed: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
let functions = self.function_breakpoints(&s.owner.key);
|
||||
let functions = self.function_breakpoints.lock().clone();
|
||||
if !functions.is_empty()
|
||||
&& s.supports("supportsFunctionBreakpoints")
|
||||
&& let Err(e) = s.send_function_breakpoints(&functions).await
|
||||
{
|
||||
tracing::debug!("setFunctionBreakpoints failed: {e}");
|
||||
}
|
||||
let data = self.data_breakpoints(&s.owner.key);
|
||||
let data = self.data_breakpoints.lock().clone();
|
||||
if !data.is_empty()
|
||||
&& s.supports("supportsDataBreakpoints")
|
||||
&& let Err(e) = s.send_data_breakpoints(&data).await
|
||||
@@ -1493,59 +1470,26 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// `owner`'s breakpoints are kept per file even without a session and sent when one of
|
||||
/// its sessions starts. Returns states from its first live session, or unverified states.
|
||||
/// Breakpoints are kept per file even without a session and sent on start.
|
||||
/// Returns states from the first live session, or unverified states when none.
|
||||
pub async fn set_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
{
|
||||
let mut store = self.breakpoints.lock();
|
||||
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
|
||||
if breakpoints.is_empty() {
|
||||
lines.remove(&path);
|
||||
store.remove(&path);
|
||||
} else {
|
||||
lines.insert(path.clone(), breakpoints.clone());
|
||||
store.insert(path.clone(), breakpoints.clone());
|
||||
}
|
||||
}
|
||||
self.send_file_breakpoints(owner, path, breakpoints).await
|
||||
}
|
||||
|
||||
/// Replaces all of `owner`'s line breakpoints with `files` (the window's whole list), sending
|
||||
/// the files that changed to its sessions. A file the window no longer lists can't stay
|
||||
/// behind and be sent to every later session, whatever made the two lists diverge (#6116).
|
||||
pub async fn replace_breakpoints(&self, owner: &str, files: BTreeMap<PathBuf, Vec<Breakpoint>>) -> IdeResult<()> {
|
||||
let changed: Vec<(PathBuf, Vec<Breakpoint>)> = {
|
||||
let mut store = self.breakpoints.lock();
|
||||
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
|
||||
let files: BTreeMap<_, _> = files.into_iter().filter(|(_, b)| !b.is_empty()).collect();
|
||||
let removed = lines.keys().filter(|p| !files.contains_key(*p)).map(|p| (p.clone(), Vec::new()));
|
||||
let changed = files.iter().filter(|(p, b)| lines.get(*p) != Some(b)).map(|(p, b)| (p.clone(), b.clone()));
|
||||
let changed = removed.chain(changed).collect();
|
||||
*lines = files;
|
||||
changed
|
||||
};
|
||||
for (path, breakpoints) in changed {
|
||||
self.send_file_breakpoints(owner, path, breakpoints).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops `owner`'s breakpoints (its window closed).
|
||||
pub fn forget_breakpoints(&self, owner: &str) {
|
||||
self.breakpoints.lock().remove(owner);
|
||||
}
|
||||
|
||||
async fn send_file_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
let mut result: Option<Vec<BreakpointState>> = None;
|
||||
for s in self.configured_sessions(owner) {
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() {
|
||||
continue;
|
||||
}
|
||||
match s.send_breakpoints(&path, &breakpoints, None).await {
|
||||
Ok(states) => {
|
||||
result.get_or_insert(states);
|
||||
@@ -1696,39 +1640,16 @@ impl DebugManager {
|
||||
}
|
||||
|
||||
pub async fn stack_trace(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<Vec<StackFrame>> {
|
||||
const MAX_FRAMES: u64 = 400;
|
||||
let session = self.session(s)?;
|
||||
session.check_thread(thread_id)?;
|
||||
let request = |start: u64, levels: u64| {
|
||||
session.conn.request_timeout(
|
||||
let body = session
|
||||
.conn
|
||||
.request_timeout(
|
||||
"stackTrace",
|
||||
json!({ "threadId": thread_id, "startFrame": start, "levels": levels }),
|
||||
json!({ "threadId": thread_id, "startFrame": 0, "levels": 400 }),
|
||||
REQUEST_TIMEOUT,
|
||||
)
|
||||
};
|
||||
let frames_of = |mut body: Value| match body.get_mut("stackFrames").map(Value::take) {
|
||||
Some(Value::Array(frames)) => frames,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let raw = match request(0, MAX_FRAMES).await {
|
||||
Ok(body) => frames_of(body),
|
||||
// java-debug fails the whole request when one frame's source lookup throws (on Windows,
|
||||
// a CGLIB proxy's `<generated>` source against `sourcePaths`): the frames come one at a
|
||||
// time instead, without the ones it cannot describe.
|
||||
// ponytail: one request per frame; page around the failing ones if deep stacks get slow.
|
||||
Err(first @ DapError::Failed { .. }) => {
|
||||
let Ok(top) = request(0, 1).await else { return Err(first.into()) };
|
||||
let total = top.get("totalFrames").and_then(Value::as_u64).unwrap_or(MAX_FRAMES).min(MAX_FRAMES);
|
||||
let mut raw = frames_of(top);
|
||||
for start in 1..total {
|
||||
if let Ok(body) = request(start, 1).await {
|
||||
raw.extend(frames_of(body));
|
||||
}
|
||||
}
|
||||
raw
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
.await?;
|
||||
let kotlin_lsp = session.kotlin_lsp_quirks().is_some();
|
||||
let frame = |f: &Value| {
|
||||
let mut frame = frame_from(f);
|
||||
@@ -1740,7 +1661,7 @@ impl DebugManager {
|
||||
}
|
||||
frame
|
||||
};
|
||||
Ok(raw.iter().map(frame).collect())
|
||||
Ok(body.get("stackFrames").and_then(Value::as_array).map(|f| f.iter().map(frame).collect()).unwrap_or_default())
|
||||
}
|
||||
|
||||
pub async fn scopes(&self, s: DebugSessionId, frame_id: i64) -> IdeResult<Vec<Scope>> {
|
||||
@@ -1932,7 +1853,7 @@ impl DebugManager {
|
||||
if force {
|
||||
self.suspend_breakpoints(&session, Some(&path)).await?;
|
||||
}
|
||||
let stored = self.stored_breakpoints(&session.owner.key, &path);
|
||||
let stored = self.stored_breakpoints(&path);
|
||||
let sent: Vec<Breakpoint> =
|
||||
if force { stored.iter().map(|b| Breakpoint { enabled: false, ..b.clone() }).collect() } else { stored };
|
||||
session.send_breakpoints(&path, &sent, Some(line)).await?;
|
||||
@@ -1947,15 +1868,10 @@ impl DebugManager {
|
||||
let files: Vec<PathBuf> = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.get(&session.owner.key)
|
||||
.map(|b| {
|
||||
b.lines
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
let sent = join_all(files.iter().map(|path| session.send_breakpoints(path, &[], None))).await;
|
||||
let mut failed = None;
|
||||
for (path, result) in files.into_iter().zip(sent) {
|
||||
@@ -1969,12 +1885,11 @@ impl DebugManager {
|
||||
if let Some(e) = failed {
|
||||
return Err(e.into());
|
||||
}
|
||||
if !self.function_breakpoints(&session.owner.key).is_empty() && session.supports("supportsFunctionBreakpoints")
|
||||
{
|
||||
if !self.function_breakpoints.lock().is_empty() && session.supports("supportsFunctionBreakpoints") {
|
||||
session.send_function_breakpoints(&[]).await?;
|
||||
session.pending_restore.lock().functions = true;
|
||||
}
|
||||
if !self.data_breakpoints(&session.owner.key).is_empty() && session.supports("supportsDataBreakpoints") {
|
||||
if !self.data_breakpoints.lock().is_empty() && session.supports("supportsDataBreakpoints") {
|
||||
session.send_data_breakpoints(&[]).await?;
|
||||
session.pending_restore.lock().data = true;
|
||||
}
|
||||
@@ -1984,11 +1899,8 @@ impl DebugManager {
|
||||
/// Re-sends what [`suspend_breakpoints`](Self::suspend_breakpoints) / run to cursor replaced.
|
||||
pub(crate) async fn restore_breakpoints(&self, session: &Arc<Session>) {
|
||||
let pending = std::mem::take(&mut *session.pending_restore.lock());
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> = pending
|
||||
.files
|
||||
.into_iter()
|
||||
.map(|path| (path.clone(), self.stored_breakpoints(&session.owner.key, &path)))
|
||||
.collect();
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> =
|
||||
pending.files.into_iter().map(|path| (path.clone(), self.stored_breakpoints(&path))).collect();
|
||||
let sent = join_all(files.iter().map(|(path, bps)| session.send_breakpoints(path, bps, None))).await;
|
||||
for ((path, _), result) in files.iter().zip(sent) {
|
||||
if let Err(e) = result {
|
||||
@@ -1996,13 +1908,13 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
if pending.functions {
|
||||
let functions = self.function_breakpoints(&session.owner.key);
|
||||
let functions = self.function_breakpoints.lock().clone();
|
||||
if let Err(e) = session.send_function_breakpoints(&functions).await {
|
||||
tracing::debug!("restoring function breakpoints failed: {e}");
|
||||
}
|
||||
}
|
||||
if pending.data {
|
||||
let data = self.data_breakpoints(&session.owner.key);
|
||||
let data = self.data_breakpoints.lock().clone();
|
||||
if let Err(e) = session.send_data_breakpoints(&data).await {
|
||||
tracing::debug!("restoring data breakpoints failed: {e}");
|
||||
}
|
||||
@@ -2212,17 +2124,14 @@ impl DebugManager {
|
||||
Ok(hot_swap_result(&body))
|
||||
}
|
||||
|
||||
/// Stores `owner`'s method breakpoints (kept without a session, sent on start) and sends them
|
||||
/// to each of its configured sessions whose adapter supports them. States from the first one.
|
||||
pub async fn set_function_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
list: Vec<FunctionBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
self.breakpoints.lock().entry(owner.to_owned()).or_default().functions = list.clone();
|
||||
/// Stores method breakpoints (kept without a session, sent on start) and sends them to
|
||||
/// every configured session whose adapter supports them. States from the first one.
|
||||
pub async fn set_function_breakpoints(&self, list: Vec<FunctionBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
|
||||
*self.function_breakpoints.lock() = list.clone();
|
||||
let mut result = None;
|
||||
for s in self.configured_sessions(owner) {
|
||||
if !s.supports("supportsFunctionBreakpoints") {
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsFunctionBreakpoints")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match s.send_function_breakpoints(&list).await {
|
||||
@@ -2235,17 +2144,12 @@ impl DebugManager {
|
||||
Ok(result.unwrap_or_else(|| unverified(list.iter().map(|b| b.enabled))))
|
||||
}
|
||||
|
||||
/// Stores `owner`'s field watchpoints and sends them to each of its configured sessions that
|
||||
/// supports them.
|
||||
pub async fn set_data_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
list: Vec<DataBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
self.breakpoints.lock().entry(owner.to_owned()).or_default().data = list.clone();
|
||||
/// Stores field watchpoints and sends them to every configured session that supports them.
|
||||
pub async fn set_data_breakpoints(&self, list: Vec<DataBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
|
||||
*self.data_breakpoints.lock() = list.clone();
|
||||
let mut result = None;
|
||||
for s in self.configured_sessions(owner) {
|
||||
if !s.supports("supportsDataBreakpoints") {
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsDataBreakpoints") {
|
||||
continue;
|
||||
}
|
||||
match s.send_data_breakpoints(&list).await {
|
||||
|
||||
@@ -126,8 +126,6 @@ struct Script {
|
||||
child_request: Option<Value>,
|
||||
ignore_configuration_done: bool,
|
||||
source_path: Option<String>,
|
||||
/// Fail each `stackTrace` request whose frames include this one (java-debug, one frame's source lookup throwing).
|
||||
failing_frame: Option<u64>,
|
||||
/// Report this process id in the adapter's `process` event (the program being debugged).
|
||||
debuggee_pid: Option<u32>,
|
||||
/// java-debug's spelling of the same event.
|
||||
@@ -208,7 +206,6 @@ impl Default for Script {
|
||||
child_request: None,
|
||||
ignore_configuration_done: false,
|
||||
source_path: None,
|
||||
failing_frame: None,
|
||||
debuggee_pid: None,
|
||||
java_process_id: false,
|
||||
output_after_terminate: false,
|
||||
@@ -523,20 +520,6 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
ok!(msg, json!({"threads": [{"id": 1, "name": "MainThread"}]}));
|
||||
}
|
||||
}
|
||||
"stackTrace" if let Some(bad) = script.failing_frame => {
|
||||
let start = msg["arguments"]["startFrame"].as_u64().unwrap();
|
||||
let end = (start + msg["arguments"]["levels"].as_u64().unwrap()).min(3);
|
||||
if (start..end).contains(&bad) {
|
||||
send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "stackTrace", "success": false, "message": "Illegal char <<> at index 21: C:\\p\\com\\x\\<generated>"})
|
||||
);
|
||||
} else {
|
||||
let frames: Vec<Value> = (start..end)
|
||||
.map(|i| json!({"id": 10 + i, "name": format!("f{i}"), "line": 1, "column": 1}))
|
||||
.collect();
|
||||
ok!(msg, json!({"stackFrames": frames, "totalFrames": 3}));
|
||||
}
|
||||
}
|
||||
"stackTrace" => ok!(
|
||||
msg,
|
||||
json!({"stackFrames": [
|
||||
@@ -916,7 +899,7 @@ async fn full_protocol_flow() {
|
||||
let path = PathBuf::from("/p/a.py");
|
||||
let disabled = Breakpoint { enabled: false, ..bp(2) };
|
||||
let cond = Breakpoint { condition: Some("x > 1".into()), ..bp(7) };
|
||||
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
|
||||
let states = h.manager.set_breakpoints(path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
|
||||
assert!(states.iter().all(|s| !s.verified), "no session yet");
|
||||
|
||||
let id = h.start(config()).await.unwrap();
|
||||
@@ -998,7 +981,7 @@ async fn full_protocol_flow() {
|
||||
assert_eq!(asked["arguments"]["frameId"], 10);
|
||||
|
||||
// Live breakpoint updates reach the session.
|
||||
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(0)]).await.unwrap();
|
||||
let states = h.manager.set_breakpoints(path.clone(), vec![bp(0)]).await.unwrap();
|
||||
assert!(states[0].verified);
|
||||
|
||||
h.manager.resume(id, 1).await.unwrap();
|
||||
@@ -1022,7 +1005,7 @@ async fn full_protocol_flow() {
|
||||
async fn run_to_cursor_uses_temporary_breakpoint() {
|
||||
let h = harness(Script::default());
|
||||
let path = PathBuf::from("/p/a.py");
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
h.manager.run_to(id, 1, path.clone(), 9, false).await.unwrap();
|
||||
@@ -1054,7 +1037,7 @@ async fn stop_terminates_and_disconnects() {
|
||||
#[tokio::test]
|
||||
async fn unity_attach_waits_for_mono_and_disconnects_without_terminating_editor() {
|
||||
let h = harness(Script { empty_thread_responses: 2, ..Script::default() });
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
|
||||
let start = h.start(LaunchConfig {
|
||||
adapter: "unity".into(),
|
||||
request: "attach".into(),
|
||||
@@ -1906,7 +1889,7 @@ fn function_bp(name: &str, enabled: bool) -> FunctionBreakpoint {
|
||||
async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
let h = harness(Script::default());
|
||||
let cond = FunctionBreakpoint { condition: Some("n > 1".into()), ..function_bp("com.a.B#run", true) };
|
||||
let states = h.manager.set_function_breakpoints(&h.owner.key, vec![cond, function_bp("off", false)]).await.unwrap();
|
||||
let states = h.manager.set_function_breakpoints(vec![cond, function_bp("off", false)]).await.unwrap();
|
||||
assert!(!states[0].verified && states[1].message.as_deref() == Some("Disabled"), "no session yet");
|
||||
let watch = DataBreakpoint {
|
||||
data_id: "Req#count".into(),
|
||||
@@ -1915,7 +1898,7 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
hit_condition: Some("2".into()),
|
||||
enabled: true,
|
||||
};
|
||||
h.manager.set_data_breakpoints(&h.owner.key, vec![watch]).await.unwrap();
|
||||
h.manager.set_data_breakpoints(vec![watch]).await.unwrap();
|
||||
|
||||
let id = h.start(config()).await.unwrap();
|
||||
assert_eq!(
|
||||
@@ -1931,11 +1914,8 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
let pos = |c: &str| order.iter().position(|x| x == c).unwrap();
|
||||
assert!(pos("setFunctionBreakpoints") < pos("configurationDone"));
|
||||
|
||||
let states = h
|
||||
.manager
|
||||
.set_function_breakpoints(&h.owner.key, vec![function_bp("missing", true), function_bp("ok", true)])
|
||||
.await
|
||||
.unwrap();
|
||||
let states =
|
||||
h.manager.set_function_breakpoints(vec![function_bp("missing", true), function_bp("ok", true)]).await.unwrap();
|
||||
assert_eq!((states[0].verified, states[1].verified), (false, true), "live states from the session");
|
||||
|
||||
let info = h.manager.data_breakpoint_info(id, 101, "count".into(), Some(10)).await.unwrap();
|
||||
@@ -1978,13 +1958,10 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
let h = harness(Script::default());
|
||||
let a = PathBuf::from("/p/a.py");
|
||||
let b = PathBuf::from("/p/b.py");
|
||||
h.manager.set_breakpoints(&h.owner.key, a.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, b.clone(), vec![bp(3)]).await.unwrap();
|
||||
h.manager
|
||||
.set_breakpoints(&h.owner.key, PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }])
|
||||
.await
|
||||
.unwrap();
|
||||
h.manager.set_function_breakpoints(&h.owner.key, vec![function_bp("run", true)]).await.unwrap();
|
||||
h.manager.set_breakpoints(a.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(b.clone(), vec![bp(3)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
h.manager.set_function_breakpoints(vec![function_bp("run", true)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let sent_for = |path: &str| -> Vec<Value> {
|
||||
@@ -2018,10 +1995,10 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
#[tokio::test]
|
||||
async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled() {
|
||||
let h = harness(Script { hold_set_breakpoints: 2, ..Script::default() });
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
|
||||
let off = PathBuf::from("/p/off.py");
|
||||
h.manager.set_breakpoints(&h.owner.key, off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
h.manager.set_breakpoints(off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
// Waiting for each answer before the next request would stall until the request timeout.
|
||||
tokio::time::timeout(Duration::from_secs(5), h.start(config())).await.expect("requests pipelined").unwrap();
|
||||
let paths: Vec<Value> = requests(&h, "setBreakpoints").into_iter().map(|r| r["source"]["path"].clone()).collect();
|
||||
@@ -2032,40 +2009,6 @@ async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sessions_get_only_their_windows_breakpoints_and_a_replaced_list_drops_stale_files() {
|
||||
let h = harness(Script::default());
|
||||
let other = "project-2";
|
||||
h.manager.set_breakpoints(other, PathBuf::from("/p/other.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_function_breakpoints(other, vec![function_bp("elsewhere", true)]).await.unwrap();
|
||||
let stale = PathBuf::from("/p/stale.py");
|
||||
h.manager.set_breakpoints(&h.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let paths = || -> Vec<(Value, Value)> {
|
||||
requests(&h, "setBreakpoints")
|
||||
.into_iter()
|
||||
.map(|r| (r["source"]["path"].clone(), r["breakpoints"].clone()))
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(paths(), [(json!("/p/stale.py"), json!([{"line": 3}]))], "another window's file is not sent");
|
||||
assert!(requests(&h, "setFunctionBreakpoints").is_empty(), "nor its method breakpoints");
|
||||
|
||||
// The window's list no longer has the stale file (#6116): replacing clears it in the session...
|
||||
let kept = PathBuf::from("/p/kept.py");
|
||||
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
|
||||
assert_eq!(paths()[1..], [(json!("/p/stale.py"), json!([])), (json!("/p/kept.py"), json!([{"line": 5}]))]);
|
||||
// ...unchanged files are not sent again...
|
||||
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
|
||||
assert_eq!(paths().len(), 3);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
// ...and the next session gets only what the window lists.
|
||||
let h2 = harness(Script::default());
|
||||
h2.manager.set_breakpoints(&h2.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
|
||||
h2.manager.replace_breakpoints(&h2.owner.key, BTreeMap::new()).await.unwrap();
|
||||
h2.start(config()).await.unwrap();
|
||||
assert!(requests(&h2, "setBreakpoints").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hot_reload_sends_its_reason_and_reports_the_flutter_app() {
|
||||
let h = harness(Script::default());
|
||||
@@ -2266,7 +2209,7 @@ async fn godot_gets_resolved_paths() {
|
||||
Arc::new(FakeLauncher { log: log.clone(), script: Script::default() }),
|
||||
);
|
||||
let bp = Breakpoint { line: 0, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
manager.set_breakpoints("main", link.join("player.gd"), vec![bp]).await.unwrap();
|
||||
manager.set_breakpoints(link.join("player.gd"), vec![bp]).await.unwrap();
|
||||
let id = manager.start(godot_launch(&link), owner).await.unwrap();
|
||||
let sent = log.lock().iter().find(|m| m["command"] == "setBreakpoints").cloned().unwrap();
|
||||
assert_eq!(sent["arguments"]["source"]["path"], json!(real.join("player.gd")));
|
||||
@@ -2293,7 +2236,7 @@ async fn kotlin_configures_without_configuration_done_response() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let path = project.path().join("Main.kt");
|
||||
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let mut config = config();
|
||||
config.adapter = kotlin::ADAPTER.into();
|
||||
config.request = "attach".into();
|
||||
@@ -2327,7 +2270,7 @@ async fn kotlin_official_release_ten_no_delay_runs() {
|
||||
let (owner, events) = recording_owner("kotlin-probe");
|
||||
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
|
||||
let h = Harness { manager, owner, events, log: Arc::default() };
|
||||
h.manager.set_breakpoints(&h.owner.key, source.clone(), vec![bp(5)]).await.unwrap();
|
||||
h.manager.set_breakpoints(source.clone(), vec![bp(5)]).await.unwrap();
|
||||
let id = h.manager.start_with(config.clone(), h.owner.clone(), |_| Some(adapter.clone())).await.unwrap();
|
||||
let stopped = h.wait_event(|e| matches!(e, DebugEvent::Stopped { reason, .. } if reason == "breakpoint")).await;
|
||||
let DebugEvent::Stopped { thread_id, .. } = stopped else { unreachable!() };
|
||||
@@ -2349,21 +2292,6 @@ async fn kotlin_official_release_ten_no_delay_runs() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stack_trace_leaves_out_a_frame_the_adapter_cannot_describe() {
|
||||
let h = harness(Script { failing_frame: Some(1), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let frames = h.manager.stack_trace(id, 1).await.unwrap();
|
||||
assert_eq!(frames.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["f0", "f2"]);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
|
||||
let h = harness(Script { failing_frame: Some(0), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let error = h.manager.stack_trace(id, 1).await.unwrap_err();
|
||||
assert!(error.message.contains("<generated>"), "{error:?}");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[tokio::test]
|
||||
async fn netcoredbg_windows_source_paths_round_trip() {
|
||||
@@ -2371,7 +2299,7 @@ async fn netcoredbg_windows_source_paths_round_trip() {
|
||||
let native = r"D:\work\LoginController.cs";
|
||||
let h = harness(Script { source_path: Some(native.into()), ..Script::default() });
|
||||
let path = PathBuf::from(client);
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(25)]).await.unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(25)]).await.unwrap();
|
||||
let mut cfg = config();
|
||||
cfg.adapter = "netcoredbg".into();
|
||||
let id = h.start(cfg).await.unwrap();
|
||||
@@ -2395,7 +2323,7 @@ async fn java_windows_source_paths_for_launch_and_attach() {
|
||||
] {
|
||||
let h = harness(Script { source_path: Some(returned.into()), ..Script::default() });
|
||||
let path = PathBuf::from(client);
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4)]).await.unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(4)]).await.unwrap();
|
||||
let mut cfg = config();
|
||||
cfg.adapter = "java-debug".into();
|
||||
cfg.request = request.into();
|
||||
@@ -3490,7 +3418,7 @@ async fn kotlin_lsp_gets_real_paths_and_its_link_holds_nothing() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let path = project.path().join("Main.kt");
|
||||
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let id = h.start(kotlin_lsp_attach(project.path())).await.unwrap();
|
||||
assert_eq!(h.request("setBreakpoints")["arguments"]["source"]["path"], json!(path));
|
||||
let sent = &h.request("attach")["arguments"];
|
||||
|
||||
@@ -47,7 +47,7 @@ async fn debugpy_end_to_end() {
|
||||
let sink: SharedSink = Arc::new(move |e: IdeEvent| sink_events.lock().push(e));
|
||||
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
|
||||
let bp = Breakpoint { line: 3, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
manager.set_breakpoints("main", script.clone(), vec![bp]).await.unwrap();
|
||||
manager.set_breakpoints(script.clone(), vec![bp]).await.unwrap();
|
||||
let id = manager
|
||||
.start(
|
||||
LaunchConfig {
|
||||
@@ -74,7 +74,7 @@ async fn debugpy_end_to_end() {
|
||||
assert!(vars.iter().any(|v| v.name == "total"), "{vars:?}");
|
||||
let v = manager.evaluate(id, Some(frames[0].id), "total + 100".into()).await.unwrap();
|
||||
assert_eq!(v.value, "100");
|
||||
manager.set_breakpoints("main", script.clone(), vec![]).await.unwrap();
|
||||
manager.set_breakpoints(script.clone(), vec![]).await.unwrap();
|
||||
manager.resume(id, thread_id).await.unwrap();
|
||||
wait(&events, |e| matches!(e, DebugEvent::Output { output, .. } if output.contains("total 3"))).await;
|
||||
wait(&events, |e| matches!(e, DebugEvent::Terminated)).await;
|
||||
|
||||
@@ -96,7 +96,6 @@ async fn breakpoints_stepping_and_variables_in_a_real_godot() {
|
||||
let script_as_opened = dir.join("player.gd");
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"main",
|
||||
script_as_opened.clone(),
|
||||
vec![Breakpoint {
|
||||
line: BREAK_LINE,
|
||||
|
||||
@@ -81,7 +81,6 @@ async fn listens_for_xdebug_until_stopped_with_path_mappings() {
|
||||
let local_script = local.join("index.php");
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"main",
|
||||
local_script.clone(),
|
||||
vec![Breakpoint {
|
||||
line: BREAK_LINE,
|
||||
|
||||
@@ -261,7 +261,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
let m = &run.manager;
|
||||
let line_bp =
|
||||
Breakpoint { line: case.loop_line, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
|
||||
|
||||
let seen = run.seen();
|
||||
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
|
||||
@@ -356,9 +356,9 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
// Method breakpoint: continue → stops in `parse`.
|
||||
if caps.function_breakpoints {
|
||||
let fb = FunctionBreakpoint { name: case.function.into(), condition: None, hit_condition: None, enabled: true };
|
||||
let states = m.set_function_breakpoints("test", vec![fb]).await.map_err(|e| e.message)?;
|
||||
let states = m.set_function_breakpoints(vec![fb]).await.map_err(|e| e.message)?;
|
||||
report.push(format!("method breakpoint `{}`: verified={}", case.function, states[0].verified));
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s, thread).await.map_err(|e| e.message)?;
|
||||
match run.stopped_after(seen).await {
|
||||
@@ -368,10 +368,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
None => report.push("method breakpoint: NOT HIT".into()),
|
||||
}
|
||||
m.set_function_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
m.set_function_breakpoints(vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.step(s, thread, StepKind::Out).await.map_err(|e| e.message)?;
|
||||
run.stopped_after(seen).await.ok_or("no stop after step out of parse")?;
|
||||
@@ -380,7 +378,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
|
||||
// Force Step Over ignores the breakpoint inside parse.
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.force_step_over(s, thread).await.map_err(|e| e.message)?;
|
||||
let (_, t, reason) = run.stopped_after(seen).await.ok_or("no stop after force step over")?;
|
||||
@@ -411,8 +409,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
hit_condition: None,
|
||||
enabled: true,
|
||||
};
|
||||
let states = m.set_data_breakpoints("test", vec![wp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let states = m.set_data_breakpoints(vec![wp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s, thread).await.map_err(|e| e.message)?;
|
||||
match run.stopped_after(seen).await {
|
||||
@@ -427,8 +425,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
None => report.push(format!("watchpoint `{data_id}`: NOT HIT")),
|
||||
}
|
||||
m.set_data_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
m.set_data_breakpoints(vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
}
|
||||
@@ -625,7 +623,7 @@ async fn attach_to_processes() {
|
||||
};
|
||||
let run = Run::new();
|
||||
run.manager
|
||||
.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.line)])
|
||||
.set_breakpoints(case.source.clone(), vec![line_bp_at(case.line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
let id =
|
||||
|
||||
@@ -253,7 +253,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
let mut report = Vec::new();
|
||||
let run = Run::new();
|
||||
let m = &run.manager;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
|
||||
|
||||
let (s, thread) = run.stopped(0, "the loop breakpoint").await?;
|
||||
@@ -312,7 +312,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
expect_line(&run.top(s2, t2).await?, LOOP_LINE, "continue")?;
|
||||
|
||||
// Without breakpoints, the program runs to its end.
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s2, t2).await.map_err(|e| e.message)?;
|
||||
run.wait(seen, "terminated", |s, e| (s == id && matches!(e, DebugEvent::Terminated)).then_some(())).await?;
|
||||
@@ -333,7 +333,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
report.push("continue to exit: output and terminated".into());
|
||||
|
||||
// Restart (the UI starts the same configuration again), then Stop while paused.
|
||||
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
let again = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("restart: {}", e.message))?;
|
||||
let (s, thread) = run.stopped(seen, "the breakpoint after restart").await?;
|
||||
|
||||
@@ -110,7 +110,6 @@ async fn real_editor_attach_breakpoint_step_variables_and_detach() {
|
||||
let line = SCRIPT.lines().position(|l| l.contains("int answer =")).unwrap() as u32;
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"smoke",
|
||||
source.clone(),
|
||||
vec![Breakpoint { line, condition: None, hit_condition: None, log_message: None, enabled: true }],
|
||||
)
|
||||
|
||||
@@ -297,8 +297,6 @@ pub struct DbManager {
|
||||
type Session = Arc<tokio::sync::Mutex<Option<Held>>>;
|
||||
|
||||
const MAX_META_ROWS: usize = 100_000;
|
||||
/// Completion columns of the default schema, which are read without the shared cap.
|
||||
const MAX_SCHEMA_COMPLETION_ROWS: usize = 1_000_000;
|
||||
|
||||
/// Rows of catalog query `q`, run again as [`sql::postgres_legacy`] when a PostgreSQL server's
|
||||
/// catalog lacks a column it reads (openGauss, PostgreSQL 9).
|
||||
@@ -1431,34 +1429,13 @@ impl DbManager {
|
||||
let pool = self.pool(id).await?;
|
||||
let driver = pool.driver();
|
||||
let mut tables: Vec<CompletionTable> = Vec::new();
|
||||
if let Pool::Jdbc(p) = &*pool {
|
||||
return self.jdbc_completion(id, p).await;
|
||||
}
|
||||
let default_schema = match sql::current_schema(driver) {
|
||||
None => "main".to_owned(),
|
||||
Some(q) => pool
|
||||
.rows(q, 1)
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|r| r.into_iter().next().flatten())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
let rows = match &*pool {
|
||||
Pool::Jdbc(p) => return self.jdbc_completion(id, p).await,
|
||||
Pool::Snowflake(p) => {
|
||||
tables = snowflake::meta::completion(p).await?;
|
||||
Vec::new()
|
||||
}
|
||||
// The default schema is read in full: under a shared row cap, a schema with many
|
||||
// tables lost the columns of the tables sorting last (#6118). Other schemas share the cap.
|
||||
_ if !default_schema.is_empty() => {
|
||||
let only = sql::completion_columns(driver, sql::CompletionScope::Only(&default_schema));
|
||||
let mut rows = pool.rows(&only, MAX_SCHEMA_COMPLETION_ROWS).await?;
|
||||
let rest = sql::completion_columns(driver, sql::CompletionScope::Except(&default_schema));
|
||||
rows.extend(pool.rows(&rest, MAX_META_ROWS).await?);
|
||||
rows
|
||||
}
|
||||
_ => pool.rows(&sql::completion_columns(driver, sql::CompletionScope::All), MAX_META_ROWS).await?,
|
||||
_ => pool.rows(sql::completion_columns(driver), MAX_META_ROWS).await?,
|
||||
};
|
||||
for r in rows {
|
||||
let mut it = r.into_iter().map(Option::unwrap_or_default);
|
||||
@@ -1494,6 +1471,16 @@ impl DbManager {
|
||||
})
|
||||
};
|
||||
let foreign_keys = group_foreign_keys(fk_rows, &tables);
|
||||
let default_schema = match sql::current_schema(driver) {
|
||||
None => "main".to_owned(),
|
||||
Some(q) => pool
|
||||
.rows(q, 1)
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|r| r.into_iter().next().flatten())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
Ok(CompletionModel { default_schema, tables, foreign_keys })
|
||||
}
|
||||
|
||||
|
||||
@@ -252,47 +252,31 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which schemas a [`completion_columns`] query reads.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CompletionScope<'a> {
|
||||
/// Every non-system schema, capped at [`COMPLETION_ROW_CAP`] rows.
|
||||
All,
|
||||
/// One schema, in full.
|
||||
Only(&'a str),
|
||||
/// Every non-system schema but this one, capped at [`COMPLETION_ROW_CAP`] rows.
|
||||
Except(&'a str),
|
||||
}
|
||||
|
||||
/// Rows a [`CompletionScope::All`] or [`CompletionScope::Except`] query returns at most.
|
||||
pub const COMPLETION_ROW_CAP: usize = 50_000;
|
||||
|
||||
/// Rows: `schema, table, kind (table/view), column, type, nullable (YES/NO), is_pk (0/1), has_default (0/1)`
|
||||
/// for SQL completion, grouped by table in column order.
|
||||
pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
let (query, schema, order) = match driver {
|
||||
pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
match driver {
|
||||
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
|
||||
DbDriver::Clickhouse => (
|
||||
DbDriver::Clickhouse => {
|
||||
"SELECT c.database, c.table, CASE t.engine WHEN 'View' THEN 'view' \
|
||||
WHEN 'MaterializedView' THEN 'materialized view' WHEN 'WindowView' THEN 'view' ELSE 'table' END, \
|
||||
c.name, c.type, CASE WHEN startsWith(c.type, 'Nullable(') \
|
||||
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1 \
|
||||
FROM system.columns c JOIN system.tables t ON t.database = c.database AND t.name = c.table \
|
||||
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0",
|
||||
"c.database",
|
||||
"c.database, c.table, c.position",
|
||||
),
|
||||
DbDriver::Sqlite => (
|
||||
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0 \
|
||||
ORDER BY c.database, c.table, c.position LIMIT 50000"
|
||||
}
|
||||
DbDriver::Sqlite => {
|
||||
"SELECT 'main', m.name, m.type, p.name, p.type, CASE WHEN p.\"notnull\" = 0 THEN 'YES' ELSE 'NO' END, \
|
||||
CASE WHEN p.pk > 0 THEN 1 ELSE 0 END, \
|
||||
CASE WHEN p.dflt_value IS NOT NULL THEN 1 \
|
||||
WHEN p.pk = 1 AND upper(p.type) = 'INTEGER' \
|
||||
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END \
|
||||
FROM sqlite_master m JOIN pragma_table_info(m.name) p \
|
||||
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\'",
|
||||
"'main'",
|
||||
"m.name, p.cid",
|
||||
),
|
||||
DbDriver::Postgres => (
|
||||
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY m.name, p.cid"
|
||||
}
|
||||
// Identity columns own their sequence through an internal dependency (`attidentity` is PostgreSQL 10+).
|
||||
DbDriver::Postgres => {
|
||||
"SELECT n.nspname, c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, a.attname, \
|
||||
format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary \
|
||||
@@ -303,21 +287,19 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid \
|
||||
WHERE c.relkind IN ('r', 'v', 'm', 'p', 'f') AND a.attnum > 0 AND NOT a.attisdropped \
|
||||
AND n.nspname NOT IN ('pg_catalog', 'information_schema') \
|
||||
AND n.nspname NOT LIKE 'pg\\_toast%' AND n.nspname NOT LIKE 'pg\\_temp%'",
|
||||
"n.nspname",
|
||||
"n.nspname, c.relname, a.attnum",
|
||||
),
|
||||
DbDriver::Mysql => (
|
||||
AND n.nspname NOT LIKE 'pg\\_toast%' AND n.nspname NOT LIKE 'pg\\_temp%' \
|
||||
ORDER BY n.nspname, c.relname, a.attnum LIMIT 50000"
|
||||
}
|
||||
DbDriver::Mysql => {
|
||||
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.column_type, c.is_nullable, CASE WHEN c.column_key = 'PRI' THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')",
|
||||
"c.table_schema",
|
||||
"c.table_schema, c.table_name, c.ordinal_position",
|
||||
),
|
||||
DbDriver::SqlServer => (
|
||||
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') \
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
"SELECT c.TABLE_SCHEMA, c.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.COLUMN_NAME, c.DATA_TYPE, c.IS_NULLABLE, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
|
||||
@@ -328,21 +310,19 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
|
||||
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
|
||||
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
|
||||
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA')",
|
||||
"c.TABLE_SCHEMA",
|
||||
"c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION",
|
||||
),
|
||||
DbDriver::Snowflake => (
|
||||
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA') \
|
||||
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION"
|
||||
}
|
||||
DbDriver::Snowflake => {
|
||||
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
|
||||
WHEN 'MATERIALIZED VIEW' THEN 'materialized view' ELSE 'table' END, c.column_name, c.data_type, \
|
||||
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema <> 'INFORMATION_SCHEMA'",
|
||||
"c.table_schema",
|
||||
"c.table_schema, c.table_name, c.ordinal_position",
|
||||
),
|
||||
DbDriver::Oracle => (
|
||||
WHERE c.table_schema <> 'INFORMATION_SCHEMA' \
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
|
||||
}
|
||||
DbDriver::Oracle => {
|
||||
"SELECT c.owner, c.table_name, CASE WHEN v.view_name IS NOT NULL THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, \
|
||||
@@ -354,22 +334,10 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
AND kc.constraint_name = con.constraint_name WHERE con.constraint_type = 'P') k \
|
||||
ON k.owner = c.owner AND k.table_name = c.table_name AND k.column_name = c.column_name \
|
||||
WHERE c.owner NOT IN ('CTXSYS', 'DBSFWUSER', 'DVSYS', 'GSMADMIN_INTERNAL', 'LBACSYS', 'MDDATA', \
|
||||
'MDSYS', 'OLAPSYS', 'OUTLN', 'SYS', 'SYSTEM', 'XDB', 'XS$NULL')",
|
||||
"c.owner",
|
||||
"c.owner, c.table_name, c.column_id",
|
||||
),
|
||||
};
|
||||
let filter = match scope {
|
||||
CompletionScope::All => String::new(),
|
||||
CompletionScope::Only(s) => format!(" AND {schema} = {}", quote_literal(driver, s)),
|
||||
CompletionScope::Except(s) => format!(" AND {schema} <> {}", quote_literal(driver, s)),
|
||||
};
|
||||
let cap = match (scope, driver) {
|
||||
(CompletionScope::Only(_), _) | (_, DbDriver::Sqlite | DbDriver::SqlServer) => String::new(),
|
||||
(_, DbDriver::Oracle) => format!(" FETCH FIRST {COMPLETION_ROW_CAP} ROWS ONLY"),
|
||||
_ => format!(" LIMIT {COMPLETION_ROW_CAP}"),
|
||||
};
|
||||
format!("{query}{filter} ORDER BY {order}{cap}")
|
||||
'MDSYS', 'OLAPSYS', 'OUTLN', 'SYS', 'SYSTEM', 'XDB', 'XS$NULL') \
|
||||
ORDER BY c.owner, c.table_name, c.column_id FETCH FIRST 50000 ROWS ONLY"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows: `schema, table, constraint, column, ref schema, ref table, ref column`
|
||||
@@ -982,7 +950,7 @@ mod tests {
|
||||
let keys = indexes(driver, "default", "events");
|
||||
assert!(keys.contains("'PRIMARY KEY' AS index_name, 0 AS is_unique, primary_key AS expression"));
|
||||
assert!(keys.contains("SELECT name, 0, expr FROM system.data_skipping_indices"));
|
||||
let completion = completion_columns(driver, CompletionScope::All);
|
||||
let completion = completion_columns(driver);
|
||||
assert!(completion.contains("c.is_in_primary_key, 1"));
|
||||
assert!(completion.contains("ORDER BY c.database, c.table, c.position LIMIT 50000"));
|
||||
}
|
||||
@@ -1092,7 +1060,7 @@ mod tests {
|
||||
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
|
||||
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
|
||||
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("OBJECT_ID(N'[dbo].[t]')"));
|
||||
assert!(completion_columns(DbDriver::SqlServer, CompletionScope::All).contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
assert!(completion_columns(DbDriver::SqlServer).contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
}
|
||||
|
||||
/// Under a case-sensitive or binary collation, catalog names only resolve as declared:
|
||||
@@ -1106,7 +1074,7 @@ mod tests {
|
||||
tables(d, "dbo"),
|
||||
columns(d, "dbo", "t"),
|
||||
indexes(d, "dbo", "t"),
|
||||
completion_columns(d, CompletionScope::All),
|
||||
completion_columns(d).to_owned(),
|
||||
foreign_keys(d).to_owned(),
|
||||
table_foreign_keys(d, "dbo", "t"),
|
||||
routines(d, "dbo").unwrap(),
|
||||
@@ -1173,7 +1141,7 @@ mod tests {
|
||||
assert!(indexes(DbDriver::Oracle, "hr", "t").contains("all_indexes"));
|
||||
assert!(foreign_keys(DbDriver::Oracle).contains("constraint_type = 'R'"));
|
||||
assert!(table_foreign_keys(DbDriver::Oracle, "hr", "t").contains("all_cons_columns"));
|
||||
assert!(completion_columns(DbDriver::Oracle, CompletionScope::All).contains("all_tab_columns"));
|
||||
assert!(completion_columns(DbDriver::Oracle).contains("all_tab_columns"));
|
||||
assert!(triggers(DbDriver::Oracle, "hr", "t").contains("all_triggers"));
|
||||
assert!(routines(DbDriver::Oracle, "hr").unwrap().contains("all_objects"));
|
||||
assert!(packages(DbDriver::Oracle, "hr").unwrap().contains("object_type = 'PACKAGE'"));
|
||||
@@ -1288,7 +1256,7 @@ mod tests {
|
||||
let columns = columns(driver, "PUBLIC", "ORDERS");
|
||||
assert!(columns.contains("'NUMBER(' || numeric_precision"), "{columns}");
|
||||
assert!(columns.contains("table_name = 'ORDERS' ORDER BY ordinal_position"), "{columns}");
|
||||
assert!(completion_columns(driver, CompletionScope::All).contains("LIMIT 50000"));
|
||||
assert!(completion_columns(driver).contains("LIMIT 50000"));
|
||||
assert!(routines(driver, "PUBLIC").unwrap().contains("information_schema.procedures"));
|
||||
assert!(sequences(driver, "PUBLIC").unwrap().contains("information_schema.sequences"));
|
||||
assert_eq!(
|
||||
@@ -1300,35 +1268,6 @@ mod tests {
|
||||
assert_eq!(crate::plan::explain_statement(driver, "select 1;"), "EXPLAIN USING TABULAR select 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_reads_the_default_schema_without_the_shared_cap() {
|
||||
// #6118: 5,000+ tables in one Oracle schema overflowed the shared cap, so tables
|
||||
// sorting last had no columns.
|
||||
let only = completion_columns(DbDriver::Oracle, CompletionScope::Only("APP's"));
|
||||
assert!(only.ends_with("AND c.owner = 'APP''s' ORDER BY c.owner, c.table_name, c.column_id"), "{only}");
|
||||
let rest = completion_columns(DbDriver::Oracle, CompletionScope::Except("APP"));
|
||||
assert!(rest.contains("AND c.owner <> 'APP' ORDER BY"), "{rest}");
|
||||
assert!(rest.ends_with(" FETCH FIRST 50000 ROWS ONLY"), "{rest}");
|
||||
let all = completion_columns(DbDriver::Oracle, CompletionScope::All);
|
||||
assert!(all.ends_with("'XS$NULL') ORDER BY c.owner, c.table_name, c.column_id FETCH FIRST 50000 ROWS ONLY"));
|
||||
for (driver, column) in [
|
||||
(DbDriver::Postgres, "n.nspname"),
|
||||
(DbDriver::Mysql, "c.table_schema"),
|
||||
(DbDriver::Clickhouse, "c.database"),
|
||||
(DbDriver::Snowflake, "c.table_schema"),
|
||||
(DbDriver::SqlServer, "c.TABLE_SCHEMA"),
|
||||
(DbDriver::Sqlite, "'main'"),
|
||||
] {
|
||||
let only = completion_columns(driver, CompletionScope::Only("app"));
|
||||
assert!(only.contains(&format!(" AND {column} = 'app' ORDER BY ")), "{only}");
|
||||
assert!(!only.contains("LIMIT") && !only.contains("FETCH FIRST"), "{only}");
|
||||
let rest = completion_columns(driver, CompletionScope::Except("app"));
|
||||
assert!(rest.contains(&format!(" AND {column} <> 'app' ORDER BY ")), "{rest}");
|
||||
let capped = !matches!(driver, DbDriver::Sqlite | DbDriver::SqlServer);
|
||||
assert_eq!(rest.ends_with(" LIMIT 50000"), capped, "{rest}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_catalog_queries_run_on_older_servers() {
|
||||
let pg = DbDriver::Postgres;
|
||||
@@ -1340,7 +1279,7 @@ mod tests {
|
||||
tables(pg, "s"),
|
||||
columns(pg, "s", "t"),
|
||||
indexes(pg, "s", "t"),
|
||||
completion_columns(pg, CompletionScope::All),
|
||||
completion_columns(pg).to_owned(),
|
||||
foreign_keys(pg).to_owned(),
|
||||
table_foreign_keys(pg, "s", "t"),
|
||||
triggers(pg, "s", "t"),
|
||||
@@ -1351,7 +1290,7 @@ mod tests {
|
||||
let upper = q.to_uppercase();
|
||||
assert!(!["LATERAL", "ORDINALITY", "ATTIDENTITY"].iter().any(|w| upper.contains(w)), "{q}");
|
||||
}
|
||||
assert_eq!(postgres_legacy(&completion_columns(pg, CompletionScope::All)), None);
|
||||
assert_eq!(postgres_legacy(completion_columns(pg)), None);
|
||||
let routines = postgres_legacy(&routines(pg, "s").unwrap()).unwrap();
|
||||
assert!(!routines.contains("prokind") && routines.contains("NOT p.proisagg"));
|
||||
assert_eq!(postgres_legacy(&indexes(pg, "s", "t")), None);
|
||||
|
||||
@@ -779,40 +779,3 @@ async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Completion reads the default schema in full: 52,000 columns there passed the cap shared with
|
||||
/// the other schemas, and the tables sorting last lost theirs (#6118).
|
||||
#[tokio::test]
|
||||
async fn completion_reads_every_column_of_a_wide_default_schema() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
let schema = format!("oi_wide_{}", uuid::Uuid::new_v4().simple());
|
||||
let mut sources = db.sources()?;
|
||||
let mut source = sources[0].clone();
|
||||
source.id = "wide".into();
|
||||
source.options.startup_script = format!("SET search_path = {schema}");
|
||||
sources.push(source);
|
||||
let password = server().map(|(.., password)| password);
|
||||
db.save_sources(sources).await?;
|
||||
db.set_password("wide", password, false).await?;
|
||||
db.execute("p", &format!("CREATE SCHEMA {schema}"), 1, &c).await?;
|
||||
let fill = format!(
|
||||
"DO $$ DECLARE cols text; BEGIN \
|
||||
SELECT string_agg('c' || g || ' int', ', ') INTO cols FROM generate_series(1, 200) g; \
|
||||
FOR i IN 1..260 LOOP EXECUTE format('CREATE TABLE {schema}.t%s (%s)', lpad(i::text, 3, '0'), cols); \
|
||||
END LOOP; END $$"
|
||||
);
|
||||
let result = async {
|
||||
db.execute("p", &fill, 1, &c).await?;
|
||||
let completion = db.completion("wide").await?;
|
||||
assert_eq!(completion.default_schema, schema);
|
||||
let wide: Vec<_> = completion.tables.iter().filter(|t| t.schema == schema).collect();
|
||||
assert_eq!(wide.len(), 260);
|
||||
assert!(wide.iter().all(|t| t.columns.len() == 200), "a table lost columns");
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
db.execute("p", &format!("DROP SCHEMA {schema} CASCADE"), 1, &c).await?;
|
||||
result
|
||||
}
|
||||
@@ -187,7 +187,7 @@ async fn sqlserver_introspection_works_under_a_case_sensitive_collation() {
|
||||
let fk = ["dbo", "Child", "FK_Child_Parent", "ParentId", "dbo", "Parent", "Id"];
|
||||
assert_eq!(cells(pool.rows(&sql::table_foreign_keys(d, "dbo", "Child"), 100).await.unwrap()), [fk]);
|
||||
assert_eq!(cells(pool.rows(sql::foreign_keys(d), 100).await.unwrap()), [fk]);
|
||||
assert_eq!(cells(pool.rows(&sql::completion_columns(d, sql::CompletionScope::All), 100).await.unwrap()).len(), 4);
|
||||
assert_eq!(cells(pool.rows(sql::completion_columns(d), 100).await.unwrap()).len(), 4);
|
||||
assert_eq!(cells(pool.rows(&sql::routines(d, "dbo").unwrap(), 100).await.unwrap())[0][..2], ["Touch", "procedure"]);
|
||||
drop(pool);
|
||||
master
|
||||
|
||||
@@ -46,26 +46,18 @@ fn main() {
|
||||
#[cfg(unix)]
|
||||
if args.first().is_some_and(|a| a == "--attach") {
|
||||
let Some(project_path) = args.get(1).filter(|p| !p.is_empty()) else {
|
||||
eprintln!("usage: openidea-server --attach <project-path> [--replace]");
|
||||
eprintln!("usage: openidea-server --attach <project-path>");
|
||||
std::process::exit(2);
|
||||
};
|
||||
// `--replace`: stop another build's backend that still holds the project.
|
||||
let replace = args.get(2).is_some_and(|a| a == "--replace");
|
||||
let home = dirs::home_dir().unwrap_or_default();
|
||||
let code = match ide_host::daemon::attach(
|
||||
&base,
|
||||
&home,
|
||||
project_path,
|
||||
replace,
|
||||
std::io::stdin(),
|
||||
std::io::stdout().lock(),
|
||||
) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
1
|
||||
}
|
||||
};
|
||||
let code =
|
||||
match ide_host::daemon::attach(&base, &home, project_path, std::io::stdin(), std::io::stdout().lock()) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
1
|
||||
}
|
||||
};
|
||||
std::process::exit(code);
|
||||
}
|
||||
let mode = match args.as_slice() {
|
||||
|
||||
@@ -121,13 +121,11 @@ fn ensure_private_dir(dir: &Path) -> io::Result<()> {
|
||||
}
|
||||
|
||||
/// Connects to the daemon for `project_path` (spawning it if needed) and bridges
|
||||
/// `input` / `output` to its Unix socket. With `replace`, a daemon of another build that
|
||||
/// refuses to retire is stopped first.
|
||||
/// `input` / `output` to its Unix socket.
|
||||
pub fn attach(
|
||||
base: &Path,
|
||||
home: &Path,
|
||||
project_path: &str,
|
||||
replace: bool,
|
||||
input: impl Read + Send + 'static,
|
||||
output: impl Write,
|
||||
) -> Result<(), String> {
|
||||
@@ -139,11 +137,11 @@ pub fn attach(
|
||||
.map_err(|e| format!("cannot identify openidea-server build: {e}"))?;
|
||||
let hex = hasher.finalize().to_hex();
|
||||
let build = &hex.as_str()[..16];
|
||||
let stream = connect_or_spawn(&exe, &paths, build, replace)?;
|
||||
let stream = connect_or_spawn(&exe, &paths, build)?;
|
||||
bridge(stream, input, output).map_err(|e| format!("daemon relay failed: {e}"))
|
||||
}
|
||||
|
||||
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str, replace: bool) -> Result<UnixStream, String> {
|
||||
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result<UnixStream, String> {
|
||||
let lock_file = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
@@ -155,11 +153,8 @@ fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str, replace: bool)
|
||||
flock(&lock_file, FlockOperation::LockExclusive)
|
||||
.map_err(|e| format!("cannot lock {}: {e}", paths.lock.display()))?;
|
||||
|
||||
match existing_daemon(paths, build) {
|
||||
Ok(Some(stream)) => return Ok(stream),
|
||||
Ok(None) => {}
|
||||
Err(e) if replace && e.contains(rpc::OTHER_BUILD_BUSY) => stop_daemon(&paths.socket)?,
|
||||
Err(e) => return Err(e),
|
||||
if let Some(stream) = existing_daemon(paths, build)? {
|
||||
return Ok(stream);
|
||||
}
|
||||
|
||||
match std::fs::remove_file(&paths.socket) {
|
||||
@@ -237,7 +232,10 @@ fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream
|
||||
Err(io::Error::other("unexpected response from stopping daemon"))
|
||||
}
|
||||
}
|
||||
BUSY => Err(io::Error::other(rpc::OTHER_BUILD_BUSY)),
|
||||
BUSY => Err(io::Error::other(
|
||||
"Another build of OpenIDEA still has this project open, is running tasks, or has unsaved changes. \
|
||||
Reconnect with that build, then stop the remote backend before upgrading.",
|
||||
)),
|
||||
_ => Err(io::Error::other("unrecognized remote backend response")),
|
||||
}
|
||||
};
|
||||
@@ -249,63 +247,6 @@ fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream
|
||||
exchange(stream).map_err(|e| format!("cannot attach to {}: {e}", paths.socket.display()))
|
||||
}
|
||||
|
||||
/// Stops the daemon serving `socket` (another build's, which refused to retire): asks it to
|
||||
/// shut down like the remote Stop Backend action does, and kills it if it hasn't after a while.
|
||||
fn stop_daemon(socket: &Path) -> Result<(), String> {
|
||||
let pids = daemon_pids(socket)?;
|
||||
if pids.is_empty() {
|
||||
return Err(format!("cannot find the backend serving {}", socket.display()));
|
||||
}
|
||||
let signal = |sig| {
|
||||
for pid in &pids {
|
||||
if let Some(pid) = rustix::process::Pid::from_raw(*pid) {
|
||||
let _ = rustix::process::kill_process(pid, sig);
|
||||
}
|
||||
}
|
||||
};
|
||||
let alive = || pids.iter().any(|pid| process_exists(*pid));
|
||||
signal(rustix::process::Signal::TERM);
|
||||
let deadline = Instant::now() + rpc::SHUTDOWN_TIMEOUT;
|
||||
while alive() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
if alive() {
|
||||
signal(rustix::process::Signal::KILL);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `pid` still runs: an exited process its parent hasn't reaped yet (a zombie) doesn't.
|
||||
fn process_exists(pid: i32) -> bool {
|
||||
if !rustix::process::Pid::from_raw(pid).is_some_and(|pid| rustix::process::test_kill_process(pid).is_ok()) {
|
||||
return false;
|
||||
}
|
||||
Command::new("ps")
|
||||
.args(["-o", "stat=", "-p", &pid.to_string()])
|
||||
.output()
|
||||
.map_or(true, |out| !String::from_utf8_lossy(&out.stdout).trim_start().starts_with('Z'))
|
||||
}
|
||||
|
||||
/// Processes started as `openidea-server --daemon <socket> <build>`.
|
||||
fn daemon_pids(socket: &Path) -> Result<Vec<i32>, String> {
|
||||
let out = Command::new("ps")
|
||||
.args(["-axww", "-o", "pid=", "-o", "args="])
|
||||
.output()
|
||||
.map_err(|e| format!("cannot list processes: {e}"))?;
|
||||
Ok(daemon_pids_in(&String::from_utf8_lossy(&out.stdout), &socket.to_string_lossy()))
|
||||
}
|
||||
|
||||
fn daemon_pids_in(ps: &str, socket: &str) -> Vec<i32> {
|
||||
ps.lines()
|
||||
.filter_map(|line| {
|
||||
let (pid, args) = line.trim_start().split_once(char::is_whitespace)?;
|
||||
let mut words = args.split_whitespace().skip_while(|w| *w != "--daemon").skip(1);
|
||||
(words.next() == Some(socket)).then(|| pid.parse().ok()).flatten()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn read_log_tail(file: &mut File, offset: u64) -> String {
|
||||
if file.seek(SeekFrom::Start(offset)).is_err() {
|
||||
return String::new();
|
||||
@@ -539,19 +480,3 @@ fn has_live_work(host: &Host) -> bool {
|
||||
.iter()
|
||||
.any(|project| project.agents.has_live_work() || project.documents.has_unsaved_changes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::daemon_pids_in;
|
||||
|
||||
#[test]
|
||||
fn finds_the_daemon_of_a_socket_in_the_process_list() {
|
||||
let ps = " 1 /sbin/init\n\
|
||||
581660 /root/.openidea/server/0.1.51/634a/openidea-server --daemon /root/.openidea/run/s-de2d.sock 634a\n\
|
||||
141712 /root/.openidea/server/0.1.53/e116/openidea-server --daemon /root/.openidea/run/s-a67f.sock e116\n\
|
||||
582484 /bin/bash --init-file /tmp/openidea-shell-integration-0.1.51/bash/openidea.bashrc -i\n\
|
||||
590000 grep --daemon /root/.openidea/run/s-de2d.sock.bak\n";
|
||||
assert_eq!(daemon_pids_in(ps, "/root/.openidea/run/s-de2d.sock"), [581660]);
|
||||
assert!(daemon_pids_in(ps, "/root/.openidea/run/s-none.sock").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -378,7 +378,6 @@ impl Host {
|
||||
self.mcp_reports.forget_window(window);
|
||||
self.mcp_requests.forget_window(window);
|
||||
self.mcp_agent_runs.forget_window(window);
|
||||
self.debugger.forget_breakpoints(self.owner_window(window));
|
||||
self.external_logs.write().remove(self.owner_window(window));
|
||||
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
|
||||
self.cancel_request(request);
|
||||
|
||||
@@ -32,19 +32,12 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut config = config;
|
||||
let enhanced = take_enhanced_redefinition(&mut config);
|
||||
let java_exec = java_exec_path(&config);
|
||||
let mut agents = if is_jvm_launch(&config) {
|
||||
let agents = if is_jvm_launch(&config) {
|
||||
ide_run::java_agent::current_for(java_exec.as_deref())
|
||||
} else {
|
||||
ide_run::java_agent::Agents::default()
|
||||
Default::default()
|
||||
};
|
||||
match enhanced {
|
||||
Some(Ok(option)) => agents.options.insert(0, option.to_owned()),
|
||||
Some(Err(note)) => agents.notes.push(note),
|
||||
None => {}
|
||||
}
|
||||
let config = add_java_agents(config, &agents.options);
|
||||
let mut config = match_java_debug_encoding(start_java_attach_listener(config, cfg!(windows)), cfg!(windows));
|
||||
if config.adapter == "debugpy"
|
||||
@@ -256,21 +249,6 @@ fn java_exec_path(config: &LaunchConfig) -> Option<std::path::PathBuf> {
|
||||
extra.get("javaExec").and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(std::path::PathBuf::from)
|
||||
}
|
||||
|
||||
/// The configuration's Enhanced class redefinition (`enhancedClassRedefinition` in the launch
|
||||
/// extras, which this removes): for a JVM the debugger starts, JetBrains Runtime's flag, or the
|
||||
/// console line saying why the session runs without it.
|
||||
fn take_enhanced_redefinition(config: &mut LaunchConfig) -> Option<Result<&'static str, String>> {
|
||||
let Some(serde_json::Value::Object(mut extra)) =
|
||||
config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok())
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let on = extra.remove("enhancedClassRedefinition")?.as_bool() == Some(true);
|
||||
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
|
||||
(on && is_jvm_launch(config))
|
||||
.then(|| ide_run::java_hotswap::enhanced_redefinition(java_exec_path(config).as_deref()))
|
||||
}
|
||||
|
||||
/// Plugins' Java agents ([`ide_run::java_agent`]) after the configuration's VM options:
|
||||
/// java-debug's and java-analyzer's `vmArgs` (one line, or a list) or the Kotlin debugger's
|
||||
/// `vmArguments` (a list).
|
||||
@@ -402,25 +380,13 @@ fn match_java_debug_encoding(mut config: LaunchConfig, windows: bool) -> LaunchC
|
||||
config
|
||||
}
|
||||
|
||||
/// This window's breakpoints of `path`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
host.debugger.set_breakpoints(host.owner_window(window), path, breakpoints).await
|
||||
}
|
||||
|
||||
/// Replaces all of this window's line breakpoints with `files`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_replace_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
files: std::collections::BTreeMap<PathBuf, Vec<Breakpoint>>,
|
||||
) -> IdeResult<()> {
|
||||
host.debugger.replace_breakpoints(host.owner_window(window), files).await
|
||||
host.debugger.set_breakpoints(path, breakpoints).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -663,20 +629,18 @@ pub fn debug_capabilities(host: &Host, session: DebugSessionId) -> IdeResult<Deb
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_function_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
breakpoints: Vec<FunctionBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
host.debugger.set_function_breakpoints(host.owner_window(window), breakpoints).await
|
||||
host.debugger.set_function_breakpoints(breakpoints).await
|
||||
}
|
||||
|
||||
/// Field watchpoints; states aligned with `breakpoints`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_data_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
breakpoints: Vec<DataBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
host.debugger.set_data_breakpoints(host.owner_window(window), breakpoints).await
|
||||
host.debugger.set_data_breakpoints(breakpoints).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -952,49 +916,6 @@ mod tests {
|
||||
assert_eq!(add_java_agents(config.clone(), &[]).extra_json, config.extra_json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enhanced_class_redefinition_is_taken_from_the_launch_extras() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let jdk = |name: &str, implementor: &str| {
|
||||
let home = tmp.path().join(name);
|
||||
std::fs::create_dir_all(home.join("bin")).unwrap();
|
||||
std::fs::write(home.join("release"), format!("IMPLEMENTOR=\"{implementor}\"\n")).unwrap();
|
||||
std::fs::write(home.join("bin/java"), "").unwrap();
|
||||
home.join("bin/java").to_string_lossy().into_owned()
|
||||
};
|
||||
let (jbr, temurin) = (jdk("jbr", "JetBrains s.r.o."), jdk("temurin", "Eclipse Adoptium"));
|
||||
let extras = |config: &LaunchConfig| {
|
||||
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()
|
||||
};
|
||||
|
||||
let mut config = launch(
|
||||
"java-debug",
|
||||
"launch",
|
||||
serde_json::json!({"javaExec": jbr, "vmArgs": "-Xmx1g", "enhancedClassRedefinition": true}),
|
||||
);
|
||||
assert_eq!(take_enhanced_redefinition(&mut config), Some(Ok(ide_run::java_hotswap::OPTION)));
|
||||
assert!(extras(&config).get("enhancedClassRedefinition").is_none(), "not passed on to the adapter");
|
||||
assert_eq!(extras(&config)["vmArgs"], "-Xmx1g");
|
||||
|
||||
let mut config =
|
||||
launch("java-debug", "launch", serde_json::json!({"javaExec": temurin, "enhancedClassRedefinition": true}));
|
||||
let note = take_enhanced_redefinition(&mut config).unwrap().unwrap_err();
|
||||
assert!(note.contains("is not a JetBrains Runtime"), "{note}");
|
||||
let mut config = launch("java-debug", "launch", serde_json::json!({"enhancedClassRedefinition": true}));
|
||||
assert!(take_enhanced_redefinition(&mut config).unwrap().unwrap_err().contains("is unknown"));
|
||||
|
||||
// Off, absent, or not a JVM the debugger starts: nothing to add, and no note.
|
||||
for (adapter, request, extra) in [
|
||||
("java-debug", "launch", serde_json::json!({"javaExec": jbr, "enhancedClassRedefinition": false})),
|
||||
("java-debug", "launch", serde_json::json!({"javaExec": jbr})),
|
||||
("java-debug", "attach", serde_json::json!({"javaExec": jbr, "enhancedClassRedefinition": true})),
|
||||
] {
|
||||
let mut config = launch(adapter, request, extra);
|
||||
assert_eq!(take_enhanced_redefinition(&mut config), None);
|
||||
assert!(extras(&config).get("enhancedClassRedefinition").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_server_port_only_for_local_java_debug() {
|
||||
let port = |adapter: &str, request: &str, extra| debug_server_port(&launch(adapter, request, extra));
|
||||
@@ -1041,7 +962,6 @@ ide_command::domain!(
|
||||
debug_listen_for_jvm,
|
||||
debug_pause,
|
||||
debug_redefine_classes,
|
||||
debug_replace_breakpoints,
|
||||
debug_resolve_variable,
|
||||
debug_restart_frame,
|
||||
debug_resume,
|
||||
|
||||
@@ -222,9 +222,6 @@ impl Host {
|
||||
ide_sdk::apply::configure_python_extra_paths(cfg, &paths);
|
||||
}
|
||||
if cfg.name == "jdtls" {
|
||||
// Before anything reads the install the command resolves to.
|
||||
let managed = ide_tools::tools_dir(&data_dir).join("jdtls").join("bin").join("jdtls");
|
||||
ide_sdk::jdtls::skip_plain_launcher_wrappers(cfg, &managed);
|
||||
// A workspace member keeps its build model under its own key (Build Project).
|
||||
let cache = match &member {
|
||||
Some(member) if member != window_root => build_cache.join(crate::project::project_key(member)),
|
||||
|
||||
@@ -32,10 +32,6 @@ use std::sync::{Arc, OnceLock};
|
||||
/// doesn't know the event would show stale output.
|
||||
pub const PROTOCOL_VERSION: u32 = 4;
|
||||
pub const SESSION_REPLACED: &str = "session_replaced";
|
||||
/// What `openidea-server --attach` reports when another build's backend keeps the project
|
||||
/// (clients match it to offer stopping that backend).
|
||||
pub const OTHER_BUILD_BUSY: &str = "Another build of OpenIDEA still has this project open, is running tasks, or has \
|
||||
unsaved changes. Reconnect with that build, or stop its backend and open the project again.";
|
||||
pub const SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(90);
|
||||
|
||||
/// Advertised only by a persistent backend with an editable idle timeout.
|
||||
|
||||
@@ -782,7 +782,7 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(!rejected.status.success());
|
||||
assert!(String::from_utf8_lossy(&rejected.stderr).contains(ide_host::rpc::OTHER_BUILD_BUSY), "{rejected:?}");
|
||||
assert!(String::from_utf8_lossy(&rejected.stderr).contains("Another build of OpenIDEA"), "{rejected:?}");
|
||||
assert!(previous_build.try_wait().unwrap().is_none(), "the live backend was replaced");
|
||||
let resumed = old_open().await;
|
||||
assert_eq!(invoke(&resumed, "term_list", json!({})).await.unwrap()[0]["id"], term["id"]);
|
||||
@@ -798,60 +798,6 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
|
||||
shutdown(&new).await;
|
||||
}
|
||||
|
||||
/// `--attach --replace` stops another build's backend that refuses to retire (#6119).
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn replace_stops_another_builds_busy_backend() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
const OLD_BUILD: &str = "fedcba9876543210";
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("h");
|
||||
let base = tmp.path().join("s");
|
||||
let project = home.join("demo");
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
|
||||
let mut previous_build = tokio::process::Command::new(SERVER)
|
||||
.arg("--daemon")
|
||||
.arg(&guard.0)
|
||||
.arg(OLD_BUILD)
|
||||
.envs(server_env(&home, &base, 10_800))
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
until("old backend socket", || guard.0.exists()).await;
|
||||
let mut stream = 'connect: {
|
||||
for _ in 0..600 {
|
||||
match UnixStream::connect(&guard.0).await {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::ConnectionRefused => {
|
||||
tokio::time::sleep(Duration::from_millis(15)).await;
|
||||
}
|
||||
other => break 'connect other.unwrap(),
|
||||
}
|
||||
}
|
||||
panic!("the old backend never accepted a connection");
|
||||
};
|
||||
stream.write_all(OLD_BUILD.as_bytes()).await.unwrap();
|
||||
assert_eq!(stream.read_u8().await.unwrap(), b'A');
|
||||
let (reader, writer) = stream.into_split();
|
||||
let old = Peer::connect(reader, writer, Arc::new(Client::default()));
|
||||
initialize(&old).await;
|
||||
let term = looping_terminal(&old, &project).await;
|
||||
old.kill();
|
||||
old.closed().await;
|
||||
|
||||
let client = Arc::new(Client::default());
|
||||
let args = ["--attach", "~/demo", "--replace"].map(str::to_owned).to_vec();
|
||||
let env = server_env(&home, &base, 10_800);
|
||||
let new = Peer::spawn(SERVER, &args, &home, &env, client, Box::new(|line| eprintln!("{line}"))).unwrap();
|
||||
initialize(&new).await;
|
||||
let old_exit = tokio::time::timeout(Duration::from_secs(15), previous_build.wait()).await.unwrap().unwrap();
|
||||
assert!(old_exit.success(), "the old backend did not shut down cleanly: {old_exit:?}");
|
||||
until("its terminal stopped", || !pid_alive(term["pid"].as_u64().unwrap() as u32)).await;
|
||||
assert!(invoke(&new, "term_list", json!({})).await.unwrap().as_array().unwrap().is_empty());
|
||||
shutdown(&new).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "requires a Docker context with Docker Compose and the busybox image"]
|
||||
async fn compose_service_survives_disconnect_and_is_removed_on_stop() {
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
//! Enhanced class redefinition for Java debug sessions: on JetBrains Runtime,
|
||||
//! `-XX:+AllowEnhancedClassRedefinition` lets HotSwap (Reload Changed Classes) apply
|
||||
//! structural changes such as added or removed methods and fields. Other JVMs refuse to
|
||||
//! start with the flag, so it is added only when the launched JDK is JetBrains Runtime.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// The JVM flag JetBrains Runtime takes.
|
||||
pub const OPTION: &str = "-XX:+AllowEnhancedClassRedefinition";
|
||||
|
||||
/// The flag when `java` (the launched `bin/java`; `None` when unknown) is JetBrains Runtime,
|
||||
/// else the console line saying why the session runs without it.
|
||||
pub fn enhanced_redefinition(java: Option<&Path>) -> Result<&'static str, String> {
|
||||
let java = java.filter(|java| java.components().count() > 1);
|
||||
match java {
|
||||
Some(java) if crate::java_agent::jdk_allows(Some(java), Some("jetbrains")) => Ok(OPTION),
|
||||
Some(java) => Err(format!(
|
||||
"Enhanced class redefinition is off for this session: {} is not a JetBrains Runtime. \
|
||||
Choose a JetBrains Runtime as the configuration's JRE.",
|
||||
java.display()
|
||||
)),
|
||||
None => Err("Enhanced class redefinition is off for this session: the JDK it runs on is unknown. \
|
||||
Choose a JetBrains Runtime as the configuration's JRE."
|
||||
.to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn jdk(dir: &Path, implementor: &str) -> std::path::PathBuf {
|
||||
let bin = dir.join("bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
std::fs::write(dir.join("release"), format!("JAVA_VERSION=\"21\"\nIMPLEMENTOR=\"{implementor}\"\n")).unwrap();
|
||||
let java = bin.join("java");
|
||||
std::fs::write(&java, "").unwrap();
|
||||
java
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jetbrains_runtime_gets_the_flag() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let java = jdk(tmp.path(), "JetBrains s.r.o.");
|
||||
assert_eq!(enhanced_redefinition(Some(&java)), Ok(OPTION));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_jdks_get_a_note_instead() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let java = jdk(tmp.path(), "Eclipse Adoptium");
|
||||
let note = enhanced_redefinition(Some(&java)).unwrap_err();
|
||||
assert!(note.contains("is not a JetBrains Runtime"), "{note}");
|
||||
assert!(note.contains(&java.display().to_string()), "{note}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_jdk_gets_a_note() {
|
||||
assert!(enhanced_redefinition(None).unwrap_err().contains("is unknown"));
|
||||
// A bare `java` names no JDK.
|
||||
assert!(enhanced_redefinition(Some(Path::new("java"))).unwrap_err().contains("is unknown"));
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,6 @@ pub mod gradle_jvm;
|
||||
pub mod import;
|
||||
pub mod java_agent;
|
||||
pub mod java_cmdline;
|
||||
pub mod java_hotswap;
|
||||
pub mod junit;
|
||||
mod process;
|
||||
pub mod python_path;
|
||||
|
||||
@@ -228,45 +228,6 @@ pub fn java_args(install: &JdtlsInstall, java_major: u32, script_args: &[String]
|
||||
args
|
||||
}
|
||||
|
||||
/// Whether `script` is a hand-written `jdtls` that starts the Equinox launcher with `java -jar`
|
||||
/// itself, like the one opencode puts into a JDK's `bin` (#6062). It knows none of the release
|
||||
/// script's options: each `--jvm-arg=` (the Lombok agent, heap, proxy) reaches jdtls as an
|
||||
/// application argument instead of a JVM option, and its own `-data` comes before the IDE's.
|
||||
fn is_plain_launcher_wrapper(script: &Path) -> bool {
|
||||
if std::fs::metadata(script).map_or(true, |m| m.len() > 64 * 1024) {
|
||||
return false;
|
||||
}
|
||||
let Ok(bytes) = std::fs::read(script) else { return false };
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
text.contains("org.eclipse.equinox.launcher") && !text.contains("--jvm-arg")
|
||||
}
|
||||
|
||||
/// Picks the `jdtls` to start when the first one on `PATH` is a [plain launcher
|
||||
/// wrapper](is_plain_launcher_wrapper): the next one there that isn't, else the IDE's own
|
||||
/// install (`managed`, `<tools>/jdtls/bin/jdtls`), which is offered for install while missing.
|
||||
/// A command naming a path is the user's choice and kept.
|
||||
pub fn skip_plain_launcher_wrappers(cfg: &mut LanguageServerConfig, managed: &Path) {
|
||||
if cfg.name != "jdtls" || Path::new(&cfg.command).components().count() != 1 {
|
||||
return;
|
||||
}
|
||||
let search = cfg.env.get("PATH").map(std::ffi::OsString::from).unwrap_or_else(ide_core::tool_path::search_path);
|
||||
let mut candidates = std::env::split_paths(&search)
|
||||
.filter(|dir| !dir.as_os_str().is_empty())
|
||||
.filter_map(|dir| ide_core::process::find_executable(&cfg.command, dir.as_os_str()));
|
||||
let Some(first) = candidates.next() else { return };
|
||||
if !is_plain_launcher_wrapper(&first) {
|
||||
return;
|
||||
}
|
||||
let chosen = candidates.find(|c| !is_plain_launcher_wrapper(c)).unwrap_or_else(|| managed.to_path_buf());
|
||||
tracing::warn!(
|
||||
"{} starts jdtls with `java -jar` itself and ignores the IDE's JVM arguments (Lombok agent, \
|
||||
workspace); using {} instead",
|
||||
first.display(),
|
||||
chosen.display()
|
||||
);
|
||||
cfg.command = chosen.to_string_lossy().into_owned();
|
||||
}
|
||||
|
||||
/// The release script a `jdtls` command on `PATH` resolves to: itself when it
|
||||
/// already is one, or the script its Scoop shim launches. `None` for a command
|
||||
/// that is neither a release script nor a jdtls Scoop shim.
|
||||
@@ -599,57 +560,6 @@ mod tests {
|
||||
assert_eq!(find_install(home, "macos", "aarch64").unwrap().config, home.join("config_mac_arm"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_java_jar_wrapper_first_on_path_is_skipped() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let exe = |dir: &Path, text: &str| {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
let name = if cfg!(windows) { "jdtls.cmd" } else { "jdtls" };
|
||||
std::fs::write(dir.join(name), text).unwrap();
|
||||
#[cfg(unix)]
|
||||
std::fs::set_permissions(dir.join(name), std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
|
||||
dir.join(name)
|
||||
};
|
||||
// opencode's wrapper (#6062), then a release script.
|
||||
let wrapper = exe(
|
||||
&dir.path().join("jdk/bin"),
|
||||
"\"%JAVA_HOME%\\bin\\java\" -jar \"%JDTLS_HOME%\\plugins\\org.eclipse.equinox.launcher_1.7.100.jar\" -data \"%DATA_DIR%\" %*\n",
|
||||
);
|
||||
let release = exe(
|
||||
&dir.path().join("jdtls/bin"),
|
||||
"parser.add_argument('--jvm-arg', action='append')\nlauncher = 'org.eclipse.equinox.launcher_*.jar'\n",
|
||||
);
|
||||
let managed = dir.path().join("tools/jdtls/bin/jdtls");
|
||||
let cfg = |dirs: &[&Path]| -> LanguageServerConfig {
|
||||
let mut cfg: LanguageServerConfig = toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap();
|
||||
let path = std::env::join_paths(dirs.iter().map(|d| d.parent().unwrap())).unwrap();
|
||||
cfg.env.insert("PATH".into(), path.to_string_lossy().into_owned());
|
||||
cfg
|
||||
};
|
||||
|
||||
let mut next = cfg(&[&wrapper, &release]);
|
||||
skip_plain_launcher_wrappers(&mut next, &managed);
|
||||
assert_eq!(Path::new(&next.command), release);
|
||||
|
||||
let mut only = cfg(&[&wrapper]);
|
||||
skip_plain_launcher_wrappers(&mut only, &managed);
|
||||
assert_eq!(Path::new(&only.command), managed, "the IDE's install, offered while missing");
|
||||
|
||||
let mut release_first = cfg(&[&release, &wrapper]);
|
||||
skip_plain_launcher_wrappers(&mut release_first, &managed);
|
||||
assert_eq!(release_first.command, "jdtls");
|
||||
|
||||
// Wrappers that delegate (Homebrew's, a Scoop shim) and named commands are kept.
|
||||
let brew = exe(&dir.path().join("brew/bin"), "#!/bin/bash\nexec \"/opt/jdtls/libexec/bin/jdtls\" \"$@\"\n");
|
||||
let mut delegating = cfg(&[&brew, &release]);
|
||||
skip_plain_launcher_wrappers(&mut delegating, &managed);
|
||||
assert_eq!(delegating.command, "jdtls");
|
||||
let mut named = cfg(&[&wrapper]);
|
||||
named.command = wrapper.to_string_lossy().into_owned();
|
||||
skip_plain_launcher_wrappers(&mut named, &managed);
|
||||
assert_eq!(Path::new(&named.command), wrapper);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn rewrites_the_release_script_to_java() {
|
||||
|
||||
@@ -152,9 +152,7 @@ double click and Enter with `event.table_activate()` (API 1.3, absolute 0-based
|
||||
Bodies, fields and events added by later APIs travel as `Other { kind, data }`: an IDE that
|
||||
doesn't know a body says it needs updating, and leaves out a field type it doesn't know.
|
||||
Item right-click menus use `viewItem.context` (see
|
||||
[Commands and actions](/en/plugins/guides/commands#menus)). A command that menu offers for the selected item,
|
||||
run from its shortcut (or Find Action) while the view has the keyboard focus, gets that
|
||||
item's key as its argument, as from the menu; none when nothing is selected.
|
||||
[Commands and actions](/en/plugins/guides/commands#menus)).
|
||||
|
||||
## Custom editors
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ register_plugin!(TodoFinder, views);
|
||||
双击和回车用 `event.table_activate()`(API 1.3,从 0 开始的绝对行号)。
|
||||
|
||||
后续 API 新增的主体、字段和事件以 `Other { kind, data }` 传递:IDE 不认识某种主体时会提示需要更新,
|
||||
不认识的字段类型则直接省略。条目右键菜单使用 `viewItem.context`(见 [命令与动作](/zh/plugins/guides/commands) 中的“菜单”一节)。视图有键盘焦点时,用快捷键(或查找动作)运行选中条目的右键菜单里有的命令,命令参数是该条目的 key,与从菜单运行相同;未选中条目时没有参数。
|
||||
不认识的字段类型则直接省略。条目右键菜单使用 `viewItem.context`(见 [命令与动作](/zh/plugins/guides/commands) 中的“菜单”一节)。
|
||||
|
||||
## 自定义编辑器
|
||||
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { commands } from "../src/platform/ipc";
|
||||
import { setInvokeRoute } from "../src/platform/tauriCore";
|
||||
import { schemeCss } from "../src/platform/colorScheme";
|
||||
import { lspDoc } from "../src/editor/lsp/lsp";
|
||||
import { semanticExtension } from "../src/editor/lsp/semantic";
|
||||
import { lspTheme } from "../src/editor/lsp/theme";
|
||||
|
||||
setInvokeRoute(() => null);
|
||||
commands.lspSemanticTokens = async () => ({
|
||||
status: "ok",
|
||||
data: {
|
||||
tokenTypes: ["namespace"],
|
||||
tokenModifiers: ["defaultLibrary", "globalScope"],
|
||||
data: [0, 0, 7, 0, 2, 1, 0, 3, 0, 3],
|
||||
},
|
||||
});
|
||||
const mode = new URLSearchParams(location.search).has("light") ? "light" : "dark";
|
||||
const style = document.createElement("style");
|
||||
style.textContent = schemeCss(mode, {
|
||||
[mode]: {
|
||||
packageReference: { foreground: "#446688" },
|
||||
predefined: { foreground: "#cc5500" },
|
||||
},
|
||||
});
|
||||
document.head.append(style);
|
||||
new EditorView({
|
||||
parent: document.body,
|
||||
doc: "example::hello();\nstd::cout << 1;",
|
||||
extensions: [
|
||||
lspTheme,
|
||||
lspDoc.of({ doc: 1, path: "demo.cpp", language: "cpp", uiMode: "C++", readOnly: false }),
|
||||
semanticExtension(),
|
||||
],
|
||||
});
|
||||
@@ -1,9 +0,0 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
</head>
|
||||
<body>
|
||||
<script type="module" src="./cppNamespaceStyle.fixture.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,12 +0,0 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
for (const mode of ["dark", "light"]) {
|
||||
test(`C++ standard and user namespaces share the namespace colour (${mode})`, async ({ page }) => {
|
||||
await page.goto(`/e2e/cppNamespaceStyle.html${mode === "light" ? "?light" : ""}`);
|
||||
const namespaces = page.locator(".cm-sem-namespace");
|
||||
await expect(namespaces).toHaveCount(2);
|
||||
for (const namespace of await namespaces.all()) {
|
||||
await expect(namespace).toHaveCSS("color", "rgb(68, 102, 136)");
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -78,8 +78,7 @@ test("precise filter values are ordered and filtering composes with result sorti
|
||||
const values = page.getByRole("group", { name: "Values", exact: true });
|
||||
const ascending = [integers[3]!, integers[2]!, integers[1]!, integers[0]!];
|
||||
await expect(values.locator("label")).toHaveText(ascending);
|
||||
// Checked values are the rows shown.
|
||||
for (const value of ascending.slice(1)) await values.getByRole("checkbox", { name: value, exact: true }).check();
|
||||
await values.getByRole("checkbox", { name: integers[3], exact: true }).uncheck();
|
||||
await page.keyboard.press("Escape");
|
||||
await grid
|
||||
.getByRole("columnheader", { name: /^value\b/ })
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("shows why the frames did not load and retries them", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 940, height: 740 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const stateModule = "/src/features/debugger/state.ts";
|
||||
const workbenchModule = "/src/workbench/contributions.ts";
|
||||
const { adoptSession, handleDebugEvent } = await import(/* @vite-ignore */ stateModule);
|
||||
const { toolWindowService } = await import(/* @vite-ignore */ workbenchModule);
|
||||
const handlers = window.__ipc.handlers;
|
||||
let failures = 1;
|
||||
handlers.debug_stack_trace = () => {
|
||||
if (failures-- > 0)
|
||||
throw { kind: "protocol", message: "debug adapter did not answer `stackTrace` in time", detail: null };
|
||||
return [{ id: 7, name: "OrderController.place(Order)", path: null, line: 41, column: 0, presentationHint: null }];
|
||||
};
|
||||
handlers.debug_threads = () => [{ id: 9, name: "http-nio-8080-exec-9" }];
|
||||
handlers.debug_scopes = () => [];
|
||||
adoptSession(98, { name: "Orders", adapter: "java-debug", status: "running" });
|
||||
toolWindowService().show("debug", true);
|
||||
handleDebugEvent(98, {
|
||||
kind: "stopped",
|
||||
threadId: 9,
|
||||
allThreadsStopped: false,
|
||||
reason: "breakpoint",
|
||||
description: null,
|
||||
});
|
||||
});
|
||||
|
||||
const frames = page.getByRole("region", { name: "Debug", exact: true }).getByRole("listbox", { name: "Frames" });
|
||||
const error = frames.getByRole("alert");
|
||||
await expect(error).toContainText("Could not load the frames: debug adapter did not answer `stackTrace` in time");
|
||||
await page.screenshot({ path: test.info().outputPath("frames-error.png") });
|
||||
await error.getByRole("button", { name: "Retry" }).click();
|
||||
await expect(frames.getByText("OrderController.place(Order)", { exact: true })).toBeVisible();
|
||||
await expect(error).toBeHidden();
|
||||
expect(await ipcCalls(page, "debug_stack_trace")).toEqual([
|
||||
{ session: 98, threadId: 9 },
|
||||
{ session: 98, threadId: 9 },
|
||||
]);
|
||||
});
|
||||
@@ -170,11 +170,7 @@ its first `:`, so `pod` for `pod:default/nginx`; the whole key when it has no
|
||||
`:`). Only the menu's `when` sees them, not the command's own `when`; a command
|
||||
whose `when` is false shows greyed out. Other menus refuse `view`, a web view
|
||||
has no item menu, and no menu opens when no declaration matches the item.
|
||||
A command run without an argument (its shortcut, Find Action) while one of the
|
||||
plugin's views has the keyboard focus gets the selected item's key too, when
|
||||
that item's `viewItem.context` menu offers the command: a shortcut acts on the
|
||||
selected item like the menu entry. With nothing selected, the focus elsewhere or
|
||||
the command not in the item's menu, it gets none. The menu is new in API 1.2, so a plugin using it declares
|
||||
The menu is new in API 1.2, so a plugin using it declares
|
||||
`engines.openidea = "^1.2"`. For example:
|
||||
|
||||
```toml
|
||||
|
||||
@@ -463,23 +463,7 @@ pub fn menu_model(app: AppHandle, state: State<'_, AppState>, menu_state: State<
|
||||
}
|
||||
let home = dirs::home_dir();
|
||||
let config = menu_state.config.lock().clone();
|
||||
let remote = menu_state.remote_recent.lock().clone();
|
||||
menu::model(&spec, &menu::recent_items(&state.recent.list(), &remote, home.as_deref()), &config)
|
||||
}
|
||||
|
||||
/// The Remote Development projects of the frontend's recent list, for Open Recent.
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn menu_set_remote_recent(
|
||||
app: AppHandle,
|
||||
menu_state: State<'_, MenuState>,
|
||||
state: State<'_, AppState>,
|
||||
projects: Vec<menu::RemoteRecent>,
|
||||
) {
|
||||
if menu::store_remote_recent(&menu_state, projects) {
|
||||
menu::install(&app, &menu_state, &state.recent.list());
|
||||
}
|
||||
menu::model(&spec, &menu::recent_items(&state.recent.list(), home.as_deref()), &config)
|
||||
}
|
||||
|
||||
/// Action ids the focused window cannot run now: their native menu items are
|
||||
@@ -1012,7 +996,6 @@ ide_command::desktop_domain!(
|
||||
menu_model,
|
||||
menu_refresh,
|
||||
menu_set_disabled,
|
||||
menu_set_remote_recent,
|
||||
window_begin_prompt,
|
||||
window_close_context,
|
||||
window_complete_launch,
|
||||
|
||||
@@ -1117,31 +1117,6 @@ pub struct MenuState {
|
||||
/// Visible menu last installed. Accelerators of actions that are not on the menu
|
||||
/// are not part of this, so they must not redraw the macOS menu bar.
|
||||
rendered: Mutex<Option<Vec<RenderedMenu>>>,
|
||||
/// The Remote Development projects of the frontend's recent list.
|
||||
pub remote_recent: Mutex<Vec<RemoteRecent>>,
|
||||
}
|
||||
|
||||
/// A recent Remote Development project (SSH, WSL, Dev Container), kept by the frontend: Open
|
||||
/// Recent lists it among the local projects, as Manage Projects does.
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RemoteRecent {
|
||||
/// `ssh://host/path`, `wsl://Ubuntu/path`…: what `file.openRecentProject` gets back.
|
||||
pub location: String,
|
||||
pub name: String,
|
||||
/// Where it lives, as shown after the name (`me@host:/srv/app`).
|
||||
pub detail: String,
|
||||
pub opened_at_ms: f64,
|
||||
}
|
||||
|
||||
/// Stores the remote recent list; `false` when it is unchanged.
|
||||
pub fn store_remote_recent(state: &MenuState, next: Vec<RemoteRecent>) -> bool {
|
||||
let mut current = state.remote_recent.lock();
|
||||
if *current == next {
|
||||
return false;
|
||||
}
|
||||
*current = next;
|
||||
true
|
||||
}
|
||||
|
||||
/// Stores `next` when it differs from the config last used to build the menu.
|
||||
@@ -1218,28 +1193,18 @@ pub struct RecentItem {
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
/// The local and remote recent projects, most recently opened first.
|
||||
pub fn recent_items(
|
||||
recent: &[ide_workspace::RecentProject],
|
||||
remote: &[RemoteRecent],
|
||||
home: Option<&Path>,
|
||||
) -> Vec<RecentItem> {
|
||||
let local = recent.iter().map(|p| {
|
||||
let shown = match home.and_then(|h| p.path.strip_prefix(h).ok()) {
|
||||
Some(rest) => format!("~/{}", rest.display()),
|
||||
None => p.path.display().to_string(),
|
||||
};
|
||||
let item =
|
||||
RecentItem { path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name) };
|
||||
(p.opened_at_ms, item)
|
||||
});
|
||||
let remote = remote.iter().map(|r| {
|
||||
(r.opened_at_ms, RecentItem { path: r.location.clone(), label: format!("{} — {}", r.name, r.detail) })
|
||||
});
|
||||
let mut items: Vec<(f64, RecentItem)> = local.chain(remote).collect();
|
||||
// Stable: the local list's own order holds among equal times.
|
||||
items.sort_by(|a, b| b.0.total_cmp(&a.0));
|
||||
items.into_iter().take(MAX_RECENT).map(|(_, item)| item).collect()
|
||||
pub fn recent_items(recent: &[ide_workspace::RecentProject], home: Option<&Path>) -> Vec<RecentItem> {
|
||||
recent
|
||||
.iter()
|
||||
.take(MAX_RECENT)
|
||||
.map(|p| {
|
||||
let shown = match home.and_then(|h| p.path.strip_prefix(h).ok()) {
|
||||
Some(rest) => format!("~/{}", rest.display()),
|
||||
None => p.path.display().to_string(),
|
||||
};
|
||||
RecentItem { path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name) }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One top-level menu, as it will actually be drawn.
|
||||
@@ -1781,7 +1746,7 @@ pub fn install<R: Runtime>(app: &AppHandle<R>, menu_state: &MenuState, recent: &
|
||||
return;
|
||||
}
|
||||
let home = dirs::home_dir();
|
||||
let items = recent_items(recent, &menu_state.remote_recent.lock(), home.as_deref());
|
||||
let items = recent_items(recent, home.as_deref());
|
||||
let config = menu_state.config.lock().clone();
|
||||
let disabled = menu_state.disabled.lock().clone();
|
||||
let rendered = render_bar(&prepared_spec(app, Os::current()), &config, &items);
|
||||
@@ -2268,39 +2233,11 @@ mod tests {
|
||||
branch: None,
|
||||
missing: false,
|
||||
}];
|
||||
let items = recent_items(&recent, &[], Some(Path::new("/home/me")));
|
||||
let items = recent_items(&recent, Some(Path::new("/home/me")));
|
||||
assert_eq!(items[0].label, "openidea — ~/code/openidea");
|
||||
assert_eq!(items[0].path, "/home/me/code/openidea");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_projects_join_the_recent_list_by_when_they_were_opened() {
|
||||
let local = |path: &str, at: f64| ide_workspace::RecentProject {
|
||||
path: path.into(),
|
||||
name: path.rsplit('/').next().unwrap().into(),
|
||||
opened_at_ms: at,
|
||||
branch: None,
|
||||
missing: false,
|
||||
};
|
||||
let recent = vec![local("/home/me/new", 30.0), local("/home/me/old", 10.0)];
|
||||
let remote = [RemoteRecent {
|
||||
location: "wsl://Ubuntu/home/me/api".into(),
|
||||
name: "api".into(),
|
||||
detail: "Ubuntu:/home/me/api".into(),
|
||||
opened_at_ms: 20.0,
|
||||
}];
|
||||
let items = recent_items(&recent, &remote, Some(Path::new("/home/me")));
|
||||
let paths: Vec<&str> = items.iter().map(|i| i.path.as_str()).collect();
|
||||
assert_eq!(paths, ["/home/me/new", "wsl://Ubuntu/home/me/api", "/home/me/old"]);
|
||||
assert_eq!(items[1].label, "api — Ubuntu:/home/me/api");
|
||||
|
||||
let many: Vec<_> = (0..20).map(|i| local(&format!("/p/{i}"), f64::from(i))).collect();
|
||||
let items = recent_items(&many, &remote, None);
|
||||
assert_eq!(items.len(), MAX_RECENT);
|
||||
assert_eq!([items[0].path.as_str(), items[1].path.as_str()], ["wsl://Ubuntu/home/me/api", "/p/19"]);
|
||||
assert_eq!(items[MAX_RECENT - 1].path, format!("/p/{}", 20 - MAX_RECENT + 1), "the remote one takes a slot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_drops_native_roles_and_fills_recent() {
|
||||
let spec = vec![sub(
|
||||
|
||||
@@ -164,7 +164,7 @@ async fn install(
|
||||
|
||||
/// The arguments of `docker` that start the server in the container: in the project folder, told
|
||||
/// that the folder is trusted and that the CLI already ran the lifecycle commands.
|
||||
fn server_args(up: &Up, bin: &str, replace: bool) -> Vec<String> {
|
||||
fn server_args(up: &Up, bin: &str) -> Vec<String> {
|
||||
let mut args: Vec<String> = ["exec", "-i", "-u", &up.user, "-w", &up.folder].map(str::to_owned).into();
|
||||
for var in [
|
||||
format!("{}={}", ide_host::trust::TRUSTED_ROOT_ENV, up.folder),
|
||||
@@ -173,9 +173,6 @@ fn server_args(up: &Up, bin: &str, replace: bool) -> Vec<String> {
|
||||
args.extend(["-e".to_owned(), var]);
|
||||
}
|
||||
args.extend([up.container.clone(), bin.to_owned(), "--attach".to_owned(), up.folder.clone()]);
|
||||
if replace {
|
||||
args.push("--replace".to_owned());
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
@@ -186,7 +183,6 @@ pub(crate) async fn connect(
|
||||
state: &crate::state::AppState,
|
||||
folder: &str,
|
||||
config: &str,
|
||||
replace: bool,
|
||||
handler: Arc<dyn Handler>,
|
||||
tail: &Tail,
|
||||
progress: &Arc<Progress>,
|
||||
@@ -219,23 +215,16 @@ pub(crate) async fn connect(
|
||||
let up = up(&cli, &docker, &local, config, tail).await?;
|
||||
let bin = ensure_server(state, &docker, &up, progress).await?;
|
||||
progress(RemoteStage::Starting, None);
|
||||
let peer = spawn(&docker, &up, &bin, replace, handler, tail)?;
|
||||
let peer = spawn(&docker, &up, &bin, handler, tail)?;
|
||||
let folder = up.folder.clone();
|
||||
Ok((peer, folder, Exec::new(docker, up, bin)))
|
||||
}
|
||||
|
||||
fn spawn(docker: &Path, up: &Up, bin: &str, replace: bool, handler: Arc<dyn Handler>, tail: &Tail) -> IdeResult<Peer> {
|
||||
fn spawn(docker: &Path, up: &Up, bin: &str, handler: Arc<dyn Handler>, tail: &Tail) -> IdeResult<Peer> {
|
||||
let tail = tail.clone();
|
||||
let program = docker.to_string_lossy();
|
||||
Peer::spawn(
|
||||
&program,
|
||||
&server_args(up, bin, replace),
|
||||
&std::env::temp_dir(),
|
||||
&[],
|
||||
handler,
|
||||
Box::new(move |l| tail.push(l)),
|
||||
)
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start docker: {e}")))
|
||||
Peer::spawn(&program, &server_args(up, bin), &std::env::temp_dir(), &[], handler, Box::new(move |l| tail.push(l)))
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start docker: {e}")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -248,7 +237,7 @@ mod tests {
|
||||
#[test]
|
||||
fn the_server_starts_in_the_folder_trusted_and_without_the_lifecycle() {
|
||||
let up = Up { container: ID.into(), user: "vscode".into(), folder: "/workspaces/my app".into() };
|
||||
let args = server_args(&up, "/home/vscode/.openidea/server/1/ab/openidea-server", false);
|
||||
let args = server_args(&up, "/home/vscode/.openidea/server/1/ab/openidea-server");
|
||||
assert_eq!(
|
||||
args,
|
||||
[
|
||||
@@ -385,7 +374,7 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
|
||||
let dir = version_dir(&found.home, "0.0.0-test");
|
||||
let bin = install(&docker, &up, &dir, "b1", &server, &progress).await.unwrap();
|
||||
assert_eq!(probe(&docker, &up, "0.0.0-test").await.unwrap().installed, std::slice::from_ref(&bin));
|
||||
let peer = spawn(&docker, &up, &bin, false, Arc::new(Silent), &tail).unwrap();
|
||||
let peer = spawn(&docker, &up, &bin, Arc::new(Silent), &tail).unwrap();
|
||||
let info: ide_host::rpc::ServerInfo = peer
|
||||
.request("initialize", serde_json::json!({ "version": ide_host::rpc::PROTOCOL_VERSION }), None)
|
||||
.await
|
||||
@@ -457,7 +446,7 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
|
||||
let live = || docker_sh(&docker, &up.container, &format!("kill -0 {pid} 2>/dev/null && printf live"));
|
||||
assert_eq!(live(), "live", "the terminal must outlive the window in a dev container");
|
||||
|
||||
let peer = spawn(&docker, &up, &bin, false, Arc::new(Silent), &Tail::default()).unwrap();
|
||||
let peer = spawn(&docker, &up, &bin, Arc::new(Silent), &Tail::default()).unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(30), async {
|
||||
let project: Value = peer.request("invoke", invoke("project_current", json!({})), None).await.unwrap();
|
||||
assert_eq!(project["root"], up.folder);
|
||||
|
||||
@@ -673,7 +673,6 @@ pub async fn remote_connect(
|
||||
state: State<'_, AppState>,
|
||||
target: RemoteTarget,
|
||||
mut path: String,
|
||||
replace: bool,
|
||||
on_progress: Channel<RemoteProgress>,
|
||||
) -> IdeResult<RemoteProject> {
|
||||
let progress: Arc<Progress> = Arc::new(move |stage, fraction| {
|
||||
@@ -705,10 +704,9 @@ pub async fn remote_connect(
|
||||
let attach_arg = if path.trim().is_empty() { "~" } else { path.trim() };
|
||||
let stream = session
|
||||
.exec_stream(&format!(
|
||||
"{} --attach {}{} 2>&1",
|
||||
"{} --attach {} 2>&1",
|
||||
ide_ssh::shell::tilde_quote(&bin),
|
||||
ide_ssh::shell::quote(attach_arg),
|
||||
if replace { " --replace" } else { "" },
|
||||
))
|
||||
.await
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start openidea-server: {e}")))?;
|
||||
@@ -725,12 +723,12 @@ pub async fn remote_connect(
|
||||
let bin = crate::remote_wsl::ensure_server(&state, distro, progress.clone()).await?;
|
||||
progress(RemoteStage::Starting, None);
|
||||
let attach_arg = if path.trim().is_empty() { "~" } else { path.trim() };
|
||||
let peer = crate::remote_wsl::spawn(distro, &bin, attach_arg, replace, handler, &tail)?;
|
||||
let peer = crate::remote_wsl::spawn(distro, &bin, attach_arg, handler, &tail)?;
|
||||
(peer, None, distro.clone(), format!("WSL: {distro}"))
|
||||
}
|
||||
RemoteTarget::DevContainer { folder, config } => {
|
||||
let (peer, root, run) =
|
||||
crate::remote_container::connect(&state, folder, config, replace, handler, &tail, &progress).await?;
|
||||
crate::remote_container::connect(&state, folder, config, handler, &tail, &progress).await?;
|
||||
path = root;
|
||||
exec = Some(Arc::new(run));
|
||||
let name = std::path::Path::new(folder)
|
||||
@@ -742,11 +740,6 @@ pub async fn remote_connect(
|
||||
// A server that dies on start-up says why on stderr (`wsl.exe` prints its own errors too).
|
||||
let with_output = |e: IdeError| match tail.text() {
|
||||
t if t.is_empty() => e,
|
||||
// Another build's backend holds the project: the window offers to stop it (#6119).
|
||||
t if t.contains(ide_host::rpc::OTHER_BUILD_BUSY) => IdeError {
|
||||
data: Some(ide_core::error::ErrorData::RemoteBackendBusy),
|
||||
..IdeError::unavailable(ide_host::rpc::OTHER_BUILD_BUSY)
|
||||
},
|
||||
t => IdeError::unavailable(format!("{}: {t}", e.message)),
|
||||
};
|
||||
let info: ServerInfo = peer
|
||||
|
||||
@@ -187,11 +187,10 @@ pub(crate) fn spawn(
|
||||
distro: &str,
|
||||
bin: &str,
|
||||
project_path: &str,
|
||||
replace: bool,
|
||||
handler: Arc<dyn Handler>,
|
||||
tail: &Tail,
|
||||
) -> IdeResult<Peer> {
|
||||
spawn_with(ide_core::wsl::EXE, distro, bin, project_path, replace, handler, tail)
|
||||
spawn_with(ide_core::wsl::EXE, distro, bin, project_path, handler, tail)
|
||||
}
|
||||
|
||||
/// [`spawn`] through `launcher` instead of `wsl.exe` (tests put a stand-in there).
|
||||
@@ -200,15 +199,10 @@ fn spawn_with(
|
||||
distro: &str,
|
||||
bin: &str,
|
||||
project_path: &str,
|
||||
replace: bool,
|
||||
handler: Arc<dyn Handler>,
|
||||
tail: &Tail,
|
||||
) -> IdeResult<Peer> {
|
||||
let mut args: Vec<String> =
|
||||
["-d", checked(distro)?, "--exec", bin, "--attach", project_path].map(str::to_owned).into();
|
||||
if replace {
|
||||
args.push("--replace".to_owned());
|
||||
}
|
||||
let args: Vec<String> = ["-d", checked(distro)?, "--exec", bin, "--attach", project_path].map(str::to_owned).into();
|
||||
let tail = tail.clone();
|
||||
Peer::spawn(launcher, &args, &std::env::temp_dir(), &[], handler, Box::new(move |line| tail.push(line)))
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start wsl.exe: {e}")))
|
||||
@@ -311,8 +305,7 @@ printf 'Content-Length: %s\r\n\r\n%s' "${{#body}}" "$body"
|
||||
std::fs::write(&launcher, script).unwrap();
|
||||
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let tail = Tail::default();
|
||||
let peer =
|
||||
spawn_with(launcher.to_str().unwrap(), distro, bin, project, false, Arc::new(Silent), &tail).unwrap();
|
||||
let peer = spawn_with(launcher.to_str().unwrap(), distro, bin, project, Arc::new(Silent), &tail).unwrap();
|
||||
let reply: String = peer.request("ping", serde_json::Value::Null, None).await.unwrap_or_else(|e| {
|
||||
panic!("{e:?}; launcher said: {}", tail.text());
|
||||
});
|
||||
@@ -321,8 +314,7 @@ printf 'Content-Length: %s\r\n\r\n%s' "${{#body}}" "$body"
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_bad_distro_name_never_starts_the_launcher() {
|
||||
let err =
|
||||
spawn_with("does-not-exist", "-d", "/x", "~", false, Arc::new(Silent), &Tail::default()).err().unwrap();
|
||||
let err = spawn_with("does-not-exist", "-d", "/x", "~", Arc::new(Silent), &Tail::default()).err().unwrap();
|
||||
assert!(err.message.contains("not a valid"), "{}", err.message);
|
||||
}
|
||||
}
|
||||
@@ -188,7 +188,6 @@ debug_jvm_thread_dump trusted project_host bin
|
||||
debug_listen_for_jvm trusted project_host bindings async
|
||||
debug_pause trusted project_host bindings async
|
||||
debug_redefine_classes trusted project_host bindings async
|
||||
debug_replace_breakpoints trusted project_host bindings async
|
||||
debug_resolve_variable trusted project_host bindings async
|
||||
debug_restart_frame trusted project_host bindings async
|
||||
debug_resume trusted project_host bindings async
|
||||
@@ -429,7 +428,6 @@ menu_configure always desktop bin
|
||||
menu_model always desktop bindings sync
|
||||
menu_refresh always desktop bindings sync
|
||||
menu_set_disabled always desktop bindings sync
|
||||
menu_set_remote_recent always desktop bindings sync
|
||||
nav_index_definitions always project_host bindings async
|
||||
nav_inheritance always project_host bindings async
|
||||
nav_python_stubs always project_host bindings async
|
||||
|
||||
+2
-22
@@ -480,8 +480,6 @@ export const commands = {
|
||||
debugPause: (session: DebugSessionId, threadId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_pause", { session, threadId })),
|
||||
/** HotSwap (Reload Changed Classes) in a java-debug session. */
|
||||
debugRedefineClasses: (session: DebugSessionId) => typedError<HotSwapResult, IdeError>(__TAURI_INVOKE("debug_redefine_classes", { session })),
|
||||
/** Replaces all of this window's line breakpoints with `files`. */
|
||||
debugReplaceBreakpoints: (files: { [key in string]: Breakpoint[] }) => typedError<null, IdeError>(__TAURI_INVOKE("debug_replace_breakpoints", { files })),
|
||||
debugResolveVariable: (session: DebugSessionId, variable: Variable_Deserialize) => typedError<Variable_Serialize, IdeError>(__TAURI_INVOKE("debug_resolve_variable", { session, variable })),
|
||||
/** Reset Frame (Drop Frame). */
|
||||
debugRestartFrame: (session: DebugSessionId, frameId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_restart_frame", { session, frameId })),
|
||||
@@ -492,7 +490,6 @@ export const commands = {
|
||||
debugSendInput: (session: DebugSessionId, text: string) => typedError<null, IdeError>(__TAURI_INVOKE("debug_send_input", { session, text })),
|
||||
/** This window's live sessions, including adapter-started child sessions. */
|
||||
debugSessions: () => typedError<SessionInfo[], IdeError>(__TAURI_INVOKE("debug_sessions")),
|
||||
/** This window's breakpoints of `path`. */
|
||||
debugSetBreakpoints: (path: string, breakpoints: Breakpoint[]) => typedError<BreakpointState[], IdeError>(__TAURI_INVOKE("debug_set_breakpoints", { path, breakpoints })),
|
||||
/** Field watchpoints; states aligned with `breakpoints`. */
|
||||
debugSetDataBreakpoints: (breakpoints: DataBreakpoint[]) => typedError<BreakpointState[], IdeError>(__TAURI_INVOKE("debug_set_data_breakpoints", { breakpoints })),
|
||||
@@ -1162,8 +1159,6 @@ export const commands = {
|
||||
* disabled in place (no rebuild).
|
||||
*/
|
||||
menuSetDisabled: (ids: string[]) => __TAURI_INVOKE<void>("menu_set_disabled", { ids }),
|
||||
/** The Remote Development projects of the frontend's recent list, for Open Recent. */
|
||||
menuSetRemoteRecent: (projects: RemoteRecent[]) => __TAURI_INVOKE<void>("menu_set_remote_recent", { projects }),
|
||||
/**
|
||||
* Index definitions named `name` within the roots `from` may navigate into (its own root
|
||||
* plus its configured dependencies).
|
||||
@@ -1519,7 +1514,7 @@ export const commands = {
|
||||
* dev container, whose project folder is the container's own) in this window (installs /
|
||||
* starts the server as needed).
|
||||
*/
|
||||
remoteConnect: (target: RemoteTarget, path: string, replace: boolean, onProgress: Channel<RemoteProgress>) => typedError<RemoteProject_Serialize, IdeError>(__TAURI_INVOKE("remote_connect", { target, path, replace, onProgress })),
|
||||
remoteConnect: (target: RemoteTarget, path: string, onProgress: Channel<RemoteProgress>) => typedError<RemoteProject_Serialize, IdeError>(__TAURI_INVOKE("remote_connect", { target, path, onProgress })),
|
||||
/** The remote session of this window (a settings window: its parent's), if any. */
|
||||
remoteCurrent: () => __TAURI_INVOKE<{
|
||||
target: RemoteTarget,
|
||||
@@ -6857,9 +6852,7 @@ report?: PushReport | null } |
|
||||
* jdtls could not set a module up as a Java project: the errors on its build files and
|
||||
* the builds enclosing it (`path: message`, the path relative to the project), nearest first.
|
||||
*/
|
||||
{ type: "javaBuildProblems"; problems: string[] } |
|
||||
/** A remote backend of another OpenIDEA build still serves the project and refused to retire. */
|
||||
{ type: "remoteBackendBusy" };
|
||||
{ type: "javaBuildProblems"; problems: string[] };
|
||||
|
||||
export type ErrorKind = "notFound" | "alreadyExists" | "permissionDenied" | "invalidInput" |
|
||||
/** The requested state is stale; the UI must use the current snapshot. */
|
||||
@@ -12168,19 +12161,6 @@ export type RemoteProject_Serialize = {
|
||||
project: ProjectInfo_Serialize,
|
||||
};
|
||||
|
||||
/**
|
||||
* A recent Remote Development project (SSH, WSL, Dev Container), kept by the frontend: Open
|
||||
* Recent lists it among the local projects, as Manage Projects does.
|
||||
*/
|
||||
export type RemoteRecent = {
|
||||
/** `ssh://host/path`, `wsl://Ubuntu/path`…: what `file.openRecentProject` gets back. */
|
||||
location: string,
|
||||
name: string,
|
||||
/** Where it lives, as shown after the name (`me@host:/srv/app`). */
|
||||
detail: string,
|
||||
openedAtMs: number | null,
|
||||
};
|
||||
|
||||
export type RemoteSession = RemoteSession_Serialize | RemoteSession_Deserialize;
|
||||
|
||||
export type RemoteSession_Deserialize = {
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Text } from "@codemirror/state";
|
||||
import { semanticRanges } from "../index";
|
||||
|
||||
const doc = Text.of(["std"]);
|
||||
const token = (type: string, modifiers: string[], language = "cpp") =>
|
||||
semanticRanges(
|
||||
doc,
|
||||
{ tokenTypes: [type], tokenModifiers: modifiers, data: [0, 0, 3, 0, (1 << modifiers.length) - 1] },
|
||||
false,
|
||||
language,
|
||||
)[0]?.className.split(" ");
|
||||
|
||||
describe("C++ namespace semantic tokens", () => {
|
||||
it.each(["cpp", "CPP"])("keeps standard-library namespaces in the namespace colour (%s)", (language) => {
|
||||
expect(token("namespace", ["defaultLibrary", "globalScope"], language)).toEqual(["cm-sem-namespace"]);
|
||||
expect(token("namespace", ["defaultLibrary"], language)).toEqual(token("namespace", [], language));
|
||||
});
|
||||
|
||||
it("preserves namespace declaration and deprecation styles", () => {
|
||||
expect(token("namespace", ["defaultLibrary", "declaration", "deprecated"])).toEqual([
|
||||
"cm-sem-namespace",
|
||||
"cm-sem-declaration",
|
||||
"cm-sem-deprecated",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(["class", "function", "variable"])("preserves builtin colouring for %s tokens", (type) => {
|
||||
expect(token(type, ["defaultLibrary"])).toContain("cm-sem-builtin");
|
||||
});
|
||||
|
||||
it("leaves other languages' namespace colouring unchanged", () => {
|
||||
expect(token("namespace", ["defaultLibrary"], "rust")).toEqual(["cm-sem-namespace", "cm-sem-builtin"]);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +0,0 @@
|
||||
import { registerLanguageSemantics } from "../languages";
|
||||
|
||||
registerLanguageSemantics("cpp", {
|
||||
tokenClasses({ type, classes }) {
|
||||
// clangd marks std and other library namespaces as defaultLibrary; keep their namespace colour.
|
||||
if (type !== "namespace") return;
|
||||
const builtin = classes.indexOf("cm-sem-builtin");
|
||||
if (builtin >= 0) classes.splice(builtin, 1);
|
||||
},
|
||||
});
|
||||
@@ -33,7 +33,6 @@ import "./php";
|
||||
import "./go";
|
||||
import "./java";
|
||||
import "./javascript";
|
||||
import "./cpp";
|
||||
|
||||
const semanticBackoff = featureBackoff();
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ const windowGroupJoin = vi.fn();
|
||||
const windowTakeLaunch = vi.fn();
|
||||
const windowCompleteLaunch = vi.fn();
|
||||
const wslResolve = vi.fn();
|
||||
const windowOpenRemote = vi.fn();
|
||||
const cancelClose = vi.fn();
|
||||
const notify = vi.fn();
|
||||
const listen = vi.fn();
|
||||
@@ -52,7 +51,6 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
windowTakeLaunch: () => windowTakeLaunch(),
|
||||
windowCompleteLaunch: () => windowCompleteLaunch(),
|
||||
wslResolve: (p: string) => wslResolve(p),
|
||||
windowOpenRemote: (...a: unknown[]) => windowOpenRemote(...a),
|
||||
lightEditOpen: (p: string) => lightEditOpen(p),
|
||||
fsReadDir: (p: string) => fsReadDir(p),
|
||||
},
|
||||
@@ -268,14 +266,6 @@ describe("a recent project opened with a modifier key", () => {
|
||||
await action.run({ arg: "/p/b" } as never);
|
||||
expect(windowOpenProject).toHaveBeenLastCalledWith("/p/b", false, []);
|
||||
});
|
||||
|
||||
it("opens a Remote Development project from Open Recent on its host (#6124)", async () => {
|
||||
windowOpenRemote.mockResolvedValue(ok({ kind: "focused" }));
|
||||
const action = windowActions().find((a) => a.id === "file.openRecentProject")!;
|
||||
await action.run({ arg: "wsl://Ubuntu/home/me/api" } as never);
|
||||
expect(windowOpenRemote).toHaveBeenCalledWith({ kind: "wsl", distro: "Ubuntu" }, "/home/me/api", false);
|
||||
expect(windowOpenProject).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("loose files (LightEdit)", () => {
|
||||
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
useKeymap,
|
||||
} from "@/platform/keymap";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { syncRemoteRecentMenu } from "@/platform/remote";
|
||||
import { useContributions, useMenuSlotItems, useStandaloneEditor } from "@/workbench/contributions";
|
||||
import { useDistractionFree } from "@/workbench/distractionFree";
|
||||
import { javaFileNameOf, menuLabelParams } from "@/workbench/menuLabels";
|
||||
@@ -259,7 +258,6 @@ export function installMenuBridge(): () => void {
|
||||
.catch(() => {});
|
||||
|
||||
push();
|
||||
syncRemoteRecentMenu();
|
||||
const onFocus = () => {
|
||||
push();
|
||||
pushEnablement(true);
|
||||
|
||||
@@ -22,10 +22,10 @@ import {
|
||||
} from "@/platform/project";
|
||||
import { confirmProjectTrust } from "@/platform/projectTrust";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { connectRemote, isRemoteWindow, parseRemoteLocation } from "@/platform/remote";
|
||||
import { connectRemote, isRemoteWindow } from "@/platform/remote";
|
||||
import { holdSplash } from "@/platform/splash";
|
||||
import { editorService, maybeEditorService, notifications } from "@/workbench/contributions";
|
||||
import { chooseProjectWindow, openRemoteProject, type ProjectWindowOverride } from "@/workbench/projectWindow";
|
||||
import { chooseProjectWindow, type ProjectWindowOverride } from "@/workbench/projectWindow";
|
||||
import { openTabColorPicker } from "@/workbench/TabColorPicker";
|
||||
import { cycleWindowTab, useWindowGroup } from "@/platform/windowGroups";
|
||||
import { editorSwitching } from "@/editor/api";
|
||||
@@ -606,15 +606,7 @@ export function windowActions(): Action[] {
|
||||
hidden: true,
|
||||
run: async (c) => {
|
||||
const recent = recentProjectArg(c.arg);
|
||||
if (!recent) return;
|
||||
// Open Recent lists Remote Development projects by their location (`ssh://host/path`).
|
||||
const remote = parseRemoteLocation(recent.path);
|
||||
if (!remote) return openProjectWithPolicy(recent.path, [], recent.window);
|
||||
try {
|
||||
await openRemoteProject(remote.target, remote.path, undefined, recent.window);
|
||||
} catch (e) {
|
||||
openFailed(remote.path, e);
|
||||
}
|
||||
if (recent) await openProjectWithPolicy(recent.path, [], recent.window);
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -82,25 +82,6 @@ describe("execution point state", () => {
|
||||
expect(useExecutionPoint.getState()).toMatchObject({ path, line: 9 });
|
||||
});
|
||||
|
||||
it("keeps a failed stack trace's reason for the frames list, and a retry loads the frames", async () => {
|
||||
const error = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
ipc.debugStackTrace.mockResolvedValueOnce({
|
||||
status: "error",
|
||||
error: { kind: "timedOut", message: "stackTrace timed out after 30s" },
|
||||
} as never);
|
||||
stopped();
|
||||
await settle();
|
||||
expect(useDebug.getState().sessions[1]).toMatchObject({
|
||||
frames: [],
|
||||
framesError: "stackTrace timed out after 30s",
|
||||
});
|
||||
expect(error).toHaveBeenCalled();
|
||||
await selectThread(1, 5);
|
||||
expect(useDebug.getState().sessions[1]).toMatchObject({ framesError: null, selectedFrame: 100 });
|
||||
expect(useExecutionPoint.getState()).toMatchObject({ path, line: 6840 });
|
||||
error.mockRestore();
|
||||
});
|
||||
|
||||
it("counts stops per session", async () => {
|
||||
adoptSession(2, { adapter: "java-debug" });
|
||||
expect(useDebug.getState().sessions[1]!.stops).toBe(0);
|
||||
|
||||
@@ -266,37 +266,6 @@ describe("HotSwap", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("points a refused structural change to Enhanced class redefinition when the configuration has it off", async () => {
|
||||
const refused = "Failed to redefine classes: add method not implemented";
|
||||
const hint = "turn on Enhanced class redefinition in the run configuration";
|
||||
expect(hotSwapMessage(0, [refused], false, true).body).toContain(hint);
|
||||
expect(hotSwapMessage(0, [refused], false, false).body).toBe(refused);
|
||||
expect(hotSwapMessage(0, ["boom"], false, true).body).toBe("boom");
|
||||
|
||||
const withConfig = (kind: string, params: Record<string, string>) => ({
|
||||
...session(1, true),
|
||||
runConfig: { id: kind, kind, params } as unknown as NonNullable<DebugSession["runConfig"]>,
|
||||
});
|
||||
ipc.debugRedefineClasses.mockImplementation(() => ipc.ok({ changedClasses: [], errorMessage: refused }));
|
||||
for (const [s, shown] of [
|
||||
[withConfig("application", {}), true],
|
||||
[withConfig("spring-boot", {}), true],
|
||||
[withConfig("application", { enhancedClassRedefinition: "true" }), false],
|
||||
[withConfig("tomcat", {}), false],
|
||||
[session(1, true), false],
|
||||
] as const) {
|
||||
useDebug.setState({ sessions: { 1: s } });
|
||||
// oxlint-disable-next-line no-await-in-loop -- one reload per session shape; each assertion reads its notification
|
||||
await reloadChangedClasses(false);
|
||||
expect(notes.at(-1)).toMatchObject({ level: "error", title: "Hot Swap failed" });
|
||||
expect(String(notes.at(-1)!.body).includes(hint)).toBe(shown);
|
||||
}
|
||||
|
||||
useDebug.setState({ sessions: { 1: withConfig("application", {}) } });
|
||||
onHotCodeReplace(1 as DebugSessionId, { kind: "hotCodeReplace", changeType: "ERROR", message: refused });
|
||||
expect(notes.at(-1)).toMatchObject({ title: "Hot Swap", body: expect.stringContaining(hint) });
|
||||
});
|
||||
|
||||
function pausedFrames(names: string[], restartFrame = true): DebugSession {
|
||||
return {
|
||||
...session(1, true),
|
||||
|
||||
@@ -157,14 +157,6 @@ describe("Java debugging (java-debug through jdtls)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("asks the host for enhanced class redefinition when the configuration turns it on", async () => {
|
||||
const on = { ...app, params: { enhancedClassRedefinition: "true" } };
|
||||
expect(JSON.parse((await javaLaunchConfig(on, "/p")).extraJson!).enhancedClassRedefinition).toBe(true);
|
||||
expect(JSON.parse((await javaLaunchConfig(app, "/p")).extraJson!)).not.toHaveProperty("enhancedClassRedefinition");
|
||||
const kotlin = { ...on, debugAdapter: "kotlin-debug-adapter" };
|
||||
expect(JSON.parse((await javaLaunchConfig(kotlin, "/p")).extraJson!).enhancedClassRedefinition).toBe(true);
|
||||
});
|
||||
|
||||
it("lets java-debug shorten a classpath too long for the OS, as Run does", async () => {
|
||||
for (const how of ["jarmanifest", "argfile"]) {
|
||||
shortenCommandLine = how;
|
||||
|
||||
@@ -25,7 +25,6 @@ import {
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
debugSetBreakpoints: vi.fn(),
|
||||
debugReplaceBreakpoints: vi.fn(async () => ({ status: "ok", data: null })),
|
||||
debugStart: vi.fn(async () => ({ status: "ok", data: 42 })),
|
||||
debugStop: vi.fn(async () => ({ status: "ok", data: null })),
|
||||
debugCapabilities: vi.fn(async () => ({ status: "ok", data: {} })),
|
||||
@@ -170,24 +169,6 @@ it("drains an in-flight update and sends pending removals before startup", async
|
||||
expect(ipc.debugStart).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("hands the window's whole list to the backend before startup, even after a failed removal (#6116)", async () => {
|
||||
ipc.debugSetBreakpoints.mockResolvedValueOnce({ status: "ok", data: [] }).mockRejectedValueOnce(new Error("lost"));
|
||||
addBreakpoint("/p/Main.java", 4);
|
||||
await vi.advanceTimersByTimeAsync(120);
|
||||
removeAllBreakpoints();
|
||||
await vi.advanceTimersByTimeAsync(120);
|
||||
addBreakpoint("/p/Other.java", 7);
|
||||
ipc.debugSetBreakpoints.mockResolvedValue({ status: "ok", data: [] });
|
||||
ipc.debugReplaceBreakpoints.mockClear();
|
||||
await startSession(config("launch"));
|
||||
expect(ipc.debugReplaceBreakpoints).toHaveBeenCalledExactlyOnceWith({
|
||||
"/p/Other.java": [expect.objectContaining({ line: 7, enabled: true })],
|
||||
});
|
||||
expect(ipc.debugReplaceBreakpoints.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
ipc.debugStart.mock.invocationCallOrder[0]!,
|
||||
);
|
||||
});
|
||||
|
||||
it("flushes persisted breakpoints immediately after project loading", async () => {
|
||||
ipc.debugSetBreakpoints.mockResolvedValue({ status: "ok", data: [] });
|
||||
localStorage.setItem(
|
||||
|
||||
@@ -87,8 +87,6 @@ export function loadBreakpoints(root: string | null) {
|
||||
}
|
||||
const previous = Object.keys(useBreakpoints.getState().byFile);
|
||||
useBreakpoints.setState({ root, byFile, muted, status: {} });
|
||||
// The backend may still hold files this window no longer lists (a reloaded window).
|
||||
void replaceBreakpoints().catch((e) => console.warn("debugReplaceBreakpoints failed", e));
|
||||
for (const path of new Set([...previous, ...Object.keys(byFile)])) scheduleSync(path);
|
||||
}
|
||||
|
||||
@@ -131,17 +129,6 @@ async function drainBreakpoints() {
|
||||
await Promise.all([...paths].map((path) => syncFile(path)));
|
||||
paths = new Set([...timers.keys(), ...inFlight.keys()]);
|
||||
}
|
||||
// The new session gets exactly the files listed here, even if a removal never reached the
|
||||
// backend (#6116). Failing that, the session still starts with what the backend has.
|
||||
await replaceBreakpoints().catch((e) => console.warn("debugReplaceBreakpoints failed", e));
|
||||
}
|
||||
|
||||
/** Makes this window's whole list the backend's: files it no longer lists are cleared there. */
|
||||
async function replaceBreakpoints() {
|
||||
if (!isTauri() || useProject.getState().project?.trusted === false) return;
|
||||
const { byFile, muted } = useBreakpoints.getState();
|
||||
const files = Object.fromEntries(Object.entries(byFile).map(([path, list]) => [path, toBackend(list, muted, path)]));
|
||||
await call(commands.debugReplaceBreakpoints(files));
|
||||
}
|
||||
|
||||
export function syncFile(path: string): Promise<void> {
|
||||
|
||||
@@ -59,40 +59,15 @@ const classesText = (n: number) => (n === 1 ? tx`${n} class` : tx`${n} classes`)
|
||||
|
||||
// java-debug reports this after redefineClasses succeeds, with no changedClasses count.
|
||||
const obsoleteMethods = (message: string) => message.trim() === "JVM contains obsolete methods";
|
||||
// JDI's refusals of a structural change: "add method not implemented", "schema change not implemented", …
|
||||
const structuralChange = (message: string) => /\bnot implemented\b/i.test(message);
|
||||
|
||||
/** Application and Spring Boot configurations offer Enhanced class redefinition (JetBrains Runtime's DCEVM). */
|
||||
const ENHANCEABLE_KINDS = new Set(["application", "spring-boot"]);
|
||||
|
||||
/** Whether the session's configuration could turn on Enhanced class redefinition but has not. */
|
||||
export function canEnhanceRedefinition(s: DebugSession): boolean {
|
||||
const rc = s.runConfig;
|
||||
return !!rc && ENHANCEABLE_KINDS.has(rc.kind) && rc.params?.enhancedClassRedefinition !== "true";
|
||||
}
|
||||
|
||||
/** The failure text, plus how to allow structural changes when JDI refused one and the configuration can. */
|
||||
function failureBody(errors: string[], enhanceable: boolean): string {
|
||||
const body = errors.join("\n");
|
||||
if (!enhanceable || !errors.some(structuralChange)) return body;
|
||||
return (
|
||||
body +
|
||||
"\n\n" +
|
||||
tx(
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/** Message for the reload result (IDEA wording). */
|
||||
export function hotSwapMessage(
|
||||
changed: number,
|
||||
errors: string[],
|
||||
bottomFrame = false,
|
||||
enhanceable = false,
|
||||
): { level: "info" | "warning" | "error"; title: string; body?: string } {
|
||||
if (errors.some((e) => !obsoleteMethods(e)))
|
||||
return { level: "error", title: "Hot Swap failed", body: failureBody(errors, enhanceable) };
|
||||
return { level: "error", title: "Hot Swap failed", body: errors.join("\n") };
|
||||
if (errors.length)
|
||||
return {
|
||||
level: "warning",
|
||||
@@ -251,7 +226,6 @@ export async function reloadChangedClasses(build = true, configId?: string, allo
|
||||
changed.size,
|
||||
errors,
|
||||
affected.some((s) => s.status === "paused" && s.frames.length === 1),
|
||||
sessions.some(canEnhanceRedefinition),
|
||||
);
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
@@ -334,7 +308,7 @@ export function onHotCodeReplace(session: DebugSessionId, event: Extract<DebugEv
|
||||
level: event.changeType === "ERROR" ? "error" : "warning",
|
||||
key: KEY,
|
||||
title: "Hot Swap",
|
||||
body: failureBody([event.message], canEnhanceRedefinition(useDebug.getState().sessions[session]!)),
|
||||
body: event.message,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -174,8 +174,6 @@ export async function javaLaunchConfig(
|
||||
preparation?.report?.(`${joinJavaArgs([resolved.command, ...resolved.args])}\n`);
|
||||
const agentNote = await remoteJavaAgentNote(rc);
|
||||
if (agentNote) preparation?.report?.(agentNote);
|
||||
// The host adds JetBrains Runtime's flag for it, or says in the console why the session runs without.
|
||||
const enhanced = rc.params?.enhancedClassRedefinition === "true" ? { enhancedClassRedefinition: true } : {};
|
||||
if (kotlin) {
|
||||
return {
|
||||
name: rc.name,
|
||||
@@ -193,7 +191,6 @@ export async function javaLaunchConfig(
|
||||
javaExec: resolved.command,
|
||||
vmArguments: [...consoleVmArgs(rc), ...parsed.vmArgs],
|
||||
programArgs: parsed.programArgs,
|
||||
...enhanced,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -215,7 +212,6 @@ export async function javaLaunchConfig(
|
||||
javaExec: resolved.command === "java" ? undefined : resolved.command,
|
||||
vmArgs: [...consoleVmArgs(rc), ...parsed.vmArgs],
|
||||
args: parsed.programArgs,
|
||||
...enhanced,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -247,7 +243,6 @@ export async function javaLaunchConfig(
|
||||
shortenCommandLine: info.shortenCommandLine ?? "none",
|
||||
console: "internalConsole",
|
||||
stopOnEntry: false,
|
||||
...enhanced,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
* (threads, frames, locals) after each stop.
|
||||
*/
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { logError } from "@/platform/errorLog";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { executeAction, getAction } from "@/platform/actions";
|
||||
import { create } from "zustand";
|
||||
@@ -97,8 +96,6 @@ export interface DebugSession {
|
||||
threads: ThreadInfo[];
|
||||
selectedThread: number | null;
|
||||
frames: StackFrame[];
|
||||
/** Why the selected thread's frames could not be loaded (Threads & Variables offers a retry). */
|
||||
framesError?: string | null;
|
||||
selectedFrame: number | null;
|
||||
/** Breakpoint hits in this session. */
|
||||
hits: number;
|
||||
@@ -1299,19 +1296,16 @@ export function selectFrame(id: DebugSessionId, frameId: number, reveal = true)
|
||||
|
||||
/** `newStop`: false when returning to an earlier stop, whose breakpoint hit was handled when it happened. */
|
||||
async function loadFrames(id: DebugSessionId, threadId: number, reveal: boolean, newStop = true) {
|
||||
if (useDebug.getState().sessions[id]?.framesError) patch(id, { framesError: null });
|
||||
const before = useDebug.getState().sessions[id];
|
||||
let frames: StackFrame[] = [];
|
||||
let framesError: string | null = null;
|
||||
try {
|
||||
frames = await call(commands.debugStackTrace(id, threadId));
|
||||
} catch (e) {
|
||||
logError("Debugger stack trace", e);
|
||||
framesError = e instanceof Error ? e.message : String(e);
|
||||
console.warn("stackTrace failed", e);
|
||||
}
|
||||
const s = useDebug.getState().sessions[id];
|
||||
if (!s || s.status !== "paused" || s.selectedThread !== threadId || s.frames !== before?.frames) return;
|
||||
patch(id, { frames, framesError });
|
||||
patch(id, { frames });
|
||||
const top = topFrame(frames);
|
||||
if (newStop && top?.path && (s.stopReason === "breakpoint" || s.stopReason === "function breakpoint")) {
|
||||
void logSuspendingHit(id, top);
|
||||
|
||||
@@ -200,14 +200,6 @@
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
|
||||
.framesError {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-1-5);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* variables */
|
||||
.variables {
|
||||
height: 100%;
|
||||
|
||||
@@ -10,7 +10,6 @@ import { formatBinding, hostBinding } from "@/platform/keymap";
|
||||
import { basename, useProject } from "@/platform/project";
|
||||
import { call, commands, isTauri, type Scope, type Variable } from "@/platform/ipc";
|
||||
import {
|
||||
Button,
|
||||
EmptyState,
|
||||
Icon,
|
||||
IconButton,
|
||||
@@ -477,14 +476,6 @@ function FramesPane({ session }: { session: DebugSession }) {
|
||||
</div>
|
||||
)}
|
||||
{stopNote(session) && <div className={styles.note}>{stopNote(session)}</div>}
|
||||
{paused && session.framesError && session.selectedThread != null && (
|
||||
<div className={clsx(styles.note, styles.framesError)} role="alert">
|
||||
<span>{tx`Could not load the frames: ${session.framesError}`}</span>
|
||||
<Button size="small" onClick={() => void selectThread(session.id, session.selectedThread!)}>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{items.map((item) =>
|
||||
item.kind === "hidden" ? (
|
||||
<button
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { convertIcls } from "../intellijTheme";
|
||||
|
||||
const opt = (name: string, value: string) =>
|
||||
`<option name="${name}"><value><option name="FOREGROUND" value="${value}"/></value></option>`;
|
||||
const scheme = (parent: string, ...options: string[]) =>
|
||||
`<scheme name="t" version="142" parent_scheme="${parent}"><attributes>${options.join("")}</attributes></scheme>`;
|
||||
|
||||
describe("annotation colour of a theme plugin's scheme (#6108)", () => {
|
||||
it("keeps Darcula's annotation colour when the file only changes DEFAULT_METADATA", () => {
|
||||
const { tokens } = convertIcls(scheme("Darcula", opt("DEFAULT_METADATA", "1d8711")));
|
||||
expect(tokens["--syn-annotation"]).toBe("#bbb529");
|
||||
expect(tokens["--syn-decorator"]).toBe("#1d8711");
|
||||
});
|
||||
|
||||
it("takes the file's annotation key for annotations", () => {
|
||||
const { tokens } = convertIcls(
|
||||
scheme("Darcula", opt("DEFAULT_METADATA", "1d8711"), opt("ANNOTATION_NAME_ATTRIBUTES", "9e880d")),
|
||||
);
|
||||
expect(tokens["--syn-annotation"]).toBe("#9e880d");
|
||||
});
|
||||
|
||||
it("leaves a light parent's annotation colour to the base theme", () => {
|
||||
const { tokens } = convertIcls(scheme("Default", opt("DEFAULT_METADATA", "1d8711")));
|
||||
expect(tokens["--syn-annotation"]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { ContextMenuHost, hideContextMenu } from "@/ui";
|
||||
import type { View, ViewEvent } from "@/bindings";
|
||||
import { executeAction, registerAction } from "@/platform/actions";
|
||||
import { registerAction } from "@/platform/actions";
|
||||
import { bindingsFor, effectiveBindings, registerExtensionBindings, useKeymap } from "@/platform/keymap";
|
||||
import { createMemoryPluginsBackend, setPluginsBackend, type PluginsBackend } from "../backend";
|
||||
import { commandArgs, defineBuiltinUiPoints } from "../points";
|
||||
@@ -11,7 +11,7 @@ import { clearUiContributions, syncUiContributions } from "../projection";
|
||||
import { pluginMenuItems, pluginViewItemMenuItems, withPluginSetting } from "../uiPoints";
|
||||
import { matchesPattern } from "../views/customEditor";
|
||||
import { FRAME_CSP, FRAME_TAG, frameDocument, frameTheme, type FrameTheme } from "../views/frame";
|
||||
import { focusedViewItem, PluginView, treeNodes, wantedViewport } from "../views/PluginView";
|
||||
import { PluginView, treeNodes, wantedViewport } from "../views/PluginView";
|
||||
import { bumpView } from "../views/viewStore";
|
||||
|
||||
let undefinePoints: () => void = () => {};
|
||||
@@ -341,70 +341,6 @@ describe("PluginView", () => {
|
||||
await waitFor(() => expect(events).toContainEqual({ kind: "button", id: "refresh" }));
|
||||
});
|
||||
|
||||
it("gives a shortcut-run command the selected item of the plugin's focused view", async () => {
|
||||
const item = (key: string, label: string) => ({
|
||||
key,
|
||||
parent: null,
|
||||
label,
|
||||
icon: null,
|
||||
detail: null,
|
||||
expandable: false,
|
||||
expanded: false,
|
||||
});
|
||||
const tree: View = {
|
||||
toolbar: [],
|
||||
body: { kind: "tree", value: [item("task:build", "build"), item("task:test", "test")] },
|
||||
status: null,
|
||||
};
|
||||
const backend = backendWith(() => tree);
|
||||
const runCommand = vi.fn(async () => null);
|
||||
setPluginsBackend({ ...backend, runCommand });
|
||||
syncUiContributions(
|
||||
[
|
||||
{ pluginId: "jobs", point: "commands", key: "open", decl: { id: "open", title: "Open Source" } },
|
||||
{ pluginId: "jobs", point: "commands", key: "sync", decl: { id: "sync", title: "Sync" } },
|
||||
{
|
||||
pluginId: "jobs",
|
||||
point: "menus",
|
||||
key: "viewItem.context/tasks/open",
|
||||
decl: { menu: "viewItem.context", view: "tasks", command: "open", when: "viewItemKind == task" },
|
||||
},
|
||||
],
|
||||
[
|
||||
{ id: "jobs", name: "Jobs", status: "active", enabled: true } as unknown as Parameters<
|
||||
typeof syncUiContributions
|
||||
>[1][number],
|
||||
],
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<PluginView
|
||||
pluginId="jobs"
|
||||
view="tasks"
|
||||
label="Tasks"
|
||||
itemMenu={(key) => pluginViewItemMenuItems("jobs", "tasks", key)}
|
||||
/>,
|
||||
);
|
||||
expect(focusedViewItem("jobs", "plugin.jobs.open")).toBeNull();
|
||||
await user.click(await screen.findByText("test"));
|
||||
await waitFor(() => expect(focusedViewItem("jobs", "plugin.jobs.open")).toBe("task:test"));
|
||||
expect(focusedViewItem("other", "plugin.other.open")).toBeNull();
|
||||
// Only a command the item's menu offers gets the item.
|
||||
expect(focusedViewItem("jobs", "plugin.jobs.sync")).toBeNull();
|
||||
await executeAction("plugin.jobs.sync");
|
||||
expect(runCommand).toHaveBeenLastCalledWith("jobs", "sync", null, null, []);
|
||||
await executeAction("plugin.jobs.open");
|
||||
expect(runCommand).toHaveBeenLastCalledWith("jobs", "open", "task:test", null, []);
|
||||
// A menu's own argument wins over the focused view.
|
||||
await executeAction("plugin.jobs.open", "task:build");
|
||||
expect(runCommand).toHaveBeenLastCalledWith("jobs", "open", "task:build", null, []);
|
||||
// Focus elsewhere: nothing selected for the command.
|
||||
(document.activeElement as HTMLElement | null)?.blur();
|
||||
expect(focusedViewItem("jobs", "plugin.jobs.open")).toBeNull();
|
||||
await executeAction("plugin.jobs.open");
|
||||
expect(runCommand).toHaveBeenLastCalledWith("jobs", "open", null, null, []);
|
||||
});
|
||||
|
||||
it("opens the item menu on right-click", async () => {
|
||||
const tree: View = {
|
||||
toolbar: [],
|
||||
|
||||
@@ -18,7 +18,6 @@ import { SecretsDetails, type SecretDecl } from "./secrets";
|
||||
import { pluginSettingsPageId } from "./settings";
|
||||
import { pluginsBackend } from "./backend";
|
||||
import { isLive, runPluginCommand, usePlugins } from "./store";
|
||||
import { focusedViewItem } from "./views/PluginView";
|
||||
import styles from "./PluginsPage.module.css";
|
||||
|
||||
/** Unpacks an action argument: a bare path, or a menu's `{ path, paths }`. */
|
||||
@@ -245,8 +244,7 @@ export function defineCoreUiPoints(): () => void {
|
||||
keywords: ["plugin", plugin.name, pluginId],
|
||||
description: tx`From plugin ${plugin.name}`,
|
||||
run: async ({ arg }: { arg?: unknown }) => {
|
||||
// A shortcut passes nothing: the plugin's focused view supplies its selected item.
|
||||
const [path, paths] = commandArgs(arg ?? focusedViewItem(pluginId, action.id));
|
||||
const [path, paths] = commandArgs(arg);
|
||||
await runPluginCommand(pluginId, decl.id, path, paths);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -163,9 +163,10 @@ export const ICLS_ATTRIBUTES: Record<string, Array<[Part, string]>> = {
|
||||
DEFAULT_PARAMETER: [["FOREGROUND", "--syn-param"]],
|
||||
DEFAULT_GLOBAL_VARIABLE: [["FOREGROUND", "--syn-global"]],
|
||||
DEFAULT_PREDEFINED_SYMBOL: [["FOREGROUND", "--syn-builtin"]],
|
||||
// Java annotations take the scheme's (or its parent's) annotation key, not DEFAULT_METADATA.
|
||||
ANNOTATION_NAME_ATTRIBUTES: [["FOREGROUND", "--syn-annotation"]],
|
||||
DEFAULT_METADATA: [["FOREGROUND", "--syn-decorator"]],
|
||||
DEFAULT_METADATA: [
|
||||
["FOREGROUND", "--syn-annotation"],
|
||||
["FOREGROUND", "--syn-decorator"],
|
||||
],
|
||||
DEFAULT_OPERATION_SIGN: [["FOREGROUND", "--syn-punct"]],
|
||||
DEFAULT_VALID_STRING_ESCAPE: [["FOREGROUND", "--syn-escape"]],
|
||||
DEFAULT_TAG: [["FOREGROUND", "--syn-tag"]],
|
||||
|
||||
@@ -62,34 +62,6 @@ export interface PluginViewProps {
|
||||
const OVERSCAN = 50;
|
||||
const ROW_HEIGHT = 24;
|
||||
|
||||
/** Each rendered view root → its item menu, read when a command runs from a shortcut. */
|
||||
const viewMenus = new WeakMap<Element, (key: string) => MenuItem[]>();
|
||||
|
||||
const offers = (items: MenuItem[], action: string): boolean =>
|
||||
items.some((i) =>
|
||||
i.kind === "action"
|
||||
? i.action === action
|
||||
: (i.kind ?? "item") === "item" && offers(("submenu" in i && i.submenu) || [], action),
|
||||
);
|
||||
|
||||
/**
|
||||
* The argument a plugin command run without one (a shortcut, Find Action) gets from the plugin's
|
||||
* view that has the keyboard focus: the selected item's key, when that item's context menu offers
|
||||
* the command — the same argument as from the menu. Null when the focus is elsewhere, in another
|
||||
* plugin's view, nothing is selected, or the menu doesn't offer the command there.
|
||||
*/
|
||||
export function focusedViewItem(
|
||||
pluginId: string,
|
||||
action: string,
|
||||
focused: Element | null = document.activeElement,
|
||||
): string | null {
|
||||
const view = focused?.closest<HTMLElement>("[data-plugin-view]");
|
||||
const key = view?.dataset.selectedKey;
|
||||
if (!view || view.dataset.pluginView !== pluginId || key === undefined) return null;
|
||||
const menu = viewMenus.get(view);
|
||||
return menu && offers(menu(key), action) ? key : null;
|
||||
}
|
||||
|
||||
/** Plugin text is shown as written: the plugin translates it through its own catalog. */
|
||||
export function PluginView(props: PluginViewProps) {
|
||||
const location = useViewLocation();
|
||||
@@ -182,19 +154,8 @@ function PluginViewContent({
|
||||
</div>
|
||||
);
|
||||
|
||||
// The item a keyboard-invoked command of this plugin gets, as from the item's context menu
|
||||
// (`focusedViewItem`); only a key the view still shows.
|
||||
const currentKey = selection && items?.some((i) => i.key === selection.key) ? selection.key : undefined;
|
||||
return (
|
||||
<div
|
||||
ref={(el) => {
|
||||
if (el && itemMenu) viewMenus.set(el, itemMenu);
|
||||
}}
|
||||
className={styles.view}
|
||||
aria-label={label}
|
||||
data-plugin-view={pluginId}
|
||||
data-selected-key={currentKey}
|
||||
>
|
||||
<div className={styles.view} aria-label={label}>
|
||||
{content.toolbar.length > 0 && (
|
||||
<div className={styles.toolbar} role="toolbar">
|
||||
{content.toolbar.map((b) =>
|
||||
|
||||
@@ -20,16 +20,8 @@ export function packageKindAt(
|
||||
): PackageKind | null {
|
||||
if (rootFor(roots, rel)?.kind === "excluded") return null;
|
||||
if (isJvmSourcePackage(rel, roots)) return "jvm";
|
||||
// A root `pyproject.toml` must not claim `frontend/src`, a root that
|
||||
// `frontend/package.json` detected, unless a deeper Python module holds the folder.
|
||||
let python = -1;
|
||||
let other = -1;
|
||||
for (const r of [...roots, ...detected]) {
|
||||
if (!r.detectedFrom) continue;
|
||||
if (PY_BUILD.test(r.detectedFrom)) {
|
||||
const dir = moduleDir(r.detectedFrom);
|
||||
if (within(rel, dir)) python = Math.max(python, dir.length);
|
||||
} else if (within(rel, r.path)) other = Math.max(other, r.path.length);
|
||||
}
|
||||
return python >= 0 && python >= other ? "python" : null;
|
||||
const python = [...roots, ...detected].some(
|
||||
(r) => r.detectedFrom && PY_BUILD.test(r.detectedFrom) && within(rel, moduleDir(r.detectedFrom)),
|
||||
);
|
||||
return python ? "python" : null;
|
||||
}
|
||||
@@ -72,25 +72,6 @@ describe("New › Package", () => {
|
||||
expect(packageKindAt("build/classes", synced)).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps a nested non-Python module out of a root-level Python project", () => {
|
||||
// The roots detection reports for a root `pyproject.toml` next to `frontend/package.json`.
|
||||
const mixed = [
|
||||
root("src", "source", "pyproject.toml"),
|
||||
root("frontend/src", "source", "frontend/package.json"),
|
||||
root("frontend/node_modules", "excluded", "frontend/package.json"),
|
||||
];
|
||||
expect(packageKindAt("frontend/src/components", mixed)).toBeNull();
|
||||
expect(packageKindAt("src/app", mixed)).toBe("python");
|
||||
expect(packageKindAt("scripts", mixed)).toBe("python");
|
||||
});
|
||||
|
||||
it("keeps Python packages next to a nested package.json outside its roots", () => {
|
||||
// A Django app folder with its own `package.json` for front-end tooling.
|
||||
const django = [root("", "source", "pyproject.toml"), root("web/node_modules", "excluded", "web/package.json")];
|
||||
expect(packageKindAt("web/blog", django)).toBe("python");
|
||||
expect(packageKindAt("web", django)).toBe("python");
|
||||
});
|
||||
|
||||
it("validates dotted package names", () => {
|
||||
expect(packageSegments("com.acme.util", "jvm")).toEqual({ segments: ["com", "acme", "util"], error: null });
|
||||
expect(packageSegments("com..x", "jvm").error).toMatch(/Not a valid package name/);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* to it (platform/remote.ts).
|
||||
*/
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { disconnectRemote, provideBackendBusyPrompt, stopRemoteBackend, useRemote } from "@/platform/remote";
|
||||
import { disconnectRemote, stopRemoteBackend, useRemote } from "@/platform/remote";
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { maybeEditorService, registerOverlay, registerStatusItem, registerToolWindow } from "@/workbench/contributions";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
@@ -57,16 +57,6 @@ function trackPortsWindow(): () => void {
|
||||
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
provideBackendBusyPrompt(() =>
|
||||
confirm({
|
||||
title: tx("Stop Remote Backend"),
|
||||
message: tx(
|
||||
"The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.",
|
||||
),
|
||||
ok: tx("Stop Backend and Open"),
|
||||
icon: "warning",
|
||||
}),
|
||||
),
|
||||
trackPortsWindow(),
|
||||
installReconnect(),
|
||||
installDirenvNotifications(),
|
||||
|
||||
@@ -146,16 +146,6 @@ describe("Application / Spring Boot command line", () => {
|
||||
expect(parsed.programArgs).toEqual(["--server.port=8081", "two words"]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["application", applicationType],
|
||||
["spring-boot", springBootType],
|
||||
] as const)("%s offers Enhanced class redefinition for Debug without changing the Run command", (_, type) => {
|
||||
expect(type.fields.find((f) => f.key === "enhancedClassRedefinition")).toMatchObject({ control: "checkbox" });
|
||||
const params = { mainClass: "a.Main", classpath: "${classpath}" };
|
||||
expect(type.commandLine({ ...params, enhancedClassRedefinition: "true" })).toEqual(type.commandLine(params));
|
||||
expect(jarApplicationType.fields.some((f) => f.key === "enhancedClassRedefinition")).toBe(false);
|
||||
});
|
||||
|
||||
it("reads VM options over several lines and with quoted spaces", () => {
|
||||
const line = applicationType.commandLine({
|
||||
mainClass: "a.Main",
|
||||
|
||||
@@ -78,17 +78,6 @@ const jreField: RunConfigTypeField = {
|
||||
})),
|
||||
};
|
||||
|
||||
/**
|
||||
* JetBrains Runtime's `-XX:+AllowEnhancedClassRedefinition` for Debug, so Reload Changed Classes can add or
|
||||
* remove methods and fields. The host adds it only on JetBrains Runtime (other JVMs refuse to start with it).
|
||||
*/
|
||||
const enhancedRedefinitionField: RunConfigTypeField = {
|
||||
key: "enhancedClassRedefinition",
|
||||
label: "Enhanced class redefinition",
|
||||
control: "checkbox",
|
||||
hint: "When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields",
|
||||
};
|
||||
|
||||
/** IDEA's "Use classpath of module": the module whose classpath and build the run uses. */
|
||||
const moduleField: RunConfigTypeField = {
|
||||
key: "module",
|
||||
@@ -130,7 +119,6 @@ function jvmApplicationType(spring: boolean): RunConfigTypeContribution {
|
||||
...(spring ? [profilesField("Comma separated; passed as --spring.profiles.active")] : []),
|
||||
...(spring ? updatePolicyFields(false) : []),
|
||||
jreField,
|
||||
enhancedRedefinitionField,
|
||||
moduleField,
|
||||
{
|
||||
key: "classpath",
|
||||
|
||||
@@ -438,12 +438,9 @@ function TwoPaneDiff({
|
||||
inputKey.current = input.key;
|
||||
// Swap Sides shows the request's sides the other way round; another request starts unswapped.
|
||||
const [swappedFor, setSwappedFor] = useState<DiffData | null>(null);
|
||||
// The one-side viewer puts its only editable document into the unified editor. A deleted
|
||||
// file's diff shows the original text as the document itself: the absent side stays on the
|
||||
// left as the diff's original, as for a staged deletion.
|
||||
const deletedOneSided =
|
||||
!(input_.left.type === "text" && input_.left.absent) && input_.right.type === "text" && !!input_.right.absent;
|
||||
const swapped = deletedOneSided || swappedFor === input_;
|
||||
// The one-side viewer puts its only editable document into the unified editor.
|
||||
const indexOnlyLeft = isIndex(input_.left) && input_.right.type === "text" && input_.right.absent;
|
||||
const swapped = !!indexOnlyLeft || swappedFor === input_;
|
||||
const data = useMemo(
|
||||
() => (swapped ? { ...input_, left: input_.right, right: input_.left } : input_),
|
||||
[input_, swapped],
|
||||
@@ -1791,7 +1788,7 @@ function TwoPaneDiff({
|
||||
return (
|
||||
<div
|
||||
ref={rootRef}
|
||||
className={clsx(styles.root, fit && styles.fit, deletedOneSided && styles.indexDeletion)}
|
||||
className={clsx(styles.root, fit && styles.fit, indexOnlyLeft && styles.indexDeletion)}
|
||||
onKeyDown={onKeyDown}
|
||||
onFocusCapture={() => {
|
||||
setFocusedDiffNavigator(nav.current);
|
||||
@@ -1997,7 +1994,7 @@ function TwoPaneDiff({
|
||||
size="small"
|
||||
onClick={() => {
|
||||
void Promise.resolve(indexDoc?.save())
|
||||
.then(() => executeAction("vcs.showDiffInNewWindow", deletedOneSided ? input_ : data))
|
||||
.then(() => executeAction("vcs.showDiffInNewWindow", indexOnlyLeft ? input_ : data))
|
||||
.catch(() => {});
|
||||
}}
|
||||
/>
|
||||
@@ -2052,25 +2049,15 @@ function TwoPaneDiff({
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
// A deleted file's swapped viewer still reads in the request's order: revision → (deleted).
|
||||
<div className={labels}>
|
||||
<span
|
||||
className={styles.label}
|
||||
title={
|
||||
sourceLabels ? (deletedOneSided ? `${captionB} → ${captionA}` : `${captionA} → ${captionB}`) : undefined
|
||||
}
|
||||
>
|
||||
<span className={styles.labelText}>{sideLabel(deletedOneSided ? right : left)}</span>
|
||||
{sourceLabels && <PaneTitleDetail {...(deletedOneSided ? titleB : titleA)} />}
|
||||
<span className={styles.label} title={sourceLabels ? `${captionA} → ${captionB}` : undefined}>
|
||||
<span className={styles.labelText}>{sideLabel(left)}</span>
|
||||
{sourceLabels && <PaneTitleDetail {...titleA} />}
|
||||
{unifiedOnLeft && <span className={styles.badge}>{tx("editable")}</span>}
|
||||
{eolDiffers && (deletedOneSided ? eolB : eolA) && (
|
||||
<span className={styles.badge}>{deletedOneSided ? badgeB : badgeA}</span>
|
||||
)}{" "}
|
||||
→<span className={styles.labelText}>{sideLabel(deletedOneSided ? left : right)}</span>
|
||||
{sourceLabels && <PaneTitleDetail {...(deletedOneSided ? titleA : titleB)} />}
|
||||
{eolDiffers && (deletedOneSided ? eolA : eolB) && (
|
||||
<span className={styles.badge}>{deletedOneSided ? badgeA : badgeB}</span>
|
||||
)}
|
||||
{eolDiffers && eolA && <span className={styles.badge}>{badgeA}</span>} →
|
||||
<span className={styles.labelText}>{sideLabel(right)}</span>
|
||||
{sourceLabels && <PaneTitleDetail {...titleB} />}
|
||||
{eolDiffers && eolB && <span className={styles.badge}>{badgeB}</span>}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, waitFor } from "@testing-library/react";
|
||||
import type { EditorInput } from "@/workbench/contributions";
|
||||
|
||||
const texts: Record<string, string> = { HEAD: "a\nb\nc\n" };
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
fsProbe: () => Promise.resolve({ status: "ok", data: { size: 0, binary: false, tooLarge: false } }),
|
||||
vcsFileAt: (_path: string, rev: string) => Promise.resolve({ status: "ok", data: texts[rev] }),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { DiffEditor } from "../DiffEditor";
|
||||
|
||||
const input = {
|
||||
kind: "diff",
|
||||
key: "diff:deleted",
|
||||
data: {
|
||||
path: "/p/a.ts",
|
||||
left: { type: "rev", rev: "HEAD" },
|
||||
right: { type: "text", text: "", label: "(deleted)", absent: true },
|
||||
},
|
||||
} as unknown as EditorInput;
|
||||
|
||||
/** Plain gutter numbers rendered for document lines (skipping the hidden width-calibration spacer). */
|
||||
const gutterNumbers = (container: HTMLElement) =>
|
||||
[...container.querySelectorAll(".cm-lineNumbers .cm-gutterElement")]
|
||||
.filter((n) => (n as HTMLElement).style.visibility !== "hidden")
|
||||
.map((n) => n.textContent)
|
||||
.filter((t) => t && /^\d+$/.test(t));
|
||||
|
||||
describe("line numbers of a deleted file's diff", () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
afterEach(() => localStorage.clear());
|
||||
|
||||
it("shows the original text as the document itself, numbered like an editor", async () => {
|
||||
const mounted = render(<DiffEditor input={input} />);
|
||||
try {
|
||||
await waitFor(() => expect(mounted.container.querySelectorAll(".cm-editor")).toHaveLength(1));
|
||||
// "a\nb\nc\n" is four CodeMirror lines, the last one empty, as in the editor itself.
|
||||
await waitFor(() => expect(gutterNumbers(mounted.container)).toEqual(["1", "2", "3", "4"]));
|
||||
const lines = [...mounted.container.querySelectorAll(".cm-content > .cm-line")].map((l) => l.textContent);
|
||||
expect(lines).toEqual(["a", "b", "c", ""]);
|
||||
// No mirrored widget numbers: the lines are real, so the gutter, selection and context
|
||||
// menu behave like the editor's.
|
||||
expect(mounted.container.querySelector(".cm-diffWidgetNumber")).toBeNull();
|
||||
} finally {
|
||||
mounted.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the document's own numbers for an added file", async () => {
|
||||
const added = {
|
||||
...input,
|
||||
data: {
|
||||
path: "/p/a.ts",
|
||||
left: { type: "text", text: "", label: "(does not exist)", absent: true },
|
||||
right: { type: "rev", rev: "HEAD" },
|
||||
},
|
||||
} as unknown as EditorInput;
|
||||
texts.HEAD = "a\nb\nc\n";
|
||||
const mounted = render(<DiffEditor input={added} />);
|
||||
try {
|
||||
await waitFor(() => expect(mounted.container.querySelectorAll(".cm-editor")).toHaveLength(1));
|
||||
await waitFor(() => expect(gutterNumbers(mounted.container)).toContain("3"));
|
||||
} finally {
|
||||
mounted.unmount();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,8 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { Chunk, MergeView } from "@codemirror/merge";
|
||||
import { EditorState, Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { Text } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { bandAt, bandPath, transferY, PaddedPanes, UnalignedPanes, type Band } from "../diffScroll";
|
||||
import { collapsedDiffLines } from "../collapsedDiffLines";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
@@ -178,32 +177,6 @@ describe("synchronized navigation scrolling", () => {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the wheel-scrolled pane in charge when the follower pane adjusts scrollTop on measure", () => {
|
||||
vi.useFakeTimers();
|
||||
const frame = vi.spyOn(window, "requestAnimationFrame").mockReturnValue(1);
|
||||
const p = panes();
|
||||
try {
|
||||
p.b.scrollDOM.dispatchEvent(new Event("wheel"));
|
||||
p.scroll(p.b, 1200);
|
||||
expect(p.a.scrollDOM.scrollTop).toBe(1200);
|
||||
// Repeated wheel events must not cancel native momentum with scrollTo(instant).
|
||||
p.b.scrollDOM.dispatchEvent(new Event("wheel"));
|
||||
expect(p.b.scrollDOM.scrollTo).not.toHaveBeenCalled();
|
||||
// Follower shifts from CodeMirror height measurement must not yank the wheel source back.
|
||||
p.scroll(p.a, 800);
|
||||
expect(p.b.scrollDOM.scrollTop).toBe(1200);
|
||||
expect(p.a.scrollDOM.scrollTop).toBe(1200);
|
||||
// Pointer interaction on the other pane hands control back immediately.
|
||||
p.a.scrollDOM.dispatchEvent(new Event("pointerdown"));
|
||||
p.scroll(p.a, 400);
|
||||
expect(p.b.scrollDOM.scrollTop).toBe(400);
|
||||
} finally {
|
||||
p.controller.destroy();
|
||||
frame.mockRestore();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("padded pane scrolling (aligned diff)", () => {
|
||||
@@ -268,60 +241,6 @@ describe("padded pane scrolling (aligned diff)", () => {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the wheel-scrolled pane in charge when the follower shifts during layout", () => {
|
||||
vi.useFakeTimers();
|
||||
const p = panes();
|
||||
try {
|
||||
p.b.scrollDOM.dispatchEvent(new Event("wheel"));
|
||||
p.scroll(p.b, 900);
|
||||
expect(p.a.scrollDOM.scrollTop).toBe(900);
|
||||
p.scroll(p.a, 500);
|
||||
expect(p.b.scrollDOM.scrollTop).toBe(900);
|
||||
expect(p.a.scrollDOM.scrollTop).toBe(900);
|
||||
vi.advanceTimersByTime(150);
|
||||
p.scroll(p.a, 200);
|
||||
expect(p.b.scrollDOM.scrollTop).toBe(200);
|
||||
} finally {
|
||||
p.controller.destroy();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("collapsed diff lines", () => {
|
||||
it("defers button DOM replacement from docViewUpdate into CodeMirror's measure write phase", () => {
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc: "a\nb\nc", extensions: [collapsedDiffLines()] }),
|
||||
parent,
|
||||
});
|
||||
const measureSpy = vi.spyOn(view, "requestMeasure");
|
||||
try {
|
||||
const row = document.createElement("div");
|
||||
row.className = "cm-collapsedLines";
|
||||
row.textContent = "10 unchanged lines";
|
||||
view.contentDOM.appendChild(row);
|
||||
const plugin = (
|
||||
view as unknown as { plugins: Array<{ value: { docViewUpdate?: () => void } | null }> }
|
||||
).plugins.find((p) => typeof p.value?.docViewUpdate === "function");
|
||||
expect(plugin).toBeDefined();
|
||||
measureSpy.mockClear();
|
||||
plugin!.value!.docViewUpdate!();
|
||||
// Must not mutate DOM synchronously during docViewUpdate (triggers WebKit scrollTop clamping).
|
||||
expect(row.querySelector("button")).toBeNull();
|
||||
expect(measureSpy).toHaveBeenCalledTimes(1);
|
||||
const req = measureSpy.mock.calls[0]![0] as { write?: (v: unknown, view: EditorView) => void };
|
||||
req.write?.(null, view);
|
||||
expect(row.querySelector("button")).not.toBeNull();
|
||||
expect(row.querySelector("button")?.textContent).toBe("10 unchanged lines");
|
||||
} finally {
|
||||
measureSpy.mockRestore();
|
||||
view.destroy();
|
||||
parent.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("divider arrows", () => {
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { survivingRowShift } from "../logScrollAnchor";
|
||||
import { commitKey, type RepoCommit } from "../multiRoot";
|
||||
|
||||
let reads = 0;
|
||||
const row = (id: string, repo: string | null = "/repo"): RepoCommit =>
|
||||
({
|
||||
get id() {
|
||||
reads++;
|
||||
return id;
|
||||
},
|
||||
repo,
|
||||
}) as unknown as RepoCommit;
|
||||
const rows = (prefix: string, n: number, repo?: string | null) =>
|
||||
Array.from({ length: n }, (_, i) => row(`${prefix}${i}`, repo));
|
||||
|
||||
describe("survivingRowShift", () => {
|
||||
it("shifts by where the first surviving row at or below the top moved", () => {
|
||||
const [a, b, c, d] = rows("c", 4);
|
||||
expect(survivingRowShift([a!, b!, c!, d!], [row("new"), c!, d!], 0)).toBe(-1);
|
||||
expect(survivingRowShift([a!, b!, c!, d!], [row("x"), row("y"), a!, b!], 1)).toBe(2);
|
||||
});
|
||||
|
||||
it("takes the first match of a commit listed twice, and repositories apart", () => {
|
||||
expect(survivingRowShift([row("a")], [row("b"), row("a"), row("a")], 0)).toBe(1);
|
||||
expect(survivingRowShift([row("a", "/one")], [row("a", "/two"), row("a", "/one")], 0)).toBe(1);
|
||||
});
|
||||
|
||||
it("is null when no row survives or the top is past the end", () => {
|
||||
expect(survivingRowShift(rows("old", 3), rows("new", 3), 0)).toBeNull();
|
||||
expect(survivingRowShift(rows("c", 2), rows("c", 2), 5)).toBeNull();
|
||||
});
|
||||
|
||||
// Checkout from main to an older commit: the newest ~21k rows of the old list are gone.
|
||||
// Searching the new list once per old row froze the window for minutes.
|
||||
it("reads each row a bounded number of times when the leading rows are gone", () => {
|
||||
const kept = rows("kept", 3000);
|
||||
const previous = [...rows("gone", 3000), ...kept];
|
||||
reads = 0;
|
||||
expect(survivingRowShift(previous, kept, 0)).toBe(-3000);
|
||||
// Per-row search on main: 3000 × 3000 × 2 = 18M reads.
|
||||
expect(reads).toBeLessThan(20 * (previous.length + kept.length));
|
||||
});
|
||||
|
||||
it("reads only up to the match when the top row survives, like a plain search", () => {
|
||||
const list = rows("c", 3000);
|
||||
reads = 0;
|
||||
expect(survivingRowShift(list, [...list, ...rows("more", 1000)], 2)).toBe(0);
|
||||
expect(reads).toBeLessThan(10);
|
||||
});
|
||||
|
||||
// The per-row search it replaces, kept as the oracle.
|
||||
const searchPerRow = (previous: readonly RepoCommit[], commits: readonly RepoCommit[], top: number) => {
|
||||
for (let i = top; i < previous.length; i++) {
|
||||
const next = commits.findIndex((c) => commitKey(c) === commitKey(previous[i]!));
|
||||
if (next >= 0) return next - i;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
it("matches the per-row search on generated lists", () => {
|
||||
let seed = 1;
|
||||
const random = (n: number) => {
|
||||
seed = (seed * 1103515245 + 12345) % 2 ** 31;
|
||||
return seed % n;
|
||||
};
|
||||
const repos = [null, "", "/one", "/two"];
|
||||
const pick = (ids: number) => ({ id: `c${random(ids)}`, repo: repos[random(4)] }) as unknown as RepoCommit;
|
||||
const list = (length: number, ids: number) => Array.from({ length: random(length) }, () => pick(ids));
|
||||
for (let run = 0; run < 5000; run++) {
|
||||
// Long previous lists with ids missing from `commits` also cover the indexed lookups.
|
||||
const previous = run % 2 ? list(15, 12) : list(80, 40);
|
||||
const commits = run % 2 ? list(15, 12) : list(15, 4);
|
||||
const top = random(previous.length + 3);
|
||||
expect(survivingRowShift(previous, commits, top)).toBe(searchPerRow(previous, commits, top));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -300,26 +300,6 @@ describe("log controls", () => {
|
||||
expect(rows[0]!.querySelector<HTMLElement>('[class*="colRepository"]')!.style.width).toBe("130px");
|
||||
});
|
||||
|
||||
it("without headers, a row strip on a leading Commit cell resizes the Repository column", async () => {
|
||||
useVcs.setState({ roots: ["/repo", "/other"] });
|
||||
const tip = { ...c("tip"), repo: "/repo" };
|
||||
api.commits = [tip];
|
||||
// Defaults: headers hidden, Commit first.
|
||||
useLogOptions.setState({ showRepository: true });
|
||||
render(<LogView />);
|
||||
const rows = await within(screen.getByRole("listbox", { name: "Commits" })).findAllByRole("option");
|
||||
const strip = rows[0]!.querySelector<HTMLElement>('[class*="colSubject"] > [class*="columnResize"]')!;
|
||||
strip.setPointerCapture = vi.fn();
|
||||
strip.hasPointerCapture = () => true;
|
||||
strip.releasePointerCapture = vi.fn();
|
||||
fireEvent.pointerDown(strip, { button: 0, pointerId: 9, clientX: 100 });
|
||||
fireEvent.pointerMove(strip, { pointerId: 9, clientX: 130 });
|
||||
fireEvent.pointerUp(strip, { pointerId: 9, clientX: 130 });
|
||||
expect(useLogOptions.getState().columnWidths.repository).toBe(130);
|
||||
// The strip swallows the press, so the row is not selected.
|
||||
expect(useGitLog.getState().selected).toBeNull();
|
||||
});
|
||||
|
||||
it("exposes a full-height column divider on data rows", async () => {
|
||||
useLogOptions.setState({ showColumnHeaders: true });
|
||||
render(<LogView />);
|
||||
|
||||
@@ -20,13 +20,8 @@ const collapseButtons = ViewPlugin.define((view) => {
|
||||
row.replaceChildren(button);
|
||||
}
|
||||
};
|
||||
// Defer DOM replacement into CodeMirror's measure write phase rather than mutating synchronously
|
||||
// during docViewUpdate: in WebKit, inserting the inline SVG while updated viewport gaps have not
|
||||
// flushed layout yet causes scrollTop to clamp backwards and trap wheel scrolling in a loop.
|
||||
const measure = { key: enhance, read: () => null, write: enhance };
|
||||
const schedule = () => view.requestMeasure(measure);
|
||||
schedule();
|
||||
return { docViewUpdate: schedule };
|
||||
view.requestMeasure({ read: () => null, write: enhance });
|
||||
return { docViewUpdate: enhance };
|
||||
});
|
||||
|
||||
export function collapsedDiffLines(): Extension {
|
||||
|
||||
@@ -193,25 +193,17 @@ export interface DiffPanes {
|
||||
* of the content, out of reach until the diff is scrolled to its end.
|
||||
*/
|
||||
export class PaddedPanes implements DiffPanes {
|
||||
readonly extension: Extension;
|
||||
readonly extension: Extension = [];
|
||||
private mv: MergeView | null = null;
|
||||
private sync: boolean;
|
||||
private scrolling: Side | null = null;
|
||||
private scrollTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
private wheelLeader: Side | null = null;
|
||||
private wheelTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
/** The scroll position a pane was last moved to by the other one, to tell its echo from the user. */
|
||||
private readonly moved: Record<Side, number | null> = { a: null, b: null };
|
||||
private readonly cleanup: (() => void)[] = [];
|
||||
|
||||
constructor(sync: boolean) {
|
||||
this.sync = sync;
|
||||
this.extension = EditorView.updateListener.of((u) => {
|
||||
if (u.heightChanged && !u.docChanged && this.mv) {
|
||||
const side: Side | null = u.view === this.mv.a ? "a" : u.view === this.mv.b ? "b" : null;
|
||||
if (side && this.moved[side] !== null) this.moved[side] = u.view.scrollDOM.scrollTop;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
attach(mv: MergeView) {
|
||||
@@ -219,22 +211,8 @@ export class PaddedPanes implements DiffPanes {
|
||||
for (const side of ["a", "b"] as const) {
|
||||
const el = this.view(side).scrollDOM;
|
||||
const onScroll = () => this.scrolled(side);
|
||||
const onWheel = () => {
|
||||
this.interruptScroll();
|
||||
this.leadWheel(side);
|
||||
};
|
||||
const onPointer = () => {
|
||||
this.interruptScroll();
|
||||
this.clearWheel();
|
||||
};
|
||||
el.addEventListener("scroll", onScroll, { passive: true });
|
||||
el.addEventListener("wheel", onWheel, { passive: true });
|
||||
el.addEventListener("pointerdown", onPointer);
|
||||
this.cleanup.push(() => {
|
||||
el.removeEventListener("scroll", onScroll);
|
||||
el.removeEventListener("wheel", onWheel);
|
||||
el.removeEventListener("pointerdown", onPointer);
|
||||
});
|
||||
this.cleanup.push(() => el.removeEventListener("scroll", onScroll));
|
||||
}
|
||||
this.resync();
|
||||
}
|
||||
@@ -247,14 +225,12 @@ export class PaddedPanes implements DiffPanes {
|
||||
setSync(on: boolean) {
|
||||
if (on === this.sync) return;
|
||||
this.interruptScroll();
|
||||
this.clearWheel();
|
||||
this.sync = on;
|
||||
this.resync();
|
||||
}
|
||||
|
||||
scrollTo(side: Side, options: ScrollToOptions) {
|
||||
this.interruptScroll();
|
||||
this.clearWheel();
|
||||
this.scrolling = this.sync ? side : null;
|
||||
this.releaseScroll();
|
||||
this.view(side).scrollDOM.scrollTo(options);
|
||||
@@ -265,14 +241,12 @@ export class PaddedPanes implements DiffPanes {
|
||||
* other pane's delayed reflow follows it instead of being mistaken for a user scroll pulling back.
|
||||
*/
|
||||
leadScroll(side: Side) {
|
||||
this.clearWheel();
|
||||
this.scrolling = this.sync ? side : null;
|
||||
this.releaseScroll();
|
||||
}
|
||||
|
||||
destroy() {
|
||||
clearTimeout(this.scrollTimer);
|
||||
clearTimeout(this.wheelTimer);
|
||||
for (const f of this.cleanup) f();
|
||||
this.mv = null;
|
||||
}
|
||||
@@ -288,16 +262,6 @@ export class PaddedPanes implements DiffPanes {
|
||||
this.releaseScroll();
|
||||
return;
|
||||
}
|
||||
if (this.wheelLeader) {
|
||||
this.moved[from] = null;
|
||||
if (from === this.wheelLeader) {
|
||||
this.leadWheel(from);
|
||||
if (this.sync) this.follow(from);
|
||||
} else if (this.sync) {
|
||||
this.follow(this.wheelLeader);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const el = this.view(from).scrollDOM;
|
||||
const moved = this.moved[from];
|
||||
const echo = moved !== null && Math.abs(el.scrollTop - moved) <= 1;
|
||||
@@ -305,17 +269,6 @@ export class PaddedPanes implements DiffPanes {
|
||||
if (!echo && this.sync) this.follow(from);
|
||||
}
|
||||
|
||||
private leadWheel(side: Side) {
|
||||
this.wheelLeader = this.sync ? side : null;
|
||||
clearTimeout(this.wheelTimer);
|
||||
if (this.wheelLeader) this.wheelTimer = setTimeout(() => (this.wheelLeader = null), 150);
|
||||
}
|
||||
|
||||
private clearWheel() {
|
||||
this.wheelLeader = null;
|
||||
clearTimeout(this.wheelTimer);
|
||||
}
|
||||
|
||||
private follow(from: Side) {
|
||||
const to: Side = from === "a" ? "b" : "a";
|
||||
const el = this.view(to).scrollDOM;
|
||||
@@ -361,8 +314,6 @@ export class UnalignedPanes implements DiffPanes {
|
||||
private sync: boolean;
|
||||
private scrolling: Side | null = null;
|
||||
private scrollTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
private wheelLeader: Side | null = null;
|
||||
private wheelTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
private frame = -1;
|
||||
private resize: ResizeObserver | null = null;
|
||||
private readonly cleanup: (() => void)[] = [];
|
||||
@@ -375,19 +326,7 @@ export class UnalignedPanes implements DiffPanes {
|
||||
opts.initialRatio != null && Number.isFinite(opts.initialRatio)
|
||||
? Math.min(MAX_RATIO, Math.max(MIN_RATIO, opts.initialRatio))
|
||||
: loadRatio();
|
||||
this.extension = [
|
||||
gapMarks,
|
||||
changedLineGutters,
|
||||
EditorView.updateListener.of((u) => {
|
||||
// When CodeMirror's measure adjusts a follower pane's scrollTop after line heights resolve,
|
||||
// update the expected echo so the layout adjustment is not mistaken for a user scroll.
|
||||
if (u.heightChanged && !u.docChanged && this.mv) {
|
||||
const side: Side | null = u.view === this.mv.a ? "a" : u.view === this.mv.b ? "b" : null;
|
||||
if (side && this.moved[side].top !== null) this.moved[side].top = u.view.scrollDOM.scrollTop;
|
||||
}
|
||||
this.schedule();
|
||||
}),
|
||||
];
|
||||
this.extension = [gapMarks, changedLineGutters, EditorView.updateListener.of(() => this.schedule())];
|
||||
this.divider.className = "cm-diffDivider";
|
||||
// A lone arrow is centred in the divider; a pair keeps to the two edges.
|
||||
this.divider.classList.toggle("cm-diffDivider-lone", !!opts.arrows && opts.arrows.toA !== opts.arrows.toB);
|
||||
@@ -410,20 +349,13 @@ export class UnalignedPanes implements DiffPanes {
|
||||
for (const side of ["a", "b"] as const) {
|
||||
const el = this.view(side).scrollDOM;
|
||||
const onScroll = () => this.scrolled(side);
|
||||
const onWheel = () => {
|
||||
this.interruptScroll();
|
||||
this.leadWheel(side);
|
||||
};
|
||||
const onPointer = () => {
|
||||
this.interruptScroll();
|
||||
this.clearWheel();
|
||||
};
|
||||
const onPointer = () => this.interruptScroll();
|
||||
el.addEventListener("scroll", onScroll, { passive: true });
|
||||
el.addEventListener("wheel", onWheel, { passive: true });
|
||||
el.addEventListener("wheel", onPointer, { passive: true });
|
||||
el.addEventListener("pointerdown", onPointer);
|
||||
this.cleanup.push(() => {
|
||||
el.removeEventListener("scroll", onScroll);
|
||||
el.removeEventListener("wheel", onWheel);
|
||||
el.removeEventListener("wheel", onPointer);
|
||||
el.removeEventListener("pointerdown", onPointer);
|
||||
});
|
||||
}
|
||||
@@ -496,7 +428,6 @@ export class UnalignedPanes implements DiffPanes {
|
||||
const onWheel = (e: WheelEvent) => {
|
||||
e.preventDefault();
|
||||
this.interruptScroll();
|
||||
this.leadWheel("b");
|
||||
mv.b.scrollDOM.scrollBy(e.deltaX, e.deltaY);
|
||||
};
|
||||
this.divider.addEventListener("wheel", onWheel, { passive: false });
|
||||
@@ -528,30 +459,17 @@ export class UnalignedPanes implements DiffPanes {
|
||||
setSync(on: boolean) {
|
||||
if (on === this.sync) return;
|
||||
this.interruptScroll();
|
||||
this.clearWheel();
|
||||
this.sync = on;
|
||||
this.resync();
|
||||
}
|
||||
|
||||
scrollTo(side: Side, options: ScrollToOptions) {
|
||||
this.interruptScroll();
|
||||
this.clearWheel();
|
||||
this.scrolling = this.sync ? side : null;
|
||||
this.releaseScroll();
|
||||
this.view(side).scrollDOM.scrollTo(options);
|
||||
}
|
||||
|
||||
private leadWheel(side: Side) {
|
||||
this.wheelLeader = this.sync ? side : null;
|
||||
clearTimeout(this.wheelTimer);
|
||||
if (this.wheelLeader) this.wheelTimer = setTimeout(() => (this.wheelLeader = null), 150);
|
||||
}
|
||||
|
||||
private clearWheel() {
|
||||
this.wheelLeader = null;
|
||||
clearTimeout(this.wheelTimer);
|
||||
}
|
||||
|
||||
private releaseScroll() {
|
||||
clearTimeout(this.scrollTimer);
|
||||
if (this.scrolling) this.scrollTimer = setTimeout(() => (this.scrolling = null), 150);
|
||||
@@ -569,7 +487,6 @@ export class UnalignedPanes implements DiffPanes {
|
||||
|
||||
destroy() {
|
||||
clearTimeout(this.scrollTimer);
|
||||
clearTimeout(this.wheelTimer);
|
||||
if (this.frame >= 0) cancelAnimationFrame(this.frame);
|
||||
this.resize?.disconnect();
|
||||
for (const f of this.cleanup) f();
|
||||
@@ -601,19 +518,6 @@ export class UnalignedPanes implements DiffPanes {
|
||||
this.schedule();
|
||||
return;
|
||||
}
|
||||
if (this.wheelLeader) {
|
||||
// Keep the actively wheel-scrolled pane in charge so follower measure adjustments never pull it back.
|
||||
const moved = this.moved[side];
|
||||
moved.top = moved.left = null;
|
||||
if (side === this.wheelLeader) {
|
||||
this.leadWheel(side);
|
||||
if (this.sync) this.follow(side);
|
||||
} else if (this.sync) {
|
||||
this.follow(this.wheelLeader);
|
||||
}
|
||||
this.schedule();
|
||||
return;
|
||||
}
|
||||
const el = this.view(side).scrollDOM;
|
||||
const moved = this.moved[side];
|
||||
const echo =
|
||||
|
||||
@@ -25,7 +25,6 @@ import { LogIdContext } from "../logContext";
|
||||
import { loadLogDetails } from "../logDetails";
|
||||
import { useLogOptions } from "../logOptions";
|
||||
import { presentLogGraph } from "../logPresentation";
|
||||
import { survivingRowShift } from "../logScrollAnchor";
|
||||
import { nextSpeedMatch } from "../logSearch";
|
||||
import {
|
||||
PAGE,
|
||||
@@ -263,8 +262,12 @@ export function CommitList({ fileHistory = false }: { fileHistory?: boolean }) {
|
||||
if (!element || previous === commits || (revealTick !== lastRevealed.current && selectedIndex >= 0)) return;
|
||||
const top = Math.max(0, Math.floor((element.scrollTop - ROW) / row));
|
||||
// Preserve the first surviving visible commit and its pixel offset.
|
||||
const shift = survivingRowShift(previous, commits, top);
|
||||
if (shift !== null) element.scrollTop += shift * row;
|
||||
for (let i = top; i < previous.length; i++) {
|
||||
const next = commits.findIndex((c) => commitKey(c) === commitKey(previous[i]!));
|
||||
if (next < 0) continue;
|
||||
element.scrollTop += (next - i) * row;
|
||||
break;
|
||||
}
|
||||
}, [commits, revealTick, selectedIndex, row]);
|
||||
const finished = done;
|
||||
const virtualizer = useVirtualizer({
|
||||
|
||||
@@ -105,24 +105,8 @@ function CommitRowView({
|
||||
left={opts.refsOnLeft}
|
||||
/>
|
||||
);
|
||||
const repository = opts.showRepository && !!commitRepo(c) && useVcs.getState().roots.length > 1;
|
||||
// The header's neighbours: an id without a shown column (a hidden one) is skipped.
|
||||
const visibleIds = columnSequence(opts.columnOrder, columns).filter(
|
||||
(cid) => cid === SUBJECT_COLUMN.id || columns.some((col) => col.id === cid),
|
||||
);
|
||||
const subjectCell = (
|
||||
<span key={SUBJECT_COLUMN.id} className={styles.colSubject}>
|
||||
{/* A leading Commit cell's left edge is the only row divider for the Repository column. */}
|
||||
{repository && visibleIds[0] === SUBJECT_COLUMN.id && (
|
||||
<RowResizeHandle
|
||||
target={{
|
||||
id: SUBJECT_COLUMN.id,
|
||||
width: 0,
|
||||
...columnPrev(visibleIds, SUBJECT_COLUMN.id, opts, columns, repository),
|
||||
leftOnly: true,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{graph && (
|
||||
<GraphCell
|
||||
row={graph}
|
||||
@@ -177,6 +161,11 @@ function CommitRowView({
|
||||
</Popup>
|
||||
</span>
|
||||
);
|
||||
const repository = opts.showRepository && !!commitRepo(c) && useVcs.getState().roots.length > 1;
|
||||
// The header's neighbours: an id without a shown column (a hidden one) is skipped.
|
||||
const visibleIds = columnSequence(opts.columnOrder, columns).filter(
|
||||
(cid) => cid === SUBJECT_COLUMN.id || columns.some((col) => col.id === cid),
|
||||
);
|
||||
return (
|
||||
<div
|
||||
id={id}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
import type { RepoCommit } from "./multiRoot";
|
||||
|
||||
/**
|
||||
* Rows to move the Log's scroll position by after its commits were replaced, so the first
|
||||
* row at or below `top` that is still listed keeps its place; null when none is.
|
||||
* Rows match as `commitKey` does: same id, same repository (null and "" alike).
|
||||
* Usually the top row survived, so rows get plain searches first. Searching once per row
|
||||
* is quadratic, though, and a checkout to an older commit drops tens of thousands of
|
||||
* leading rows; after about eight full misses the rest are looked up in an index instead,
|
||||
* which costs a few plain searches to build.
|
||||
*/
|
||||
export function survivingRowShift(
|
||||
previous: readonly RepoCommit[],
|
||||
commits: readonly RepoCommit[],
|
||||
top: number,
|
||||
): number | null {
|
||||
let budget = 8 * commits.length;
|
||||
let index: Map<string, Map<string, number>> | undefined;
|
||||
for (let i = top; i < previous.length; i++) {
|
||||
const { id } = previous[i]!;
|
||||
const repo = previous[i]!.repo || "";
|
||||
let next: number;
|
||||
if (index) next = index.get(repo)?.get(id) ?? -1;
|
||||
else {
|
||||
next = commits.findIndex((c) => c.id === id && (c.repo || "") === repo);
|
||||
budget -= next < 0 ? commits.length : next + 1;
|
||||
if (budget < 0) index = indexCommits(commits);
|
||||
}
|
||||
if (next >= 0) return next - i;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Repository → id → first index. */
|
||||
function indexCommits(commits: readonly RepoCommit[]) {
|
||||
const index = new Map<string, Map<string, number>>();
|
||||
for (let i = commits.length - 1; i >= 0; i--) {
|
||||
const repo = commits[i]!.repo || "";
|
||||
let ids = index.get(repo);
|
||||
if (!ids) index.set(repo, (ids = new Map()));
|
||||
ids.set(commits[i]!.id, i);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
@@ -4071,8 +4071,5 @@
|
||||
"Granted with grant option": "Granted with grant option",
|
||||
"No privileges are granted on this table.": "No privileges are granted on this table.",
|
||||
"* With grant option: the grantee may grant the privilege to others.": "* With grant option: the grantee may grant the privilege to others.",
|
||||
"Separate several prefixes with commas: they are tried in order, then the official source.": "Separate several prefixes with commas: they are tried in order, then the official source.",
|
||||
"The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.": "The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.",
|
||||
"Stop Backend and Open": "Stop Backend and Open",
|
||||
"Could not load the frames: {0}": "Could not load the frames: {0}"
|
||||
"Separate several prefixes with commas: they are tried in order, then the official source.": "Separate several prefixes with commas: they are tried in order, then the official source."
|
||||
}
|
||||
@@ -1700,9 +1700,6 @@
|
||||
"Reload All Gradle Projects": "Recargar todos los proyectos de Gradle",
|
||||
"Reload All Maven Projects": "Recargar todos los proyectos de Maven",
|
||||
"Reload Changed Classes": "Recargar clases modificadas",
|
||||
"Enhanced class redefinition": "Redefinición de clases mejorada",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "Al depurar en JetBrains Runtime, Recargar clases modificadas también puede añadir o eliminar métodos y campos",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Para añadir o eliminar métodos y campos, activa Redefinición de clases mejorada en la configuración de ejecución y depura en JetBrains Runtime.",
|
||||
"Reload Environments": "Recargar entornos",
|
||||
"Reload History": "Recargar historial",
|
||||
"Reload List of Packages": "Recargar lista de paquetes",
|
||||
|
||||
@@ -1619,9 +1619,6 @@
|
||||
"Reload All Gradle Projects": "Recharger tous les projets Gradle",
|
||||
"Reload All Maven Projects": "Recharger tous les projets Maven",
|
||||
"Reload Changed Classes": "Recharger les classes modifiées",
|
||||
"Enhanced class redefinition": "Redéfinition de classes étendue",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "Lors du débogage sur JetBrains Runtime, Recharger les classes modifiées peut aussi ajouter ou supprimer des méthodes et des champs",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Pour ajouter ou supprimer des méthodes et des champs, activez Redéfinition de classes étendue dans la configuration d'exécution et déboguez sur JetBrains Runtime.",
|
||||
"Reload Environments": "Recharger les environnements",
|
||||
"Reload History": "Recharger l'historique",
|
||||
"Reload List of Packages": "Recharger la liste des paquets",
|
||||
|
||||
@@ -1750,9 +1750,6 @@
|
||||
"Reload All Gradle Projects": "모든 Gradle 프로젝트 다시 로드",
|
||||
"Reload All Maven Projects": "모든 Maven 프로젝트 다시 로드",
|
||||
"Reload Changed Classes": "변경된 클래스 다시 로드",
|
||||
"Enhanced class redefinition": "향상된 클래스 재정의",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "JetBrains Runtime에서 디버그할 때 변경된 클래스 다시 로드로 메서드와 필드도 추가하거나 제거할 수 있습니다",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "메서드와 필드를 추가하거나 제거하려면 실행 구성에서 향상된 클래스 재정의를 켜고 JetBrains Runtime에서 디버그하세요.",
|
||||
"Reload Environments": "환경 다시 로드",
|
||||
"Reload History": "기록 다시 로드",
|
||||
"Reload List of Packages": "패키지 목록 다시 로드",
|
||||
|
||||
@@ -1690,9 +1690,6 @@
|
||||
"Reload All Gradle Projects": "Przeładuj wszystkie projekty Gradle",
|
||||
"Reload All Maven Projects": "Przeładuj wszystkie projekty Maven",
|
||||
"Reload Changed Classes": "Przeładuj zmienione klasy",
|
||||
"Enhanced class redefinition": "Rozszerzona redefinicja klas",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "Podczas debugowania w JetBrains Runtime Przeładuj zmienione klasy może też dodawać lub usuwać metody i pola",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Aby dodawać lub usuwać metody i pola, włącz Rozszerzoną redefinicję klas w konfiguracji uruchomieniowej i debuguj w JetBrains Runtime.",
|
||||
"Reload Environments": "Przeładuj środowiska",
|
||||
"Reload History": "Przeładuj historię",
|
||||
"Reload List of Packages": "Przeładuj listę pakietów",
|
||||
|
||||
@@ -1690,9 +1690,6 @@
|
||||
"Reload All Gradle Projects": "Recarregar todos os projetos Gradle",
|
||||
"Reload All Maven Projects": "Recarregar todos os projetos Maven",
|
||||
"Reload Changed Classes": "Recarregar classes alteradas",
|
||||
"Enhanced class redefinition": "Redefinição de classes aprimorada",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "Ao depurar no JetBrains Runtime, Recarregar classes alteradas também pode adicionar ou remover métodos e campos",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Para adicionar ou remover métodos e campos, ative Redefinição de classes aprimorada na configuração de execução e depure no JetBrains Runtime.",
|
||||
"Reload Environments": "Recarregar ambientes",
|
||||
"Reload History": "Recarregar histórico",
|
||||
"Reload List of Packages": "Recarregar lista de pacotes",
|
||||
|
||||
@@ -2947,9 +2947,6 @@
|
||||
"Generate Sources and Update Folders": "Сгенерировать исходный код и обновить каталоги",
|
||||
"Runs generate-sources, then reloads the Maven projects so generated folders become source folders": "Запускает generate-sources, затем перезагружает проекты Maven, чтобы сгенерированные каталоги стали каталогами исходного кода",
|
||||
"Reload Changed Classes": "Перезагрузить изменённые классы",
|
||||
"Enhanced class redefinition": "Расширенное переопределение классов",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "При отладке на JetBrains Runtime команда «Перезагрузить изменённые классы» также может добавлять и удалять методы и поля",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Чтобы добавлять или удалять методы и поля, включите «Расширенное переопределение классов» в конфигурации запуска и отлаживайте на JetBrains Runtime.",
|
||||
"Reload Environments": "Перезагрузить окружения",
|
||||
"Reload History": "Перезагрузить историю",
|
||||
"Reload List of Packages": "Перезагрузить список пакетов",
|
||||
|
||||
@@ -4449,9 +4449,6 @@
|
||||
"Reload All Gradle Projects": "Tüm Gradle Projelerini Yeniden Yükle",
|
||||
"Reload All Maven Projects": "Tüm Maven Projelerini Yeniden Yükle",
|
||||
"Reload Changed Classes": "Değiştirilen Sınıfları Yeniden Yükle",
|
||||
"Enhanced class redefinition": "Gelişmiş sınıf yeniden tanımlama",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "JetBrains Runtime üzerinde hata ayıklarken Değiştirilen Sınıfları Yeniden Yükle, yöntem ve alan da ekleyip kaldırabilir",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "Yöntem ve alan eklemek veya kaldırmak için çalıştırma yapılandırmasında Gelişmiş sınıf yeniden tanımlamayı açın ve JetBrains Runtime üzerinde hata ayıklayın.",
|
||||
"Reload Environments": "Ortamları Yeniden Yükle",
|
||||
"Reload History": "Geçmişi Yeniden Yükle",
|
||||
"Reload List of Packages": "Paket Listesini Yeniden Yükle",
|
||||
|
||||
@@ -2523,9 +2523,6 @@
|
||||
"Generate Sources and Update Folders": "產生原始碼並更新資料夾",
|
||||
"Runs generate-sources, then reloads the Maven projects so generated folders become source folders": "執行 generate-sources,然後重新載入 Maven 專案,使產生的資料夾成為原始碼資料夾",
|
||||
"Reload Changed Classes": "重新載入已更改的類別",
|
||||
"Enhanced class redefinition": "增強類別重新定義",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "在 JetBrains Runtime 上偵錯時,「重新載入已更改的類別」也可以新增或刪除方法和欄位",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "如需新增或刪除方法和欄位,請在執行組態中開啟「增強類別重新定義」,並使用 JetBrains Runtime 偵錯。",
|
||||
"Reload Environments": "重新載入環境",
|
||||
"Reload History": "重新載入歷史記錄",
|
||||
"Reload List of Packages": "重新載入軟體包清單",
|
||||
|
||||
@@ -3016,9 +3016,6 @@
|
||||
"Generate Sources and Update Folders": "生成源代码并更新文件夹",
|
||||
"Runs generate-sources, then reloads the Maven projects so generated folders become source folders": "执行 generate-sources,然后重新加载 Maven 项目,使生成的文件夹成为源代码文件夹",
|
||||
"Reload Changed Classes": "重新加载已更改的类",
|
||||
"Enhanced class redefinition": "增强类重定义",
|
||||
"When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields": "在 JetBrains Runtime 上调试时,“重新加载已更改的类”还可以添加或删除方法和字段",
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.": "如需添加或删除方法和字段,请在运行配置中开启“增强类重定义”,并使用 JetBrains Runtime 调试。",
|
||||
"Reload Environments": "重新加载环境",
|
||||
"Reload History": "重新加载历史记录",
|
||||
"Reload List of Packages": "重新加载软件包列表",
|
||||
@@ -10405,8 +10402,5 @@
|
||||
"No privileges are granted on this table.": "此表未授予任何权限。",
|
||||
"* With grant option: the grantee may grant the privilege to others.": "* WITH GRANT OPTION:被授权者可以将该权限再授予他人。",
|
||||
"Separate several prefixes with commas: they are tried in order, then the official source.": "多个前缀用逗号分隔:按顺序尝试,最后回退到官方源。",
|
||||
"Recent Find Usages": "最近的查找用法",
|
||||
"The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.": "另一个 OpenIDEA 版本(例如升级前的版本)的后端仍打开着这个项目,当前版本无法打开它。要停止那个后端并打开项目吗?它的终端、运行和智能体会话会结束,未保存的修改会丢失。",
|
||||
"Stop Backend and Open": "停止后端并打开",
|
||||
"Could not load the frames: {0}": "无法加载栈帧:{0}"
|
||||
"Recent Find Usages": "最近的查找用法"
|
||||
}
|
||||
@@ -237,27 +237,6 @@ async function attachRemote(r: RemoteProject, path: string): Promise<void> {
|
||||
|
||||
let connectAttempt = 0;
|
||||
|
||||
let backendBusyPrompt: ((target: RemoteTarget) => Promise<boolean>) | null = null;
|
||||
|
||||
/** Asks whether to stop another build's backend that still holds the project (#6119). */
|
||||
export function provideBackendBusyPrompt(value: (target: RemoteTarget) => Promise<boolean>): () => void {
|
||||
backendBusyPrompt = value;
|
||||
return () => {
|
||||
if (backendBusyPrompt === value) backendBusyPrompt = null;
|
||||
};
|
||||
}
|
||||
|
||||
/** Connects; when another build's backend still holds the project, stops it once the user agrees. */
|
||||
async function connectOrReplace(target: RemoteTarget, path: string, onProgress: Channel<RemoteProgress>) {
|
||||
try {
|
||||
return await call(commands.remoteConnect(target, path, false, onProgress));
|
||||
} catch (e) {
|
||||
const busy = e instanceof IpcError && e.data?.type === "remoteBackendBusy";
|
||||
if (!busy || !backendBusyPrompt || !(await backendBusyPrompt(target))) throw e;
|
||||
return await call(commands.remoteConnect(target, path, true, onProgress));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens `path` of `target` (an SSH host or a WSL distribution) in this window. A dev container's
|
||||
* project folder is the one in the container: `path` is then only a label.
|
||||
@@ -277,7 +256,7 @@ export async function connectRemote(target: RemoteTarget, path: string) {
|
||||
location,
|
||||
});
|
||||
try {
|
||||
const r = await connectOrReplace(target, path, onProgress);
|
||||
const r = await call(commands.remoteConnect(target, path, onProgress));
|
||||
// Another connect replaced this one, or the user cancelled. Disconnecting here
|
||||
// would drop the connection that replacement published. Cancel already disconnects.
|
||||
if (!current()) {
|
||||
@@ -301,7 +280,7 @@ export async function reconnectRemote(): Promise<void> {
|
||||
if (!session) return;
|
||||
useRemote.setState({ reconnecting: true });
|
||||
try {
|
||||
const r = await connectOrReplace(session.target, session.root, new Channel<RemoteProgress>());
|
||||
const r = await call(commands.remoteConnect(session.target, session.root, new Channel<RemoteProgress>()));
|
||||
useProject.setState({ project: null });
|
||||
await attachRemote(r, session.root);
|
||||
} finally {
|
||||
@@ -455,21 +434,6 @@ function saveRemotes(list: RecentRemote[]) {
|
||||
} catch {
|
||||
/* storage unavailable */
|
||||
}
|
||||
syncRemoteRecentMenu();
|
||||
}
|
||||
|
||||
/** Hands the recent remote projects to File › Open Recent, which lists them among the local ones. */
|
||||
export function syncRemoteRecentMenu() {
|
||||
if (!isTauri()) return;
|
||||
const projects = recentRemotes().map((r) => ({
|
||||
location: remoteLocation(r.target, r.path),
|
||||
name: r.name,
|
||||
detail: `${r.host || targetName(r.target)}:${r.path}`,
|
||||
openedAtMs: r.openedAtMs,
|
||||
}));
|
||||
void Promise.resolve()
|
||||
.then(() => commands.menuSetRemoteRecent(projects))
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
const sameRemote = (a: Pick<RecentRemote, "target" | "path">, b: Pick<RecentRemote, "target" | "path">) =>
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { commands, type RemoteTarget } from "./ipc";
|
||||
import { connectRemote, provideBackendBusyPrompt } from "./remote";
|
||||
|
||||
vi.mock("@tauri-apps/api/core", async (original) => ({
|
||||
...(await original<typeof import("@tauri-apps/api/core")>()),
|
||||
Channel: class {
|
||||
onmessage: unknown = null;
|
||||
},
|
||||
}));
|
||||
vi.mock("./ipc", async (original) => ({
|
||||
...(await original<typeof import("./ipc")>()),
|
||||
isTauri: () => true,
|
||||
}));
|
||||
|
||||
const target: RemoteTarget = { kind: "ssh", config: "box" };
|
||||
const busy = {
|
||||
status: "error" as const,
|
||||
error: { kind: "unavailable" as const, message: "busy", data: { type: "remoteBackendBusy" as const } },
|
||||
};
|
||||
const stop = { status: "error" as const, error: { kind: "unavailable" as const, message: "second attempt" } };
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it("stops another build's backend once the user agrees, then connects again (#6119)", async () => {
|
||||
const connect = vi.spyOn(commands, "remoteConnect").mockResolvedValueOnce(busy).mockResolvedValueOnce(stop);
|
||||
const prompt = vi.fn(async () => true);
|
||||
const dispose = provideBackendBusyPrompt(prompt);
|
||||
await expect(connectRemote(target, "/srv/app")).rejects.toThrow("second attempt");
|
||||
dispose();
|
||||
expect(prompt).toHaveBeenCalledOnce();
|
||||
expect(connect.mock.calls.map((c) => c[2])).toEqual([false, true]);
|
||||
});
|
||||
|
||||
it("keeps the error when the user declines", async () => {
|
||||
const connect = vi.spyOn(commands, "remoteConnect").mockResolvedValue(busy);
|
||||
const dispose = provideBackendBusyPrompt(async () => false);
|
||||
await expect(connectRemote(target, "/srv/app")).rejects.toThrow("busy");
|
||||
dispose();
|
||||
expect(connect).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("doesn't ask about other connection errors", async () => {
|
||||
vi.spyOn(commands, "remoteConnect").mockResolvedValue(stop);
|
||||
const prompt = vi.fn(async () => true);
|
||||
const dispose = provideBackendBusyPrompt(prompt);
|
||||
await expect(connectRemote(target, "/srv/app")).rejects.toThrow("second attempt");
|
||||
dispose();
|
||||
expect(prompt).not.toHaveBeenCalled();
|
||||
});
|
||||
Reference in new issue
Заблокувати користувача