дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-29 22:02:59 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
7fd1ae9aa7 | ||
|
|
a4ad387085 | ||
|
|
f8a148c06d | ||
|
|
aa1a027162 | ||
|
|
b30716e22c | ||
|
|
7fb21003f3 | ||
|
|
ad8d32d9c7 | ||
|
|
08aef06844 |
No files matched your search
@@ -1696,16 +1696,39 @@ 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 body = session
|
||||
.conn
|
||||
.request_timeout(
|
||||
let request = |start: u64, levels: u64| {
|
||||
session.conn.request_timeout(
|
||||
"stackTrace",
|
||||
json!({ "threadId": thread_id, "startFrame": 0, "levels": 400 }),
|
||||
json!({ "threadId": thread_id, "startFrame": start, "levels": levels }),
|
||||
REQUEST_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
};
|
||||
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()),
|
||||
};
|
||||
let kotlin_lsp = session.kotlin_lsp_quirks().is_some();
|
||||
let frame = |f: &Value| {
|
||||
let mut frame = frame_from(f);
|
||||
@@ -1717,7 +1740,7 @@ impl DebugManager {
|
||||
}
|
||||
frame
|
||||
};
|
||||
Ok(body.get("stackFrames").and_then(Value::as_array).map(|f| f.iter().map(frame).collect()).unwrap_or_default())
|
||||
Ok(raw.iter().map(frame).collect())
|
||||
}
|
||||
|
||||
pub async fn scopes(&self, s: DebugSessionId, frame_id: i64) -> IdeResult<Vec<Scope>> {
|
||||
|
||||
@@ -126,6 +126,8 @@ 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.
|
||||
@@ -206,6 +208,7 @@ 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,
|
||||
@@ -520,6 +523,20 @@ 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": [
|
||||
@@ -2332,6 +2349,21 @@ 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() {
|
||||
|
||||
@@ -152,7 +152,9 @@ 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)).
|
||||
[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.
|
||||
|
||||
## 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) 中的“菜单”一节)。
|
||||
不认识的字段类型则直接省略。条目右键菜单使用 `viewItem.context`(见 [命令与动作](/zh/plugins/guides/commands) 中的“菜单”一节)。视图有键盘焦点时,用快捷键(或查找动作)运行选中条目的右键菜单里有的命令,命令参数是该条目的 key,与从菜单运行相同;未选中条目时没有参数。
|
||||
|
||||
## 自定义编辑器
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
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,7 +170,11 @@ 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.
|
||||
The menu is new in API 1.2, so a plugin using it declares
|
||||
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
|
||||
`engines.openidea = "^1.2"`. For example:
|
||||
|
||||
```toml
|
||||
|
||||
@@ -463,7 +463,23 @@ pub fn menu_model(app: AppHandle, state: State<'_, AppState>, menu_state: State<
|
||||
}
|
||||
let home = dirs::home_dir();
|
||||
let config = menu_state.config.lock().clone();
|
||||
menu::model(&spec, &menu::recent_items(&state.recent.list(), home.as_deref()), &config)
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
/// Action ids the focused window cannot run now: their native menu items are
|
||||
@@ -996,6 +1012,7 @@ 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,6 +1117,31 @@ 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.
|
||||
@@ -1193,18 +1218,28 @@ pub struct RecentItem {
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
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()
|
||||
/// 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()
|
||||
}
|
||||
|
||||
/// One top-level menu, as it will actually be drawn.
|
||||
@@ -1746,7 +1781,7 @@ pub fn install<R: Runtime>(app: &AppHandle<R>, menu_state: &MenuState, recent: &
|
||||
return;
|
||||
}
|
||||
let home = dirs::home_dir();
|
||||
let items = recent_items(recent, home.as_deref());
|
||||
let items = recent_items(recent, &menu_state.remote_recent.lock(), 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);
|
||||
@@ -2233,11 +2268,39 @@ 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(
|
||||
|
||||
@@ -429,6 +429,7 @@ 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
|
||||
|
||||
@@ -1162,6 +1162,8 @@ 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).
|
||||
@@ -12166,6 +12168,19 @@ 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 = {
|
||||
|
||||
@@ -12,6 +12,7 @@ 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();
|
||||
@@ -51,6 +52,7 @@ 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),
|
||||
},
|
||||
@@ -266,6 +268,14 @@ 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,6 +20,7 @@ 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";
|
||||
@@ -258,6 +259,7 @@ 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 } from "@/platform/remote";
|
||||
import { connectRemote, isRemoteWindow, parseRemoteLocation } from "@/platform/remote";
|
||||
import { holdSplash } from "@/platform/splash";
|
||||
import { editorService, maybeEditorService, notifications } from "@/workbench/contributions";
|
||||
import { chooseProjectWindow, type ProjectWindowOverride } from "@/workbench/projectWindow";
|
||||
import { chooseProjectWindow, openRemoteProject, type ProjectWindowOverride } from "@/workbench/projectWindow";
|
||||
import { openTabColorPicker } from "@/workbench/TabColorPicker";
|
||||
import { cycleWindowTab, useWindowGroup } from "@/platform/windowGroups";
|
||||
import { editorSwitching } from "@/editor/api";
|
||||
@@ -606,7 +606,15 @@ export function windowActions(): Action[] {
|
||||
hidden: true,
|
||||
run: async (c) => {
|
||||
const recent = recentProjectArg(c.arg);
|
||||
if (recent) await openProjectWithPolicy(recent.path, [], recent.window);
|
||||
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);
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -82,6 +82,25 @@ 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);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* (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";
|
||||
@@ -96,6 +97,8 @@ 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;
|
||||
@@ -1296,16 +1299,19 @@ 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) {
|
||||
console.warn("stackTrace failed", e);
|
||||
logError("Debugger stack trace", e);
|
||||
framesError = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
const s = useDebug.getState().sessions[id];
|
||||
if (!s || s.status !== "paused" || s.selectedThread !== threadId || s.frames !== before?.frames) return;
|
||||
patch(id, { frames });
|
||||
patch(id, { frames, framesError });
|
||||
const top = topFrame(frames);
|
||||
if (newStop && top?.path && (s.stopReason === "breakpoint" || s.stopReason === "function breakpoint")) {
|
||||
void logSuspendingHit(id, top);
|
||||
|
||||
@@ -200,6 +200,14 @@
|
||||
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,6 +10,7 @@ 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,
|
||||
@@ -476,6 +477,14 @@ 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
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
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 { registerAction } from "@/platform/actions";
|
||||
import { executeAction, 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 { PluginView, treeNodes, wantedViewport } from "../views/PluginView";
|
||||
import { focusedViewItem, PluginView, treeNodes, wantedViewport } from "../views/PluginView";
|
||||
import { bumpView } from "../views/viewStore";
|
||||
|
||||
let undefinePoints: () => void = () => {};
|
||||
@@ -341,6 +341,70 @@ 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,6 +18,7 @@ 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 }`. */
|
||||
@@ -244,7 +245,8 @@ export function defineCoreUiPoints(): () => void {
|
||||
keywords: ["plugin", plugin.name, pluginId],
|
||||
description: tx`From plugin ${plugin.name}`,
|
||||
run: async ({ arg }: { arg?: unknown }) => {
|
||||
const [path, paths] = commandArgs(arg);
|
||||
// A shortcut passes nothing: the plugin's focused view supplies its selected item.
|
||||
const [path, paths] = commandArgs(arg ?? focusedViewItem(pluginId, action.id));
|
||||
await runPluginCommand(pluginId, decl.id, path, paths);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -163,10 +163,9 @@ 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"]],
|
||||
DEFAULT_METADATA: [
|
||||
["FOREGROUND", "--syn-annotation"],
|
||||
["FOREGROUND", "--syn-decorator"],
|
||||
],
|
||||
// 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_OPERATION_SIGN: [["FOREGROUND", "--syn-punct"]],
|
||||
DEFAULT_VALID_STRING_ESCAPE: [["FOREGROUND", "--syn-escape"]],
|
||||
DEFAULT_TAG: [["FOREGROUND", "--syn-tag"]],
|
||||
|
||||
@@ -62,6 +62,34 @@ 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();
|
||||
@@ -154,8 +182,19 @@ 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 className={styles.view} aria-label={label}>
|
||||
<div
|
||||
ref={(el) => {
|
||||
if (el && itemMenu) viewMenus.set(el, itemMenu);
|
||||
}}
|
||||
className={styles.view}
|
||||
aria-label={label}
|
||||
data-plugin-view={pluginId}
|
||||
data-selected-key={currentKey}
|
||||
>
|
||||
{content.toolbar.length > 0 && (
|
||||
<div className={styles.toolbar} role="toolbar">
|
||||
{content.toolbar.map((b) =>
|
||||
|
||||
@@ -20,8 +20,16 @@ export function packageKindAt(
|
||||
): PackageKind | null {
|
||||
if (rootFor(roots, rel)?.kind === "excluded") return null;
|
||||
if (isJvmSourcePackage(rel, roots)) return "jvm";
|
||||
const python = [...roots, ...detected].some(
|
||||
(r) => r.detectedFrom && PY_BUILD.test(r.detectedFrom) && within(rel, moduleDir(r.detectedFrom)),
|
||||
);
|
||||
return python ? "python" : null;
|
||||
// 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;
|
||||
}
|
||||
@@ -72,6 +72,25 @@ 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/);
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
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));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -25,6 +25,7 @@ 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,
|
||||
@@ -262,12 +263,8 @@ 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.
|
||||
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;
|
||||
}
|
||||
const shift = survivingRowShift(previous, commits, top);
|
||||
if (shift !== null) element.scrollTop += shift * row;
|
||||
}, [commits, revealTick, selectedIndex, row]);
|
||||
const finished = done;
|
||||
const virtualizer = useVirtualizer({
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
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;
|
||||
}
|
||||
@@ -4073,5 +4073,6 @@
|
||||
"* 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"
|
||||
"Stop Backend and Open": "Stop Backend and Open",
|
||||
"Could not load the frames: {0}": "Could not load the frames: {0}"
|
||||
}
|
||||
@@ -10407,5 +10407,6 @@
|
||||
"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": "停止后端并打开"
|
||||
"Stop Backend and Open": "停止后端并打开",
|
||||
"Could not load the frames: {0}": "无法加载栈帧:{0}"
|
||||
}
|
||||
@@ -455,6 +455,21 @@ 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">) =>
|
||||
|
||||
Reference in new issue
Заблокувати користувача