Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/main/editContextMenu.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { ContextMenuParams, MenuItemConstructorOptions, WebContents } from "electron";
import type { LocaleId } from "../shared/contracts.ts";

type EditParams = Pick<ContextMenuParams, "isEditable" | "selectionText" | "editFlags">;

/**
* 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);
});
}
11 changes: 11 additions & 0 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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<typeof setTimeout> | null = null;
let updateInterval: ReturnType<typeof setInterval> | null = null;
let startupRunning = false;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -327,6 +332,7 @@ async function initializeServices(ipc: IpcRegistrar): Promise<void> {
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);
Expand Down Expand Up @@ -836,6 +842,9 @@ async function initializeServices(ipc: IpcRegistrar): Promise<void> {
if (active) browserService?.cancelCanvasNavigationGesture();
canvasNavigationInput?.setShortcutCaptureActive(active);
},
setCanvasNavigationTerminalEditFocus: (contents, active) => {
canvasNavigationInput?.setTerminalEditFocus(contents, active);
},
setCanvasNavigationPointerBinding: (input) => {
canvasNavigationInput?.updatePointerBinding(input);
},
Expand Down Expand Up @@ -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();
Expand Down
9 changes: 8 additions & 1 deletion src/main/ipc/registerIpc.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -74,6 +74,7 @@ interface Dependencies {
getMainWindow(): BrowserWindow | null;
applyBrowserSettings(settings: AppSettings): Promise<void> | void;
setCanvasNavigationShortcutCapture(active: boolean): void;
setCanvasNavigationTerminalEditFocus(contents: WebContents, active: boolean): void;
setCanvasNavigationPointerBinding(input: CanvasNavigationPointerBindingInput): void;
openPluginWindow(pluginId: string, contributionId: string): Promise<void>;
closePluginWindows(pluginId: string): void;
Expand Down Expand Up @@ -210,6 +211,7 @@ export function registerIpc(ipcMain: IpcRegistrar, {
getMainWindow,
applyBrowserSettings,
setCanvasNavigationShortcutCapture,
setCanvasNavigationTerminalEditFocus,
setCanvasNavigationPointerBinding,
openPluginWindow,
closePluginWindows,
Expand Down Expand Up @@ -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;
Expand Down
23 changes: 23 additions & 0 deletions src/main/services/CanvasNavigationOverride.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,8 @@ export class CanvasNavigationInputController {
private readonly attachedContents = new Set<WebContents>();
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<WebContents>();

constructor(
bindings: CanvasNavigationBindings,
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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;
}
1 change: 1 addition & 0 deletions src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
),
Expand Down
7 changes: 6 additions & 1 deletion src/renderer/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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]);

Expand Down
32 changes: 32 additions & 0 deletions src/renderer/src/lib/shortcuts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 3 additions & 0 deletions src/shared/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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",
Expand Down
24 changes: 24 additions & 0 deletions tests/app-shortcuts.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
matchesShortcut,
shouldKeepNativeKeyboardInput,
shortcutFromKeyboardEvent,
trackTerminalEditFocus,
shortcutFromPointerEvent
} from "../src/renderer/src/lib/shortcuts.ts";

Expand Down Expand Up @@ -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);
});
Loading
Loading