diff --git a/src/main/editContextMenu.ts b/src/main/editContextMenu.ts new file mode 100644 index 000000000..ad553d444 --- /dev/null +++ b/src/main/editContextMenu.ts @@ -0,0 +1,36 @@ +import type { ContextMenuParams, MenuItemConstructorOptions, WebContents } from "electron"; +import type { LocaleId } from "../shared/contracts.ts"; + +type EditParams = Pick; + +/** + * The right-click menu for text: Cut/Copy/Paste/Select All in an editable field (an app field or a field in a plugin + * page), Copy for selected page text, nothing elsewhere. A page that handles its own right click (the canvas, a + * terminal) cancels the DOM event, and Electron then never asks for this menu. + */ +export function editContextMenuTemplate(params: EditParams, locale: LocaleId): MenuItemConstructorOptions[] { + const ru = locale === "ru"; + const label = { cut: ru ? "Вырезать" : "Cut", copy: ru ? "Скопировать" : "Copy", paste: ru ? "Вставить" : "Paste", selectAll: ru ? "Выбрать все" : "Select All" }; + if (params.isEditable) { + return [ + { role: "cut", label: label.cut, enabled: params.editFlags.canCut }, + { role: "copy", label: label.copy, enabled: params.editFlags.canCopy }, + { role: "paste", label: label.paste, enabled: params.editFlags.canPaste }, + { type: "separator" }, + { role: "selectAll", label: label.selectAll, enabled: params.editFlags.canSelectAll } + ]; + } + if (params.selectionText.length > 0) return [{ role: "copy", label: label.copy, enabled: params.editFlags.canCopy }]; + return []; +} + +export function attachEditContextMenu( + contents: WebContents, + locale: () => LocaleId, + popup: (template: MenuItemConstructorOptions[], contents: WebContents) => void +): void { + contents.on("context-menu", (_event, params) => { + const template = editContextMenuTemplate(params, locale()); + if (template.length) popup(template, contents); + }); +} diff --git a/src/main/index.ts b/src/main/index.ts index e2fb63e29..f34f74c90 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -92,6 +92,7 @@ import { import { startupPageUrl } from "./startupPage"; import { mainWindowChromeOptions } from "./windowChrome"; import { markMainBoot, mainBootMarks } from "./bootMarks"; +import { attachEditContextMenu } from "./editContextMenu"; import { macApplicationMenuTemplate } from "./macApplicationMenu"; if (process.env.CANVASTTY_USER_DATA_DIR) { @@ -194,6 +195,8 @@ let appSurfaceReady = false; let pendingMenuUpdateCheck = false; let checkUpdatesFromMenu: (() => void) | null = null; let installMacMenu: (() => void) | null = null; +/** The locale of the text right-click menu; startApplication points it at the settings once they are loaded. */ +let editMenuLocale: () => LocaleId = () => (app.getLocale().toLowerCase().startsWith("ru") ? "ru" : "en"); let updateTimer: ReturnType | null = null; let updateInterval: ReturnType | null = null; let startupRunning = false; @@ -256,6 +259,8 @@ function createWindow(): BrowserWindow { preventMouseBindings: false, captureMacEditShortcuts: process.platform === "darwin" }); + attachEditContextMenu(window.webContents, () => editMenuLocale(), + (template, contents) => Menu.buildFromTemplate(template).popup({ window: BrowserWindow.fromWebContents(contents) ?? undefined })); // Crash recovery: a dead renderer must never leave the user staring at a // blank window. The application surface is reloaded in place — the same entry // startup loads — so services, sessions and their scrollback stay untouched @@ -327,6 +332,7 @@ async function initializeServices(ipc: IpcRegistrar): Promise { recoverKimiConfigurationOnStartup(kimiHomeDirectory); const userDataPath = app.getPath("userData"); const settings = new SettingsStore(userDataPath, app.getLocale(), process.platform, providerCliAvailability(providerClis)); + editMenuLocale = () => settings.get().locale; const terminalBorderSkins = new SkinRegistry(userDataPath); const pixelSkinPacks = new PixelSkinPackRegistry(userDataPath); pluginManager = new PluginManager(userDataPath); @@ -836,6 +842,9 @@ async function initializeServices(ipc: IpcRegistrar): Promise { if (active) browserService?.cancelCanvasNavigationGesture(); canvasNavigationInput?.setShortcutCaptureActive(active); }, + setCanvasNavigationTerminalEditFocus: (contents, active) => { + canvasNavigationInput?.setTerminalEditFocus(contents, active); + }, setCanvasNavigationPointerBinding: (input) => { canvasNavigationInput?.updatePointerBinding(input); }, @@ -1264,6 +1273,8 @@ async function openPluginWindow(pluginId: string, contributionId: string): Promi } }); pluginWindows.set(window, pluginId); + attachEditContextMenu(window.webContents, () => editMenuLocale(), + (template, contents) => Menu.buildFromTemplate(template).popup({ window: BrowserWindow.fromWebContents(contents) ?? undefined })); window.webContents.setWindowOpenHandler(() => ({ action: "deny" })); window.webContents.on("will-navigate", (event, url) => { if (!url.startsWith(`canvastty-plugin://${pluginId}/`)) event.preventDefault(); diff --git a/src/main/ipc/registerIpc.ts b/src/main/ipc/registerIpc.ts index 7c2277e96..9a3606338 100644 --- a/src/main/ipc/registerIpc.ts +++ b/src/main/ipc/registerIpc.ts @@ -1,6 +1,6 @@ import { realpath } from "node:fs/promises"; import { app, BrowserWindow, clipboard, dialog, shell } from "electron"; -import type { IpcMainEvent, IpcMainInvokeEvent, OpenDialogOptions } from "electron"; +import type { IpcMainEvent, IpcMainInvokeEvent, OpenDialogOptions, WebContents } from "electron"; import type { AppSettings, AgentChatHistoryProviderId, @@ -74,6 +74,7 @@ interface Dependencies { getMainWindow(): BrowserWindow | null; applyBrowserSettings(settings: AppSettings): Promise | void; setCanvasNavigationShortcutCapture(active: boolean): void; + setCanvasNavigationTerminalEditFocus(contents: WebContents, active: boolean): void; setCanvasNavigationPointerBinding(input: CanvasNavigationPointerBindingInput): void; openPluginWindow(pluginId: string, contributionId: string): Promise; closePluginWindows(pluginId: string): void; @@ -210,6 +211,7 @@ export function registerIpc(ipcMain: IpcRegistrar, { getMainWindow, applyBrowserSettings, setCanvasNavigationShortcutCapture, + setCanvasNavigationTerminalEditFocus, setCanvasNavigationPointerBinding, openPluginWindow, closePluginWindows, @@ -260,6 +262,11 @@ export function registerIpc(ipcMain: IpcRegistrar, { if (typeof active !== "boolean") return; setCanvasNavigationShortcutCapture(active); }); + ipcMain.on(IPC.canvasNavigationTerminalEditFocus, (event, active: boolean) => { + assertMainRenderer(event, getMainWindow); + if (typeof active !== "boolean") return; + setCanvasNavigationTerminalEditFocus(event.sender, active); + }); ipcMain.on(IPC.canvasNavigationPointerBinding, (event, input: unknown) => { assertMainRenderer(event, getMainWindow); if (!isCanvasNavigationPointerBindingInput(input)) return; diff --git a/src/main/services/CanvasNavigationOverride.ts b/src/main/services/CanvasNavigationOverride.ts index 800482766..a8f15c67d 100644 --- a/src/main/services/CanvasNavigationOverride.ts +++ b/src/main/services/CanvasNavigationOverride.ts @@ -200,6 +200,8 @@ export class CanvasNavigationInputController { private readonly attachedContents = new Set(); private readonly onActiveChange: (state: CanvasNavigationOverrideState) => void; private menuShortcutContents: WebContents | null = null; + /** Contents whose renderer reported keyboard focus in a terminal surface or shortcut recorder. */ + private readonly terminalEditFocus = new WeakSet(); constructor( bindings: CanvasNavigationBindings, @@ -233,6 +235,19 @@ export class CanvasNavigationInputController { }); } + /** + * The renderer reports whether a terminal surface or shortcut recorder has keyboard focus. Both consume + * Command+C/V/A themselves, so those shortcuts bypass the Edit menu. The terminal-named API covers both; + * ordinary fields and plugin pages keep the menu's native Copy, Paste and Select All. + */ + setTerminalEditFocus(contents: WebContents, focused: boolean): void { + if (focused) this.terminalEditFocus.add(contents); + else { + this.terminalEditFocus.delete(contents); + if (this.menuShortcutContents === contents) this.releaseMenuShortcuts(); + } + } + setBindings(bindings: CanvasNavigationBindings): void { this.releaseMenuShortcuts(); const previous = this.state(); @@ -299,6 +314,7 @@ export class CanvasNavigationInputController { const wheelTransition = this.wheelTracker.update(keyboardInput); const navigationTransition = this.navigationTracker.update(keyboardInput); const macEditShortcut = options.captureMacEditShortcuts === true + && this.terminalEditFocus.has(contents) && topFrameFocused(contents) && input.type === "keyDown" && input.meta && !input.control && !input.alt && !input.shift && (input.code === "KeyA" || input.code === "KeyC" || input.code === "KeyV"); @@ -374,3 +390,10 @@ export class CanvasNavigationInputController { } } + +/** An iframe (a plugin page) with focus is never a terminal surface; contents without the property count as top. */ +function topFrameFocused(contents: WebContents): boolean { + const focused = (contents as { focusedFrame?: unknown }).focusedFrame; + const top = (contents as { mainFrame?: unknown }).mainFrame; + return focused === undefined || focused === null || top === undefined || focused === top; +} diff --git a/src/preload/index.ts b/src/preload/index.ts index 5e1f5c304..8fc45548a 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -258,6 +258,7 @@ const api: CanvasTTYApi = { ipcRenderer.sendSync(IPC.canvasNavigationOwnerWheel, { clientX, clientY }); }, setShortcutCaptureActive: (active: boolean) => ipcRenderer.send(IPC.canvasNavigationShortcutCapture, active), + setTerminalEditFocus: (active: boolean) => ipcRenderer.send(IPC.canvasNavigationTerminalEditFocus, active), setPointerBindingState: (input: CanvasNavigationPointerBindingInput) => ( ipcRenderer.send(IPC.canvasNavigationPointerBinding, input) ), diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 74a31805a..d9ccfb589 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -77,7 +77,8 @@ import { isShortcutCaptureTarget, matchesPointerShortcut, matchesShortcut, - shouldKeepNativeKeyboardInput + shouldKeepNativeKeyboardInput, + trackTerminalEditFocus } from "./lib/shortcuts"; import { homeGridPixelSize, homeLayoutFitsGrid, placeHomeWidget } from "./features/home/homeLayout"; import { boundsInsideRegion, translateBounds } from "./features/workspace/canvasRegions"; @@ -1438,9 +1439,13 @@ export function App(): React.JSX.Element { window.addEventListener("keydown", handleShortcut, true); window.addEventListener("pointerdown", handlePointerShortcut, true); + const stopTerminalFocus = window.canvasTTY.window.isMacOS + ? trackTerminalEditFocus(document, (focused) => window.canvasTTY.canvasNavigation.setTerminalEditFocus(focused)) + : () => undefined; return () => { window.removeEventListener("keydown", handleShortcut, true); window.removeEventListener("pointerdown", handlePointerShortcut, true); + stopTerminalFocus(); }; }, [activeSessionId, fullscreenSessionId, goHome, homeEditDraft, launchProvider, pendingTerminalUrl, settings.locale, settings.shortcuts, settingsOpen, shortcutReferenceOpen, showToast, toggleSessionFullscreen]); diff --git a/src/renderer/src/lib/shortcuts.ts b/src/renderer/src/lib/shortcuts.ts index 85f3fc846..0b037c770 100644 --- a/src/renderer/src/lib/shortcuts.ts +++ b/src/renderer/src/lib/shortcuts.ts @@ -62,6 +62,38 @@ export function isRenameInputTarget(target: EventTarget | null): boolean { return target instanceof Element && Boolean(target.closest('[data-terminal-rename="true"]')); } +/** + * Renderer-owned editing includes terminal surfaces and shortcut recorders: both need Command+C/V/A delivered + * as keyboard events. The terminal-named focus API also covers these recorder controls. Ordinary fields and plugin + * pages (an iframe is the active element) use the menu's native editing. + */ +export function isTerminalEditTarget(target: EventTarget | null): boolean { + return isShortcutCaptureTarget(target) + || (target instanceof Element && Boolean(target.closest(".terminal-card__surface, .xterm"))); +} + +/** Reports changes in renderer-owned edit focus, including shortcut recorders (macOS edit-shortcut routing). */ +export function trackTerminalEditFocus(doc: Document, report: (focused: boolean) => void): () => void { + let last: boolean | null = null; + const update = (): void => { + const focused = isTerminalEditTarget(doc.activeElement); + if (focused === last) return; + last = focused; + report(focused); + }; + // focusout runs before the next element is active: read it once the move has settled. + const settle = (): void => { queueMicrotask(update); }; + doc.addEventListener("focusin", update, true); + doc.addEventListener("focusout", settle, true); + doc.defaultView?.addEventListener("blur", settle); + update(); + return () => { + doc.removeEventListener("focusin", update, true); + doc.removeEventListener("focusout", settle, true); + doc.defaultView?.removeEventListener("blur", settle); + }; +} + export function shouldKeepNativeKeyboardInput( target: EventTarget | null, _isMacOS: boolean, diff --git a/src/shared/contracts.ts b/src/shared/contracts.ts index df5fec146..7828b81b7 100644 --- a/src/shared/contracts.ts +++ b/src/shared/contracts.ts @@ -1756,6 +1756,8 @@ export interface CanvasTTYApi { canvasNavigation: { armOwnerWheelSequence(clientX: number, clientY: number): void; setShortcutCaptureActive(active: boolean): void; + /** macOS: a terminal surface gained or lost keyboard focus (decides who handles Command+C/V/A). */ + setTerminalEditFocus(active: boolean): void; setPointerBindingState(input: CanvasNavigationPointerBindingInput): void; setPointerGestureActive(active: boolean): void; onOverrideState(listener: (event: CanvasNavigationOverrideStateEvent) => void): () => void; @@ -1920,6 +1922,7 @@ export const IPC = { browserCanvasPointer: "browser:canvas-pointer", browserCanvasNavigationPointer: "browser:canvas-navigation-pointer", canvasNavigationShortcutCapture: "canvas-navigation:shortcut-capture", + canvasNavigationTerminalEditFocus: "canvas-navigation:terminal-edit-focus", canvasNavigationPointerBinding: "canvas-navigation:pointer-binding", canvasNavigationOwnerWheel: "canvas-navigation:owner-wheel", canvasNavigationPointerGesture: "canvas-navigation:pointer-gesture", diff --git a/tests/app-shortcuts.test.mjs b/tests/app-shortcuts.test.mjs index 7d6ad297c..05998bb2e 100644 --- a/tests/app-shortcuts.test.mjs +++ b/tests/app-shortcuts.test.mjs @@ -11,6 +11,7 @@ import { matchesShortcut, shouldKeepNativeKeyboardInput, shortcutFromKeyboardEvent, + trackTerminalEditFocus, shortcutFromPointerEvent } from "../src/renderer/src/lib/shortcuts.ts"; @@ -205,3 +206,26 @@ test("App restores native Command+A before its native-input guard without interc assert.equal(otherPlatform.selectionStart, 4); assert.deepEqual(actions, []); }); + +test("terminal keyboard focus is reported on change only; a plugin iframe or app field is not a terminal", async (t) => { + const previousElement = globalThis.Element; + class FakeElement { constructor(selector) { this.selector = selector; } closest(query) { return this.selector && query.includes(this.selector) ? this : null; } } + globalThis.Element = FakeElement; + t.after(() => { if (previousElement === undefined) delete globalThis.Element; else globalThis.Element = previousElement; }); + const listeners = new Map(); + const doc = { + activeElement: new FakeElement(null), + addEventListener: (type, fn) => listeners.set(type, fn), + removeEventListener: (type) => listeners.delete(type), + defaultView: { addEventListener() {}, removeEventListener() {} } + }; + const reports = []; + const stop = trackTerminalEditFocus(doc, (focused) => reports.push(focused)); + doc.activeElement = new FakeElement(".xterm"); listeners.get("focusin")(); + doc.activeElement = new FakeElement(".xterm"); listeners.get("focusin")(); + doc.activeElement = new FakeElement(null); listeners.get("focusout")(); // e.g. the plugin iframe took focus + await new Promise((resolve) => queueMicrotask(resolve)); + assert.deepEqual(reports, [false, true, false]); + stop(); + assert.equal(listeners.size, 0); +}); diff --git a/tests/canvas-navigation-override.test.mjs b/tests/canvas-navigation-override.test.mjs index f3016aa64..d2985208a 100644 --- a/tests/canvas-navigation-override.test.mjs +++ b/tests/canvas-navigation-override.test.mjs @@ -7,6 +7,8 @@ import { shouldPreventCanvasNavigationInput } from "../src/main/services/CanvasNavigationOverride.ts"; +import { trackTerminalEditFocus } from "../src/renderer/src/lib/shortcuts.ts"; + const input = (type, key, modifiers = {}) => ({ type, key, @@ -230,7 +232,7 @@ test("modifier-only Meta full override does not swallow ordinary Command shortcu assert.equal(prevented, false); }); -test("macOS Select All, Copy and Paste reach the renderer without capturing other Command shortcuts", () => { +test("macOS Select All, Copy and Paste reach a focused terminal without capturing other Command shortcuts", () => { const contents = new EventEmitter(); const ignored = []; contents.isDestroyed = () => false; @@ -240,6 +242,7 @@ test("macOS Select All, Copy and Paste reach the renderer without capturing othe navigationBinding: null }, () => undefined); controller.attach(contents, { captureMacEditShortcuts: true }); + controller.setTerminalEditFocus(contents, true); let prevented = false; const event = { preventDefault: () => { prevented = true; } }; @@ -430,3 +433,99 @@ test("changing a binding resets pressed state instead of activating it retroacti }); assert.equal(tracker.active, false); }); + +test("macOS Command+C/V/A keep the Edit menu in ordinary fields and plugin pages; only a focused terminal captures them", () => { + const top = { name: "top" }; + const pluginFrame = { name: "plugin iframe" }; + const contents = new EventEmitter(); + const ignored = []; + contents.isDestroyed = () => false; + contents.setIgnoreMenuShortcuts = (active) => ignored.push(active); + contents.mainFrame = top; + contents.focusedFrame = top; + const controller = new CanvasNavigationInputController({ wheelBinding: null, navigationBinding: null }, () => undefined); + controller.attach(contents, { captureMacEditShortcuts: true }); + const event = { preventDefault: () => assert.fail("editing keys are never cancelled") }; + const pressV = () => { + contents.emit("before-input-event", event, input("keyDown", "v", { code: "KeyV", meta: true })); + contents.emit("before-input-event", event, input("keyUp", "v", { code: "KeyV", meta: true })); + }; + + // An app field (no terminal focus reported): the menu's native Paste must run. + pressV(); + assert.deepEqual(ignored, [], "an ordinary field keeps Edit > Paste"); + + // A plugin page's field: the iframe has focus, even if a terminal had focus before. + controller.setTerminalEditFocus(contents, true); + contents.focusedFrame = pluginFrame; + pressV(); + assert.deepEqual(ignored, [], "a plugin iframe keeps Edit > Paste"); + + // Back in the terminal: captured for xterm's own paste. + contents.focusedFrame = top; + pressV(); + assert.deepEqual(ignored, [true, false]); + + // Focus leaves the terminal while the capture is held: it is released at once. + contents.emit("before-input-event", event, input("keyDown", "c", { code: "KeyC", meta: true })); + controller.setTerminalEditFocus(contents, false); + assert.deepEqual(ignored, [true, false, true, false]); + pressV(); + assert.deepEqual(ignored, [true, false, true, false]); +}); + + +test("focused shortcut recorders receive Command+A/C/V while ordinary fields keep native editing", (t) => { + const previousElement = globalThis.Element; + class FakeElement { + constructor(selector) { this.selector = selector; } + closest(query) { return query.includes(this.selector) ? this : null; } + } + globalThis.Element = FakeElement; + t.after(() => { + if (previousElement === undefined) delete globalThis.Element; + else globalThis.Element = previousElement; + }); + const top = {}; + const contents = new EventEmitter(); + const ignored = []; + contents.isDestroyed = () => false; + contents.setIgnoreMenuShortcuts = (active) => ignored.push(active); + contents.mainFrame = top; + contents.focusedFrame = top; + const controller = new CanvasNavigationInputController({ wheelBinding: "Meta", navigationBinding: "Alt" }, () => undefined); + controller.attach(contents, { captureMacEditShortcuts: true }); + // The canvas-navigation recorder suspends these bindings while listening for its new chord. + controller.setShortcutCaptureActive(true); + const listeners = new Map(); + const doc = { + activeElement: new FakeElement("input"), + addEventListener: (type, fn) => listeners.set(type, fn), + removeEventListener: (type) => listeners.delete(type), + defaultView: { addEventListener() {}, removeEventListener() {} } + }; + const stop = trackTerminalEditFocus(doc, (focused) => controller.setTerminalEditFocus(contents, focused)); + t.after(stop); + const pressEditKeys = () => { + for (const key of ["a", "c", "v"]) { + const event = { preventDefault: () => assert.fail("the renderer must receive recorder keyboard events") }; + contents.emit("before-input-event", event, input("keyDown", key, { code: `Key${key.toUpperCase()}`, meta: true })); + contents.emit("before-input-event", event, input("keyUp", key, { code: `Key${key.toUpperCase()}`, meta: true })); + } + }; + pressEditKeys(); + assert.deepEqual(ignored, [], "ordinary inputs retain the native Edit menu"); + doc.activeElement = new FakeElement('[data-shortcut-capture="true"]'); + listeners.get("focusin")(); + pressEditKeys(); + assert.deepEqual(ignored, [true, false, true, false, true, false], "all three chords bypass the menu for the recorder"); + ignored.length = 0; + contents.focusedFrame = {}; + pressEditKeys(); + assert.deepEqual(ignored, [], "a focused plugin frame still uses native editing even with a stale recorder report"); + contents.focusedFrame = top; + doc.activeElement = new FakeElement("textarea"); + listeners.get("focusin")(); + pressEditKeys(); + assert.deepEqual(ignored, [], "leaving the recorder restores native editing"); +}); diff --git a/tests/edit-context-menu.test.mjs b/tests/edit-context-menu.test.mjs new file mode 100644 index 000000000..b58e6f957 --- /dev/null +++ b/tests/edit-context-menu.test.mjs @@ -0,0 +1,85 @@ +import assert from "node:assert/strict"; +import { EventEmitter } from "node:events"; +import { readFile } from "node:fs/promises"; +import { stripTypeScriptTypes } from "node:module"; +import { join } from "node:path"; +import { runInNewContext } from "node:vm"; +import test from "node:test"; +import { attachEditContextMenu, editContextMenuTemplate } from "../src/main/editContextMenu.ts"; + +const flags = { canCut: true, canCopy: true, canPaste: true, canSelectAll: true, canUndo: false, canRedo: false, canDelete: true, canEditRichly: false }; + +test("an editable field (app or plugin page) gets native Cut, Copy, Paste and Select All", () => { + const template = editContextMenuTemplate({ isEditable: true, selectionText: "", editFlags: flags }, "ru"); + assert.deepEqual(template.filter(item => item.role).map(item => [item.role, item.label]), + [["cut", "Вырезать"], ["copy", "Скопировать"], ["paste", "Вставить"], ["selectAll", "Выбрать все"]]); + const empty = editContextMenuTemplate({ isEditable: true, selectionText: "", editFlags: { ...flags, canCut: false, canCopy: false } }, "en"); + assert.deepEqual(empty.filter(item => item.role).map(item => [item.role, item.enabled]), + [["cut", false], ["copy", false], ["paste", true], ["selectAll", true]]); +}); + +test("selected page text gets Copy only; anything else gets no menu", () => { + assert.deepEqual(editContextMenuTemplate({ isEditable: false, selectionText: "abc", editFlags: flags }, "en").map(item => item.role), ["copy"]); + for (const selectionText of [" ", "\t", "\n", " \t\n"]) { + assert.deepEqual(editContextMenuTemplate({ isEditable: false, selectionText, editFlags: flags }, "en"), + [{ role: "copy", label: "Copy", enabled: true }]); + } + assert.deepEqual(editContextMenuTemplate({ isEditable: false, selectionText: "", editFlags: flags }, "en"), []); +}); + +test("the context-menu event pops the menu only when there is something to show", () => { + const contents = new EventEmitter(); + const shown = []; + attachEditContextMenu(contents, () => "en", (template) => shown.push(template.map(item => item.role ?? item.type))); + contents.emit("context-menu", {}, { isEditable: true, selectionText: "", editFlags: flags }); + contents.emit("context-menu", {}, { isEditable: false, selectionText: "", editFlags: flags }); + assert.deepEqual(shown, [["cut", "copy", "paste", "separator", "selectAll"]]); +}); + + +test("a standalone plugin window gets its native edit menu before loading and uses the current locale", async () => { + const source = await readFile(new URL("../src/main/index.ts", import.meta.url), "utf8"); + const start = source.indexOf("async function openPluginWindow("); + const end = source.indexOf("function closePluginWindows(", start); + assert.ok(start >= 0 && end > start); + const windows = []; + const shown = []; + let locale = "en"; + class BrowserWindow extends EventEmitter { + constructor() { + super(); + this.webContents = new EventEmitter(); + this.webContents.setWindowOpenHandler = () => {}; + windows.push(this); + } + static fromWebContents(contents) { + return windows.find(window => window.webContents === contents); + } + async loadURL(url) { + assert.equal(url, "canvastty-plugin://test/window.html"); + this.webContents.emit("context-menu", {}, { isEditable: true, selectionText: "", editFlags: flags }); + assert.equal(shown.length, 1, "the page can request an edit menu as soon as loading starts"); + } + } + const openPluginWindow = runInNewContext(`${stripTypeScriptTypes(source.slice(start, end))}; openPluginWindow`, { + BrowserWindow, + appIcon: undefined, + join, + __dirname: "/test/main", + pluginWindows: new Map(), + pluginManager: { + contribution: () => ({ kind: "window", title: "Test", defaultSize: { width: 400, height: 300 } }), + entryUrl: () => "canvastty-plugin://test/window.html" + }, + attachEditContextMenu, + editMenuLocale: () => locale, + Menu: { buildFromTemplate: template => ({ popup: options => shown.push({ template, window: options.window }) }) } + }); + await openPluginWindow("test", "window"); + assert.equal(shown[0].window, windows[0]); + assert.deepEqual(shown[0].template.filter(item => item.role).map(item => item.role), ["cut", "copy", "paste", "selectAll"]); + locale = "ru"; + windows[0].webContents.emit("context-menu", {}, { isEditable: false, selectionText: " \t", editFlags: flags }); + assert.equal(shown[1].window, windows[0]); + assert.deepEqual(shown[1].template, [{ role: "copy", label: "Скопировать", enabled: true }]); +});