diff --git a/apps/lutra-desktop/src/screenshot.rs b/apps/lutra-desktop/src/screenshot.rs index cbf702e..961c534 100644 --- a/apps/lutra-desktop/src/screenshot.rs +++ b/apps/lutra-desktop/src/screenshot.rs @@ -39,7 +39,8 @@ const CAPTURE_TIMEOUT: Duration = Duration::from_secs(10); /// /// # Errors /// A message if the window does not exist or is minimised, the capture fails -/// or times out, the result is not a PNG, or the file cannot be written. +/// or times out, the result is not a PNG, or the file cannot be written (or +/// is missing or short when read back). pub fn capture_window(app: &AppHandle, label: &str, path: &Path) -> Result<(), String> { let window = app .get_webview_window(label) @@ -55,7 +56,17 @@ pub fn capture_window(app: &AppHandle, label: &str, path: &Path) -> Result<(), S if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?; } - std::fs::write(path, png).map_err(|e| format!("{}: {e}", path.display())) + std::fs::write(path, &png).map_err(|e| format!("{}: {e}", path.display()))?; + match std::fs::metadata(path) { + Ok(meta) if meta.len() == png.len() as u64 => Ok(()), + Ok(meta) => Err(format!( + "{}: wrote {} of {} bytes", + path.display(), + meta.len(), + png.len() + )), + Err(e) => Err(format!("{}: not found after writing: {e}", path.display())), + } } /// Checks that `bytes` start with the PNG signature and stay within diff --git a/crates/control/src/methods.rs b/crates/control/src/methods.rs index 54d01e7..16c4091 100644 --- a/crates/control/src/methods.rs +++ b/crates/control/src/methods.rs @@ -12,6 +12,8 @@ pub const ENGINE_EXECUTE: &str = "engine.execute"; /// `engine.listCommands`: lists the engine's commands. pub const ENGINE_LIST_COMMANDS: &str = "engine.listCommands"; /// `ui.screenshot`: writes a PNG of the main window without focusing it. +/// A relative `path` is resolved against the app's working directory; the +/// result names the absolute path written. pub const UI_SCREENSHOT: &str = "ui.screenshot"; /// `events.subscribe`: streams engine events on this connection. pub const EVENTS_SUBSCRIBE: &str = "events.subscribe"; diff --git a/crates/control/src/protocol.rs b/crates/control/src/protocol.rs index c8161ca..255d72b 100644 --- a/crates/control/src/protocol.rs +++ b/crates/control/src/protocol.rs @@ -190,10 +190,13 @@ fn dispatch(request: Request, backend: &dyn Backend) -> Response { Err(e) => Response::err(id, "internal", e.to_string()), }, UI_SCREENSHOT => match serde_json::from_value::(params) { - Ok(p) => match backend.screenshot(&p.path) { - Ok(()) => Response::ok(id, json!({ "path": p.path })), - Err(message) => Response::err(id, codes::SCREENSHOT_FAILED, message), - }, + Ok(p) => { + let path = std::path::absolute(&p.path).unwrap_or(p.path); + match backend.screenshot(&path) { + Ok(()) => Response::ok(id, json!({ "path": path })), + Err(message) => Response::err(id, codes::SCREENSHOT_FAILED, message), + } + } Err(e) => Response::err(id, codes::INVALID_PARAMS, e.to_string()), }, APP_AUTH => Response::ok(id, json!({ "authenticated": true })), @@ -256,10 +259,12 @@ mod tests { } fn screenshot(&self, path: &Path) -> Result<(), String> { - if path.as_os_str() == "panic" { - panic!("screenshot exploded"); + assert!(path.is_absolute(), "{}", path.display()); + match path.file_name().and_then(|n| n.to_str()) { + Some("panic") => panic!("screenshot exploded"), + Some("ok.png") => Ok(()), + _ => Err("no window".into()), } - Err("no window".into()) } fn subscribe(&self, _sink: crate::EventSink) {} @@ -332,6 +337,14 @@ mod tests { ); } + #[test] + fn screenshot_reports_the_absolute_path() { + let r = call(r#"{"id":1,"method":"ui.screenshot","params":{"path":"shots/ok.png"}}"#); + let path = std::path::PathBuf::from(r.result.unwrap()["path"].as_str().unwrap()); + assert!(path.is_absolute()); + assert!(path.ends_with("shots/ok.png")); + } + #[test] fn backend_panics_become_internal_errors() { let r = call(r#"{"id":9,"method":"ui.screenshot","params":{"path":"panic"}}"#); diff --git a/docs/architecture.md b/docs/architecture.md index 3701e03..d94fe77 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -61,7 +61,7 @@ As built in M0: - Transport: one JSON object per line, UTF-8, at most 16 MiB per line; longer lines get an error response and the connection is closed. - Request: `{"id": , "method": "", "params": {...}}`. Response: `{"id": ..., "result": ...}` or `{"id": ..., "error": {"code": "...", "message": "..."}}`. A line that is not valid JSON gets an error response with `"id": null`. -- Methods: `app.ping`, `app.auth {token}`, `app.focus`, `engine.execute {command, params}`, `engine.listCommands`, `ui.screenshot {path}`, `events.subscribe`. Names and docs live in `crates/control/src/methods.rs`. +- Methods: `app.ping`, `app.auth {token}`, `app.focus`, `engine.execute {command, params}`, `engine.listCommands`, `ui.screenshot {path}` (→ `{path}`, absolute; the file is read back after writing and a missing or short file is an error), `events.subscribe`. Names and docs live in `crates/control/src/methods.rs`. - `events.subscribe` answers `{subscribed: true}` and from then on writes `{"event": {...}}` lines for every engine event on that connection, between responses; a shared writer writes each line whole. Subscribing twice is a no-op. Each subscriber has a queue of 4096 events (`lutra_control::EVENT_QUEUE`); a subscriber that falls behind or disconnects is dropped by `Subscribers::publish`, and the connection gets a final `{"event": {"kind": "subscriptionLost"}}` line if it is still open. - `lutra_control` defines a `Backend` trait; the desktop app implements it (engine access, effects, screenshots, event subscribers), tests implement it with a bare engine (`lutra_testkit::EngineBackend`). Hosts publish each outcome's events through `lutra_control::Subscribers`. One thread accepts connections and each connection gets its own thread; no async runtime is needed in the crate. - Screenshots never focus, raise or show the window; `app.focus` is the only method that does. On Windows the webview captures itself with WebView2 `CapturePreview` (PNG into a memory stream, scheduled on the main thread through `with_webview`, the control thread waits up to 10 s), so windows covering Lutra do not appear and the native title bar is not part of the image (`apps/lutra-desktop/src/screenshot/webview2.rs`). Fallback on macOS and Linux until WKWebView's and WebKitGTK's snapshot APIs are wired: `xcap` captures the screen region under the client area (it does not enumerate windows of its own process, whose title queries can deadlock), without focusing, so covering windows appear (`screenshot/region.rs`). A capture that does not arrive within 10 s is explained: the main thread never ran the request (blocked), or WebView2 accepted it but drew no frame; in that case the page's `document.visibilityState` is read and a hidden page is reported with its likely causes (locked session, display asleep, minimised or on another virtual desktop). Covered, off-screen and DWM-cloaked windows capture fine (checked on Windows 11). A `--control` instance builds its window and webview with `focused(false)`; when it is started from the foreground app's process tree it still becomes the foreground window about 1 s after start (seen 2026-10-29; see `docs/gaps.md`). The ignored test `apps/lutra-desktop/tests/screenshot_focus.rs` starts a built app and fails if its window is ever in the foreground while it starts and takes screenshots. diff --git a/ui/src/components/layout/MainLayout.vue b/ui/src/components/layout/MainLayout.vue index 7a19b3d..65d4218 100644 --- a/ui/src/components/layout/MainLayout.vue +++ b/ui/src/components/layout/MainLayout.vue @@ -35,7 +35,8 @@ * path, of the active editor tab's file); neither has a default shortcut. * `vcs.showCommit {hash}` (M4.7) shows the Log with that commit selected * (a click on a blame annotation); `vcs.toggleBlame {path?}` shows or - * hides the blame annotations of a file (default: the active tab's). No + * hides the blame annotations of a file (default: the active tab's, once + * tabs for buffers just opened are adopted). No * default shortcuts. * * A slim header bar along the top (M3.9) holds the app menu @@ -248,8 +249,11 @@ onMounted(() => { enabled: () => project.root !== null, }), commands.provide(TOGGLE_BLAME_COMMAND, { - run: (params) => { + run: async (params) => { const given = (params as { path?: unknown } | null)?.path; + if (typeof given !== "string" || given === "") { + await editor.adopted(); + } const path = typeof given === "string" && given !== "" ? given : editor.activeTab?.path; if (path !== undefined) { toggleBlame(path); diff --git a/ui/src/components/problems/ProblemsToolWindow.vue b/ui/src/components/problems/ProblemsToolWindow.vue index 2d58da2..6803403 100644 --- a/ui/src/components/problems/ProblemsToolWindow.vue +++ b/ui/src/components/problems/ProblemsToolWindow.vue @@ -68,13 +68,27 @@ const status = computed(() => { return t("problems.empty"); } const c = problems.counts; + const others = c.info + c.hint; return t("problems.summary", { - errors: String(c.error), - warnings: String(c.warning), - infos: String(c.info + c.hint), + errors: + c.error === 1 ? t("problems.count.error.one") : t("problems.count.error.other", { count: String(c.error) }), + warnings: + c.warning === 1 + ? t("problems.count.warning.one") + : t("problems.count.warning.other", { count: String(c.warning) }), + infos: t("problems.count.other", { count: String(others) }), }); }); +/** + * The tooltip of a file's problem count, singular for one. + * + * @param count - the file's problems. + */ +function fileCountTitle(count: number): string { + return count === 1 ? t("problems.file.count.one") : t("problems.file.count.other", { count: String(count) }); +} + /** A file with its rows and their indexes in the flat list. */ interface ProblemGroup { /** Project-relative path. */ @@ -238,7 +252,7 @@ watch( {{ dirName(group.path) }} {{ group.rows.length }}
{ closePrompt.value = null; } + /** Adoptions of `bufferOpened` buffers still fetching their state. */ + const adopting = new Set>(); + /** * Adds a tab for a buffer opened elsewhere (control channel, replay after * a reload), fetching its text first. When several open at once, the @@ -445,6 +448,15 @@ export const useEditorStore = defineStore("editor", () => { } } + /** + * Waits until the tabs of buffers opened so far are adopted, so a + * command right after `file.open` (over the control channel) sees the + * new tab as the active one. + */ + async function adopted(): Promise { + await Promise.all([...adopting]); + } + /** * Activates the tab of a buffer that `file.open` found already open * (`bufferFocused`). It also outranks adoptions still fetching, so the @@ -468,9 +480,12 @@ export const useEditorStore = defineStore("editor", () => { case "projectClosed": clear(); break; - case "bufferOpened": - void adoptOpened(event.id); + case "bufferOpened": { + const adoption = adoptOpened(event.id); + adopting.add(adoption); + void adoption.finally(() => adopting.delete(adoption)); break; + } case "bufferFocused": focusOpened(event.id); break; @@ -523,6 +538,7 @@ export const useEditorStore = defineStore("editor", () => { tabs, activeId, activeTab, + adopted, closePrompt, lastError, lastOpen, diff --git a/ui/tests/problems/ProblemsToolWindow.test.ts b/ui/tests/problems/ProblemsToolWindow.test.ts index 968aef3..08f1052 100644 --- a/ui/tests/problems/ProblemsToolWindow.test.ts +++ b/ui/tests/problems/ProblemsToolWindow.test.ts @@ -211,7 +211,15 @@ describe("ProblemsToolWindow", () => { items: [diag(4, "warning", "Unused variable"), { ...diag(1, "error", "Undefined method"), code: "E12" }], }); await emit({ kind: "diagnosticsChanged", path: "a.php", items: [diag(0, "hint", "Could be final")] }); - expect(wrapper.get("[data-test=problems-status]").text()).toBe("Errors: 1, warnings: 1, other: 1"); + expect(wrapper.get("[data-test=problems-status]").text()).toBe("1 error, 1 warning, 1 other"); + expect(wrapper.findAll(".problems__file-count").map((c) => c.attributes("title"))).toEqual(["1 problem", "2 problems"]); + await emit({ + kind: "diagnosticsChanged", + path: "b.php", + items: [diag(0, "error", "One"), diag(1, "error", "Two")], + }); + expect(wrapper.get("[data-test=problems-status]").text()).toBe("3 errors, 1 warning, 1 other"); + await emit({ kind: "diagnosticsChanged", path: "b.php", items: [] }); const files = wrapper.findAll("[data-test=problems-file]").map((f) => f.text()); expect(files[0]).toContain("a.php"); expect(files[1]).toContain("Service.php"); diff --git a/ui/tests/vcs/Log.test.ts b/ui/tests/vcs/Log.test.ts index 0a68b8d..1d4d142 100644 --- a/ui/tests/vcs/Log.test.ts +++ b/ui/tests/vcs/Log.test.ts @@ -37,6 +37,7 @@ import { useLogStore, } from "../../src/components/vcs/log/log"; import LogToolWindow from "../../src/components/vcs/log/LogToolWindow.vue"; +import { useEditorStore } from "../../src/stores/editor"; import { useNotificationsStore } from "../../src/stores/notifications"; import { useProjectStore } from "../../src/stores/project"; @@ -139,6 +140,8 @@ function execute(command: string, p: Record): Promise truncated: false, }); } + case "buffer.get": + return Promise.resolve({ id: p.id, path: "src/opened.php", text: " { expect(isBlameShown("src/a.php")).toBe(true); await commands.execute(TOGGLE_BLAME_COMMAND, { path: "src/a.php" }); expect(isBlameShown("src/a.php")).toBe(false); + + useEditorStore(pinia).handleEvent({ kind: "bufferOpened", id: 5, path: "src/opened.php" }); + await commands.execute(TOGGLE_BLAME_COMMAND, {}); + expect(isBlameShown("src/opened.php")).toBe(true); }); });