Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(desktop): capture a screen region to a note with a shortcut

tianma-ifd869aa660735
diff --git a/apps/desktop/src/main/desktop-menu.mjs b/apps/desktop/src/main/desktop-menu.mjs
index 764be1d2..cffe500f 100644
--- a/apps/desktop/src/main/desktop-menu.mjs
+++ b/apps/desktop/src/main/desktop-menu.mjs
@@ -109,3 +109,40 @@ export const desktopMenuCopy = (locale) => {
if (normalized === "pl" || normalized.startsWith("pl-")) return menuCopy.pl;
return menuCopy.en;
};
+
+const regionCopy = {
+ en: {
+ hint: "Drag to select an area. Release to save it as a note",
+ cancel: "Esc to cancel",
+ full: "Double-click to capture the whole screen",
+ },
+ zh: {
+ hint: "拖拽选择区域,松开后保存为笔记",
+ cancel: "Esc 取消",
+ full: "双击截取整个屏幕",
+ },
+ pl: {
+ hint: "Przeciągnij, aby zaznaczyć obszar. Puść, aby zapisać jako notatkę",
+ cancel: "Esc anuluje",
+ full: "Kliknij dwukrotnie, aby przechwycić cały ekran",
+ },
+ ja: {
+ hint: "ドラッグして範囲を選択し、離すとノートに保存します",
+ cancel: "Esc でキャンセル",
+ full: "ダブルクリックで画面全体",
+ },
+ ru: {
+ hint: "Перетащите, чтобы выбрать область. Отпустите, чтобы сохранить в заметку",
+ cancel: "Esc — отмена",
+ full: "Двойной щелчок — весь экран",
+ },
+};
+
+export const screenshotRegionCopy = (locale) => {
+ const normalized = typeof locale === "string" ? locale.toLowerCase() : "";
+ if (normalized.startsWith("zh")) return regionCopy.zh;
+ if (normalized === "pl" || normalized.startsWith("pl-")) return regionCopy.pl;
+ if (normalized === "ja" || normalized.startsWith("ja-")) return regionCopy.ja;
+ if (normalized === "ru" || normalized.startsWith("ru-")) return regionCopy.ru;
+ return regionCopy.en;
+};
diff --git a/apps/desktop/src/main/desktop-menu.test.mjs b/apps/desktop/src/main/desktop-menu.test.mjs
index 0214f408..ab24abe0 100644
--- a/apps/desktop/src/main/desktop-menu.test.mjs
+++ b/apps/desktop/src/main/desktop-menu.test.mjs
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
-import { desktopMenuCopy } from "./desktop-menu.mjs";
+import { desktopMenuCopy, screenshotRegionCopy } from "./desktop-menu.mjs";
describe("desktop native menu localization", () => {
test("uses Chinese labels for Chinese Windows locales", () => {
@@ -10,6 +10,10 @@ describe("desktop native menu localization", () => {
expect(copy.window).toBe("窗口");
expect(copy.restartToUpdate).toBe("重启以更新");
expect(copy.screenshotToNote).toBe("截取屏幕到笔记");
+ expect(screenshotRegionCopy("zh-CN").hint).toBe("拖拽选择区域,松开后保存为笔记");
+ expect(screenshotRegionCopy("zh-CN").full).toBe("双击截取整个屏幕");
+ expect(screenshotRegionCopy("en-US").cancel).toBe("Esc to cancel");
+ expect(screenshotRegionCopy("ja").full).toContain("ダブルクリック");
});
test("recognizes other Chinese locale variants", () => {
diff --git a/apps/desktop/src/main/global-shortcut.mjs b/apps/desktop/src/main/global-shortcut.mjs
index 43e41eee..48bd9dfe 100644
--- a/apps/desktop/src/main/global-shortcut.mjs
+++ b/apps/desktop/src/main/global-shortcut.mjs
@@ -23,6 +23,41 @@ export const globalShortcutAccelerator = (binding) => {
].filter(Boolean).join("+");
};
+export const formatGlobalShortcutForHumans = (binding, platform = process.platform) => {
+ if (!binding) return "";
+ const mac = platform === "darwin";
+ const parts = [
+ binding.ctrl && (mac ? "⌃" : "Ctrl"),
+ binding.meta && (mac ? "⌘" : "Meta"),
+ binding.alt && (mac ? "⌥" : "Alt"),
+ binding.shift && (mac ? "⇧" : "Shift"),
+ binding.key.toUpperCase(),
+ ].filter(Boolean);
+ return parts.join(mac ? "" : "+");
+};
+
+export const globalShortcutAcceleratorsConflict = (left, right) => {
+ const first = globalShortcutAccelerator(left);
+ const second = globalShortcutAccelerator(right);
+ return Boolean(first && second && first === second);
+};
+
+// Older installs stored only the window shortcut. Keep that binding and treat a
+// missing screenshot shortcut as unset.
+export const parseStoredGlobalShortcuts = (stored, platform = process.platform) => {
+ const normalize = (value) => {
+ const binding = normalizeGlobalShortcutBinding(value, platform);
+ return binding === undefined ? null : binding;
+ };
+ if (!stored || typeof stored !== "object" || Array.isArray(stored)) {
+ return { binding: null, screenshot: null };
+ }
+ return {
+ binding: normalize(stored.binding),
+ screenshot: normalize(stored.screenshot),
+ };
+};
+
export const toggleMainWindow = ({ window, showWindow, activateApp }) => {
if (!window || window.isDestroyed()) return false;
if (window.isVisible() && !window.isMinimized() && window.isFocused()) {
diff --git a/apps/desktop/src/main/global-shortcut.test.mjs b/apps/desktop/src/main/global-shortcut.test.mjs
index 506a51f6..3f101623 100644
--- a/apps/desktop/src/main/global-shortcut.test.mjs
+++ b/apps/desktop/src/main/global-shortcut.test.mjs
@@ -1,7 +1,10 @@
import { describe, expect, test } from "bun:test";
import {
+ formatGlobalShortcutForHumans,
globalShortcutAccelerator,
+ globalShortcutAcceleratorsConflict,
normalizeGlobalShortcutBinding,
+ parseStoredGlobalShortcuts,
replaceGlobalShortcut,
toggleMainWindow,
} from "./global-shortcut.mjs";
@@ -13,12 +16,32 @@ describe("desktop global shortcut", () => {
test("accepts safe key combinations and rejects single modifiers or unsupported keys", () => {
expect(normalizeGlobalShortcutBinding(oldBinding, "win32")).toEqual(oldBinding);
expect(globalShortcutAccelerator(oldBinding)).toBe("Control+Alt+W");
+ expect(formatGlobalShortcutForHumans(oldBinding, "win32")).toBe("Ctrl+Alt+W");
+ expect(formatGlobalShortcutForHumans(oldBinding, "darwin")).toBe("⌃⌥W");
expect(normalizeGlobalShortcutBinding({ ...oldBinding, alt: false }, "win32")).toBeUndefined();
expect(normalizeGlobalShortcutBinding({ ...oldBinding, key: "escape" }, "win32")).toBeUndefined();
expect(normalizeGlobalShortcutBinding({ ...oldBinding, meta: true }, "linux")).toBeUndefined();
expect(normalizeGlobalShortcutBinding(null, "win32")).toBeNull();
});
+ test("keeps an older window shortcut file and rejects a duplicate screenshot chord", () => {
+ expect(parseStoredGlobalShortcuts({ binding: oldBinding }, "win32")).toEqual({
+ binding: oldBinding,
+ screenshot: null,
+ });
+ expect(parseStoredGlobalShortcuts({
+ binding: oldBinding,
+ screenshot: { ...oldBinding, key: "a" },
+ }, "win32")).toEqual({
+ binding: oldBinding,
+ screenshot: { ...oldBinding, key: "a" },
+ });
+ expect(parseStoredGlobalShortcuts({ binding: { ...oldBinding, key: "escape" } }, "win32").binding).toBeNull();
+ expect(globalShortcutAcceleratorsConflict(oldBinding, { ...oldBinding })).toBe(true);
+ expect(globalShortcutAcceleratorsConflict(oldBinding, newBinding)).toBe(false);
+ expect(globalShortcutAcceleratorsConflict(null, oldBinding)).toBe(false);
+ });
+
test("shows a background window and hides only a focused window", () => {
const calls = [];
const window = {
diff --git a/apps/desktop/src/main/index.mjs b/apps/desktop/src/main/index.mjs
index acb1c109..b8981bcc 100644
--- a/apps/desktop/src/main/index.mjs
+++ b/apps/desktop/src/main/index.mjs
@@ -33,18 +33,19 @@ import { userDataDirectoryFromArguments } from "./user-data-directory.mjs";
import { PRINT_PDF_OPTIONS } from "./print-pdf.mjs";
import { isAllowedAppNavigation, isAllowedPrintPreviewUrl, isResourceDownloadUrl } from "./window-open-policy.mjs";
import { showWindow } from "./window-visibility.mjs";
-import { globalShortcutAccelerator, normalizeGlobalShortcutBinding, replaceGlobalShortcut, toggleMainWindow } from "./global-shortcut.mjs";
+import { formatGlobalShortcutForHumans, globalShortcutAccelerator, globalShortcutAcceleratorsConflict, normalizeGlobalShortcutBinding, parseStoredGlobalShortcuts, replaceGlobalShortcut, toggleMainWindow } from "./global-shortcut.mjs";
import { trayIconPath } from "./tray-icon.mjs";
import { writeImageClipboard, writeRichClipboard, writeTextClipboard } from "./clipboard-write.mjs";
import { registerClipboardReadIpc } from "./clipboard-read.mjs";
-import { captureScreenToNote, createScreenshotCaptureGuard, screenshotImportIpcPayload, writeScreenshotTempPath } from "./screenshot-capture.mjs";
+import { captureRegionScreenToNote, captureScreenToNote, createScreenshotCaptureGuard, screenshotImportIpcPayload, writeScreenshotTempPath } from "./screenshot-capture.mjs";
+import { cancelScreenshotRegionSelection, openScreenshotRegionSelector } from "./screenshot-region.mjs";
import { LocalDataResetError, scheduleMacLocalDataReset } from "./local-data-reset.mjs";
import { buildDesktopDiagnosticIssueUrl, normalizeDesktopDiagnostic } from "./desktop-diagnostics.mjs";
import { readDesktopDeviceModel } from "./desktop-device-model.mjs";
import { createRendererStartupGuard } from "./renderer-startup-guard.mjs";
import { waitForChildProcessSpawn } from "./child-process-start.mjs";
import { ScheduledTaskScheduler } from "./scheduled-task-scheduler.mjs";
-import { desktopMenuCopy } from "./desktop-menu.mjs";
+import { desktopMenuCopy, screenshotRegionCopy } from "./desktop-menu.mjs";
import { createHeadingShortcutGuard } from "./heading-shortcut.mjs";
import { buildEditContextMenuTemplate } from "./edit-context-menu.mjs";
import {
@@ -202,15 +203,24 @@ let desktopSessionTokenOrigin = null;
let instanceChangePending = false;
let configuredGlobalShortcut = null;
let registeredGlobalShortcut = null;
+let configuredScreenshotShortcut = null;
+let registeredScreenshotShortcut = null;
let globalShortcutUpdate = Promise.resolve();
+const shortcutIsRegistered = (binding) => Boolean(binding && globalShortcut.isRegistered(globalShortcutAccelerator(binding)));
const globalShortcutState = () => ({
binding: configuredGlobalShortcut,
- registered: Boolean(registeredGlobalShortcut && globalShortcut.isRegistered(globalShortcutAccelerator(registeredGlobalShortcut))),
+ registered: shortcutIsRegistered(registeredGlobalShortcut),
+ screenshot: configuredScreenshotShortcut,
+ screenshotRegistered: shortcutIsRegistered(registeredScreenshotShortcut),
});
-const persistGlobalShortcut = async (binding) => {
+const persistGlobalShortcutFile = async (slot, next) => {
const temporaryPath = `${globalShortcutPath()}.tmp`;
+ const payload = {
+ binding: slot === "binding" ? next : configuredGlobalShortcut,
+ screenshot: slot === "screenshot" ? next : configuredScreenshotShortcut,
+ };
try {
- await writeFile(temporaryPath, JSON.stringify({ binding }), { mode: 0o600 });
+ await writeFile(temporaryPath, JSON.stringify(payload), { mode: 0o600 });
await rename(temporaryPath, globalShortcutPath());
} catch (error) {
await unlink(temporaryPath).catch(() => {});
@@ -222,54 +232,77 @@ const toggleWindowFromGlobalShortcut = () => toggleMainWindow({
showWindow,
activateApp: process.platform === "darwin" ? () => app.show() : undefined,
});
-const loadGlobalShortcut = async () => {
- try {
- const stored = JSON.parse(await readFile(globalShortcutPath(), "utf8"));
- configuredGlobalShortcut = normalizeGlobalShortcutBinding(stored?.binding);
- if (configuredGlobalShortcut === undefined) configuredGlobalShortcut = null;
- } catch {
- configuredGlobalShortcut = null;
- }
- const accelerator = globalShortcutAccelerator(configuredGlobalShortcut);
+const captureScreenFromGlobalShortcut = () => { void captureScreenshotToNote(); };
+const registerLoadedShortcut = (slot, binding, callback) => {
+ const accelerator = globalShortcutAccelerator(binding);
if (!accelerator) return;
try {
- if (globalShortcut.register(accelerator, toggleWindowFromGlobalShortcut)) {
- registeredGlobalShortcut = configuredGlobalShortcut;
- void writeDiagnostic("global-shortcut.registered", { accelerator });
+ if (globalShortcut.register(accelerator, callback)) {
+ if (slot === "screenshot") registeredScreenshotShortcut = binding;
+ else registeredGlobalShortcut = binding;
+ void writeDiagnostic("global-shortcut.registered", { slot, accelerator });
} else {
- void writeDiagnostic("global-shortcut.registration-failed", { accelerator });
+ void writeDiagnostic("global-shortcut.registration-failed", { slot, accelerator });
}
} catch (error) {
void writeDiagnostic("global-shortcut.registration-failed", {
+ slot,
accelerator,
message: error instanceof Error ? error.message : String(error),
});
// Keep the preference so the user can change it when registration fails.
}
};
-const setGlobalShortcut = (value) => {
+const loadGlobalShortcut = async () => {
+ try {
+ const stored = JSON.parse(await readFile(globalShortcutPath(), "utf8"));
+ const parsed = parseStoredGlobalShortcuts(stored);
+ configuredGlobalShortcut = parsed.binding;
+ configuredScreenshotShortcut = parsed.screenshot;
+ } catch {
+ configuredGlobalShortcut = null;
+ configuredScreenshotShortcut = null;
+ }
+ registerLoadedShortcut("binding", configuredGlobalShortcut, toggleWindowFromGlobalShortcut);
+ registerLoadedShortcut("screenshot", configuredScreenshotShortcut, captureScreenFromGlobalShortcut);
+ refreshTrayMenu();
+};
+const setNamedGlobalShortcut = (slot, value, callback) => {
const next = normalizeGlobalShortcutBinding(value);
if (next === undefined) return Promise.resolve({ ...globalShortcutState(), error: "invalid" });
+ const other = slot === "screenshot" ? configuredGlobalShortcut : configuredScreenshotShortcut;
+ if (globalShortcutAcceleratorsConflict(next, other)) {
+ return Promise.resolve({ ...globalShortcutState(), error: "unavailable" });
+ }
+ const previous = slot === "screenshot" ? registeredScreenshotShortcut : registeredGlobalShortcut;
const update = async () => {
const result = await replaceGlobalShortcut({
globalShortcut,
- previous: registeredGlobalShortcut,
+ previous,
next,
- callback: toggleWindowFromGlobalShortcut,
- persist: persistGlobalShortcut,
+ callback,
+ persist: (binding) => persistGlobalShortcutFile(slot, binding),
});
if (!result.ok) {
- void writeDiagnostic("global-shortcut.update-failed", { reason: result.reason });
+ void writeDiagnostic("global-shortcut.update-failed", { slot, reason: result.reason });
return { ...globalShortcutState(), error: result.reason };
}
- configuredGlobalShortcut = next;
- registeredGlobalShortcut = next;
+ if (slot === "screenshot") {
+ configuredScreenshotShortcut = next;
+ registeredScreenshotShortcut = next;
+ } else {
+ configuredGlobalShortcut = next;
+ registeredGlobalShortcut = next;
+ }
+ refreshTrayMenu();
return globalShortcutState();
};
const result = globalShortcutUpdate.then(update, update);
globalShortcutUpdate = result.then(() => undefined, () => undefined);
return result;
};
+const setGlobalShortcut = (value) => setNamedGlobalShortcut("binding", value, toggleWindowFromGlobalShortcut);
+const setScreenshotShortcut = (value) => setNamedGlobalShortcut("screenshot", value, captureScreenFromGlobalShortcut);
const sidecarDataDirectory = (accountId = null) => {
return accountId
? accountDataDirectory(app.getPath("userData"), configuredApiBaseUrl, accountId)
@@ -752,9 +785,11 @@ const flushPendingScreenshotImport = () => {
const captureScreenshotToNote = async () => {
if (!screenshotCaptureGuard.tryBegin()) return;
+ const captureStartedAt = Date.now();
const copy = desktopMenuCopy(app.getLocale());
const wasVisible = Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible());
const revealWindow = () => {
+ if (isQuitting) return;
if (process.platform === "darwin") app.show();
showWindow(mainWindow);
};
@@ -762,13 +797,28 @@ const captureScreenshotToNote = async () => {
if (process.platform === "darwin") app.hide();
else if (wasVisible) mainWindow.hide();
await new Promise((resolve) => setTimeout(resolve, 250));
- const captured = await captureScreenToNote({
- platform: process.platform,
- locale: app.getLocale(),
- outputPath: process.platform === "darwin" ? writeScreenshotTempPath(app.getPath("temp")) : undefined,
- desktopCapturer,
- screen,
- });
+ const captured = process.platform === "darwin"
+ ? await captureScreenToNote({
+ platform: process.platform,
+ locale: app.getLocale(),
+ outputPath: writeScreenshotTempPath(app.getPath("temp")),
+ desktopCapturer,
+ screen,
+ })
+ : await captureRegionScreenToNote({
+ locale: app.getLocale(),
+ desktopCapturer,
+ screen,
+ selectRegion: ({ display, image }) => openScreenshotRegionSelector({
+ BrowserWindow,
+ ipcMain,
+ display,
+ image,
+ copy: screenshotRegionCopy(app.getLocale()),
+ preloadPath: join(currentDirectory, "screenshot-region-preload.cjs"),
+ htmlPath: join(currentDirectory, "screenshot-region.html"),
+ }),
+ });
if (!captured) {
if (wasVisible) revealWindow();
return;
@@ -780,12 +830,15 @@ const captureScreenshotToNote = async () => {
void writeDiagnostic("screenshot.failed", {
message: error instanceof Error ? error.message : String(error),
});
- await dialog.showMessageBox({
- type: "warning",
- message: copy.screenshotFailed,
- });
+ if (!isQuitting) {
+ await dialog.showMessageBox({
+ type: "warning",
+ message: copy.screenshotFailed,
+ });
+ }
} finally {
- screenshotCaptureGuard.end();
+ if (Date.now() - captureStartedAt >= 1000) screenshotCaptureGuard.release();
+ else screenshotCaptureGuard.end();
}
};
@@ -907,9 +960,13 @@ const buildApplicationMenu = () => {
const buildTrayContextMenu = () => {
const copy = desktopMenuCopy(app.getLocale());
+ const screenshotShortcut = formatGlobalShortcutForHumans(configuredScreenshotShortcut);
return Menu.buildFromTemplate([
{ label: copy.show, click: () => showWindow(mainWindow) },
- { label: copy.screenshotToNote, click: () => void captureScreenshotToNote() },
+ {
+ label: screenshotShortcut ? `${copy.screenshotToNote} ${screenshotShortcut}` : copy.screenshotToNote,
+ click: () => void captureScreenshotToNote(),
+ },
...(updateState === "downloaded" ? [{ label: copy.restartToUpdate, click: () => installDownloadedUpdate() }] : []),
{ type: "separator" },
{ label: copy.quit, click: () => { isQuitting = true; app.quit(); } },
@@ -1808,6 +1865,10 @@ const startApplication = async () => {
if (event.sender !== mainWindow?.webContents) return null;
return setGlobalShortcut(binding);
});
+ ipcMain.handle("desktop:set-screenshot-shortcut", (event, binding) => {
+ if (event.sender !== mainWindow?.webContents) return null;
+ return setScreenshotShortcut(binding);
+ });
ipcMain.handle("desktop:capture-global-shortcut", (event, capturing) => {
if (event.sender !== mainWindow?.webContents || typeof capturing !== "boolean") return false;
globalShortcut.setSuspended(capturing);
@@ -2333,6 +2394,7 @@ app.on("before-quit", (event) => {
event.preventDefault();
shutdownCleanupStarted = true;
isQuitting = true;
+ cancelScreenshotRegionSelection();
globalShortcut.unregisterAll();
scheduledTaskScheduler.clear();
rendererStartupGuard?.complete();
diff --git a/apps/desktop/src/main/screenshot-capture.mjs b/apps/desktop/src/main/screenshot-capture.mjs
index a7b406eb..e0f87689 100644
--- a/apps/desktop/src/main/screenshot-capture.mjs
+++ b/apps/desktop/src/main/screenshot-capture.mjs
@@ -7,7 +7,11 @@ import { promisify } from "node:util";
const execFileAsync = promisify(execFileCallback);
const MAC_SCREENCAPTURE = "/usr/sbin/screencapture";
-export const macScreencaptureArgs = (outputPath) => ["-x", "-t", "png", outputPath];
+// -i opens the system selection UI (drag a region, Space for a window, Esc cancels).
+// -x keeps the capture silent. The temp path receives only the chosen area.
+export const macScreencaptureArgs = (outputPath) => ["-i", "-x", "-t", "png", outputPath];
+
+export const MIN_REGION_SELECTION_PX = 8;
export const normalizeIpcBytes = (value) => {
if (value instanceof Uint8Array) {
@@ -70,6 +74,13 @@ export const createScreenshotCaptureGuard = ({
cooldownTimer = null;
}, cooldownMs);
},
+ // A region selection outlives the tray's double-click, so the next capture
+ // can start as soon as the user finishes instead of waiting out the cooldown.
+ release() {
+ if (cooldownTimer != null) cancel(cooldownTimer);
+ cooldownTimer = null;
+ inFlight = false;
+ },
};
};
@@ -146,7 +157,61 @@ const matchCaptureSource = (sources, display) => {
return sources.find((source) => source && String(source.display_id) === displayId) || sources[0];
};
-export const captureDisplayScreenshot = async ({ desktopCapturer, screen }) => {
+export const clampRegionSelection = (selection, displaySize, minimum = MIN_REGION_SELECTION_PX) => {
+ if (!selection || typeof selection !== "object") return null;
+ if (selection.full === true) return { full: true };
+ const width = Number(selection.width);
+ const height = Number(selection.height);
+ const x = Number(selection.x);
+ const y = Number(selection.y);
+ const displayWidth = Number(displaySize?.width);
+ const displayHeight = Number(displaySize?.height);
+ if (![x, y, width, height, displayWidth, displayHeight].every(Number.isFinite)) return null;
+ if (displayWidth <= 0 || displayHeight <= 0 || width < minimum || height < minimum) return null;
+ const left = Math.max(0, Math.min(x, displayWidth));
+ const top = Math.max(0, Math.min(y, displayHeight));
+ const right = Math.max(left, Math.min(x + width, displayWidth));
+ const bottom = Math.max(top, Math.min(y + height, displayHeight));
+ if (right - left < minimum || bottom - top < minimum) return null;
+ return { x: left, y: top, width: right - left, height: bottom - top };
+};
+
+export const cropRectForDisplay = ({ selection, displaySize, imageSize }) => {
+ if (!selection || selection.full) return null;
+ const displayWidth = Number(displaySize?.width);
+ const displayHeight = Number(displaySize?.height);
+ const imageWidth = Number(imageSize?.width);
+ const imageHeight = Number(imageSize?.height);
+ if (![displayWidth, displayHeight, imageWidth, imageHeight].every((value) => value > 0)) return null;
+ if (![selection.x, selection.y, selection.width, selection.height].every(Number.isFinite)) return null;
+ const scaleX = imageWidth / displayWidth;
+ const scaleY = imageHeight / displayHeight;
+ let x = Math.round(selection.x * scaleX);
+ let y = Math.round(selection.y * scaleY);
+ let width = Math.round(selection.width * scaleX);
+ let height = Math.round(selection.height * scaleY);
+ x = Math.max(0, Math.min(x, imageWidth - 1));
+ y = Math.max(0, Math.min(y, imageHeight - 1));
+ width = Math.max(1, Math.min(width, imageWidth - x));
+ height = Math.max(1, Math.min(height, imageHeight - y));
+ if (width < 2 || height < 2) return null;
+ return { x, y, width, height };
+};
+
+export const pngBytesForRegion = (image, display, selection) => {
+ if (!image || image.isEmpty?.()) return null;
+ const imageSize = image.getSize?.();
+ if (!imageSize?.width || !imageSize?.height) return null;
+ if (selection?.full) return toPngBytes(image);
+ const rect = cropRectForDisplay({ selection, displaySize: display?.size, imageSize });
+ if (!rect) return null;
+ if (rect.x === 0 && rect.y === 0 && rect.width === imageSize.width && rect.height === imageSize.height) {
+ return toPngBytes(image);
+ }
+ return toPngBytes(image.crop?.(rect));
+};
+
+export const captureCursorDisplayImage = async ({ desktopCapturer, screen }) => {
const point = screen.getCursorScreenPoint();
const display = screen.getDisplayNearestPoint(point);
const thumbnailSize = displayThumbnailSize(display);
@@ -156,29 +221,50 @@ export const captureDisplayScreenshot = async ({ desktopCapturer, screen }) => {
});
const source = matchCaptureSource(sources, display);
const thumbnail = source?.thumbnail;
- if (!thumbnail || thumbnail.isEmpty()) {
- throw new Error("Screen capture is unavailable");
- }
+ if (!thumbnail || thumbnail.isEmpty()) return null;
+ return { display, image: thumbnail };
+};
- const screenshotBytes = toPngBytes(thumbnail);
+export const captureDisplayScreenshot = async (input) => {
+ const captured = await captureCursorDisplayImage(input);
+ if (!captured) throw new Error("Screen capture is unavailable");
+ const screenshotBytes = toPngBytes(captured.image);
if (!screenshotBytes) throw new Error("Screen capture is unavailable");
return screenshotBytes;
};
-export const captureScreenToNote = async (input) => {
- const bytes = input.platform === "darwin"
- ? await captureMacScreenScreenshot(input)
- : await captureDisplayScreenshot(input);
- if (!bytes || bytes.byteLength === 0) return null;
- const capturedAt = input.now ? new Date(input.now) : new Date();
+const screenshotResult = (locale, now, bytes) => {
+ const capturedAt = now ? new Date(now) : new Date();
return {
captureId: screenshotCaptureId(capturedAt),
bytes: normalizeIpcBytes(bytes),
name: screenshotFileName(capturedAt),
type: "image/png",
- title: screenshotNoteTitle(input.locale, capturedAt),
+ title: screenshotNoteTitle(locale, capturedAt),
};
};
+export const captureScreenToNote = async (input) => {
+ const bytes = input.platform === "darwin"
+ ? await captureMacScreenScreenshot(input)
+ : await captureDisplayScreenshot(input);
+ if (!bytes || bytes.byteLength === 0) return null;
+ return screenshotResult(input.locale, input.now, bytes);
+};
+
+// Windows and Linux have no system region tool that returns a file. Freeze the
+// display under the cursor, let the caller collect a selection, then crop.
+export const captureRegionScreenToNote = async (input) => {
+ const captured = await captureCursorDisplayImage(input);
+ if (!captured) throw new Error("Screen capture is unavailable");
+ const choice = await input.selectRegion(captured);
+ if (!choice) return null;
+ const selection = clampRegionSelection(choice, captured.display?.size);
+ if (!selection) return null;
+ const bytes = pngBytesForRegion(captured.image, captured.display, selection);
+ if (!bytes) throw new Error("Screen capture is unavailable");
+ return screenshotResult(input.locale, input.now, bytes);
+};
+
export const writeScreenshotTempPath = (root = tmpdir()) =>
join(root, `edgeever-screenshot-${Date.now()}-${Math.random().toString(16).slice(2)}.png`);
diff --git a/apps/desktop/src/main/screenshot-capture.test.mjs b/apps/desktop/src/main/screenshot-capture.test.mjs
index be50d3b0..c035d999 100644
--- a/apps/desktop/src/main/screenshot-capture.test.mjs
+++ b/apps/desktop/src/main/screenshot-capture.test.mjs
@@ -2,7 +2,10 @@ import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import {
captureDisplayScreenshot,
+ captureRegionScreenToNote,
+ clampRegionSelection,
createScreenshotCaptureGuard,
+ cropRectForDisplay,
isScreenshotCancelledExit,
macScreencaptureArgs,
normalizeIpcBytes,
@@ -17,8 +20,21 @@ const preloadSource = readFileSync(new URL("../preload/index.cjs", import.meta.u
const workspaceSource = readFileSync(new URL("../../../web/src/components/WorkspaceApp.tsx", import.meta.url), "utf8");
describe("screenshot capture helpers", () => {
- test("captures the full screen on macOS without an interactive selection", () => {
- expect(macScreencaptureArgs("/tmp/capture.png")).toEqual(["-x", "-t", "png", "/tmp/capture.png"]);
+ test("opens the macOS interactive region selector and writes a png", () => {
+ expect(macScreencaptureArgs("/tmp/capture.png")).toEqual(["-i", "-x", "-t", "png", "/tmp/capture.png"]);
+ });
+
+ test("clamps a dragged region and maps it onto the captured pixels", () => {
+ expect(clampRegionSelection({ x: -5, y: 1, width: 30, height: 20 }, { width: 100, height: 50 })).toEqual({
+ x: 0, y: 1, width: 25, height: 20,
+ });
+ expect(clampRegionSelection({ x: 0, y: 0, width: 4, height: 4 }, { width: 100, height: 50 })).toBeNull();
+ expect(clampRegionSelection({ full: true }, { width: 100, height: 50 })).toEqual({ full: true });
+ expect(cropRectForDisplay({
+ selection: { x: 10, y: 5, width: 20, height: 10 },
+ displaySize: { width: 100, height: 50 },
+ imageSize: { width: 200, height: 100 },
+ })).toEqual({ x: 20, y: 10, width: 40, height: 20 });
});
test("treats screencapture cancel exit codes as a quiet abort", () => {
@@ -98,6 +114,61 @@ describe("screenshot capture helpers", () => {
});
});
+describe("region screenshot to note", () => {
+ const display = {
+ id: 2,
+ size: { width: 100, height: 50 },
+ scaleFactor: 2,
+ bounds: { x: 0, y: 0, width: 100, height: 50 },
+ };
+ const image = {
+ isEmpty: () => false,
+ getSize: () => ({ width: 200, height: 100 }),
+ crop: (rect) => ({
+ isEmpty: () => false,
+ toPNG: () => Buffer.from(`crop:${rect.x},${rect.y},${rect.width},${rect.height}`),
+ }),
+ toPNG: () => Buffer.from("full"),
+ };
+ const input = {
+ locale: "zh-CN",
+ now: new Date(2026, 8, 14, 11, 8, 3),
+ screen: {
+ getCursorScreenPoint: () => ({ x: 1, y: 1 }),
+ getDisplayNearestPoint: () => display,
+ },
+ desktopCapturer: {
+ getSources: async () => [{ display_id: "2", thumbnail: image }],
+ },
+ };
+
+ test("crops the selected region into a note payload", async () => {
+ const selected = await captureRegionScreenToNote({
+ ...input,
+ selectRegion: async () => ({ x: 10, y: 5, width: 20, height: 10 }),
+ });
+ expect(Buffer.from(selected.bytes).toString()).toBe("crop:20,10,40,20");
+ expect(selected.title).toBe("截图 2026-09-14 11:08");
+ expect(selected.type).toBe("image/png");
+ });
+
+ test("keeps the whole display when the user double-clicks", async () => {
+ const selected = await captureRegionScreenToNote({
+ ...input,
+ selectRegion: async () => ({ full: true }),
+ });
+ expect(Buffer.from(selected.bytes).toString()).toBe("full");
+ });
+
+ test("returns null when the selection is cancelled", async () => {
+ const cancelled = await captureRegionScreenToNote({
+ ...input,
+ selectRegion: async () => null,
+ });
+ expect(cancelled).toBeNull();
+ });
+});
+
describe("screenshot capture guard", () => {
test("rejects a second capture until the cooldown elapses", () => {
const timers = [];
@@ -116,19 +187,39 @@ describe("screenshot capture guard", () => {
timers.at(-1)();
expect(guard.tryBegin()).toBe(true);
});
+
+ test("releases immediately after a region selection instead of keeping the cooldown", () => {
+ const guard = createScreenshotCaptureGuard({
+ cooldownMs: 20,
+ schedule: () => 1,
+ cancel: () => {},
+ });
+ expect(guard.tryBegin()).toBe(true);
+ guard.release();
+ expect(guard.tryBegin()).toBe(true);
+ });
});
describe("desktop screenshot to note wiring", () => {
test("replaces the tray sync and backup actions with screenshot capture", () => {
expect(mainSource).toContain("captureScreenshotToNote");
expect(mainSource).toContain("captureScreenToNote");
+ expect(mainSource).toContain("captureRegionScreenToNote");
+ expect(mainSource).toContain("openScreenshotRegionSelector");
+ expect(mainSource).toContain("cancelScreenshotRegionSelection");
+ expect(mainSource).toContain("desktop:set-screenshot-shortcut");
+ expect(mainSource).toContain("parseStoredGlobalShortcuts");
+ expect(mainSource).not.toContain("JSON.stringify({ binding })");
expect(mainSource).toContain("createScreenshotCaptureGuard");
expect(mainSource).toContain("sentScreenshotCaptureIds");
expect(mainSource).toContain("pendingScreenshotImport = null");
expect(mainSource).not.toContain("overlay.html");
+ expect(mainSource).toContain("screenshot-region.html");
expect(mainSource).toContain("copy.screenshotToNote");
+ expect(mainSource).toContain("formatGlobalShortcutForHumans");
expect(mainSource).not.toContain('label: copy.syncNow, click: () => sendDesktopCommand("sync-now")');
expect(mainSource).not.toContain('label: copy.backupNow, click: () => sendDesktopCommand("backup-now")');
+ expect(preloadSource).toContain("setScreenshotShortcut");
expect(preloadSource).toContain("onImportScreenshot");
expect(preloadSource).toContain("screenshotImportListener");
expect(preloadSource).toContain("rendererReadySent");
diff --git a/apps/desktop/src/main/screenshot-region-preload.cjs b/apps/desktop/src/main/screenshot-region-preload.cjs
new file mode 100644
index 00000000..499754a1
--- /dev/null
+++ b/apps/desktop/src/main/screenshot-region-preload.cjs
@@ -0,0 +1,13 @@
+const { contextBridge, ipcRenderer } = require("electron");
+
+contextBridge.exposeInMainWorld("edgeeverScreenshotRegion", {
+ onStart(callback) {
+ ipcRenderer.on("desktop:screenshot-region-start", (_event, payload) => callback(payload));
+ },
+ complete(selection) {
+ ipcRenderer.send("desktop:screenshot-region-complete", selection);
+ },
+ cancel() {
+ ipcRenderer.send("desktop:screenshot-region-cancel");
+ },
+});
diff --git a/apps/desktop/src/main/screenshot-region.html b/apps/desktop/src/main/screenshot-region.html
new file mode 100644
index 00000000..811e8b08
--- /dev/null
+++ b/apps/desktop/src/main/screenshot-region.html
@@ -0,0 +1,165 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>EdgeEver</title>
+ <style>
+ html, body {
+ margin: 0;
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ background: #111;
+ cursor: crosshair;
+ user-select: none;
+ }
+ img {
+ position: fixed;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: fill;
+ pointer-events: none;
+ }
+ #shade {
+ position: fixed;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.4);
+ pointer-events: none;
+ }
+ #selection {
+ position: fixed;
+ display: none;
+ box-sizing: border-box;
+ border: 2px solid #fff;
+ box-shadow: 0 0 0 100vmax rgba(0, 0, 0, 0.45);
+ pointer-events: none;
+ }
+ #hint, #size {
+ position: fixed;
+ pointer-events: none;
+ color: #fff;
+ background: rgba(7, 19, 11, 0.88);
+ font: 13px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+ }
+ #hint {
+ top: 16px;
+ left: 50%;
+ transform: translateX(-50%);
+ max-width: min(720px, calc(100% - 32px));
+ padding: 8px 14px;
+ border-radius: 16px;
+ text-align: center;
+ }
+ #size {
+ display: none;
+ padding: 2px 6px;
+ border-radius: 6px;
+ }
+ </style>
+</head>
+<body>
+ <img id="shot" alt="">
+ <div id="shade"></div>
+ <div id="selection"></div>
+ <div id="hint"></div>
+ <div id="size"></div>
+ <script>
+ const api = window.edgeeverScreenshotRegion;
+ const shot = document.getElementById("shot");
+ const shade = document.getElementById("shade");
+ const selectionEl = document.getElementById("selection");
+ const hint = document.getElementById("hint");
+ const sizeEl = document.getElementById("size");
+ const minimum = 8;
+ let displayWidth = 1;
+ let displayHeight = 1;
+ let dragging = false;
+ let start = null;
+
+ const toDisplayPoint = (event) => {
+ const viewWidth = window.innerWidth || 1;
+ const viewHeight = window.innerHeight || 1;
+ return {
+ x: Math.max(0, Math.min(displayWidth, event.clientX * displayWidth / viewWidth)),
+ y: Math.max(0, Math.min(displayHeight, event.clientY * displayHeight / viewHeight)),
+ };
+ };
+
+ const paint = (end) => {
+ const x = Math.min(start.x, end.x);
+ const y = Math.min(start.y, end.y);
+ const width = Math.abs(end.x - start.x);
+ const height = Math.abs(end.y - start.y);
+ const viewWidth = window.innerWidth || 1;
+ const viewHeight = window.innerHeight || 1;
+ const left = x * viewWidth / displayWidth;
+ const top = y * viewHeight / displayHeight;
+ const viewSelectionWidth = width * viewWidth / displayWidth;
+ const viewSelectionHeight = height * viewHeight / displayHeight;
+ selectionEl.style.display = "block";
+ selectionEl.style.left = left + "px";
+ selectionEl.style.top = top + "px";
+ selectionEl.style.width = viewSelectionWidth + "px";
+ selectionEl.style.height = viewSelectionHeight + "px";
+ shade.style.display = "none";
+ sizeEl.style.display = "block";
+ sizeEl.textContent = Math.round(width) + " × " + Math.round(height);
+ sizeEl.style.left = Math.max(8, Math.min(viewWidth - 88, left + viewSelectionWidth + 8)) + "px";
+ sizeEl.style.top = Math.max(8, Math.min(viewHeight - 28, top + viewSelectionHeight + 8)) + "px";
+ };
+
+ if (api) {
+ api.onStart((payload) => {
+ displayWidth = Number(payload.displayWidth) || window.innerWidth || 1;
+ displayHeight = Number(payload.displayHeight) || window.innerHeight || 1;
+ shot.src = payload.imageUrl || "";
+ hint.textContent = [payload.hint, payload.cancel, payload.full].filter(Boolean).join(" · ");
+ });
+ }
+
+ window.addEventListener("mousedown", (event) => {
+ if (event.button !== 0 || !displayWidth || !displayHeight) return;
+ event.preventDefault();
+ dragging = true;
+ start = toDisplayPoint(event);
+ });
+
+ window.addEventListener("mousemove", (event) => {
+ if (!dragging || !start) return;
+ paint(toDisplayPoint(event));
+ });
+
+ window.addEventListener("mouseup", (event) => {
+ if (!dragging || !start || event.button !== 0) return;
+ dragging = false;
+ const end = toDisplayPoint(event);
+ const width = Math.abs(end.x - start.x);
+ const height = Math.abs(end.y - start.y);
+ if (width < minimum || height < minimum) return;
+ api?.complete({
+ x: Math.min(start.x, end.x),
+ y: Math.min(start.y, end.y),
+ width,
+ height,
+ });
+ });
+
+ window.addEventListener("dblclick", (event) => {
+ event.preventDefault();
+ api?.complete({ full: true });
+ });
+
+ window.addEventListener("contextmenu", (event) => {
+ event.preventDefault();
+ api?.cancel();
+ });
+
+ window.addEventListener("keydown", (event) => {
+ if (event.key !== "Escape") return;
+ event.preventDefault();
+ api?.cancel();
+ });
+ </script>
+</body>
+</html>
diff --git a/apps/desktop/src/main/screenshot-region.mjs b/apps/desktop/src/main/screenshot-region.mjs
new file mode 100644
index 00000000..56004ba2
--- /dev/null
+++ b/apps/desktop/src/main/screenshot-region.mjs
@@ -0,0 +1,165 @@
+const START_CHANNEL = "desktop:screenshot-region-start";
+const COMPLETE_CHANNEL = "desktop:screenshot-region-complete";
+const CANCEL_CHANNEL = "desktop:screenshot-region-cancel";
+
+let cancelActiveRegionSelection = null;
+
+export const cancelScreenshotRegionSelection = () => {
+ cancelActiveRegionSelection?.();
+};
+
+export const openScreenshotRegionSelector = ({
+ BrowserWindow,
+ ipcMain,
+ display,
+ image,
+ copy,
+ preloadPath,
+ htmlPath,
+}) => new Promise((resolve, reject) => {
+ const displaySize = {
+ width: Number(display?.size?.width) || Number(display?.bounds?.width) || 0,
+ height: Number(display?.size?.height) || Number(display?.bounds?.height) || 0,
+ };
+ const bounds = display?.bounds;
+ if (!bounds || displaySize.width <= 0 || displaySize.height <= 0) {
+ reject(new Error("Screen capture is unavailable"));
+ return;
+ }
+
+ let imageUrl = "";
+ try {
+ imageUrl = image?.toDataURL?.() || "";
+ } catch (error) {
+ reject(error);
+ return;
+ }
+ if (!imageUrl) {
+ reject(new Error("Screen capture is unavailable"));
+ return;
+ }
+
+ let settled = false;
+ let win = null;
+ const detach = () => {
+ ipcMain.removeListener(COMPLETE_CHANNEL, onComplete);
+ ipcMain.removeListener(CANCEL_CHANNEL, onCancel);
+ if (cancelActiveRegionSelection === finish) cancelActiveRegionSelection = null;
+ };
+ const finish = (selection) => {
+ if (settled) return;
+ settled = true;
+ detach();
+ const closing = win;
+ win = null;
+ if (closing && !closing.isDestroyed()) {
+ closing.removeListener("closed", onClosed);
+ closing.close();
+ }
+ resolve(selection);
+ };
+ const fail = (error) => {
+ if (settled) return;
+ settled = true;
+ detach();
+ const closing = win;
+ win = null;
+ if (closing && !closing.isDestroyed()) {
+ closing.removeListener("closed", onClosed);
+ closing.close();
+ }
+ reject(error instanceof Error ? error : new Error("Screen capture is unavailable"));
+ };
+ const onComplete = (event, payload) => {
+ if (!win || win.isDestroyed() || event.sender !== win.webContents) return;
+ if (payload?.full === true) {
+ finish({ full: true });
+ return;
+ }
+ const width = Number(payload?.width);
+ const height = Number(payload?.height);
+ const x = Number(payload?.x);
+ const y = Number(payload?.y);
+ if (![x, y, width, height].every(Number.isFinite)) return;
+ finish({ x, y, width, height });
+ };
+ const onCancel = (event) => {
+ if (!win || win.isDestroyed() || event.sender !== win.webContents) return;
+ finish(null);
+ };
+ const onClosed = () => finish(null);
+
+ ipcMain.on(COMPLETE_CHANNEL, onComplete);
+ ipcMain.on(CANCEL_CHANNEL, onCancel);
+ cancelActiveRegionSelection = finish;
+
+ try {
+ win = new BrowserWindow({
+ x: Math.round(bounds.x),
+ y: Math.round(bounds.y),
+ width: Math.round(bounds.width),
+ height: Math.round(bounds.height),
+ frame: false,
+ resizable: false,
+ movable: false,
+ minimizable: false,
+ maximizable: false,
+ fullscreenable: false,
+ skipTaskbar: true,
+ alwaysOnTop: true,
+ focusable: true,
+ show: false,
+ hasShadow: false,
+ roundedCorners: false,
+ thickFrame: false,
+ enableLargerThanScreen: true,
+ autoHideMenuBar: true,
+ backgroundColor: "#111111",
+ webPreferences: {
+ preload: preloadPath,
+ contextIsolation: true,
+ nodeIntegration: false,
+ sandbox: true,
+ },
+ });
+ } catch (error) {
+ fail(error);
+ return;
+ }
+
+ win.setMenu(null);
+ win.setMenuBarVisibility(false);
+ win.on("closed", onClosed);
+ win.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
+ win.webContents.on("did-finish-load", () => {
+ if (settled || !win || win.isDestroyed()) return;
+ win.webContents.send(START_CHANNEL, {
+ imageUrl,
+ hint: copy?.hint || "",
+ cancel: copy?.cancel || "",
+ full: copy?.full || "",
+ displayWidth: displaySize.width,
+ displayHeight: displaySize.height,
+ });
+ win.setBounds({
+ x: Math.round(bounds.x),
+ y: Math.round(bounds.y),
+ width: Math.round(bounds.width),
+ height: Math.round(bounds.height),
+ });
+ win.show();
+ try {
+ win.setAlwaysOnTop(true, "screen-saver");
+ } catch {
+ win.setAlwaysOnTop(true);
+ }
+ win.moveTop?.();
+ win.focus();
+ win.webContents.on("will-navigate", (event) => event.preventDefault());
+ });
+ win.webContents.on("did-fail-load", (_event, _errorCode, _description, _url, isMainFrame) => {
+ if (isMainFrame === false) return;
+ fail(new Error("Screen capture is unavailable"));
+ });
+ win.loadFile(htmlPath).catch((error) => fail(error));
+});
diff --git a/apps/desktop/src/preload/index.cjs b/apps/desktop/src/preload/index.cjs
index d5fcbd6c..c314f4fb 100644
--- a/apps/desktop/src/preload/index.cjs
+++ b/apps/desktop/src/preload/index.cjs
@@ -32,6 +32,7 @@ contextBridge.exposeInMainWorld("edgeeverDesktop", Object.freeze({
systemInfo: () => ipcRenderer.invoke("desktop:system-info"),
globalShortcut: () => ipcRenderer.invoke("desktop:global-shortcut"),
setGlobalShortcut: (binding) => ipcRenderer.invoke("desktop:set-global-shortcut", binding),
+ setScreenshotShortcut: (binding) => ipcRenderer.invoke("desktop:set-screenshot-shortcut", binding),
loginItem: () => ipcRenderer.invoke("desktop:login-item"),
setLoginItem: (patch) => ipcRenderer.invoke("desktop:set-login-item", patch),
captureGlobalShortcut: (capturing) => ipcRenderer.invoke("desktop:capture-global-shortcut", capturing),
diff --git a/apps/web/src/components/settings/ShortcutSettingsItem.tsx b/apps/web/src/components/settings/ShortcutSettingsItem.tsx
index 1d65e85c..6eab3f30 100644
--- a/apps/web/src/components/settings/ShortcutSettingsItem.tsx
+++ b/apps/web/src/components/settings/ShortcutSettingsItem.tsx
@@ -20,6 +20,8 @@ interface ShortcutSettingsItemProps {
onShortcutSettingsChange: (settings: ShortcutSettings) => void;
}
+type GlobalShortcutTarget = "window" | "screenshot";
+
const getConflictAction = (
action: ShortcutAction,
binding: ShortcutBinding,
@@ -47,6 +49,15 @@ const formatGlobalBinding = (binding: DesktopGlobalShortcutBinding) => {
return parts.join(isMac ? "" : " + ");
};
+const globalBindingsEqual = (left: DesktopGlobalShortcutBinding | null | undefined, right: DesktopGlobalShortcutBinding | null | undefined) => Boolean(
+ left && right
+ && left.key === right.key
+ && left.ctrl === right.ctrl
+ && left.meta === right.meta
+ && left.alt === right.alt
+ && left.shift === right.shift
+);
+
const globalBindingMatchesLocal = (global: DesktopGlobalShortcutBinding, local: ShortcutBinding) => {
const modifiers = resolvedShortcutModifiers(local);
return global.key === local.key
@@ -61,7 +72,7 @@ export const ShortcutSettingsItem = ({ shortcutSettings, onShortcutSettingsChang
const [recordingAction, setRecordingAction] = useState<ShortcutAction | null>(null);
const [captureMessage, setCaptureMessage] = useState("");
const [globalShortcut, setGlobalShortcut] = useState<DesktopGlobalShortcutState | null>(null);
- const [recordingGlobal, setRecordingGlobal] = useState(false);
+ const [recordingTarget, setRecordingTarget] = useState<GlobalShortcutTarget | null>(null);
const [globalBusy, setGlobalBusy] = useState(false);
const [globalMessage, setGlobalMessage] = useState("");
const captureButtonRef = useRef<HTMLButtonElement | null>(null);
@@ -79,11 +90,11 @@ export const ShortcutSettingsItem = ({ shortcutSettings, onShortcutSettingsChang
useEffect(() => () => { void window.edgeeverDesktop?.captureGlobalShortcut(false); }, []);
- const beginRecording = async (action: ShortcutAction | "global") => {
+ const beginRecording = async (action: ShortcutAction | GlobalShortcutTarget) => {
try {
await window.edgeeverDesktop?.captureGlobalShortcut(true);
- if (action === "global") {
- setRecordingGlobal(true);
+ if (action === "window" || action === "screenshot") {
+ setRecordingTarget(action);
setGlobalMessage("");
} else {
setRecordingAction(action);
@@ -96,12 +107,12 @@ export const ShortcutSettingsItem = ({ shortcutSettings, onShortcutSettingsChang
const finishRecording = () => {
setRecordingAction(null);
- setRecordingGlobal(false);
+ setRecordingTarget(null);
void window.edgeeverDesktop?.captureGlobalShortcut(false);
};
useEffect(() => {
- if (!recordingGlobal) return;
+ if (!recordingTarget) return;
const handleGlobalKeyDown = (event: KeyboardEvent) => {
event.preventDefault();
event.stopImmediatePropagation();
@@ -115,17 +126,25 @@ export const ShortcutSettingsItem = ({ shortcutSettings, onShortcutSettingsChang
setGlobalMessage(t("shortcuts.global.requireModifiers"));
return;
}
+ const otherBinding = recordingTarget === "screenshot" ? globalShortcut?.binding : globalShortcut?.screenshot;
+ const otherLabel = recordingTarget === "screenshot" ? t("shortcuts.global.label") : t("shortcuts.screenshot.label");
+ if (globalBindingsEqual(binding, otherBinding)) {
+ setGlobalMessage(t("shortcuts.conflict", { label: otherLabel }));
+ return;
+ }
const conflict = getShortcutActionForEvent(event, shortcutSettings);
if (conflict) {
const label = shortcutActionOptions.find((item) => item.value === conflict)?.label ?? conflict;
setGlobalMessage(t("shortcuts.conflict", { label }));
return;
}
+ const target = recordingTarget;
finishRecording();
setGlobalBusy(true);
void (async () => {
await window.edgeeverDesktop?.captureGlobalShortcut(false);
- const state = await window.edgeeverDesktop?.setGlobalShortcut(binding);
+ const setter = target === "screenshot" ? window.edgeeverDesktop?.setScreenshotShortcut : window.edgeeverDesktop?.setGlobalShortcut;
+ const state = await setter?.(binding);
if (state) {
setGlobalShortcut(state);
setGlobalMessage(state.error ? t(`shortcuts.global.${state.error}`) : "");
@@ -134,7 +153,7 @@ export const ShortcutSettingsItem = ({ shortcutSettings, onShortcutSettingsChang
};
window.addEventListener("keydown", handleGlobalKeyDown, { capture: true });
return () => window.removeEventListener("keydown", handleGlobalKeyDown, { capture: true });
- }, [recordingGlobal, shortcutActionOptions, shortcutSettings, t]);
+ }, [globalShortcut, recordingTarget, shortcutActionOptions, shortcutSettings, t]);
useEffect(() => {
if (!recordingAction) {
@@ -174,6 +193,10 @@ export const ShortcutSettingsItem = ({ shortcutSettings, onShortcutSettingsChang
setCaptureMessage(t("shortcuts.conflict", { label: t("shortcuts.global.label") }));
return;
}
+ if (globalShortcut?.screenshot && globalBindingMatchesLocal(globalShortcut.screenshot, nextBinding)) {
+ setCaptureMessage(t("shortcuts.conflict", { label: t("shortcuts.screenshot.label") }));
+ return;
+ }
onShortcutSettingsChange({
...shortcutSettings,
@@ -193,35 +216,64 @@ export const ShortcutSettingsItem = ({ shortcutSettings, onShortcutSettingsChang
setCaptureMessage("");
};
+ const disableGlobalShortcut = (target: GlobalShortcutTarget) => {
+ setGlobalBusy(true);
+ const setter = target === "screenshot" ? window.edgeeverDesktop?.setScreenshotShortcut : window.edgeeverDesktop?.setGlobalShortcut;
+ void setter?.(null).then((state) => {
+ if (state) {
+ setGlobalShortcut(state);
+ setGlobalMessage(state.error ? t(`shortcuts.global.${state.error}`) : "");
+ }
+ }).catch(() => setGlobalMessage(t("shortcuts.global.saveFailed"))).finally(() => setGlobalBusy(false));
+ };
+
+ const globalRows: Array<{ target: GlobalShortcutTarget; label: string; description: string; binding: DesktopGlobalShortcutBinding | null | undefined; registered: boolean }> = [
+ {
+ target: "window",
+ label: t("shortcuts.global.label"),
+ description: t("shortcuts.global.description"),
+ binding: globalShortcut?.binding,
+ registered: Boolean(globalShortcut?.registered),
+ },
+ {
+ target: "screenshot",
+ label: t("shortcuts.screenshot.label"),
+ description: t("shortcuts.screenshot.description"),
+ binding: globalShortcut?.screenshot,
+ registered: Boolean(globalShortcut?.screenshotRegistered),
+ },
+ ];
+
return (
<div className="grid gap-4">
{window.edgeeverDesktop?.isAvailable ? (
<div className="overflow-hidden rounded-xl border border-slate-200 bg-card">
- <div className="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
- <div>
- <div className={SETTINGS_ITEM_TITLE_CLASSNAME}>{t("shortcuts.global.label")}</div>
- <p className="mt-1 text-xs text-slate-500">{t("shortcuts.global.description")}</p>
- </div>
- <div className="flex items-center gap-2">
- <Button type="button" variant="outline" className="h-8 min-w-24 px-3 font-mono text-xs font-normal" disabled={!globalShortcut || globalBusy || Boolean(recordingAction)} onClick={() => { void beginRecording("global"); }}>
- {recordingGlobal ? t("shortcuts.recording") : globalShortcut?.binding ? formatGlobalBinding(globalShortcut.binding) : t("shortcuts.global.disabled")}
- </Button>
- {globalShortcut?.binding ? (
- <Button type="button" variant="outline" className="h-8 px-3 text-xs font-normal" disabled={globalBusy || recordingGlobal || Boolean(recordingAction)} onClick={() => {
- setGlobalBusy(true);
- void window.edgeeverDesktop?.setGlobalShortcut(null).then((state) => {
- if (state) {
- setGlobalShortcut(state);
- setGlobalMessage(state.error ? t(`shortcuts.global.${state.error}`) : "");
- }
- }).catch(() => setGlobalMessage(t("shortcuts.global.saveFailed"))).finally(() => setGlobalBusy(false));
- }}>{t("shortcuts.global.disable")}</Button>
- ) : null}
- </div>
- </div>
- {globalShortcut?.binding && !globalShortcut.registered && !globalMessage ? (
- <div className="border-t border-amber-200 bg-amber-50 px-4 py-2 text-xs text-amber-700">{t("shortcuts.global.unavailable")}</div>
- ) : null}
+ {globalRows.map((row, index) => {
+ const recording = recordingTarget === row.target;
+ return (
+ <div key={row.target} className={cn(index > 0 && "border-t border-slate-100")}>
+ <div className="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
+ <div>
+ <div className={SETTINGS_ITEM_TITLE_CLASSNAME}>{row.label}</div>
+ <p className="mt-1 text-xs text-slate-500">{row.description}</p>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button type="button" variant="outline" className="h-8 min-w-24 px-3 font-mono text-xs font-normal" disabled={!globalShortcut || globalBusy || Boolean(recordingAction) || (Boolean(recordingTarget) && !recording)} onClick={() => { void beginRecording(row.target); }}>
+ {recording ? t("shortcuts.recording") : row.binding ? formatGlobalBinding(row.binding) : t("shortcuts.global.disabled")}
+ </Button>
+ {row.binding ? (
+ <Button type="button" variant="outline" className="h-8 px-3 text-xs font-normal" disabled={globalBusy || Boolean(recordingTarget) || Boolean(recordingAction)} onClick={() => disableGlobalShortcut(row.target)}>
+ {t("shortcuts.global.disable")}
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ {row.binding && !row.registered && !globalMessage ? (
+ <div className="border-t border-amber-200 bg-amber-50 px-4 py-2 text-xs text-amber-700">{t("shortcuts.global.unavailable")}</div>
+ ) : null}
+ </div>
+ );
+ })}
{globalMessage ? <div className="border-t border-amber-200 bg-amber-50 px-4 py-2 text-xs text-amber-700">{globalMessage}</div> : null}
</div>
) : null}
@@ -246,7 +298,7 @@ export const ShortcutSettingsItem = ({ shortcutSettings, onShortcutSettingsChang
variant={recording ? "solid" : "outline"}
className={cn("h-8 min-w-24 shrink-0 px-3 font-mono text-xs font-normal", !recording && "bg-card")}
onClick={() => { void beginRecording(item.value); }}
- disabled={recordingGlobal || globalBusy}
+ disabled={Boolean(recordingTarget) || globalBusy}
>
{recording ? t("shortcuts.recording") : formatShortcutBinding(shortcutSettings[item.value])}
</Button>
diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts
index 85bcf4bc..ec359227 100644
--- a/apps/web/src/vite-env.d.ts
+++ b/apps/web/src/vite-env.d.ts
@@ -25,6 +25,8 @@ interface DesktopGlobalShortcutBinding {
interface DesktopGlobalShortcutState {
binding: DesktopGlobalShortcutBinding | null;
registered: boolean;
+ screenshot: DesktopGlobalShortcutBinding | null;
+ screenshotRegistered: boolean;
error?: "invalid" | "unavailable" | "saveFailed";
}
@@ -91,6 +93,7 @@ interface EdgeEverDesktopBridge {
}>;
globalShortcut(): Promise<DesktopGlobalShortcutState>;
setGlobalShortcut(binding: DesktopGlobalShortcutBinding | null): Promise<DesktopGlobalShortcutState>;
+ setScreenshotShortcut(binding: DesktopGlobalShortcutBinding | null): Promise<DesktopGlobalShortcutState>;
loginItem(): Promise<DesktopLoginItemState | null>;
setLoginItem(patch: { openAtLogin?: boolean; launchMode?: "window" | "tray" }): Promise<DesktopLoginItemState | null>;
captureGlobalShortcut(capturing: boolean): Promise<boolean>;
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 9686e485..c81ab9b8 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -2088,6 +2088,10 @@ export const enUS = {
unavailable: "The system could not register this shortcut. Choose another combination or check system shortcut settings.",
saveFailed: "The shortcut could not be saved. Try again.",
},
+ screenshot: {
+ label: "Capture screen to note",
+ description: "Works from other apps. Press it, drag a region, and the screenshot becomes a note. Saved only on this device.",
+ },
title: "Keyboard shortcuts",
manage: "Manage",
description: "Set key combinations for common note actions. Press Esc to cancel recording.",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index 96071edb..42a1ba75 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -2077,6 +2077,10 @@ export const ja = {
unavailable: "システムに登録できませんでした。別の組み合わせを選ぶか、システム設定を確認してください。",
saveFailed: "ショートカットを保存できませんでした。再試行してください。",
},
+ screenshot: {
+ label: "画面をノートに取り込む",
+ description: "他のアプリからも使えます。押して範囲をドラッグすると、スクリーンショットがノートになります。この端末にのみ保存されます。",
+ },
title: "キーボードショートカット",
manage: "管理",
description: "よく使うノート操作のキー組み合わせを設定します。Esc で記録をキャンセルします。",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index 65ade940..134e733a 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -2077,6 +2077,10 @@ export const pl = {
unavailable: "System nie mógł zarejestrować skrótu. Wybierz inną kombinację lub sprawdź ustawienia systemowe.",
saveFailed: "Nie udało się zapisać skrótu. Spróbuj ponownie.",
},
+ screenshot: {
+ label: "Zrzut ekranu do notatki",
+ description: "Działa także w innych aplikacjach. Naciśnij skrót, zaznacz obszar, a zrzut zostanie zapisany jako notatka. Skrót jest zapisany tylko na tym urządzeniu.",
+ },
title: "Skróty klawiszowe",
manage: "Zarządzaj",
description: "Ustaw kombinacje klawiszy dla częstych działań na notatkach. Naciśnij Esc, aby przerwać nagrywanie.",
diff --git a/packages/shared/src/i18n/ru.ts b/packages/shared/src/i18n/ru.ts
index c30953d0..4afd7887 100644
--- a/packages/shared/src/i18n/ru.ts
+++ b/packages/shared/src/i18n/ru.ts
@@ -2088,6 +2088,10 @@ export const ru = {
unavailable: "Система не смогла зарегистрировать сочетание. Выберите другое или проверьте системные сочетания.",
saveFailed: "Не удалось сохранить сочетание. Повторите.",
},
+ screenshot: {
+ label: "Снимок экрана в заметку",
+ description: "Работает из других приложений. Нажмите сочетание, выделите область, и снимок станет заметкой. Сочетание хранится только на этом устройстве.",
+ },
title: "Горячие клавиши",
manage: "Управление",
description: "Задайте комбинации клавиш для типичных действий с заметками. Нажмите Esc, чтобы отменить запись.",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index c420199c..7b2d2bfb 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -2088,6 +2088,10 @@ export const zhCN = {
unavailable: "系统未能注册这个快捷键。请换一个组合键,或检查系统快捷键设置。",
saveFailed: "无法保存快捷键,请重试。",
},
+ screenshot: {
+ label: "截取屏幕到笔记",
+ description: "在其他应用中也可使用。按下后拖拽选择区域,截图会直接创建为笔记。此快捷键只保存在当前设备。",
+ },
title: "绑定快捷键",
manage: "管理",
description: "为常用笔记动作设置组合键。按 Esc 可取消当前录制。",