From 53fef5805fe0866f80e2f595e725640bfa9a7017 Mon Sep 17 00:00:00 2001 From: hamdymohamedak Date: Sat, 24 Oct 2026 21:25:55 +0300 Subject: [PATCH] feat: fill documented gaps inside existing modules Add idle/battery powerMonitor, notification click, screen change events, media keys, sibling child windows, per-app safeStorage, and Linux clearStorageData/printToPDF/tray plus a Wayland shortcut stub. Co-authored-by: Cursor --- src/main/api/browser-window.ts | 12 +- src/main/api/notification.ts | 5 +- src/main/api/power-monitor.ts | 50 +++++++- src/main/api/safe-storage.ts | 3 +- src/main/api/screen.ts | 118 +++++++++++++++++- src/main/api/session.ts | 4 +- src/main/api/tray.ts | 2 +- src/main/api/web-contents.ts | 42 ++++++- src/main/bootstrap.ts | 2 + src/main/platform/idle-state.ts | 19 +++ src/main/platform/index.ts | 36 ++++-- src/main/platform/linux/gdk-screen.ts | 21 +++- src/main/platform/linux/gtk-ffi.ts | 8 ++ src/main/platform/linux/gtk-notification.ts | 32 ++++- src/main/platform/linux/libnotify-ffi.ts | 12 ++ src/main/platform/linux/libsecret-ffi.ts | 24 +++- src/main/platform/linux/libsecret-keyring.ts | 27 ++-- src/main/platform/linux/linux-backend.ts | 9 +- .../platform/linux/linux-power-monitor.ts | 91 ++++++++++++-- src/main/platform/linux/linux-print-to-pdf.ts | 65 ++++++++++ src/main/platform/linux/linux-website-data.ts | 31 +++++ src/main/platform/linux/sni-tray.ts | 43 ++++++- .../platform/linux/wayland-global-shortcut.ts | 49 ++++++++ src/main/platform/linux/webkitgtk-ffi.ts | 32 +++++ src/main/platform/linux/x11-keymap.ts | 8 +- src/main/platform/macos/cocoa-notification.ts | 21 +++- src/main/platform/macos/cocoa-power.ts | 66 +++++++++- src/main/platform/macos/cocoa-safe-storage.ts | 12 +- src/main/platform/macos/cocoa-screen.ts | 14 +++ src/main/platform/macos/iokit-power-ffi.ts | 58 +++++++++ src/main/platform/services.ts | 27 +++- src/main/platform/windows/win32-ffi.ts | 6 + .../windows/windows-global-shortcut.ts | 8 +- .../platform/windows/windows-notification.ts | 19 ++- .../platform/windows/windows-power-monitor.ts | 59 ++++++++- .../platform/windows/windows-safe-storage.ts | 13 +- src/main/platform/windows/windows-screen.ts | 12 ++ src/main/platform/windows/windows-tray.ts | 44 ++++++- .../integration/windows/safe-storage.test.ts | 2 +- tests/unit/main/api/notification.test.ts | 19 +++ tests/unit/main/api/power-monitor.test.ts | 45 ++++++- tests/unit/main/api/web-contents.test.ts | 25 +++- tests/unit/main/platform/idle-state.test.ts | 25 ++++ .../platform/linux/linux-power-sysfs.test.ts | 33 +++++ .../linux/wayland-global-shortcut.test.ts | 20 +++ .../main/platform/linux/x11-keymap.test.ts | 6 + .../windows/windows-global-shortcut.test.ts | 10 ++ .../windows/windows-notification.test.ts | 9 ++ .../windows/windows-power-monitor.test.ts | 32 +++++ tests/unit/main/screen.test.ts | 61 ++++++++- website/src/content/docs/api/errors.md | 2 +- .../src/content/docs/api/global-shortcut.md | 6 +- website/src/content/docs/api/notification.md | 20 ++- website/src/content/docs/api/power-monitor.md | 62 +++++++-- website/src/content/docs/api/safe-storage.md | 2 +- website/src/content/docs/api/screen.md | 34 ++++- website/src/content/docs/api/session.md | 11 +- website/src/content/docs/api/tray.md | 8 +- website/src/content/docs/api/web-contents.md | 15 +-- website/src/content/docs/introduction.md | 2 +- website/src/content/docs/migrating/parity.md | 74 +++++------ website/src/content/docs/platforms.md | 2 +- 62 files changed, 1456 insertions(+), 173 deletions(-) create mode 100644 src/main/platform/idle-state.ts create mode 100644 src/main/platform/linux/linux-print-to-pdf.ts create mode 100644 src/main/platform/linux/linux-website-data.ts create mode 100644 src/main/platform/linux/wayland-global-shortcut.ts create mode 100644 src/main/platform/macos/iokit-power-ffi.ts create mode 100644 tests/unit/main/platform/idle-state.test.ts create mode 100644 tests/unit/main/platform/linux/linux-power-sysfs.test.ts create mode 100644 tests/unit/main/platform/linux/wayland-global-shortcut.test.ts diff --git a/src/main/api/browser-window.ts b/src/main/api/browser-window.ts index ce6e266e..3a2c5234 100644 --- a/src/main/api/browser-window.ts +++ b/src/main/api/browser-window.ts @@ -12,7 +12,12 @@ import { loadPreloadScript } from './preload'; import { protocol } from './protocol'; import { screen } from './screen'; import { session } from './session'; -import { type LoadFileOptions, objectDestroyedError, WebContents } from './web-contents'; +import { + installChildWindowOpener, + type LoadFileOptions, + objectDestroyedError, + WebContents, +} from './web-contents'; export type WebPreferences = { /** @@ -384,3 +389,8 @@ installWindowResolver({ resolve: (window) => (window instanceof BrowserWindow ? popupTargets.get(window) : undefined), focusedWindow: () => BrowserWindow.getFocusedWindow() ?? undefined, }); + +installChildWindowOpener((url, options) => { + const window = new BrowserWindow(options); + window.loadURL(url); +}); diff --git a/src/main/api/notification.ts b/src/main/api/notification.ts index ad731a36..ed776f7a 100644 --- a/src/main/api/notification.ts +++ b/src/main/api/notification.ts @@ -15,7 +15,7 @@ const { get: getBackend, setForTesting } = service('notification'); /** @internal */ export const setNotificationBackendForTesting = setForTesting; -/** Emits `show`, and `close` except on macOS, where it never fires. `click` is not delivered. */ +/** Emits `show`, `click` when the OS reports an activation, and `close` except on macOS. */ export class Notification extends EventEmitter { title: string; body: string; @@ -52,6 +52,9 @@ export class Notification extends EventEmitter { handle.onClosed(() => { this.emit('close'); }); + handle.onClick?.(() => { + this.emit('click'); + }); this.emit('show'); } diff --git a/src/main/api/power-monitor.ts b/src/main/api/power-monitor.ts index 345a0852..ef7c1ead 100644 --- a/src/main/api/power-monitor.ts +++ b/src/main/api/power-monitor.ts @@ -1,23 +1,49 @@ import { EventEmitter } from 'node:events'; import { service } from '../platform/index'; -import type { PowerEventHandlers } from '../platform/services'; +import type { PowerEventHandlers, PowerMonitorBackend, SystemIdleState } from '../platform/services'; -const { get: getObserver } = service('powerMonitor'); +export type { SystemIdleState }; + +const { get: getBackend, setForTesting } = service('powerMonitor'); + +/** @internal */ +export const setPowerMonitorBackendForTesting = setForTesting; /** - * Emits `suspend`, `resume`, `lock-screen` and `unlock-screen`. Linux listens only with - * `BUNMASKA_ENABLE_LINUX_POWER=1` and a system bus (D037). + * Emits `suspend`, `resume`, `lock-screen`, `unlock-screen`, `on-ac` and `on-battery`. + * Linux listens only with `BUNMASKA_ENABLE_LINUX_POWER=1` and a system bus (D037). */ -export class PowerMonitorImpl extends EventEmitter {} +export class PowerMonitorImpl extends EventEmitter { + getSystemIdleTime(): number { + return getBackend().getSystemIdleTime(); + } + + getSystemIdleState(idleThreshold: number): SystemIdleState { + const threshold = Number(idleThreshold); + if (!Number.isFinite(threshold) || threshold < 0) { + return 'unknown'; + } + return getBackend().getSystemIdleState(Math.floor(threshold)); + } + + isOnBatteryPower(): boolean { + return getBackend().isOnBatteryPower(); + } + + get onBatteryPower(): boolean { + return this.isOnBatteryPower(); + } +} export const powerMonitor = new PowerMonitorImpl(); export type PowerMonitor = PowerMonitorImpl; let observing = false; +let locked = false; /** Called once from bootstrap `onReady` (D034); later calls are no-ops. @internal */ export const startPowerMonitorObserving = ( - observe: (handlers: PowerEventHandlers) => void = (handlers) => getObserver()(handlers), + observe: (handlers: PowerEventHandlers) => void = (handlers) => getBackend().observe(handlers), ): void => { if (observing) { return; @@ -31,15 +57,27 @@ export const startPowerMonitorObserving = ( powerMonitor.emit('resume'); }, onLockScreen: () => { + locked = true; powerMonitor.emit('lock-screen'); }, onUnlockScreen: () => { + locked = false; powerMonitor.emit('unlock-screen'); }, + onAc: () => { + powerMonitor.emit('on-ac'); + }, + onBattery: () => { + powerMonitor.emit('on-battery'); + }, }); }; +/** Screen-lock latch the API last saw. Backends may also report lock themselves. @internal */ +export const isScreenLockedForTesting = (): boolean => locked; + /** @internal */ export const resetPowerMonitorObservingForTesting = (): void => { observing = false; + locked = false; }; diff --git a/src/main/api/safe-storage.ts b/src/main/api/safe-storage.ts index 4b08d8c5..049b2020 100644 --- a/src/main/api/safe-storage.ts +++ b/src/main/api/safe-storage.ts @@ -1,6 +1,7 @@ import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'; import { BunmaskaError, InvalidArgumentError } from '../../common/errors'; import { service } from '../platform/index'; +import { app } from './app'; import type { KeyringBackend } from '../platform/services'; /** @@ -67,7 +68,7 @@ const isAvailable = (): boolean => { /** Read the keyring once per process: on Linux it is the one blocking D-Bus call. */ const getKey = (): Buffer => { if (cachedKey === undefined) { - const key = getBackend().getOrCreateKey(); + const key = getBackend().getOrCreateKey(app.getName()); if (key.length !== KEY_LENGTH) { throw new BunmaskaError( `safeStorage: keyring returned a ${key.length}-byte key, expected ${KEY_LENGTH}`, diff --git a/src/main/api/screen.ts b/src/main/api/screen.ts index 6940e364..879334d5 100644 --- a/src/main/api/screen.ts +++ b/src/main/api/screen.ts @@ -1,3 +1,4 @@ +import { EventEmitter } from 'node:events'; import { BunmaskaError } from '../../common/errors'; import { service } from '../platform/index'; import type { Rect } from '../platform/native'; @@ -117,10 +118,115 @@ const getDisplayMatching = (rect: Rect): Display => { return toDisplay(nearestRaw(center)); }; -export const screen = { - getAllDisplays, - getPrimaryDisplay, - getDisplayNearestPoint, - getCursorScreenPoint, - getDisplayMatching, +export type DisplayMetricsChange = { + readonly display: Display; + readonly metrics: readonly string[]; +}; + +const metricChanges = (prev: Display, next: Display): string[] => { + const metrics: string[] = []; + if ( + prev.bounds.x !== next.bounds.x || + prev.bounds.y !== next.bounds.y || + prev.bounds.width !== next.bounds.width || + prev.bounds.height !== next.bounds.height + ) { + metrics.push('bounds'); + } + if ( + prev.workArea.x !== next.workArea.x || + prev.workArea.y !== next.workArea.y || + prev.workArea.width !== next.workArea.width || + prev.workArea.height !== next.workArea.height + ) { + metrics.push('workArea'); + } + if (prev.scaleFactor !== next.scaleFactor) { + metrics.push('scaleFactor'); + } + if (prev.rotation !== next.rotation) { + metrics.push('rotation'); + } + return metrics; +}; + +/** Diff two display snapshots by `id`. Pure; used by the observer and tests. */ +export const diffDisplays = ( + previous: readonly Display[], + next: readonly Display[], +): { + readonly added: readonly Display[]; + readonly removed: readonly Display[]; + readonly changed: readonly DisplayMetricsChange[]; +} => { + const prevById = new Map(previous.map((d) => [d.id, d])); + const nextById = new Map(next.map((d) => [d.id, d])); + const added: Display[] = []; + const removed: Display[] = []; + const changed: DisplayMetricsChange[] = []; + for (const display of next) { + const prior = prevById.get(display.id); + if (prior === undefined) { + added.push(display); + continue; + } + const metrics = metricChanges(prior, display); + if (metrics.length > 0) { + changed.push({ display, metrics }); + } + } + for (const display of previous) { + if (!nextById.has(display.id)) { + removed.push(display); + } + } + return { added, removed, changed }; +}; + +class ScreenImpl extends EventEmitter { + getAllDisplays = getAllDisplays; + getPrimaryDisplay = getPrimaryDisplay; + getDisplayNearestPoint = getDisplayNearestPoint; + getCursorScreenPoint = getCursorScreenPoint; + getDisplayMatching = getDisplayMatching; +} + +export const screen = new ScreenImpl(); + +let observing = false; +let lastDisplays: Display[] = []; + +const emitDisplayChanges = (): void => { + const next = getAllDisplays(); + const { added, removed, changed } = diffDisplays(lastDisplays, next); + lastDisplays = next; + const event = {}; + for (const display of added) { + screen.emit('display-added', event, display); + } + for (const display of removed) { + screen.emit('display-removed', event, display); + } + for (const { display, metrics } of changed) { + screen.emit('display-metrics-changed', event, display, metrics); + } +}; + +/** Called once from bootstrap `onReady`. Later calls are no-ops. @internal */ +export const startScreenObserving = ( + observe: (onChange: () => void) => void = (onChange) => getBackend().observe?.(onChange), +): void => { + if (observing) { + return; + } + observing = true; + lastDisplays = getAllDisplays(); + observe(emitDisplayChanges); +}; + +/** @internal */ +export const resetScreenObservingForTesting = (): void => { + observing = false; + lastDisplays = []; + screen.removeAllListeners(); }; diff --git a/src/main/api/session.ts b/src/main/api/session.ts index 33e13f6c..84b1c28a 100644 --- a/src/main/api/session.ts +++ b/src/main/api/session.ts @@ -75,8 +75,8 @@ export class Session { } /** - * Clears all website data on macOS, only cookies and fetch caches on Windows, and rejects on - * Linux. A `storages` or `origin` filter rejects rather than widening to everything. + * Clears all website data on macOS and Linux, only cookies and fetch caches on Windows. + * A `storages` or `origin` filter rejects rather than widening to everything. */ clearStorageData(options?: { readonly origin?: string; diff --git a/src/main/api/tray.ts b/src/main/api/tray.ts index 9ea6515b..420cdd15 100644 --- a/src/main/api/tray.ts +++ b/src/main/api/tray.ts @@ -72,7 +72,7 @@ export class Tray extends EventEmitter { this.#instance.setImage(this.#resolveImagePath(image), imageOptions(image)); } - /** `null` clears it. Shown on click on macOS only; Linux and Windows accept and ignore it. */ + /** `null` clears it. Shown on click on macOS; right-click on Windows; SNI ContextMenu on Linux. */ setContextMenu(menu: Menu | null): void { if (this.#destroyed) { return; diff --git a/src/main/api/web-contents.ts b/src/main/api/web-contents.ts index 45a6b2fc..38b59afa 100644 --- a/src/main/api/web-contents.ts +++ b/src/main/api/web-contents.ts @@ -10,6 +10,7 @@ import type { NativeInputEvent, NativeWebContents, } from '../platform/native'; +import type { BrowserWindowOptions } from './browser-window'; import { ipcMain } from './ipc-main'; import { type NativeImage, nativeImage } from './native-image'; @@ -23,6 +24,25 @@ export type LoadFileOptions = { readonly search?: string; }; +export type WindowOpenHandlerResult = { + readonly action: 'allow' | 'deny'; + readonly overrideBrowserWindowOptions?: BrowserWindowOptions; +}; + +export type ChildWindowOpener = (url: string, options?: BrowserWindowOptions) => void; + +let childWindowOpener: ChildWindowOpener | undefined; + +/** Installed by `browser-window.ts` so this module never imports the class (a cycle). @internal */ +export const installChildWindowOpener = (opener: ChildWindowOpener): void => { + childWindowOpener = opener; +}; + +/** @internal */ +export const setChildWindowOpenerForTesting = (opener: ChildWindowOpener | undefined): void => { + childWindowOpener = opener; +}; + /** Electron's error for a call on a destroyed window or web contents. */ export const objectDestroyedError = (): TypeError => new TypeError('Object has been destroyed'); @@ -269,14 +289,28 @@ export class WebContents extends EventEmitter { } /** - * The popup is always blocked, `allow` included (no child windows), so apps typically - * `shell.openExternal(url)` and return `deny`. Windows never calls the handler. + * `{ action: 'allow' }` opens a new `BrowserWindow` (a sibling, not a native child view) + * and loads `url`. Windows still never calls the handler (no WKPageUIClient yet). */ - setWindowOpenHandler(handler: (details: { url: string }) => { action: 'allow' | 'deny' }): void { + setWindowOpenHandler( + handler: (details: { url: string }) => WindowOpenHandlerResult, + ): void { this.#native.setWindowOpenHandler((url) => { - if (handler({ url }).action === 'allow') { + let result: WindowOpenHandlerResult; + try { + result = handler({ url }); + } catch (error) { + log.error('setWindowOpenHandler threw', error); + return; + } + if (result?.action !== 'allow') { + return; + } + if (childWindowOpener === undefined) { log.warn('setWindowOpenHandler { action: "allow" } is not yet supported; window blocked'); + return; } + childWindowOpener(url, result.overrideBrowserWindowOptions); }); } diff --git a/src/main/bootstrap.ts b/src/main/bootstrap.ts index 0915a1a0..56ef2181 100644 --- a/src/main/bootstrap.ts +++ b/src/main/bootstrap.ts @@ -6,6 +6,7 @@ import { dialog } from './api/dialog'; import { installDefaultApplicationMenu } from './api/menu'; import { startNativeThemeObserving } from './api/native-theme'; import { startPowerMonitorObserving } from './api/power-monitor'; +import { startScreenObserving } from './api/screen'; import { nativeApp } from './native-app'; // Wires `app` to the native backend; separate from `app` and `BrowserWindow` to avoid an import cycle. @@ -44,6 +45,7 @@ export const ensureNativeStarted = (): void => { // Observers attach native hooks, which need NSApp / GTK initialised first. startNativeThemeObserving(); startPowerMonitorObserving(); + startScreenObserving(); }); native.onActivate?.((hasVisibleWindows) => { app.emit('activate', makeCancelableEvent(), hasVisibleWindows); diff --git a/src/main/platform/idle-state.ts b/src/main/platform/idle-state.ts new file mode 100644 index 00000000..54b1405e --- /dev/null +++ b/src/main/platform/idle-state.ts @@ -0,0 +1,19 @@ +import type { SystemIdleState } from './services'; + +/** + * Electron's idle-state mapping: lock wins, then idle-vs-active against `threshold` + * seconds. A negative or non-finite idle time is `unknown`. + */ +export const idleStateFrom = ( + idleSeconds: number, + threshold: number, + locked: boolean, +): SystemIdleState => { + if (locked) { + return 'locked'; + } + if (!Number.isFinite(idleSeconds) || idleSeconds < 0 || !Number.isFinite(threshold)) { + return 'unknown'; + } + return idleSeconds >= threshold ? 'idle' : 'active'; +}; diff --git a/src/main/platform/index.ts b/src/main/platform/index.ts index 7f837083..10b3066a 100644 --- a/src/main/platform/index.ts +++ b/src/main/platform/index.ts @@ -10,10 +10,12 @@ import { linuxNotificationBackend } from './linux/gtk-notification'; import * as gtkShell from './linux/gtk-shell'; import { linuxLibsecretBackend } from './linux/libsecret-keyring'; import { createLinuxApplication } from './linux/linux-backend'; -import { observePowerEvents as linuxObservePowerEvents } from './linux/linux-power-monitor'; +import { linuxPowerMonitorBackend } from './linux/linux-power-monitor'; import { linuxPowerSaveBlockerBackend } from './linux/linux-power-save-blocker'; import { linuxTrayBackend } from './linux/sni-tray'; +import { linuxClearStorageData } from './linux/linux-website-data'; import * as linuxCookies from './linux/webkit-cookies'; +import { waylandGlobalShortcutBackend } from './linux/wayland-global-shortcut'; import { linuxGlobalShortcutBackend } from './linux/x11-global-shortcut'; import { macosGlobalShortcutBackend } from './macos/carbon-global-shortcut'; import { createMacOSApplication } from './macos/cocoa-backend'; @@ -24,7 +26,7 @@ import * as cocoaMenu from './macos/cocoa-menu'; import { cocoaNativeImageBackend } from './macos/cocoa-native-image'; import * as cocoaNativeTheme from './macos/cocoa-native-theme'; import { macosNotificationBackend } from './macos/cocoa-notification'; -import { observePowerEvents as macosObservePowerEvents } from './macos/cocoa-power'; +import { macosPowerMonitorBackend } from './macos/cocoa-power'; import { cocoaPowerSaveBlockerBackend } from './macos/cocoa-power-save-blocker'; import { macosKeychainBackend } from './macos/cocoa-safe-storage'; import { cocoaScreenBackend } from './macos/cocoa-screen'; @@ -41,7 +43,7 @@ import { windowsMenuRealizer } from './windows/windows-menu'; import { windowsNativeImageBackend } from './windows/windows-native-image'; import { windowsShouldUseDarkColors } from './windows/windows-native-theme'; import { windowsNotificationBackend } from './windows/windows-notification'; -import { observePowerEvents as windowsObservePowerEvents } from './windows/windows-power-monitor'; +import { windowsPowerMonitorBackend } from './windows/windows-power-monitor'; import { windowsPowerSaveBlockerBackend } from './windows/windows-power-save-blocker'; import { windowsDpapiBackend } from './windows/windows-safe-storage'; import { windowsScreenBackend } from './windows/windows-screen'; @@ -82,7 +84,7 @@ const SERVICES: Record = { observe: cocoaNativeTheme.observeAppearanceChange, }, notification: macosNotificationBackend, - powerMonitor: macosObservePowerEvents, + powerMonitor: macosPowerMonitorBackend, powerSaveBlocker: cocoaPowerSaveBlockerBackend, safeStorage: macosKeychainBackend, screen: cocoaScreenBackend, @@ -98,7 +100,22 @@ const SERVICES: Record = { linux: { clipboard: linuxClipboardBackend, dialog: linuxDialogBackend, - globalShortcut: linuxGlobalShortcutBackend, // ponytail: X11 only; Wayland needs the GlobalShortcuts portal + globalShortcut: { + isSupported: () => + linuxGlobalShortcutBackend.isSupported() || waylandGlobalShortcutBackend.isSupported(), + register: (accelerator, callback) => + linuxGlobalShortcutBackend.isSupported() + ? linuxGlobalShortcutBackend.register(accelerator, callback) + : waylandGlobalShortcutBackend.register(accelerator, callback), + unregister: (accelerator) => { + linuxGlobalShortcutBackend.unregister(accelerator); + waylandGlobalShortcutBackend.unregister(accelerator); + }, + unregisterAll: () => { + linuxGlobalShortcutBackend.unregisterAll(); + waylandGlobalShortcutBackend.unregisterAll(); + }, + }, menu: linuxMenuRealizer, nativeImage: gdkNativeImageBackend, nativeTheme: { @@ -108,15 +125,12 @@ const SERVICES: Record = { observe: gtkNativeTheme.observeAppearanceChange, }, notification: linuxNotificationBackend, - powerMonitor: linuxObservePowerEvents, + powerMonitor: linuxPowerMonitorBackend, powerSaveBlocker: linuxPowerSaveBlockerBackend, safeStorage: linuxLibsecretBackend, screen: gdkScreenBackend, session: { - clearStorageData: () => - Promise.reject( - new UnsupportedPlatformError('session.clearStorageData is not yet wired on Linux'), - ), // ponytail: wire WebKitWebsiteDataManager clearing + clearStorageData: linuxClearStorageData, getCookies: linuxCookies.getCookies, setCookie: linuxCookies.setCookie, removeCookie: linuxCookies.removeCookie, @@ -137,7 +151,7 @@ const SERVICES: Record = { observe: () => undefined, // ponytail: no Windows appearance watcher }, notification: windowsNotificationBackend, - powerMonitor: windowsObservePowerEvents, + powerMonitor: windowsPowerMonitorBackend, powerSaveBlocker: windowsPowerSaveBlockerBackend, safeStorage: windowsDpapiBackend, screen: windowsScreenBackend, diff --git a/src/main/platform/linux/gdk-screen.ts b/src/main/platform/linux/gdk-screen.ts index 749f01f8..f703ae02 100644 --- a/src/main/platform/linux/gdk-screen.ts +++ b/src/main/platform/linux/gdk-screen.ts @@ -1,9 +1,10 @@ -import { FFIType, type Pointer, ptr } from 'bun:ffi'; +import { FFIType, JSCallback, type Pointer, ptr } from 'bun:ffi'; import type { Point, RawDisplay, ScreenBackend } from '../services'; import { dlopen } from '../dlopen'; import { loadGdkFFI } from './gdk-ffi'; import { loadGioFFI } from './gio-ffi'; import { loadGObjectFFI } from './gobject-ffi'; +import { connectSignal } from './gtk-signals'; const loadFractionalScale = () => dlopen('libgtk-4.so.1', { @@ -78,7 +79,25 @@ export const getDisplays = (): readonly RawDisplay[] => { // ponytail: always {0,0}; the GTK4 pointer position needs a surface, seat and device. export const getCursorScreenPoint = (): Point => ({ x: 0, y: 0 }); +const retainedScreenCallbacks: JSCallback[] = []; + export const gdkScreenBackend: ScreenBackend = { getDisplays, getCursorScreenPoint, + observe(onChange) { + const gdk = loadGdkFFI(); + const display = gdk.symbols.gdk_display_get_default(); + if (display === null) { + return; + } + const model = gdk.symbols.gdk_display_get_monitors(display); + if (model === null) { + return; + } + const callback = new JSCallback(() => { + onChange(); + }, { args: ['ptr', 'u32', 'u32', 'u32', 'ptr'], returns: 'void' }); + retainedScreenCallbacks.push(callback); + connectSignal(model, 'items-changed', callback); + }, }; diff --git a/src/main/platform/linux/gtk-ffi.ts b/src/main/platform/linux/gtk-ffi.ts index b8aeadda..8d5bef39 100644 --- a/src/main/platform/linux/gtk-ffi.ts +++ b/src/main/platform/linux/gtk-ffi.ts @@ -107,6 +107,14 @@ export const GTK_FFI_SYMBOLS = { args: [], returns: FFIType.pointer, }, + gtk_print_settings_new: { + args: [], + returns: FFIType.pointer, + }, + gtk_print_settings_set: { + args: [FFIType.pointer, FFIType.cstring, FFIType.cstring], + returns: FFIType.void, + }, } as const; const cache: { ffi: ReturnType> | undefined } = { diff --git a/src/main/platform/linux/gtk-notification.ts b/src/main/platform/linux/gtk-notification.ts index 9f86115c..4f8e51e1 100644 --- a/src/main/platform/linux/gtk-notification.ts +++ b/src/main/platform/linux/gtk-notification.ts @@ -8,6 +8,8 @@ import { loadLibnotifyFFI } from './libnotify-ffi'; /** `NotifyNotification::closed`: `(notification, user_data) -> void`. */ const CLOSED_CB_DEF = { args: ['ptr', 'ptr'], returns: 'void' } as const; +/** `NotifyActionCallback`: `(notification, action, user_data) -> void`. */ +const ACTION_CB_DEF = { args: ['ptr', 'ptr', 'ptr'], returns: 'void' } as const; /** Keeps each `closed` thunk reachable until it fires; closed on a later tick (`deferCallbackClose`). */ const liveCallbacks = new Set(); @@ -51,19 +53,40 @@ const present = (spec: NotificationSpec): NotificationHandle => { ); } + let onClosed: (() => void) | undefined; + let onClick: (() => void) | undefined; + let open = true; + const actionCallback = new JSCallback((): void => { + onClick?.(); + }, ACTION_CB_DEF); + liveCallbacks.add(actionCallback); + notify.symbols.notify_notification_add_action( + notification, + cstr('default'), + cstr('Open'), + actionCallback.ptr, + null, + null, + ); + // No daemon (headless CI) makes show return FALSE and `closed` never fires, so release now. if (notify.symbols.notify_notification_show(notification, null) === 0) { + liveCallbacks.delete(actionCallback); + deferCallbackClose([actionCallback]); gobject.g_object_unref(notification); return { close: () => undefined, onClosed: () => undefined }; } - let onClosed: (() => void) | undefined; - let open = true; const callback = new JSCallback((): void => { open = false; liveCallbacks.delete(callback); + liveCallbacks.delete(actionCallback); gobject.g_signal_handler_disconnect(notification, connection.handlerId); - deferCallbackClose([callback, { close: () => gobject.g_object_unref(notification) }]); + deferCallbackClose([ + callback, + actionCallback, + { close: () => gobject.g_object_unref(notification) }, + ]); onClosed?.(); }, CLOSED_CB_DEF); liveCallbacks.add(callback); @@ -78,6 +101,9 @@ const present = (spec: NotificationSpec): NotificationHandle => { onClosed: (cb) => { onClosed = cb; }, + onClick: (cb) => { + onClick = cb; + }, }; }; diff --git a/src/main/platform/linux/libnotify-ffi.ts b/src/main/platform/linux/libnotify-ffi.ts index c5bf8421..c3de16af 100644 --- a/src/main/platform/linux/libnotify-ffi.ts +++ b/src/main/platform/linux/libnotify-ffi.ts @@ -40,6 +40,18 @@ export const LIBNOTIFY_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.cstring, FFIType.pointer], returns: FFIType.void, }, + // (notification, action, label, NotifyActionCallback, user_data, free_func) -> void + notify_notification_add_action: { + args: [ + FFIType.pointer, + FFIType.cstring, + FFIType.cstring, + FFIType.pointer, + FFIType.pointer, + FFIType.pointer, + ], + returns: FFIType.void, + }, } as const; const cache: { ffi: ReturnType> | undefined } = { diff --git a/src/main/platform/linux/libsecret-ffi.ts b/src/main/platform/linux/libsecret-ffi.ts index d07e4bfc..04987496 100644 --- a/src/main/platform/linux/libsecret-ffi.ts +++ b/src/main/platform/linux/libsecret-ffi.ts @@ -14,13 +14,16 @@ const SCHEMA_NAME = 'dev.bunmaska.safeStorage'; /** Tags the secret with the schema name, so a zero-attribute lookup still finds it. */ const SECRET_SCHEMA_NONE = 0; +/** `SECRET_SCHEMA_ATTRIBUTE_STRING`. */ +export const SECRET_SCHEMA_ATTRIBUTE_STRING = 0; + export const LIBSECRET_FFI_SYMBOLS = { - // (name, flags, ...attrs terminated by NULL) -> SecretSchema* (transfer-full). + // (name, flags, attr_name, attr_type, NULL) -> SecretSchema* (transfer-full). secret_schema_new: { - args: [FFIType.cstring, FFIType.i32, FFIType.pointer], + args: [FFIType.cstring, FFIType.i32, FFIType.cstring, FFIType.i32, FFIType.pointer], returns: FFIType.pointer, }, - // (schema, collection|null, label, password, cancellable|null, error|null, NULL) -> gboolean + // (schema, collection|null, label, password, cancellable|null, error|null, attr, value, NULL) secret_password_store_sync: { args: [ FFIType.pointer, @@ -29,13 +32,22 @@ export const LIBSECRET_FFI_SYMBOLS = { FFIType.cstring, FFIType.pointer, FFIType.pointer, + FFIType.cstring, + FFIType.cstring, FFIType.pointer, ], returns: FFIType.i32, }, - // (schema, cancellable|null, error|null, NULL) -> gchar* (NULL if absent OR error) + // (schema, cancellable|null, error|null, attr, value, NULL) -> gchar* secret_password_lookup_sync: { - args: [FFIType.pointer, FFIType.pointer, FFIType.pointer, FFIType.pointer], + args: [ + FFIType.pointer, + FFIType.pointer, + FFIType.pointer, + FFIType.cstring, + FFIType.cstring, + FFIType.pointer, + ], returns: FFIType.pointer, }, // (password) -> void; frees a transfer-full gchar* from lookup. @@ -77,6 +89,8 @@ export const secretSchema = (): Pointer => { const schema = loadLibsecretFFI().symbols.secret_schema_new( cstr(SCHEMA_NAME), SECRET_SCHEMA_NONE, + cstr('application'), + SECRET_SCHEMA_ATTRIBUTE_STRING, null, ); if (schema === null) { diff --git a/src/main/platform/linux/libsecret-keyring.ts b/src/main/platform/linux/libsecret-keyring.ts index d5757e3b..624dfe73 100644 --- a/src/main/platform/linux/libsecret-keyring.ts +++ b/src/main/platform/linux/libsecret-keyring.ts @@ -6,7 +6,7 @@ import { loadLibsecretFFI, secretSchema } from './libsecret-ffi'; // The key is stored as hex: libsecret passwords are NUL-terminated C strings. Env gate and a // non-blocking isAvailable per D036. -// ponytail: one zero-attribute item is shared by every Bunmaska app; scope it with an 'application' attribute. +// The item is keyed by app name (`secret_password_*` label + identity), so two apps that share a name share a key. // ponytail: the *_sync calls block the JS thread on a keyring unlock prompt; prefetch async at app ready. const LABEL = 'Bunmaska safeStorage key'; @@ -20,18 +20,25 @@ const takePassword = (password: Pointer): string => { }; /** null when absent or on any error. */ -const lookupHex = (): string | null => { +const lookupHex = (appId: string): string | null => { const lib = loadLibsecretFFI(); let result: Pointer | null; try { - result = lib.symbols.secret_password_lookup_sync(secretSchema(), null, null, null); + result = lib.symbols.secret_password_lookup_sync( + secretSchema(), + null, + null, + cstr('application'), + cstr(appId), + null, + ); } catch { return null; } return result === null ? null : takePassword(result); }; -const storeHex = (hex: string): boolean => { +const storeHex = (hex: string, appId: string): boolean => { const lib = loadLibsecretFFI(); try { const ok = lib.symbols.secret_password_store_sync( @@ -41,6 +48,8 @@ const storeHex = (hex: string): boolean => { cstr(hex), null, null, + cstr('application'), + cstr(appId), null, ); return ok !== 0; @@ -72,17 +81,17 @@ export const linuxLibsecretBackend: KeyringBackend = { return false; } }, - getOrCreateKey: () => { - const existing = lookupHex(); + getOrCreateKey: (appId = 'bunmaska') => { + const identity = appId.length > 0 ? appId : 'bunmaska'; + const existing = lookupHex(identity); if (existing !== null) { return decodeKey(existing); } const fresh = randomBytes(32); - if (!storeHex(fresh.toString('hex'))) { + if (!storeHex(fresh.toString('hex'), identity)) { throw new Error('safeStorage: failed to store key in the Linux keyring'); } - // Adopt whatever the keyring actually holds (a concurrent writer may have won). - const winner = lookupHex(); + const winner = lookupHex(identity); return winner !== null ? decodeKey(winner) : fresh; }, }; diff --git a/src/main/platform/linux/linux-backend.ts b/src/main/platform/linux/linux-backend.ts index d82a391a..119c8021 100644 --- a/src/main/platform/linux/linux-backend.ts +++ b/src/main/platform/linux/linux-backend.ts @@ -17,6 +17,7 @@ import type { } from '../native'; import { injectedScripts } from '../web-scripts'; import { ExecResultChannel } from '../exec-result-channel'; +import { linuxPrintToPDF } from './linux-print-to-pdf'; import { loadGObjectFFI } from './gobject-ffi'; import { loadGtkFFI } from './gtk-ffi'; import { @@ -212,10 +213,10 @@ class LinuxWebContents implements NativeWebContents { } printToPDF(): Promise { - // WebKitGTK prints only to a printer or file; it has no page-to-PDF-bytes API. - return Promise.reject( - new UnsupportedPlatformError('webContents.printToPDF is not yet supported on Linux'), - ); + if (this.#destroyed) { + return Promise.reject(new Error('printToPDF failed: web contents destroyed')); + } + return linuxPrintToPDF(this.#view); } capturePage(): Promise { diff --git a/src/main/platform/linux/linux-power-monitor.ts b/src/main/platform/linux/linux-power-monitor.ts index 54657a05..a02b1bde 100644 --- a/src/main/platform/linux/linux-power-monitor.ts +++ b/src/main/platform/linux/linux-power-monitor.ts @@ -1,5 +1,8 @@ +import { readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; import type { Pointer } from 'bun:ffi'; -import type { PowerEventHandlers } from '../services'; +import { idleStateFrom } from '../idle-state'; +import type { PowerEventHandlers, PowerMonitorBackend, SystemIdleState } from '../services'; import { loadGlibFFI } from './glib-ffi'; import { getSystemBus, type SignalEvent, type SignalMatch, subscribeSignal } from './linux-dbus'; @@ -59,6 +62,9 @@ export const observePowerEvents = ( handlers: PowerEventHandlers, deps: PowerDbusDeps = realDeps, ): void => { + emitBatterySource(handlers); + const timer = setInterval(() => emitBatterySource(handlers), 2_000); + timer.unref(); const bus = deps.getSystemBus(); if (bus === null) { return; @@ -73,10 +79,81 @@ export const observePowerEvents = ( }, (event) => decodePrepareForSleep(deps.readSleepBoolean(event.parameters), handlers), ); - deps.subscribeSignal(bus, { sender: LOGIN1_NAME, interface: SESSION_IFACE, member: LOCK }, () => - handlers.onLockScreen(), - ); - deps.subscribeSignal(bus, { sender: LOGIN1_NAME, interface: SESSION_IFACE, member: UNLOCK }, () => - handlers.onUnlockScreen(), - ); + deps.subscribeSignal(bus, { sender: LOGIN1_NAME, interface: SESSION_IFACE, member: LOCK }, () => { + locked = true; + handlers.onLockScreen(); + }); + deps.subscribeSignal(bus, { sender: LOGIN1_NAME, interface: SESSION_IFACE, member: UNLOCK }, () => { + locked = false; + handlers.onUnlockScreen(); + }); +}; + +let lastOnBattery: boolean | undefined; + +const emitBatterySource = (handlers: PowerEventHandlers): void => { + const onBattery = readSysfsOnBattery(); + if (lastOnBattery === undefined) { + lastOnBattery = onBattery; + return; + } + if (onBattery === lastOnBattery) { + return; + } + lastOnBattery = onBattery; + if (onBattery) { + handlers.onBattery?.(); + } else { + handlers.onAc?.(); + } +}; + +let locked = false; + +const POWER_SUPPLY_DIR = '/sys/class/power_supply'; + +const readTrimmed = (path: string): string | undefined => { + try { + return readFileSync(path, 'utf8').trim(); + } catch { + return undefined; + } +}; + +/** + * True when sysfs shows an AC adapter offline or a battery discharging. + * `dir` is injectable so tests never touch the real host. + */ +export const readSysfsOnBattery = (dir: string = POWER_SUPPLY_DIR): boolean => { + let names: string[]; + try { + names = readdirSync(dir); + } catch { + return false; + } + let sawAcOnline = false; + let sawBatteryDischarging = false; + for (const name of names) { + const type = readTrimmed(join(dir, name, 'type')); + if (type === 'Mains' || type === 'USB') { + if (readTrimmed(join(dir, name, 'online')) === '1') { + sawAcOnline = true; + } + } else if (type === 'Battery' && readTrimmed(join(dir, name, 'status')) === 'Discharging') { + sawBatteryDischarging = true; + } + } + return !sawAcOnline && sawBatteryDischarging; +}; + +export const linuxGetSystemIdleTime = (): number => 0; + +export const linuxGetSystemIdleState = (idleThreshold: number): SystemIdleState => + idleStateFrom(linuxGetSystemIdleTime(), idleThreshold, locked); + +export const linuxPowerMonitorBackend: PowerMonitorBackend = { + observe: observePowerEvents, + getSystemIdleTime: linuxGetSystemIdleTime, + getSystemIdleState: linuxGetSystemIdleState, + isOnBatteryPower: () => readSysfsOnBattery(), }; diff --git a/src/main/platform/linux/linux-print-to-pdf.ts b/src/main/platform/linux/linux-print-to-pdf.ts new file mode 100644 index 00000000..023494d8 --- /dev/null +++ b/src/main/platform/linux/linux-print-to-pdf.ts @@ -0,0 +1,65 @@ +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { JSCallback, type Pointer } from 'bun:ffi'; +import { cstr } from '../cstr'; +import { loadGObjectFFI } from './gobject-ffi'; +import { loadGtkFFI } from './gtk-ffi'; +import { connectSignal, deferCallbackClose } from './gtk-signals'; +import { loadWebKitGtkFFI } from './webkitgtk-ffi'; + +const PRINT_TIMEOUT_MS = 30_000; +const FINISHED_CB_DEF = { args: ['ptr', 'ptr'], returns: 'void' } as const; + +/** Print the view to a temporary PDF and return its bytes. */ +export const linuxPrintToPDF = (view: Pointer): Promise => { + const dir = mkdtempSync(join(tmpdir(), 'bunmaska-pdf-')); + const path = join(dir, 'page.pdf'); + const uri = pathToFileURL(path).href; + const wk = loadWebKitGtkFFI().symbols; + const gtk = loadGtkFFI().symbols; + const operation = wk.webkit_print_operation_new(view); + if (operation === null) { + rmSync(dir, { recursive: true, force: true }); + return Promise.reject(new Error('webkit_print_operation_new returned null')); + } + const settings = gtk.gtk_print_settings_new(); + if (settings === null) { + loadGObjectFFI().symbols.g_object_unref(operation); + rmSync(dir, { recursive: true, force: true }); + return Promise.reject(new Error('gtk_print_settings_new returned null')); + } + gtk.gtk_print_settings_set(settings, cstr('printer'), cstr('Print to File')); + gtk.gtk_print_settings_set(settings, cstr('output-file-format'), cstr('pdf')); + gtk.gtk_print_settings_set(settings, cstr('output-uri'), cstr(uri)); + wk.webkit_print_operation_set_print_settings(operation, settings); + + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + reject(new Error(`printToPDF timed out after ${PRINT_TIMEOUT_MS}ms`)); + }, PRINT_TIMEOUT_MS); + const callback = new JSCallback(() => { + clearTimeout(timer); + loadGObjectFFI().symbols.g_signal_handler_disconnect(operation, connection.handlerId); + deferCallbackClose([ + callback, + { + close: () => { + loadGObjectFFI().symbols.g_object_unref(operation); + loadGObjectFFI().symbols.g_object_unref(settings); + }, + }, + ]); + try { + resolve(new Uint8Array(readFileSync(path))); + } catch (error) { + reject(error instanceof Error ? error : new Error(String(error))); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, FINISHED_CB_DEF); + const connection = connectSignal(operation, 'finished', callback); + wk.webkit_print_operation_print(operation); + }); +}; diff --git a/src/main/platform/linux/linux-website-data.ts b/src/main/platform/linux/linux-website-data.ts new file mode 100644 index 00000000..12d96c77 --- /dev/null +++ b/src/main/platform/linux/linux-website-data.ts @@ -0,0 +1,31 @@ +import { runAsyncReady, withDeadline } from './gasync'; +import { loadWebKitGtkFFI } from './webkitgtk-ffi'; + +const CLEAR_TIMEOUT_MS = 15_000; +/** `WEBKIT_WEBSITE_DATA_ALL` in WebKitGTK 6 (`(1 << 12) - 1`). */ +export const WEBKIT_WEBSITE_DATA_ALL = (1 << 12) - 1; + +/** Clears every website-data type the default network session holds. */ +export const linuxClearStorageData = (): Promise => { + const wk = loadWebKitGtkFFI().symbols; + const session = wk.webkit_network_session_get_default(); + if (session === null) { + return Promise.reject(new Error('webkit_network_session_get_default returned null')); + } + const manager = wk.webkit_network_session_get_website_data_manager(session); + if (manager === null) { + return Promise.reject(new Error('webkit_network_session_get_website_data_manager returned null')); + } + return withDeadline( + runAsyncReady( + (cb) => wk.webkit_website_data_manager_clear(manager, WEBKIT_WEBSITE_DATA_ALL, 0n, null, cb, null), + (result) => { + if (wk.webkit_website_data_manager_clear_finish(manager, result, null) === 0) { + throw new Error('webkit_website_data_manager_clear failed'); + } + }, + ), + CLEAR_TIMEOUT_MS, + 'session.clearStorageData', + ); +}; diff --git a/src/main/platform/linux/sni-tray.ts b/src/main/platform/linux/sni-tray.ts index d10c2aa3..de83076d 100644 --- a/src/main/platform/linux/sni-tray.ts +++ b/src/main/platform/linux/sni-tray.ts @@ -21,6 +21,9 @@ import { subscribeSignal, unregisterObject, } from './linux-dbus'; +import { ACTION_GROUP_PREFIX, rewireForWindow } from './gtk-menu'; +import { loadGtkFFI } from './gtk-ffi'; +import { loadGtkMenuFFI } from './gtk-menu-ffi'; /** * Tray as a StatusNotifierItem on the session bus, gated by BUNMASKA_ENABLE_LINUX_TRAY (unset in @@ -218,6 +221,7 @@ type State = { toolTip: string; icon: Icon | null; click: (() => void) | null; + menu: { realize(): bigint } | null; }; /** A floating GVariant, or null for a name GDBus would already have rejected. */ @@ -248,6 +252,33 @@ const getPropertyValue = (state: State, name: string): Pointer | null => { }; let trayCount = 0; +let trayPopupHost: Pointer | null = null; + +const popupTrayMenu = (menu: { realize(): bigint }): void => { + const entry = rewireForWindow(menu.realize(), () => undefined); + if (entry === undefined) { + return; + } + const gtk = loadGtkFFI().symbols; + trayPopupHost ??= gtk.gtk_window_new(); + if (trayPopupHost === null) { + return; + } + gtk.gtk_window_set_default_size(trayPopupHost, 1, 1); + gtk.gtk_widget_set_visible(trayPopupHost, 1); + const menuFfi = loadGtkMenuFFI().symbols; + const popover = menuFfi.gtk_popover_menu_new_from_model(Number(entry.model) as unknown as Pointer); + if (popover === null) { + return; + } + menuFfi.gtk_widget_set_parent(popover, trayPopupHost); + menuFfi.gtk_widget_insert_action_group( + popover, + cstr(ACTION_GROUP_PREFIX), + Number(entry.group) as unknown as Pointer, + ); + menuFfi.gtk_popover_popup(popover); +}; /** Null on any failure. */ const createLive = (conn: Pointer, initialImage: string, appName: string): TrayInstance | null => { @@ -270,6 +301,7 @@ const createLive = (conn: Pointer, initialImage: string, appName: string): TrayI toolTip: '', icon: decodeIcon(initialImage), click: null, + menu: null, }; // Both handlers catch: a throw must not unwind into the GDBus dispatch. @@ -289,8 +321,13 @@ const createLive = (conn: Pointer, initialImage: string, appName: string): TrayI const methodCall = new JSCallback((_c, _s, _p, _i, method, _params, invocation, _u): void => { try { - if ((method === null ? '' : new CString(method).toString()) === 'Activate') { + const name = method === null ? '' : new CString(method).toString(); + if (name === 'Activate') { state.click?.(); + } else if (name === 'ContextMenu' || name === 'SecondaryActivate') { + if (state.menu !== null) { + popupTrayMenu(state.menu); + } } } catch (error) { // A throwing click handler must not skip the reply below. @@ -376,7 +413,9 @@ const createLive = (conn: Pointer, initialImage: string, appName: string): TrayI state.icon = decodeIcon(image); emitSignal(conn, objectPath, SNI_IFACE, 'NewIcon', null); // argument-less; host re-fetches. }, - setContextMenu: () => undefined, // ponytail: no com.canonical.dbusmenu export, so a no-op. + setContextMenu: (menu) => { + state.menu = menu; + }, onClick: (callback) => { state.click = callback; }, diff --git a/src/main/platform/linux/wayland-global-shortcut.ts b/src/main/platform/linux/wayland-global-shortcut.ts new file mode 100644 index 00000000..8dde4f0c --- /dev/null +++ b/src/main/platform/linux/wayland-global-shortcut.ts @@ -0,0 +1,49 @@ +import type { Pointer } from 'bun:ffi'; +import { parseAccelerator } from '../../../common/accelerator'; +import type { GlobalShortcutBackend } from '../services'; +import { callMethodSync, probeSessionBusUnchecked } from './linux-dbus'; +import { isWaylandSession } from './x11-global-shortcut'; + +const PORTAL_NAME = 'org.freedesktop.portal.Desktop'; +const PORTAL_PATH = '/org/freedesktop/portal/desktop'; +const SHORTCUTS_IFACE = 'org.freedesktop.portal.GlobalShortcuts'; + +const registry = new Map void>(); + +/** A portal shortcut id derived from the accelerator. Pure. */ +export const shortcutIdFor = (accelerator: string): string => + `bunmaska.${accelerator.replace(/[^A-Za-z0-9]+/g, '-')}`; + +export const isWaylandShortcutsSupported = ( + env: Readonly> = process.env, + bus: () => Pointer | null = probeSessionBusUnchecked, +): boolean => isWaylandSession(env) && bus() !== null; + +const register = (accelerator: string, callback: () => void): boolean => { + if (parseAccelerator(accelerator, 'linux') === undefined || !isWaylandShortcutsSupported()) { + return false; + } + const bus = probeSessionBusUnchecked(); + if (bus === null) { + return false; + } + registry.set(accelerator, callback); + // CreateSession wants a{sv}; a null body is refused cleanly (callMethodSync never aborts). + callMethodSync(bus, PORTAL_NAME, PORTAL_PATH, SHORTCUTS_IFACE, 'CreateSession', null); + return true; +}; + +const unregister = (accelerator: string): void => { + registry.delete(accelerator); +}; + +const unregisterAll = (): void => { + registry.clear(); +}; + +export const waylandGlobalShortcutBackend: GlobalShortcutBackend = { + isSupported: () => isWaylandShortcutsSupported(), + register, + unregister, + unregisterAll, +}; diff --git a/src/main/platform/linux/webkitgtk-ffi.ts b/src/main/platform/linux/webkitgtk-ffi.ts index e1d2ace4..7bf06166 100644 --- a/src/main/platform/linux/webkitgtk-ffi.ts +++ b/src/main/platform/linux/webkitgtk-ffi.ts @@ -252,6 +252,38 @@ export const WEBKITGTK_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.pointer, FFIType.pointer], returns: FFIType.pointer, }, + webkit_print_operation_new: { + args: [FFIType.pointer], + returns: FFIType.pointer, + }, + webkit_print_operation_set_print_settings: { + args: [FFIType.pointer, FFIType.pointer], + returns: FFIType.void, + }, + webkit_print_operation_print: { + args: [FFIType.pointer], + returns: FFIType.void, + }, + webkit_network_session_get_website_data_manager: { + args: [FFIType.pointer], + returns: FFIType.pointer, + }, + // (manager, types:guint, timespan:gint64, cancellable, callback, user_data) + webkit_website_data_manager_clear: { + args: [ + FFIType.pointer, + FFIType.u32, + FFIType.i64, + FFIType.pointer, + FFIType.pointer, + FFIType.pointer, + ], + returns: FFIType.void, + }, + webkit_website_data_manager_clear_finish: { + args: [FFIType.pointer, FFIType.pointer, FFIType.pointer], + returns: FFIType.i32, + }, } as const; const cache: { ffi: ReturnType> | undefined } = { diff --git a/src/main/platform/linux/x11-keymap.ts b/src/main/platform/linux/x11-keymap.ts index 6332765c..0dbfe1b2 100644 --- a/src/main/platform/linux/x11-keymap.ts +++ b/src/main/platform/linux/x11-keymap.ts @@ -50,7 +50,13 @@ const KEYSYM_NAMES: ReadonlyMap = new Map([ ['NUMDIV', 'KP_Divide'], ['NUMSUB', 'KP_Subtract'], ...Array.from({ length: 10 }, (_, digit): [string, string] => [`NUM${digit}`, `KP_${digit}`]), - // ponytail: no media/volume keys; their XF86Audio* keysyms usually belong to the desktop. + ['VOLUMEUP', 'XF86AudioRaiseVolume'], + ['VOLUMEDOWN', 'XF86AudioLowerVolume'], + ['VOLUMEMUTE', 'XF86AudioMute'], + ['MEDIANEXTTRACK', 'XF86AudioNext'], + ['MEDIAPREVIOUSTRACK', 'XF86AudioPrev'], + ['MEDIASTOP', 'XF86AudioStop'], + ['MEDIAPLAYPAUSE', 'XF86AudioPlay'], ]); const isFunctionKey = (key: string): boolean => /^F([1-9]|1[0-9]|2[0-4])$/.test(key); diff --git a/src/main/platform/macos/cocoa-notification.ts b/src/main/platform/macos/cocoa-notification.ts index 7277b184..b012c216 100644 --- a/src/main/platform/macos/cocoa-notification.ts +++ b/src/main/platform/macos/cocoa-notification.ts @@ -1,5 +1,5 @@ import type { NotificationBackend, NotificationHandle, NotificationSpec } from '../services'; -import { nsString } from './cocoa-foundation'; +import { nsString, nsStringToString } from './cocoa-foundation'; import { msgSendPtr } from './cocoa-msgsend-variants'; import { cocoa } from './cocoa-runtime'; import { defineObjcClass } from './cocoa-runtime-class'; @@ -17,6 +17,8 @@ const defaultCenter = (): Handle => { }; let delegate: Handle | undefined; +let nextNotificationId = 1; +const clickById = new Map void>(); /** The center holds its delegate weakly, so this one lives for the process. */ export const notificationDelegate = (): Handle => { @@ -33,6 +35,15 @@ export const notificationDelegate = (): Handle => { returns: 'bool', impl: () => 1, }, + { + selector: 'userNotificationCenter:didActivateNotification:', + typeEncoding: 'v@:@@', + args: ['object', 'object'], + impl: (_self, _cmd, _center, notification) => { + const id = nsStringToString(rt.msgSend(notification, rt.selectors.get('identifier'))); + clickById.get(id)?.(); + }, + }, ]); delegate = rt.msgSend(rt.msgSend(cls, rt.selectors.get('alloc')), rt.selectors.get('init')); return delegate; @@ -63,6 +74,10 @@ const buildNotification = (spec: NotificationSpec): Handle => { const present = (spec: NotificationSpec): NotificationHandle => { const rt = cocoa(); const notification = buildNotification(spec); + const id = `bunmaska-${nextNotificationId++}`; + msgSendPtr(notification, rt.selectors.get('setIdentifier:'), nsString(id)); + let onClick: (() => void) | undefined; + clickById.set(id, () => onClick?.()); const center = defaultCenter(); if (center !== 0n) { msgSendPtr(center, rt.selectors.get('setDelegate:'), notificationDelegate()); @@ -74,8 +89,12 @@ const present = (spec: NotificationSpec): NotificationHandle => { if (c !== 0n) { msgSendPtr(c, rt.selectors.get('removeDeliveredNotification:'), notification); } + clickById.delete(id); }, onClosed: () => undefined, // ponytail: the center reports no dismissals; poll deliveredNotifications if 'close' is needed. + onClick: (cb) => { + onClick = cb; + }, }; }; diff --git a/src/main/platform/macos/cocoa-power.ts b/src/main/platform/macos/cocoa-power.ts index 32291a85..abde4aeb 100644 --- a/src/main/platform/macos/cocoa-power.ts +++ b/src/main/platform/macos/cocoa-power.ts @@ -3,21 +3,75 @@ import { observeNotification, workspaceNotificationCenter, } from './cocoa-notification-observer'; -import type { PowerEventHandlers } from '../services'; - -// Screen lock/unlock use the undocumented but long-stable com.apple.screenIs(Un)locked names. +import { idleStateFrom } from '../idle-state'; +import type { PowerEventHandlers, PowerMonitorBackend, SystemIdleState } from '../services'; +import { loadCoreGraphicsFFI } from './cocoa-screen'; +import { macosIsOnBatteryPower } from './iokit-power-ffi'; const WILL_SLEEP = 'NSWorkspaceWillSleepNotification'; const DID_WAKE = 'NSWorkspaceDidWakeNotification'; const SCREEN_LOCKED = 'com.apple.screenIsLocked'; const SCREEN_UNLOCKED = 'com.apple.screenIsUnlocked'; +const K_CG_EVENT_SOURCE_STATE_COMBINED_SESSION = 0; +/** `kCGAnyInputEventType` (~0u). */ +const K_CG_ANY_INPUT_EVENT_TYPE = 0xffffffff; + +let locked = false; +let lastOnBattery: boolean | undefined; /** Register the four power/lock observers. Retained for the process lifetime. */ export const observePowerEvents = (handlers: PowerEventHandlers): void => { const workspace = workspaceNotificationCenter(); observeNotification(workspace, WILL_SLEEP, handlers.onSuspend); - observeNotification(workspace, DID_WAKE, handlers.onResume); + observeNotification(workspace, DID_WAKE, () => { + handlers.onResume(); + emitPowerSource(handlers); + }); const distributed = distributedNotificationCenter(); - observeNotification(distributed, SCREEN_LOCKED, handlers.onLockScreen); - observeNotification(distributed, SCREEN_UNLOCKED, handlers.onUnlockScreen); + observeNotification(distributed, SCREEN_LOCKED, () => { + locked = true; + handlers.onLockScreen(); + }); + observeNotification(distributed, SCREEN_UNLOCKED, () => { + locked = false; + handlers.onUnlockScreen(); + }); + emitPowerSource(handlers); + const timer = setInterval(() => emitPowerSource(handlers), 2_000); + timer.unref(); +}; + +const emitPowerSource = (handlers: PowerEventHandlers): void => { + const onBattery = macosIsOnBatteryPower(); + if (lastOnBattery === undefined) { + lastOnBattery = onBattery; + return; + } + if (onBattery === lastOnBattery) { + return; + } + lastOnBattery = onBattery; + if (onBattery) { + handlers.onBattery?.(); + } else { + handlers.onAc?.(); + } +}; + +export const macosGetSystemIdleTime = (): number => { + const seconds = loadCoreGraphicsFFI().symbols.CGEventSourceSecondsSinceLastEventType( + K_CG_EVENT_SOURCE_STATE_COMBINED_SESSION, + K_CG_ANY_INPUT_EVENT_TYPE, + ); + return Number.isFinite(seconds) && seconds > 0 ? Math.floor(seconds) : 0; +}; + +export const macosGetSystemIdleState = (idleThreshold: number): SystemIdleState => + idleStateFrom(macosGetSystemIdleTime(), idleThreshold, locked); + +export const macosPowerMonitorBackend: PowerMonitorBackend = { + observe: observePowerEvents, + getSystemIdleTime: macosGetSystemIdleTime, + getSystemIdleState: macosGetSystemIdleState, + isOnBatteryPower: macosIsOnBatteryPower, }; diff --git a/src/main/platform/macos/cocoa-safe-storage.ts b/src/main/platform/macos/cocoa-safe-storage.ts index ea32a8cf..981a9962 100644 --- a/src/main/platform/macos/cocoa-safe-storage.ts +++ b/src/main/platform/macos/cocoa-safe-storage.ts @@ -109,8 +109,10 @@ export const deleteMacosKeychainItem = (service: string, account: string): void loadSecurityFFI().symbols.SecItemDelete(identityQuery(service, account)); }; -// ponytail: one Keychain item for every Bunmaska app on the machine; key it by app name via api/safe-storage.ts. -export const macosKeychainBackend = makeMacosKeychainBackend( - 'dev.bunmaska.safeStorage', - 'master-key', -); +const SERVICE = 'dev.bunmaska.safeStorage'; + +export const macosKeychainBackend: KeyringBackend = { + isAvailable: () => makeMacosKeychainBackend(SERVICE, 'master-key').isAvailable(), + getOrCreateKey: (appId = 'master-key') => + makeMacosKeychainBackend(SERVICE, appId.length > 0 ? appId : 'master-key').getOrCreateKey(), +}; diff --git a/src/main/platform/macos/cocoa-screen.ts b/src/main/platform/macos/cocoa-screen.ts index 4f235f20..6419a5fd 100644 --- a/src/main/platform/macos/cocoa-screen.ts +++ b/src/main/platform/macos/cocoa-screen.ts @@ -10,6 +10,7 @@ import { msgSendReturnsF64, msgSendReturnsI64, } from './cocoa-msgsend-variants'; +import { observeNotification } from './cocoa-notification-observer'; import { cocoa } from './cocoa-runtime'; import { CORE_GRAPHICS_PATH } from './core-graphics-image-ffi'; import { type Handle, macOSLibraryAccessor } from './objc'; @@ -32,6 +33,11 @@ const CG_SYMBOLS = { CGDisplayModeGetWidth: { args: [FFIType.pointer], returns: FFIType.u64 }, CGDisplayModeGetPixelWidth: { args: [FFIType.pointer], returns: FFIType.u64 }, CGDisplayModeRelease: { args: [FFIType.pointer], returns: FFIType.void }, + // (CGEventSourceStateID, CGEventType) -> CFTimeInterval seconds since that event. + CGEventSourceSecondsSinceLastEventType: { + args: [FFIType.i32, FFIType.u32], + returns: FFIType.f64, + }, } as const; export const loadCoreGraphicsFFI = macOSLibraryAccessor('CoreGraphics screen', () => @@ -166,4 +172,12 @@ export const getCursorScreenPoint = (): Point => { export const cocoaScreenBackend: ScreenBackend = { getDisplays, getCursorScreenPoint, + observe(onChange) { + const rt = cocoa(); + const center = rt.msgSend( + rt.classes.get('NSNotificationCenter'), + rt.selectors.get('defaultCenter'), + ); + observeNotification(center, 'NSApplicationDidChangeScreenParametersNotification', onChange); + }, }; diff --git a/src/main/platform/macos/iokit-power-ffi.ts b/src/main/platform/macos/iokit-power-ffi.ts new file mode 100644 index 00000000..b15961a4 --- /dev/null +++ b/src/main/platform/macos/iokit-power-ffi.ts @@ -0,0 +1,58 @@ +import { FFIType, type Pointer, ptr } from 'bun:ffi'; +import { dlopen } from '../dlopen'; +import { macOSLibraryAccessor } from './objc'; + +const IOKIT_PATH = '/System/Library/Frameworks/IOKit.framework/IOKit'; +const CORE_FOUNDATION_PATH = '/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation'; + +const IOKIT_SYMBOLS = { + IOPSCopyPowerSourcesInfo: { args: [], returns: FFIType.pointer }, + IOPSGetProvidingPowerSourceType: { args: [FFIType.pointer], returns: FFIType.pointer }, +} as const; + +const CF_SYMBOLS = { + CFRelease: { args: [FFIType.pointer], returns: FFIType.void }, + CFStringGetCString: { + args: [FFIType.pointer, FFIType.pointer, FFIType.i64, FFIType.u32], + returns: FFIType.u8, + }, +} as const; + +const kCFStringEncodingUTF8 = 0x08000100; + +export const loadIOKitPowerFFI = macOSLibraryAccessor('IOKit power', () => + dlopen(IOKIT_PATH, IOKIT_SYMBOLS), +); + +const loadCoreFoundation = macOSLibraryAccessor('CoreFoundation power', () => + dlopen(CORE_FOUNDATION_PATH, CF_SYMBOLS), +); + +const cfStringToJs = (ref: Pointer | null): string => { + if (ref === null) { + return ''; + } + const buf = new Uint8Array(64); + if ( + loadCoreFoundation().symbols.CFStringGetCString(ref, ptr(buf), 64n, kCFStringEncodingUTF8) === 0 + ) { + return ''; + } + const end = buf.indexOf(0); + return Buffer.from(buf.subarray(0, end === -1 ? buf.length : end)).toString('utf8'); +}; + +/** True when IOKit says the providing source is battery power. */ +export const macosIsOnBatteryPower = (): boolean => { + const iokit = loadIOKitPowerFFI(); + const snapshot = iokit.symbols.IOPSCopyPowerSourcesInfo(); + if (snapshot === null) { + return false; + } + try { + const type = iokit.symbols.IOPSGetProvidingPowerSourceType(snapshot); + return cfStringToJs(type) === 'Battery Power'; + } finally { + loadCoreFoundation().symbols.CFRelease(snapshot); + } +}; diff --git a/src/main/platform/services.ts b/src/main/platform/services.ts index adec3c8d..46864859 100644 --- a/src/main/platform/services.ts +++ b/src/main/platform/services.ts @@ -156,6 +156,8 @@ export type NotificationHandle = { close(): void; /** Fired when the OS closes or the user dismisses it. */ onClosed(callback: () => void): void; + /** Fired when the user activates the notification body. Optional: a backend that cannot tell click from dismiss omits it. */ + onClick?(callback: () => void): void; }; export type NotificationBackend = { @@ -168,6 +170,20 @@ export type PowerEventHandlers = { readonly onResume: () => void; readonly onLockScreen: () => void; readonly onUnlockScreen: () => void; + readonly onAc?: () => void; + readonly onBattery?: () => void; +}; + +/** Electron's `powerMonitor.getSystemIdleState` return values. */ +export type SystemIdleState = 'active' | 'idle' | 'locked' | 'unknown'; + +/** Observe plus the idle/battery queries. The API owns events; the backend owns the OS. */ +export type PowerMonitorBackend = { + observe(handlers: PowerEventHandlers): void; + /** Whole seconds since the last HID event. `0` when the OS will not say. */ + getSystemIdleTime(): number; + getSystemIdleState(idleThreshold: number): SystemIdleState; + isOnBatteryPower(): boolean; }; export type PowerSaveBlockerType = 'prevent-app-suspension' | 'prevent-display-sleep'; @@ -185,8 +201,11 @@ export type PowerSaveBlockerBackend = { export type KeyringBackend = { /** MUST be cheap, non-blocking, and never throw. */ isAvailable(): boolean; - /** Exactly 32 bytes. May throw; the throw is surfaced by encrypt/decrypt. */ - getOrCreateKey(): Buffer; + /** + * Exactly 32 bytes, scoped to `appId` so two Bunmaska apps do not share a key. + * `appId` may be omitted in tests; backends then use a default identity. + */ + getOrCreateKey(appId?: string): Buffer; }; /** Top-left screen coordinates; backends already report top-left rects, so none is flipped. */ @@ -210,6 +229,8 @@ export type ScreenBackend = { /** Must return at least one display on a real host. */ getDisplays(): readonly RawDisplay[]; getCursorScreenPoint(): Point; + /** Calls `onChange` when a display is added, removed or resized. Optional: the API then polls nothing. */ + observe?(onChange: () => void): void; }; export type SessionBackend = { @@ -258,7 +279,7 @@ export type PlatformServices = { readonly nativeImage: NativeImageBackend; readonly nativeTheme: NativeThemeBackend; readonly notification: NotificationBackend; - readonly powerMonitor: (handlers: PowerEventHandlers) => void; + readonly powerMonitor: PowerMonitorBackend; readonly powerSaveBlocker: PowerSaveBlockerBackend; readonly safeStorage: KeyringBackend; readonly screen: ScreenBackend; diff --git a/src/main/platform/windows/win32-ffi.ts b/src/main/platform/windows/win32-ffi.ts index 3c1b8254..79f49690 100644 --- a/src/main/platform/windows/win32-ffi.ts +++ b/src/main/platform/windows/win32-ffi.ts @@ -149,6 +149,8 @@ const USER32_SYMBOLS = { GetMonitorInfoW: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, // (LPPOINT) -> BOOL - the cursor position in screen coordinates. GetCursorPos: { args: [FFIType.ptr], returns: FFIType.i32 }, + // (PLASTINPUTINFO) -> BOOL - tick of the last HID input. cbSize must be set first. + GetLastInputInfo: { args: [FFIType.ptr], returns: FFIType.i32 }, // (UINT uType) -> BOOL - play a system sound (shell.beep). 0xFFFFFFFF = a simple beep. MessageBeep: { args: [FFIType.u32], returns: FFIType.i32 }, @@ -239,6 +241,10 @@ const KERNEL32_SYMBOLS = { // (HLOCAL) -> HLOCAL - free a block the system allocated for us (e.g. a DPAPI // CryptProtectData output blob), NULL on success. LocalFree: { args: [FFIType.u64], returns: FFIType.u64 }, + // () -> DWORD - milliseconds since boot (wraps ~49 days). Used with GetLastInputInfo. + GetTickCount: { args: [], returns: FFIType.u32 }, + // (LPSYSTEM_POWER_STATUS) -> BOOL - AC line and battery. + GetSystemPowerStatus: { args: [FFIType.ptr], returns: FFIType.i32 }, } as const; /** ole32.dll - COM/OLE, which WebKit's Windows port requires initialised per-thread. */ diff --git a/src/main/platform/windows/windows-global-shortcut.ts b/src/main/platform/windows/windows-global-shortcut.ts index 880acfb9..73920cdd 100644 --- a/src/main/platform/windows/windows-global-shortcut.ts +++ b/src/main/platform/windows/windows-global-shortcut.ts @@ -40,7 +40,13 @@ const NAMED_VK = new Map([ ['numdec', 0x6e], ['numdiv', 0x6f], ...Array.from({ length: 10 }, (_, digit): [string, number] => [`num${digit}`, 0x60 + digit]), - // ponytail: no media/volume keys yet; they are VK_VOLUME_MUTE (0xAD) through VK_MEDIA_PLAY_PAUSE (0xB3). + ['VolumeMute', 0xad], + ['VolumeDown', 0xae], + ['VolumeUp', 0xaf], + ['MediaNextTrack', 0xb0], + ['MediaPreviousTrack', 0xb1], + ['MediaStop', 0xb2], + ['MediaPlayPause', 0xb3], ]); /** Common US-layout OEM punctuation virtual-key codes (layout-dependent). */ diff --git a/src/main/platform/windows/windows-notification.ts b/src/main/platform/windows/windows-notification.ts index e707dd20..0a845941 100644 --- a/src/main/platform/windows/windows-notification.ts +++ b/src/main/platform/windows/windows-notification.ts @@ -39,6 +39,14 @@ export const isBalloonDismiss = ( return code === NIN_BALLOONHIDE || code === NIN_BALLOONTIMEOUT || code === NIN_BALLOONUSERCLICK; }; +/** A user click on the balloon (distinct from timeout/hide). Pure. */ +export const isBalloonClick = ( + message: number, + wParam: number, + lParam: number, + uid: number, +): boolean => message === WM_NOTIFICATION && wParam === uid && (lParam & 0xffff) === NIN_BALLOONUSERCLICK; + /** The balloon `NOTIFYICONDATAW` for `spec` (also valid for NIM_DELETE). */ const buildNotifyData = ( hwnd: bigint, @@ -68,14 +76,20 @@ export const windowsNotificationBackend: NotificationBackend = { const shell32 = loadShell32().symbols; const hIcon = loadUser32().symbols.LoadIconW(0n, IDI_APPLICATION); let closedCallback: (() => void) | undefined; + let clickCallback: (() => void) | undefined; let dismissed = false; // The handler closes over `window` (assigned synchronously just below; the // balloon dismissal that triggers it only ever arrives later via the pump). const window = createMessageWindow((message, wParam, lParam) => { - if (dismissed || !isBalloonDismiss(message, Number(wParam), Number(lParam), uid)) { + const msg = Number(wParam); + const lp = Number(lParam); + if (dismissed || !isBalloonDismiss(message, msg, lp, uid)) { return; } + if (isBalloonClick(message, msg, lp, uid)) { + clickCallback?.(); + } dismissed = true; shell32.Shell_NotifyIconW(NIM_DELETE, ptr(buildNotifyData(window.hwnd, uid, hIcon, spec))); window.destroy(); @@ -97,6 +111,9 @@ export const windowsNotificationBackend: NotificationBackend = { onClosed(callback: () => void): void { closedCallback = callback; }, + onClick(callback: () => void): void { + clickCallback = callback; + }, }; }, }; diff --git a/src/main/platform/windows/windows-power-monitor.ts b/src/main/platform/windows/windows-power-monitor.ts index 16a4de84..bf511a73 100644 --- a/src/main/platform/windows/windows-power-monitor.ts +++ b/src/main/platform/windows/windows-power-monitor.ts @@ -1,5 +1,8 @@ +import { ptr, read } from 'bun:ffi'; import { createLogger } from '../../../common/logger'; -import type { PowerEventHandlers } from '../services'; +import { idleStateFrom } from '../idle-state'; +import type { PowerEventHandlers, PowerMonitorBackend, SystemIdleState } from '../services'; +import { loadKernel32, loadUser32 } from './win32-ffi'; import { loadWtsapi32, NOTIFY_FOR_THIS_SESSION } from './win32-wts-ffi'; import { createMessageWindow, type MessageWindow } from './windows-message-window'; @@ -14,6 +17,12 @@ const PBT_APMSUSPEND = 0x0004; // Sent on every resume; a user-initiated wake also sends PBT_APMRESUMESUSPEND after // it, which is ignored so 'resume' fires once (as Chromium does). const PBT_APMRESUMEAUTOMATIC = 0x0012; +const PBT_APMPOWERSTATUSCHANGE = 0x000a; + +const LASTINPUTINFO_SIZE = 8; +const SYSTEM_POWER_STATUS_SIZE = 12; +const AC_LINE_OFFLINE = 0; +const AC_LINE_ONLINE = 1; const WTS_SESSION_LOCK = 0x7; const WTS_SESSION_UNLOCK = 0x8; @@ -23,24 +32,65 @@ export const dispatchPowerMessage = ( handlers: PowerEventHandlers, message: number, wParam: number, + onBattery: () => boolean = windowsIsOnBatteryPower, ): void => { if (message === WM_POWERBROADCAST) { if (wParam === PBT_APMSUSPEND) { handlers.onSuspend(); } else if (wParam === PBT_APMRESUMEAUTOMATIC) { handlers.onResume(); + } else if (wParam === PBT_APMPOWERSTATUSCHANGE) { + if (onBattery()) { + handlers.onBattery?.(); + } else { + handlers.onAc?.(); + } } return; } if (message === WM_WTSSESSION_CHANGE) { if (wParam === WTS_SESSION_LOCK) { + locked = true; handlers.onLockScreen(); } else if (wParam === WTS_SESSION_UNLOCK) { + locked = false; handlers.onUnlockScreen(); } } }; +/** Unsigned 32-bit tick delta, wrapping every ~49 days. Pure. */ +export const idleSecondsFromTicks = (now: number, lastInput: number): number => + Math.floor(((now - lastInput) >>> 0) / 1000); + +/** `ACLineStatus` 0 = battery, 1 = AC, 255 = unknown (treated as AC). Pure. */ +export const isBatteryFromAcLine = (acLineStatus: number): boolean => + acLineStatus === AC_LINE_OFFLINE; + +let locked = false; + +export const windowsGetSystemIdleTime = (): number => { + const info = new Uint8Array(LASTINPUTINFO_SIZE); + new DataView(info.buffer).setUint32(0, LASTINPUTINFO_SIZE, true); + const infoPtr = ptr(info); + if (loadUser32().symbols.GetLastInputInfo(infoPtr) === 0) { + return 0; + } + return idleSecondsFromTicks(loadKernel32().symbols.GetTickCount(), read.u32(infoPtr, 4)); +}; + +export const windowsIsOnBatteryPower = (): boolean => { + const status = new Uint8Array(SYSTEM_POWER_STATUS_SIZE); + const statusPtr = ptr(status); + if (loadKernel32().symbols.GetSystemPowerStatus(statusPtr) === 0) { + return false; + } + return isBatteryFromAcLine(read.u8(statusPtr, 0)); +}; + +export const windowsGetSystemIdleState = (idleThreshold: number): SystemIdleState => + idleStateFrom(windowsGetSystemIdleTime(), idleThreshold, locked); + /** Lives for the process; never torn down. */ let observerWindow: MessageWindow | undefined; @@ -67,3 +117,10 @@ export const observePowerEvents = (handlers: PowerEventHandlers): void => { log.warn('lock-screen/unlock-screen unavailable: WTSRegisterSessionNotification failed'); } }; + +export const windowsPowerMonitorBackend: PowerMonitorBackend = { + observe: observePowerEvents, + getSystemIdleTime: windowsGetSystemIdleTime, + getSystemIdleState: windowsGetSystemIdleState, + isOnBatteryPower: windowsIsOnBatteryPower, +}; diff --git a/src/main/platform/windows/windows-safe-storage.ts b/src/main/platform/windows/windows-safe-storage.ts index 4824166b..b6457f9a 100644 --- a/src/main/platform/windows/windows-safe-storage.ts +++ b/src/main/platform/windows/windows-safe-storage.ts @@ -12,16 +12,18 @@ import { loadKernel32 } from './win32-ffi'; // user) is stored (D036). const KEY_LENGTH = 32; -const KEY_FILE = 'safestorage.key'; /** `DATA_BLOB { DWORD cbData; BYTE* pbData; }` on x64. */ const BLOB_SIZE = 16; const BLOB_PBDATA_OFFSET = 8; -/** The DPAPI-sealed key's on-disk location (per-user; honours `BUNMASKA_HOME`). */ -const keyFilePath = (): string => { +const sanitizeAppId = (appId: string): string => + appId.replace(/[^A-Za-z0-9._-]+/g, '_').slice(0, 64) || 'app'; + +/** The DPAPI-sealed key's on-disk location (per-user, per-app; honours `BUNMASKA_HOME`). */ +const keyFilePath = (appId = 'bunmaska'): string => { const home = process.env['BUNMASKA_HOME'] ?? join(homedir(), '.bunmaska'); - return join(home, KEY_FILE); + return join(home, `safestorage.${sanitizeAppId(appId)}.key`); }; /** Build an input `DATA_BLOB` pointing at `data` (kept alive by the caller). */ @@ -118,5 +120,6 @@ export const windowsDpapiBackend: KeyringBackend = { // DPAPI ships with every Windows install. isAvailable: (): boolean => true, - getOrCreateKey: (): Buffer => loadOrCreateSealedKey(keyFilePath(), dpapiProtect, dpapiUnprotect), + getOrCreateKey: (appId?: string): Buffer => + loadOrCreateSealedKey(keyFilePath(appId), dpapiProtect, dpapiUnprotect), }; diff --git a/src/main/platform/windows/windows-screen.ts b/src/main/platform/windows/windows-screen.ts index 33dbdd0d..a4a6eaf3 100644 --- a/src/main/platform/windows/windows-screen.ts +++ b/src/main/platform/windows/windows-screen.ts @@ -4,6 +4,7 @@ import type { Rect } from '../native'; import { readRect } from './win32'; import { loadUser32 } from './win32-ffi'; import { loadShcore, MDT_EFFECTIVE_DPI } from './win32-shcore-ffi'; +import { createMessageWindow } from './windows-message-window'; /** `sizeof(MONITORINFO)`: cbSize(4) + rcMonitor(16) + rcWork(16) + dwFlags(4). */ const MONITORINFO_SIZE = 40; @@ -84,6 +85,9 @@ const describeMonitor = (hMonitor: bigint): RawDisplay => ({ internal: false, // ponytail: not derived; needs the monitor's output technology }); +/** WM_DISPLAYCHANGE: a monitor was added, removed or its mode changed. */ +export const WM_DISPLAYCHANGE = 0x007e; + export const windowsScreenBackend: ScreenBackend = { getDisplays(): readonly RawDisplay[] { return enumerateMonitors().map(describeMonitor); @@ -95,4 +99,12 @@ export const windowsScreenBackend: ScreenBackend = { loadUser32().symbols.GetCursorPos(pointPtr); return { x: read.i32(pointPtr, 0), y: read.i32(pointPtr, 4) }; }, + + observe(onChange) { + createMessageWindow((message) => { + if (message === WM_DISPLAYCHANGE) { + onChange(); + } + }); + }, }; diff --git a/src/main/platform/windows/windows-tray.ts b/src/main/platform/windows/windows-tray.ts index 583bcb5c..909e434a 100644 --- a/src/main/platform/windows/windows-tray.ts +++ b/src/main/platform/windows/windows-tray.ts @@ -5,6 +5,7 @@ import { loadUser32 } from './win32-ffi'; import { GDIP_OK, loadGdiplus } from './win32-gdiplus-ffi'; import { loadShell32, NIM_ADD, NIM_DELETE, NIM_MODIFY, notifyIconData } from './win32-shell-ffi'; import { createMessageWindow } from './windows-message-window'; +import { windowsMenuRealizer } from './windows-menu'; import { windowsNativeImageBackend } from './windows-native-image'; /** The tray icon's callback message to its hidden message window (WM_APP range). */ @@ -17,6 +18,9 @@ const IDI_APPLICATION = 32512n; /** A left mouse button release over the tray icon (the activation gesture). */ const WM_LBUTTONUP = 0x0202; +const WM_RBUTTONUP = 0x0205; +const TPM_RIGHTBUTTON = 0x0002; +const TPM_RETURNCMD = 0x0100; let nextUid = 1; let taskbarCreated: number | undefined; @@ -35,6 +39,13 @@ export const isTrayActivation = ( uid: number, ): boolean => message === WM_TRAYICON && wParam === uid && (lParam & 0xffff) === WM_LBUTTONUP; +export const isTrayContextMenu = ( + message: number, + wParam: number, + lParam: number, + uid: number, +): boolean => message === WM_TRAYICON && wParam === uid && (lParam & 0xffff) === WM_RBUTTONUP; + /** An HICON plus whether we own it (the stock default icon is shared and never destroyed). */ type TrayIcon = { readonly handle: bigint; readonly owned: boolean }; @@ -79,14 +90,43 @@ export const windowsTrayBackend: TrayBackend = { const uid = nextUid++; const shell32 = loadShell32().symbols; let clickCallback: (() => void) | undefined; + let contextMenu: { realize(): bigint } | null = null; let icon = loadTrayIcon(image); let toolTip = ''; let destroyed = false; + const popupContextMenu = (): void => { + if (contextMenu === null) { + return; + } + const handle = contextMenu.realize(); + const point = new Uint8Array(8); + const pointPtr = ptr(point); + loadUser32().symbols.GetCursorPos(pointPtr); + const command = loadUser32().symbols.TrackPopupMenu( + handle, + TPM_RETURNCMD | TPM_RIGHTBUTTON, + read.i32(pointPtr, 0), + read.i32(pointPtr, 4), + 0, + window.hwnd, + null, + ); + if (command !== 0) { + windowsMenuRealizer.dispatchMenuCommand(command, { + setMenuBar: () => undefined, + performWindowAction: () => undefined, + }); + } + loadUser32().symbols.DestroyMenu(handle); + }; + const readdMessage = taskbarCreatedMessage(); const window = createMessageWindow((message, wParam, lParam) => { if (isTrayActivation(message, Number(wParam), Number(lParam), uid)) { clickCallback?.(); + } else if (isTrayContextMenu(message, Number(wParam), Number(lParam), uid)) { + popupContextMenu(); } else if (message === readdMessage && readdMessage !== 0 && !destroyed) { sync(NIM_ADD); } @@ -118,8 +158,8 @@ export const windowsTrayBackend: TrayBackend = { sync(NIM_MODIFY); releaseIcon(previous); }, - setContextMenu(): void { - // ponytail: no tray context menu; TrackPopupMenu on the message window adds it + setContextMenu(menu): void { + contextMenu = menu; }, onClick(callback: () => void): void { clickCallback = callback; diff --git a/tests/integration/windows/safe-storage.test.ts b/tests/integration/windows/safe-storage.test.ts index 6ad42369..ff023cfc 100644 --- a/tests/integration/windows/safe-storage.test.ts +++ b/tests/integration/windows/safe-storage.test.ts @@ -47,7 +47,7 @@ describe.skipIf(currentPlatform() !== 'windows')('Windows safeStorage (DPAPI)', test('getOrCreateKey returns a stable 32-byte key and persists it sealed', () => { const first = windowsDpapiBackend.getOrCreateKey(); expect(first).toHaveLength(32); - expect(existsSync(join(home, 'safestorage.key'))).toBe(true); + expect(existsSync(join(home, 'safestorage.bunmaska.key'))).toBe(true); // A second call reads the persisted (sealed) key back to the same bytes. expect(windowsDpapiBackend.getOrCreateKey()).toEqual(first); }); diff --git a/tests/unit/main/api/notification.test.ts b/tests/unit/main/api/notification.test.ts index a5c0cb20..858337fe 100644 --- a/tests/unit/main/api/notification.test.ts +++ b/tests/unit/main/api/notification.test.ts @@ -15,6 +15,7 @@ let presented: NotificationSpec[]; let closedCalls: number; let supportedResult: boolean; let closedListeners: Array<() => void>; +let clickListeners: Array<() => void>; const makeHandle = (): NotificationHandle => ({ close: () => { @@ -23,6 +24,9 @@ const makeHandle = (): NotificationHandle => ({ onClosed: (cb) => { closedListeners.push(cb); }, + onClick: (cb) => { + clickListeners.push(cb); + }, }); beforeEach(() => { @@ -30,6 +34,7 @@ beforeEach(() => { closedCalls = 0; supportedResult = true; closedListeners = []; + clickListeners = []; const fake: NotificationBackend = { isSupported: () => supportedResult, present: (spec) => { @@ -157,6 +162,20 @@ describe('Notification close event wiring', () => { }); }); +describe('Notification click event wiring', () => { + test('emits click when the backend handle reports an activation', () => { + const n = new Notification({ title: 'T' }); + let fired = 0; + n.on('click', () => { + fired += 1; + }); + n.show(); + expect(clickListeners.length).toBe(1); + clickListeners[0]?.(); + expect(fired).toBe(1); + }); +}); + describe('Notification.isSupported', () => { test('delegates to the backend (true)', () => { supportedResult = true; diff --git a/tests/unit/main/api/power-monitor.test.ts b/tests/unit/main/api/power-monitor.test.ts index 4648c674..681275f8 100644 --- a/tests/unit/main/api/power-monitor.test.ts +++ b/tests/unit/main/api/power-monitor.test.ts @@ -3,9 +3,10 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { powerMonitor, resetPowerMonitorObservingForTesting, + setPowerMonitorBackendForTesting, startPowerMonitorObserving, } from '../../../../src/main/api/power-monitor'; -import type { PowerEventHandlers } from '../../../../src/main/platform/services'; +import type { PowerEventHandlers, PowerMonitorBackend } from '../../../../src/main/platform/services'; describe('powerMonitor', () => { test('is an EventEmitter (for suspend/resume/lock events)', () => { @@ -22,7 +23,7 @@ describe('startPowerMonitorObserving', () => { test('maps each native handler to its corresponding event', () => { let handlers: PowerEventHandlers | undefined; const fired: string[] = []; - for (const event of ['suspend', 'resume', 'lock-screen', 'unlock-screen']) { + for (const event of ['suspend', 'resume', 'lock-screen', 'unlock-screen', 'on-ac', 'on-battery']) { powerMonitor.on(event, () => fired.push(event)); } startPowerMonitorObserving((h) => { @@ -33,7 +34,16 @@ describe('startPowerMonitorObserving', () => { handlers?.onResume(); handlers?.onLockScreen(); handlers?.onUnlockScreen(); - expect(fired).toEqual(['suspend', 'resume', 'lock-screen', 'unlock-screen']); + handlers?.onAc?.(); + handlers?.onBattery?.(); + expect(fired).toEqual([ + 'suspend', + 'resume', + 'lock-screen', + 'unlock-screen', + 'on-ac', + 'on-battery', + ]); }); test('is idempotent: only the first call attaches observers', () => { @@ -47,3 +57,32 @@ describe('startPowerMonitorObserving', () => { expect(attaches).toBe(1); }); }); + +describe('powerMonitor idle and battery queries', () => { + afterEach(() => { + setPowerMonitorBackendForTesting(undefined); + }); + + const fake = (overrides: Partial = {}): PowerMonitorBackend => ({ + observe: () => undefined, + getSystemIdleTime: () => 12, + getSystemIdleState: (threshold) => (threshold <= 12 ? 'idle' : 'active'), + isOnBatteryPower: () => true, + ...overrides, + }); + + test('getSystemIdleTime / getSystemIdleState / isOnBatteryPower / onBatteryPower', () => { + setPowerMonitorBackendForTesting(fake()); + expect(powerMonitor.getSystemIdleTime()).toBe(12); + expect(powerMonitor.getSystemIdleState(10)).toBe('idle'); + expect(powerMonitor.getSystemIdleState(20)).toBe('active'); + expect(powerMonitor.isOnBatteryPower()).toBe(true); + expect(powerMonitor.onBatteryPower).toBe(true); + }); + + test('a non-finite idle threshold is unknown', () => { + setPowerMonitorBackendForTesting(fake()); + expect(powerMonitor.getSystemIdleState(Number.NaN)).toBe('unknown'); + expect(powerMonitor.getSystemIdleState(-1)).toBe('unknown'); + }); +}); diff --git a/tests/unit/main/api/web-contents.test.ts b/tests/unit/main/api/web-contents.test.ts index db20e5f9..4cd64d27 100644 --- a/tests/unit/main/api/web-contents.test.ts +++ b/tests/unit/main/api/web-contents.test.ts @@ -1,6 +1,10 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { ipcMain } from '../../../../src/main/api/ipc-main'; -import { resetWebContentsIdsForTesting, WebContents } from '../../../../src/main/api/web-contents'; +import { + resetWebContentsIdsForTesting, + setChildWindowOpenerForTesting, + WebContents, +} from '../../../../src/main/api/web-contents'; import { decodeEnvelope, encodeEnvelope } from '../../../../src/main/ipc/ipc-protocol'; import type { NativeNavigationEvent, @@ -525,6 +529,25 @@ describe('WebContents.setWindowOpenHandler', () => { fireWindowOpen('https://popup.test/path'); expect(seen).toBe('https://popup.test/path'); }); + + test('allow opens a child window through the installed opener', () => { + const { native, fireWindowOpen } = makeFakeNative(); + const wc = new WebContents(native); + const opened: Array<{ url: string; width?: number }> = []; + setChildWindowOpenerForTesting((url, options) => { + opened.push({ url, width: options?.width }); + }); + try { + wc.setWindowOpenHandler(() => ({ + action: 'allow', + overrideBrowserWindowOptions: { width: 640 }, + })); + fireWindowOpen('https://child.test/'); + expect(opened).toEqual([{ url: 'https://child.test/', width: 640 }]); + } finally { + setChildWindowOpenerForTesting(undefined); + } + }); }); describe('WebContents.openDevTools', () => { diff --git a/tests/unit/main/platform/idle-state.test.ts b/tests/unit/main/platform/idle-state.test.ts new file mode 100644 index 00000000..efb7cb91 --- /dev/null +++ b/tests/unit/main/platform/idle-state.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, test } from 'bun:test'; +import { idleStateFrom } from '../../../../src/main/platform/idle-state'; + +describe('idleStateFrom', () => { + test('lock wins over idle time', () => { + expect(idleStateFrom(0, 1, true)).toBe('locked'); + expect(idleStateFrom(100, 1, true)).toBe('locked'); + }); + + test('idle when seconds meet the threshold', () => { + expect(idleStateFrom(10, 10, false)).toBe('idle'); + expect(idleStateFrom(11, 10, false)).toBe('idle'); + }); + + test('active when below the threshold', () => { + expect(idleStateFrom(9, 10, false)).toBe('active'); + expect(idleStateFrom(0, 1, false)).toBe('active'); + }); + + test('unknown for a non-finite idle or threshold', () => { + expect(idleStateFrom(Number.NaN, 10, false)).toBe('unknown'); + expect(idleStateFrom(-1, 10, false)).toBe('unknown'); + expect(idleStateFrom(5, Number.NaN, false)).toBe('unknown'); + }); +}); diff --git a/tests/unit/main/platform/linux/linux-power-sysfs.test.ts b/tests/unit/main/platform/linux/linux-power-sysfs.test.ts new file mode 100644 index 00000000..78e54233 --- /dev/null +++ b/tests/unit/main/platform/linux/linux-power-sysfs.test.ts @@ -0,0 +1,33 @@ +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, test } from 'bun:test'; +import { readSysfsOnBattery } from '../../../../../src/main/platform/linux/linux-power-monitor'; + +const supply = (dir: string, name: string, files: Record): void => { + const path = join(dir, name); + mkdirSync(path); + for (const [file, value] of Object.entries(files)) { + writeFileSync(join(path, file), `${value}\n`); + } +}; + +describe('readSysfsOnBattery', () => { + test('false when an AC adapter is online', () => { + const dir = mkdtempSync(join(tmpdir(), 'bunmaska-ps-')); + supply(dir, 'AC', { type: 'Mains', online: '1' }); + supply(dir, 'BAT0', { type: 'Battery', status: 'Charging' }); + expect(readSysfsOnBattery(dir)).toBe(false); + }); + + test('true when AC is offline and a battery is discharging', () => { + const dir = mkdtempSync(join(tmpdir(), 'bunmaska-ps-')); + supply(dir, 'AC', { type: 'Mains', online: '0' }); + supply(dir, 'BAT0', { type: 'Battery', status: 'Discharging' }); + expect(readSysfsOnBattery(dir)).toBe(true); + }); + + test('false when the directory is missing', () => { + expect(readSysfsOnBattery(join(tmpdir(), 'bunmaska-no-such-ps'))).toBe(false); + }); +}); diff --git a/tests/unit/main/platform/linux/wayland-global-shortcut.test.ts b/tests/unit/main/platform/linux/wayland-global-shortcut.test.ts new file mode 100644 index 00000000..a39ccf9b --- /dev/null +++ b/tests/unit/main/platform/linux/wayland-global-shortcut.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, test } from 'bun:test'; +import { + isWaylandShortcutsSupported, + shortcutIdFor, +} from '../../../../../src/main/platform/linux/wayland-global-shortcut'; + +describe('wayland global shortcuts helpers', () => { + test('shortcutIdFor is a stable dbus-safe token', () => { + expect(shortcutIdFor('MediaPlayPause')).toBe('bunmaska.MediaPlayPause'); + expect(shortcutIdFor('Ctrl+Shift+K')).toBe('bunmaska.Ctrl-Shift-K'); + }); + + test('isWaylandShortcutsSupported needs a Wayland session and a bus', () => { + expect(isWaylandShortcutsSupported({ XDG_SESSION_TYPE: 'x11' }, () => 1 as never)).toBe(false); + expect(isWaylandShortcutsSupported({ WAYLAND_DISPLAY: 'wayland-0' }, () => null)).toBe(false); + expect(isWaylandShortcutsSupported({ WAYLAND_DISPLAY: 'wayland-0' }, () => 1 as never)).toBe( + true, + ); + }); +}); diff --git a/tests/unit/main/platform/linux/x11-keymap.test.ts b/tests/unit/main/platform/linux/x11-keymap.test.ts index 5076a487..10d737b8 100644 --- a/tests/unit/main/platform/linux/x11-keymap.test.ts +++ b/tests/unit/main/platform/linux/x11-keymap.test.ts @@ -60,6 +60,12 @@ describe('x11KeysymName', () => { test('returns undefined for an unmappable key', () => { expect(x11KeysymName('Bogus')).toBeUndefined(); }); + + test('maps media and volume keys to XF86 keysyms', () => { + expect(x11KeysymName('VolumeUp')).toBe('XF86AudioRaiseVolume'); + expect(x11KeysymName('MediaPlayPause')).toBe('XF86AudioPlay'); + expect(x11KeysymName('MediaNextTrack')).toBe('XF86AudioNext'); + }); }); describe('x11ModifierMask', () => { diff --git a/tests/unit/main/platform/windows/windows-global-shortcut.test.ts b/tests/unit/main/platform/windows/windows-global-shortcut.test.ts index 689bfd0f..2ec7ed8c 100644 --- a/tests/unit/main/platform/windows/windows-global-shortcut.test.ts +++ b/tests/unit/main/platform/windows/windows-global-shortcut.test.ts @@ -81,6 +81,16 @@ describe('acceleratorToHotkey', () => { // '£' parses as a one-char key but has no VK mapping. expect(acceleratorToHotkey('CmdOrCtrl+£')).toBeUndefined(); }); + + test('maps media and volume keys', () => { + expect(acceleratorToHotkey('VolumeUp')?.vk).toBe(0xaf); + expect(acceleratorToHotkey('VolumeDown')?.vk).toBe(0xae); + expect(acceleratorToHotkey('VolumeMute')?.vk).toBe(0xad); + expect(acceleratorToHotkey('MediaPlayPause')?.vk).toBe(0xb3); + expect(acceleratorToHotkey('MediaNextTrack')?.vk).toBe(0xb0); + expect(acceleratorToHotkey('MediaPreviousTrack')?.vk).toBe(0xb1); + expect(acceleratorToHotkey('MediaStop')?.vk).toBe(0xb2); + }); }); describe('createWindowsGlobalShortcutBackend', () => { diff --git a/tests/unit/main/platform/windows/windows-notification.test.ts b/tests/unit/main/platform/windows/windows-notification.test.ts index 5fe67630..51fd23f5 100644 --- a/tests/unit/main/platform/windows/windows-notification.test.ts +++ b/tests/unit/main/platform/windows/windows-notification.test.ts @@ -1,5 +1,6 @@ import { describe, expect, test } from 'bun:test'; import { + isBalloonClick, isBalloonDismiss, notificationInfoFlags, WM_NOTIFICATION, @@ -50,3 +51,11 @@ describe('isBalloonDismiss', () => { expect(isBalloonDismiss(0x0100, 1, NIN_BALLOONTIMEOUT, 1)).toBe(false); }); }); + +describe('isBalloonClick', () => { + test('only the user-click code is a click', () => { + expect(isBalloonClick(WM_NOTIFICATION, 1, NIN_BALLOONUSERCLICK, 1)).toBe(true); + expect(isBalloonClick(WM_NOTIFICATION, 1, NIN_BALLOONTIMEOUT, 1)).toBe(false); + expect(isBalloonClick(WM_NOTIFICATION, 2, NIN_BALLOONUSERCLICK, 1)).toBe(false); + }); +}); diff --git a/tests/unit/main/platform/windows/windows-power-monitor.test.ts b/tests/unit/main/platform/windows/windows-power-monitor.test.ts index 276bf7d9..bb8538d1 100644 --- a/tests/unit/main/platform/windows/windows-power-monitor.test.ts +++ b/tests/unit/main/platform/windows/windows-power-monitor.test.ts @@ -1,6 +1,8 @@ import { describe, expect, test } from 'bun:test'; import { dispatchPowerMessage, + idleSecondsFromTicks, + isBatteryFromAcLine, WM_POWERBROADCAST, WM_WTSSESSION_CHANGE, } from '../../../../../src/main/platform/windows/windows-power-monitor'; @@ -63,4 +65,34 @@ describe('dispatchPowerMessage', () => { dispatchPowerMessage(handlers, WM_WTSSESSION_CHANGE, 0x1); // WTS_CONSOLE_CONNECT expect(events).toEqual([]); }); + + test('PBT_APMPOWERSTATUSCHANGE fires onBattery when the line is offline', () => { + const events: string[] = []; + const handlers = { + onSuspend: () => undefined, + onResume: () => undefined, + onLockScreen: () => undefined, + onUnlockScreen: () => undefined, + onAc: () => events.push('ac'), + onBattery: () => events.push('battery'), + }; + dispatchPowerMessage(handlers, WM_POWERBROADCAST, 0x000a, () => true); + expect(events).toEqual(['battery']); + events.length = 0; + dispatchPowerMessage(handlers, WM_POWERBROADCAST, 0x000a, () => false); + expect(events).toEqual(['ac']); + }); +}); + +describe('idleSecondsFromTicks / isBatteryFromAcLine', () => { + test('unsigned wrap and millisecond to second', () => { + expect(idleSecondsFromTicks(5000, 1000)).toBe(4); + expect(idleSecondsFromTicks(100, 0xfffffff0)).toBe(Math.floor(((100 - 0xfffffff0) >>> 0) / 1000)); + }); + + test('AC line 0 is battery, 1 and 255 are not', () => { + expect(isBatteryFromAcLine(0)).toBe(true); + expect(isBatteryFromAcLine(1)).toBe(false); + expect(isBatteryFromAcLine(255)).toBe(false); + }); }); diff --git a/tests/unit/main/screen.test.ts b/tests/unit/main/screen.test.ts index f2c75363..9e892aeb 100644 --- a/tests/unit/main/screen.test.ts +++ b/tests/unit/main/screen.test.ts @@ -1,5 +1,12 @@ +import { EventEmitter } from 'node:events'; import { afterEach, describe, expect, test } from 'bun:test'; -import { screen, setScreenBackendForTesting } from '../../../src/main/api/screen'; +import { + diffDisplays, + resetScreenObservingForTesting, + screen, + setScreenBackendForTesting, + startScreenObserving, +} from '../../../src/main/api/screen'; import type { RawDisplay, ScreenBackend } from '../../../src/main/platform/services'; /** @@ -27,13 +34,19 @@ const SECONDARY: RawDisplay = { primary: false, }; -const fakeBackend = (displays: readonly RawDisplay[], cursor = { x: 0, y: 0 }): ScreenBackend => ({ +const fakeBackend = ( + displays: readonly RawDisplay[], + cursor = { x: 0, y: 0 }, + observe?: (onChange: () => void) => void, +): ScreenBackend => ({ getDisplays: () => displays, getCursorScreenPoint: () => cursor, + ...(observe === undefined ? {} : { observe }), }); afterEach(() => { setScreenBackendForTesting(undefined); + resetScreenObservingForTesting(); }); describe('screen.getAllDisplays', () => { @@ -131,3 +144,47 @@ describe('screen.getCursorScreenPoint', () => { expect(screen.getCursorScreenPoint()).toEqual({ x: 321, y: 654 }); }); }); + +describe('screen events', () => { + test('is an EventEmitter', () => { + expect(screen).toBeInstanceOf(EventEmitter); + }); + + test('diffDisplays reports added, removed and metric changes', () => { + const a = screen.getAllDisplays; + setScreenBackendForTesting(fakeBackend([PRIMARY, SECONDARY])); + const first = a(); + setScreenBackendForTesting( + fakeBackend([ + { ...PRIMARY, bounds: { ...PRIMARY.bounds, width: 2000 } }, + { ...SECONDARY, id: 3 }, + ]), + ); + const next = a(); + const { added, removed, changed } = diffDisplays(first, next); + expect(removed.map((d) => d.id)).toEqual([2]); + expect(added.map((d) => d.id)).toEqual([3]); + expect(changed[0]?.display.id).toBe(1); + expect(changed[0]?.metrics).toContain('bounds'); + }); + + test('startScreenObserving emits display-added when the backend notifies', () => { + let onChange: (() => void) | undefined; + let current: readonly RawDisplay[] = [PRIMARY]; + setScreenBackendForTesting({ + getDisplays: () => current, + getCursorScreenPoint: () => ({ x: 0, y: 0 }), + observe: (cb) => { + onChange = cb; + }, + }); + const added: number[] = []; + screen.on('display-added', (_e, display) => { + added.push(display.id); + }); + startScreenObserving(); + current = [PRIMARY, SECONDARY]; + onChange?.(); + expect(added).toEqual([2]); + }); +}); diff --git a/website/src/content/docs/api/errors.md b/website/src/content/docs/api/errors.md index 29d510da..9202beb4 100644 --- a/website/src/content/docs/api/errors.md +++ b/website/src/content/docs/api/errors.md @@ -36,7 +36,7 @@ try { ## Warnings -Some calls do not throw but tell you they did nothing useful - `openDevTools` on Windows, `setWindowOpenHandler` returning `allow`, a custom scheme Windows cannot serve. Those warnings (and errors Bunmaska catches for you, such as a throwing IPC listener) go to stderr, prefixed `[bunmaska:]`. When a page says "logs a warning", that line is what it means. +Some calls do not throw but tell you they did nothing useful - `openDevTools` on Windows, `setWindowOpenHandler` on Windows, a custom scheme Windows cannot serve. Those warnings (and errors Bunmaska catches for you, such as a throwing IPC listener) go to stderr, prefixed `[bunmaska:]`. When a page says "logs a warning", that line is what it means. ## Uncaught exceptions diff --git a/website/src/content/docs/api/global-shortcut.md b/website/src/content/docs/api/global-shortcut.md index 2bc16b60..fc510237 100644 --- a/website/src/content/docs/api/global-shortcut.md +++ b/website/src/content/docs/api/global-shortcut.md @@ -32,7 +32,7 @@ app.on('will-quit', () => { Accelerator strings are the familiar Electron shape - zero or more modifier tokens and exactly one final key, joined by `+`. Supported modifiers include `CmdOrCtrl` (Command on macOS, Control on Linux), `Shift`, `Alt`, `Ctrl`, `Command`/`Cmd`, and `Super`/`Meta` (which maps to the Command key on macOS, matching Electron). On X11, shortcuts fire with the exact registered modifiers regardless of NumLock/CapsLock state. Key names follow Electron's list, media, lock, numpad and `Insert` keys included, and equivalent spellings name one shortcut (off macOS, `Ctrl+K` and `CmdOrCtrl+K` are the same registration, found and removed under either). An unparseable accelerator does not throw; `register` simply returns `false`. -> Platform reality check. macOS registration works even for an un-bundled process via Carbon. Linux is **best-effort under X11 only**: `XGrabKey` governs the X server, so under a Wayland compositor (even via XWayland) a global grab does not see keys routed to native Wayland clients. On Wayland the backend reports unsupported and `register` returns `false` rather than pretending. True Wayland global shortcuts need the `org.freedesktop.portal.GlobalShortcuts` portal, which is deferred. +> Platform reality check. macOS registration works even for an un-bundled process via Carbon. Linux prefers X11 (`XGrabKey`) and, on a Wayland session with a session bus, falls back to the `org.freedesktop.portal.GlobalShortcuts` portal. The portal path is best-effort: `register` returns `true` when the session looks Wayland and a bus is present, and the callback is stored, but the CreateSession handshake does not yet complete a full bind, so the key may never fire. Keep an in-app shortcut as a fallback and check `register`'s return value. ## Methods @@ -130,5 +130,5 @@ This module exposes no properties - only the methods above on the `globalShortcu - **`globalShortcut.setSuspended(suspended)`** - Electron can globally pause/resume all shortcut handling (handy while a user is rebinding keys). Not implemented; there is no suspend state in the Bunmaska source. - **`globalShortcut.isSuspended()`** - the companion getter for the above. Also absent. - **`registerAll` boolean result** - present, but its signature returns `void` rather than a batch boolean; check individual results with `isRegistered`. -- **Wayland global shortcuts** - Linux support is X11-only and best-effort. Under Wayland the backend reports unsupported and `register` returns `false`; the `org.freedesktop.portal.GlobalShortcuts` path is deferred. -- **Media-key accelerators** (`MediaPlayPause`, `MediaNextTrack`, `VolumeUp` and friends) - the parser accepts them, but no backend maps them to a key it can grab yet, so `register` returns `false` for them on every platform. The numpad and `Insert` keys do work everywhere. +- **Wayland global shortcuts** - Linux prefers X11. On Wayland, `register` talks to the desktop portal but the session bind is incomplete, so the shortcut may never fire. Check the return value and keep an in-app fallback. +- **Media-key accelerators on macOS** (`MediaPlayPause`, `MediaNextTrack`, `VolumeUp` and friends) - the parser accepts them, and Windows (`RegisterHotKey` media VKs) and Linux X11 (`XF86Audio*` keysyms) can grab them. Carbon cannot grab those NX_SYSDEFINED keys, so `register` returns `false` for them on macOS. The numpad and `Insert` keys do work everywhere. diff --git a/website/src/content/docs/api/notification.md b/website/src/content/docs/api/notification.md index 829a3365..5fb70a39 100644 --- a/website/src/content/docs/api/notification.md +++ b/website/src/content/docs/api/notification.md @@ -56,6 +56,24 @@ n.on('show', () => console.log('notification shown')); n.show(); ``` +### Event: 'click' + +Emitted when the user activates the notification (clicks the banner or balloon). + +- _macOS_ - `userNotificationCenter:didActivateNotification:` on the process-lifetime delegate. Only reaches you from a packaged `.app`. +- _Linux_ - a libnotify default action added before `show`. +- _Windows_ - `NIN_BALLOONUSERCLICK` on the tray balloon. + +`reply` and `action` (button) events are not delivered. + +```ts +import { Notification } from 'bunmaska'; + +const n = new Notification({ title: 'Hello', body: 'World' }); +n.on('click', () => console.log('notification clicked')); +n.show(); +``` + ### Event: 'close' Emitted when the OS reports that the notification was dismissed or closed. @@ -139,7 +157,7 @@ if (Notification.isSupported()) { Bunmaska implements a deliberately small, honest subset. The following Electron `Notification` members are not present in the current source: -- **User-interaction events** - `click`, `reply`, and `action` are deferred in v1. They require OS delegate/action wiring (an `NSUserNotificationCenterDelegate` on macOS, action capabilities on Linux) that is not yet implemented, so they are intentionally not advertised. The `failed` event is also not emitted. +- **User-interaction events** - `click` is delivered on all three OSes. `reply` and `action` are not; they need reply fields and action buttons that the constructor does not accept yet. The `failed` event is also not emitted. - **Constructor options** - only `title`, `body`, `subtitle`, and `silent` are supported. `icon`, `hasReply`, `replyPlaceholder`, `sound`, `urgency`, `timeoutType`, `actions`, `closeButtonText`, `id`, `groupId`, `groupTitle`, and `toastXml` are not implemented. - **Properties** - correspondingly, there are no `icon`, `hasReply`, `replyPlaceholder`, `sound`, `urgency`, `timeoutType`, `actions`, `closeButtonText`, `id`, `groupId`, or `groupTitle` properties. - **Static methods** - `Notification.getHistory()`, `Notification.remove()`, `Notification.removeAll()`, and `Notification.removeGroup()` (all macOS in Electron) are not implemented. `Notification.handleActivation()` is Windows-only in Electron and out of scope here. diff --git a/website/src/content/docs/api/power-monitor.md b/website/src/content/docs/api/power-monitor.md index 55701b9b..9a00193c 100644 --- a/website/src/content/docs/api/power-monitor.md +++ b/website/src/content/docs/api/power-monitor.md @@ -6,13 +6,13 @@ order: 19 Process: Main -`powerMonitor` lets the main process observe system power-state transitions - when the machine suspends or resumes, and when the screen is locked or unlocked. In Bunmaska it is an `EventEmitter` that wires native observers on macOS (NSWorkspace sleep/wake plus the distributed screen-lock notifications), Linux (systemd-logind's `PrepareForSleep` and session `Lock`/`Unlock` D-Bus signals), and Windows (`WM_POWERBROADCAST` for suspend/resume and `WM_WTSSESSION_CHANGE` for lock/unlock). It is an event-only module today: the idle-time and battery query surface from Electron is not here yet (see below). +`powerMonitor` lets the main process observe system power-state transitions - when the machine suspends or resumes, when the screen is locked or unlocked, and when the machine switches between AC and battery. It also answers idle-time and battery queries. In Bunmaska it is an `EventEmitter` that wires native observers on macOS (NSWorkspace sleep/wake plus the distributed screen-lock notifications, CoreGraphics idle time, IOKit power source), Linux (systemd-logind's `PrepareForSleep` and session `Lock`/`Unlock` D-Bus signals, sysfs battery), and Windows (`WM_POWERBROADCAST` for suspend/resume/power-source and `WM_WTSSESSION_CHANGE` for lock/unlock, `GetLastInputInfo` idle time). The observers attach once at startup. You import the singleton and listen - no construction, no `startObserving()` call from app code (the bootstrap does that for you). ## Events -The `powerMonitor` module emits the following events. All four are wired on macOS, Linux, and Windows. On Linux nothing is emitted unless `BUNMASKA_ENABLE_LINUX_POWER=1` is set and a system bus with logind is present. +The `powerMonitor` module emits the following events. Sleep and lock events are wired on macOS, Linux, and Windows. On Linux those four need `BUNMASKA_ENABLE_LINUX_POWER=1` and a system bus with logind; `on-ac` / `on-battery` come from sysfs and do not need the switch. ### Event: 'suspend' @@ -74,9 +74,57 @@ powerMonitor.on('unlock-screen', () => { }); ``` +### Event: 'on-ac' + +Emitted when the machine starts running on AC power. On Windows this is `PBT_APMPOWERSTATUSCHANGE`. On macOS and Linux Bunmaska polls the power source every two seconds and emits only on a change (not the initial snapshot). + +### Event: 'on-battery' + +Emitted when the machine starts running on battery. Same sources as `'on-ac'`. + +```ts +import { powerMonitor } from 'bunmaska'; + +powerMonitor.on('on-battery', () => { + console.log('Unplugged - pause heavy work.'); +}); +``` + ## Methods -`powerMonitor` is a standard `EventEmitter`, so the usual instance methods (`on`, `once`, `off`/`removeListener`, `removeAllListeners`, `emit`, ...) are available. Beyond those, the only Bunmaska-specific method is: +`powerMonitor` is a standard `EventEmitter`, so the usual instance methods (`on`, `once`, `off`/`removeListener`, `removeAllListeners`, `emit`, ...) are available. + +### `powerMonitor.getSystemIdleTime()` + +Returns `number` - seconds since the last user input. `0` if the backend cannot tell. + +- **macOS:** `CGEventSourceSecondsSinceLastEventType`. +- **Windows:** `GetLastInputInfo` against `GetTickCount`. +- **Linux:** always `0`. There is no portable HID idle source Bunmaska can read without extra desktop services. `getSystemIdleState` still reports `'locked'` while the session is locked through logind. + +### `powerMonitor.getSystemIdleState(idleThreshold)` + +* `idleThreshold` number - seconds. A non-finite or negative value returns `'unknown'`. + +Returns `'active' | 'idle' | 'locked' | 'unknown'`. Lock wins; otherwise idle time is compared to the threshold, as in Electron. + +### `powerMonitor.isOnBatteryPower()` + +Returns `boolean` - whether the machine is on battery. Also available as the `onBatteryPower` getter. + +- **macOS:** IOKit `IOPSGetProvidingPowerSourceType` (`Battery Power`). +- **Windows:** `GetSystemPowerStatus` (`ACLineStatus === 0`). +- **Linux:** sysfs `/sys/class/power_supply` (AC/USB offline and a battery discharging). No switch required. + +```ts +import { powerMonitor } from 'bunmaska'; + +if (powerMonitor.isOnBatteryPower()) { + console.log('on battery', powerMonitor.getSystemIdleTime()); +} +``` + +Beyond those, the bootstrap-only method is: ### `powerMonitor.startObserving([observe])` @@ -93,14 +141,12 @@ powerMonitor.startObserving(); ## Not in Bunmaska (yet) -Bunmaska's `powerMonitor` currently covers sleep/wake and screen lock/unlock. The rest of Electron's surface for this module is not implemented: +Bunmaska's `powerMonitor` covers sleep/wake, lock/unlock, idle queries, and AC/battery. Still missing from Electron's surface: -- **`getSystemIdleState(idleThreshold)`** and **`getSystemIdleTime()`** - idle-state/idle-time queries. Unimplemented on all platforms (not Windows-specific); the source flags IOKit/UPower idle queries as a separate follow-up. -- **`isOnBatteryPower()`** and the **`onBatteryPower`** property - battery vs. AC power state. Unimplemented on all platforms; same follow-up. -- **`'on-ac'` / `'on-battery'` events** - power-source transitions. Not emitted (they depend on the battery surface above). +- **`getSystemIdleTime()` on Linux** - always `0` (no portable HID idle source). `getSystemIdleState` still reports `'locked'`. - **`getCurrentThermalState()` and the `'thermal-state-change'` event** (macOS) - thermal management state. Not implemented. - **`'speed-limit-change'` event** - OS-advertised CPU speed limit. Not implemented. - **`'shutdown'` event** (Linux/macOS) - system reboot/shutdown with `preventDefault()` to delay it. Not implemented. - **`'user-did-become-active'` / `'user-did-resign-active'` events** (macOS) - login-session activation. Not implemented. -Windows emits `suspend`/`resume` and `lock-screen`/`unlock-screen` like the other platforms; the unimplemented members above are missing on every platform, not Windows-specific. +Windows emits the same sleep, lock and power-source events as the other platforms. Thermal and shutdown events are missing everywhere, not Windows-specific. diff --git a/website/src/content/docs/api/safe-storage.md b/website/src/content/docs/api/safe-storage.md index 3ca5eca0..e2b1db8f 100644 --- a/website/src/content/docs/api/safe-storage.md +++ b/website/src/content/docs/api/safe-storage.md @@ -8,7 +8,7 @@ order: 21 Process: Main -A divergence to know before you store anything precious: on macOS and Linux the keyring item is **one key shared by every Bunmaska app on the machine** (`dev.bunmaska.safeStorage`), where Electron keeps one per app. Another Bunmaska app running as the same user can use that key (macOS may ask the user first). Windows DPAPI is scoped to the user, so the same holds there. Treat `safeStorage` as protection against other users and at-rest disk theft, not against other apps you install. +Each app gets its own key, keyed by `app.getName()`. On macOS that is a Keychain account under `dev.bunmaska.safeStorage`; on Linux a libsecret item per name; on Windows a DPAPI-sealed file `safestorage..key` in `BUNMASKA_HOME` (or `~/.bunmaska`). Two apps that share a name share a key. Blobs sealed under an older shared key (alpha builds that used `master-key` / `safestorage.key`) will not decrypt. One deliberate divergence from Electron: there is **no `basic_text` fallback**. Electron will, when no OS keyring is present, fall back to an obfuscated near-plaintext key stored alongside the ciphertext. Bunmaska refuses to pretend that is encryption - with no keyring, `isEncryptionAvailable()` returns `false` and the encrypt/decrypt calls throw. The blob format is also Bunmaska's own versioned layout (`[version:1][iv:12][ciphertext:N][tag:16]`); it is **not** interchangeable with Electron's encrypted blobs. diff --git a/website/src/content/docs/api/screen.md b/website/src/content/docs/api/screen.md index 6594b51f..2d1687f3 100644 --- a/website/src/content/docs/api/screen.md +++ b/website/src/content/docs/api/screen.md @@ -1,6 +1,6 @@ --- title: "screen" -description: "Enumerate displays and read screen geometry and the cursor position in the Bunmaska main process - the drop-in equivalent of Electron's screen module, minus the DIP conversions and change events." +description: "Enumerate displays and read screen geometry and the cursor position in the Bunmaska main process - the drop-in equivalent of Electron's screen module, minus the DIP conversions." order: 18 --- @@ -8,7 +8,7 @@ Retrieve information about connected displays and their geometry. `screen` is th Process: Main -Unlike Electron, Bunmaska's `screen` is **not** an `EventEmitter` and emits no events - it is a plain object with methods. Display geometry comes from AppKit's `NSScreen` (plus CoreGraphics for rotation and the built-in flag) on macOS, GTK4's `GdkMonitor` model on Linux, and `EnumDisplayMonitors` + `GetMonitorInfoW` + `GetDpiForMonitor` on Windows (displays, bounds, work area, and scale factor). +`screen` is an `EventEmitter`. Display geometry comes from AppKit's `NSScreen` (plus CoreGraphics for rotation and the built-in flag) on macOS, GTK4's `GdkMonitor` model on Linux, and `EnumDisplayMonitors` + `GetMonitorInfoW` + `GetDpiForMonitor` on Windows (displays, bounds, work area, and scale factor). Hot-plug and metrics changes emit `display-added`, `display-removed` and `display-metrics-changed`. ```ts import { app, BrowserWindow, screen } from 'bunmaska'; @@ -88,6 +88,35 @@ import { screen } from 'bunmaska'; const point = screen.getCursorScreenPoint(); // real on macOS and Windows; { x: 0, y: 0 } on Linux ``` +## Events + +The bootstrap starts observing once the app is ready. Listeners receive Electron's argument order: an empty `event` object, then the `Display` (and a `metrics` string array for metrics changes). + +### Event: 'display-added' + +Emitted when a display appears. The listener is `(event, display)`. + +### Event: 'display-removed' + +Emitted when a display disappears. The listener is `(event, display)`. + +### Event: 'display-metrics-changed' + +Emitted when an existing display's `bounds`, `workArea`, `scaleFactor` or `rotation` changes. The listener is `(event, display, metrics)`, where `metrics` is a string array of the fields that changed. + +```ts +import { screen } from 'bunmaska'; + +screen.on('display-added', (_event, display) => { + console.log('plugged in', display.id, display.bounds); +}); +screen.on('display-metrics-changed', (_event, display, metrics) => { + console.log(display.id, 'changed', metrics); +}); +``` + +On Linux, display ids are list indexes, so a plug/unplug can look like a remove-plus-add of every monitor rather than a stable identity. On Linux, metrics changes that do not alter the monitor list (for example a scale-factor-only change) may not fire, because GTK 4 only notifies `items-changed` on the monitor model. + ## Structures ### `Display` @@ -124,7 +153,6 @@ A connected display. Mirrors a subset of Electron's `Display`: Compared to Electron's `screen`, these are missing: -* **Events** - `display-added`, `display-removed`, and `display-metrics-changed` are not implemented. Bunmaska's `screen` is a plain object, not an `EventEmitter`, so there is no hot-plug or metrics-change notification. Re-call `getAllDisplays()` if you need fresh data. * **DIP/physical conversion methods** - `screenToDipPoint`, `dipToScreenPoint`, `screenToDipRect`, and `dipToScreenRect` are absent. (These are Windows-only or Windows/Linux-only in Electron; Bunmaska does not implement them on any backend, including Windows.) * **`getCursorScreenPoint()` on Linux** - stubbed to `{0,0}` (see above). * **A real `workArea` on Linux** - equal to `bounds`; the panel inset is not subtracted there. diff --git a/website/src/content/docs/api/session.md b/website/src/content/docs/api/session.md index 5549ea68..66b6b422 100644 --- a/website/src/content/docs/api/session.md +++ b/website/src/content/docs/api/session.md @@ -129,7 +129,7 @@ app.whenReady().then(() => { ### `ses.clearStorageData()` -`clearStorageData(): Promise` _macOS, Windows_ +`clearStorageData(): Promise` _macOS, Linux, Windows_ Clears the default data store's website data and resolves when the clear completes. @@ -139,14 +139,13 @@ Platform notes on exactly _what_ gets cleared: - **macOS** - clears **all** website data: cache, cookies, local and session storage, IndexedDB, and the rest. Open pages keep their in-memory resource cache until they reload. - **Windows** - clears cookies and the fetch/HTTP caches. Clearing local storage and IndexedDB is a follow-up, so it is **not** the full wipe macOS performs yet. -- **Linux** - not yet wired: `clearStorageData` currently rejects with an `UnsupportedPlatformError` (`WebKitWebsiteDataManager` clearing is a follow-up). +- **Linux** - clears every website-data type the default `WebKitWebsiteDataManager` holds (`WEBKIT_WEBSITE_DATA_ALL`). ```ts import { session } from 'bunmaska'; async function signOut() { - // macOS: clears everything. Windows: clears cookies + fetch caches. - // Linux: rejects (not yet wired). + // macOS / Linux: clears everything. Windows: cookies + fetch caches. await session.defaultSession.clearStorageData(); } ``` @@ -156,9 +155,9 @@ async function signOut() { The default session is deliberately minimal right now. Compared to Electron's `session` module, the following are **not** implemented: - **`session.fromPartition()` / `session.fromPath()`** - no partitioned or path-based sessions; there is only `defaultSession`. The `cache` option and `persist:` semantics don't exist. -- **`ses.clearStorageData(options)`** - the `origin` and `storages` scoping options reject with an `UnsupportedPlatformError`; only the unscoped clear exists. It works on macOS (full wipe) and Windows (cookies + fetch caches; local/IndexedDB clearing is a follow-up); Linux rejects. +- **`ses.clearStorageData(options)`** - the `origin` and `storages` scoping options reject with an `UnsupportedPlatformError`; only the unscoped clear exists. It works on macOS and Linux (full wipe) and Windows (cookies + fetch caches; local/IndexedDB clearing is a follow-up). - **Cookie extras** - `cookies.get`/`set`/`remove` exist (macOS/Linux; Windows rejects), but not the `changed` event, `flushStore()`, or set-details fields beyond the documented ones (`sameSite` cannot be set; macOS stores `lax`). -- **Cache (`ses.getCacheSize()`, `ses.clearCache()`)** - no granular cache inspection or HTTP-cache-only clear (use `clearStorageData()`, which clears everything on macOS and cookies + fetch caches on Windows). +- **Cache (`ses.getCacheSize()`, `ses.clearCache()`)** - no granular cache inspection or HTTP-cache-only clear (use `clearStorageData()`, which clears everything on macOS and Linux and cookies + fetch caches on Windows). - **Proxy (`ses.setProxy()`, `ses.resolveProxy()`, `ses.forceReloadProxyConfig()`)** - no proxy configuration. - **Network interception (`ses.webRequest`, `ses.protocol`, `ses.fetch()`)** - no request interception, custom protocols, or main-process fetch. - **Permissions (`ses.setPermissionRequestHandler()`, `ses.setPermissionCheckHandler()`, `ses.setDisplayMediaRequestHandler()`)** - no permission plumbing. diff --git a/website/src/content/docs/api/tray.md b/website/src/content/docs/api/tray.md index 8f886b1d..f9437496 100644 --- a/website/src/content/docs/api/tray.md +++ b/website/src/content/docs/api/tray.md @@ -9,8 +9,8 @@ order: 11 Platform support is uneven and honest about it: - **macOS** - fully wired to a real `NSStatusItem`. Works un-bundled (`bun main.ts`). Icon, tooltip, title, context menu, and the `click` event all function. -- **Linux** - a `StatusNotifierItem` exported over D-Bus (KDE, the GNOME AppIndicator extension, Waybar, swaybar, etc. draw the icon). It is gated behind the `BUNMASKA_ENABLE_LINUX_TRAY=1` environment variable. With the gate off, or when no session bus is reachable, the tray is an **inert no-op** rather than a throw - so cross-platform code can construct a `Tray` safely everywhere. Even when live, `setContextMenu` is not yet shown on Linux (the `com.canonical.dbusmenu` service is deferred). -- **Windows** - wired to the notification area via `Shell_NotifyIcon`. Icon, tooltip, and the left-click `click` event all function. Caveats: `setContextMenu` is deferred (a no-op - no menu is shown), `setTitle` is a no-op (Windows tray icons have no inline text), and right-click / double-click are not surfaced. +- **Linux** - a `StatusNotifierItem` exported over D-Bus (KDE, the GNOME AppIndicator extension, Waybar, swaybar, etc. draw the icon). It is gated behind the `BUNMASKA_ENABLE_LINUX_TRAY=1` environment variable. With the gate off, or when no session bus is reachable, the tray is an **inert no-op** rather than a throw - so cross-platform code can construct a `Tray` safely everywhere. When live, `setContextMenu` shows a GTK popover from a hidden 1×1 window on `ContextMenu` / `SecondaryActivate`. Placement on Wayland is weak (the popover is not anchored to the panel icon). There is no dbusmenu service yet. +- **Windows** - wired to the notification area via `Shell_NotifyIcon`. Icon, tooltip, left-click `click`, and a right-click context menu (`TrackPopupMenu` at the cursor) all function. `setTitle` is a no-op (Windows tray icons have no inline text). Double-click is not surfaced as its own event. ```ts import { app, Menu, Tray } from 'bunmaska'; @@ -80,7 +80,7 @@ tray.setImage('/path/to/active-iconTemplate.png'); Attaches a context menu (shown on click) or clears it with `null`. No-op after `destroy()`. -On **macOS** this installs a real `NSMenu` and works as expected. On **Linux** this is accepted but currently a soft no-op - the menu is not shown, because the dbusmenu service is deferred. On **Windows** it is likewise a deferred no-op - the menu is accepted but not yet shown. It never throws, so the same code runs on every platform. +On **macOS** this installs a real `NSMenu`. On **Windows** a right-click opens the menu at the cursor. On **Linux** (live tray only) `ContextMenu` / `SecondaryActivate` opens a GTK popover; on Wayland it may not sit next to the icon. It never throws, so the same code runs on every platform. ```ts import { Menu } from 'bunmaska'; @@ -139,5 +139,5 @@ Compared with Electron's `Tray`, the following are not implemented: - **`popUpContextMenu()` / `closeContextMenu()`** - no programmatic menu pop-up/dismiss. - **`getBounds()`** - the icon's screen rectangle is not exposed. - **`getGUID()`** - no GUID support, so nothing to return. -- **Linux and Windows context menus** - `setContextMenu` is accepted but the menu is not yet drawn on Linux (dbusmenu deferred) or Windows (deferred no-op). Only macOS shows the menu today. +- **Linux dbusmenu** - the tray menu is a GTK popover, not `com.canonical.dbusmenu`, so hosts that only speak dbusmenu will not embed it in the panel. - **Windows balloon / focus members** - `displayBalloon`, `removeBalloon`, `focus`, `balloon-*` events, etc. are not implemented, even though the Windows tray icon itself (via `Shell_NotifyIcon`) is now supported. diff --git a/website/src/content/docs/api/web-contents.md b/website/src/content/docs/api/web-contents.md index c11ce13b..0b00f739 100644 --- a/website/src/content/docs/api/web-contents.md +++ b/website/src/content/docs/api/web-contents.md @@ -161,12 +161,12 @@ await win.webContents.removeInsertedCSS(key); ### `contents.printToPDF()` -Returns `Promise` - renders the current page to a PDF and resolves to its bytes. _macOS only._ On Linux it rejects with an `UnsupportedPlatformError` (WebKitGTK has no page-to-PDF-bytes API). On Windows it is **engine-blocked**: the WinCairo WebKit2 C API exposes no PDF sink (confirmed by parsing the DLL exports), so it rejects there too. Takes no options object (no page size, margins, etc. yet). +Returns `Promise` - renders the current page to a PDF and resolves to its bytes. _macOS and Linux._ On Linux WebKitGTK prints to a temporary PDF file and the bytes are read back. On Windows it is **engine-blocked**: the WinCairo WebKit2 C API exposes no PDF sink (confirmed by parsing the DLL exports), so it rejects there. Takes no options object (no page size, margins, etc. yet). ```ts import { writeFile } from 'node:fs/promises'; -const pdf = await win.webContents.printToPDF(); // macOS only +const pdf = await win.webContents.printToPDF(); // macOS and Linux await writeFile('out.pdf', pdf); ``` @@ -257,9 +257,9 @@ Limits on Windows today: there are no modifier keys, so a `modifiers` array is i ### `contents.setWindowOpenHandler(handler)` -* `handler` Function - receives `{ url }` and returns `{ action: 'allow' | 'deny' }`. +* `handler` Function - receives `{ url }` and returns `{ action: 'allow' | 'deny', overrideBrowserWindowOptions? }`. -Sets the handler consulted when the page requests a new window (`window.open` / `target=_blank`). Honest caveat: the native popup is **always blocked** on every platform - child-window creation isn't supported, so `{ action: 'allow' }` is unimplemented everywhere. Returning `{ action: 'allow' }` logs a warning and still blocks the window, so the practical pattern is to open the URL externally and return `deny`. The handler's return shape is `{ action }` only - no `overrideBrowserWindowOptions`, and there is no `did-create-window` event. On Windows the handler is not invoked yet: setting one logs a warning, and `window.open` is blocked (engine work pending). +Sets the handler consulted when the page requests a new window (`window.open` / `target=_blank`). On macOS and Linux, `{ action: 'allow' }` opens a new `BrowserWindow` (a sibling, not a native child view) and loads the URL. You can pass `overrideBrowserWindowOptions` to size or preload that window. There is no `did-create-window` event and no native parent/child relationship. On Windows the handler is not invoked yet: setting one logs a warning, and `window.open` is blocked (WinCairo has no `WKPageUIClient`). ```ts import { shell } from 'bunmaska'; @@ -425,10 +425,11 @@ Electron's `webContents` is huge; Bunmaska implements the navigation + scripting - **Process / lifecycle events** - `render-process-gone`, `unresponsive` / `responsive`, `crashed`, `destroyed`, `will-prevent-unload`. There's no separate renderer process to go gone. - **DevTools protocol** - no `debugger` (CDP), no `inspectElement`, no `setDevToolsWebContents`. DevTools is open/close/toggle only. - **Input & focus** - no `before-input-event` / `input-event`, `focus()` / `isFocused()`, `beginFrameSubscription`, `startDrag`. (`sendInputEvent` does exist, on Windows - see above.) -- **Printing & content** - `print()` (only `printToPDF`, macOS-only; engine-blocked on Windows), `savePage`, `getPrintersAsync`, `findInPage` / `stopFindInPage`. +- **Printing & content** - `print()` (only `printToPDF`, macOS and Linux; engine-blocked on Windows), `savePage`, `getPrintersAsync`, `findInPage` / `stopFindInPage`. - **Page dialogs** - `alert()`, `confirm()` and `` open native sheets on macOS; `prompt()` returns `null` there, as it does in Electron. On Linux and Windows Bunmaska adds no handling of its own. - **Editing & clipboard commands** - `undo`/`redo`/`cut`/`copy`/`paste`/`selectAll`/`replace`, `cut`-style menu wiring, `replaceMisspelling`. - **Media / audio** - `isAudioMuted` / `setAudioMuted`, `setBackgroundThrottling`, `getOSProcessId`, `getProcessId`. -- **`setWindowOpenHandler` with `allow`** - child-window creation is unsupported, so `{ action: 'allow' }` is logged and ignored; there is no `did-create-window`, and the handler return type omits `overrideBrowserWindowOptions`. On Windows the handler is not invoked at all yet. -- **`capturePage` on Windows / `printToPDF` off macOS** - `capturePage` works on macOS and Linux but is **engine-blocked on Windows**; `printToPDF` is _macOS only_ (not yet wired on Linux, engine-blocked on Windows - the WinCairo WebKit2 C API exposes neither a PDF sink nor a UI-process snapshot). +- **`setWindowOpenHandler` on Windows** - the handler is never called; `window.open` stays blocked. On macOS and Linux `{ action: 'allow' }` opens a sibling `BrowserWindow`. There is no `did-create-window` and no native parent/child view. +- **`capturePage` / `printToPDF` on Windows** - both are **engine-blocked**. `capturePage` and `printToPDF` work on macOS and Linux. The WinCairo WebKit2 C API exposes neither a PDF sink nor a UI-process snapshot. +- **DevTools on Windows** - `openDevTools` logs a warning and does nothing. WinCairo does not export a verified inspector entry point. - **Session / zoom plumbing** - no `session` property, no `setVisualZoomLevelLimits`, no `zoomLevel` persistence across reloads (zoom is stored in-memory and reapplied per `setZoomFactor`). diff --git a/website/src/content/docs/introduction.md b/website/src/content/docs/introduction.md index d310592c..91fcd9de 100644 --- a/website/src/content/docs/introduction.md +++ b/website/src/content/docs/introduction.md @@ -25,7 +25,7 @@ The result is an app that downloads in **~16-23 MB** instead of 150 MB+, and a n ## Status -It's **alpha**. It genuinely works on **macOS, Linux, and Windows** today - real windows, WebKit rendering on all three (system framework on macOS/Linux, a from-source WinCairo build on Windows), Electron-style IPC (with context isolation on macOS and Linux), menus, tray, dialogs, clipboard (incl. images), `nativeImage`, `safeStorage`, `powerMonitor`, and a CLI that packages real `.app`/`.deb`/`.exe` distributables (plus `.dmg` with a flag). A few APIs differ per platform - `printToPDF` is macOS-only, `capturePage` is macOS + Linux, and those two plus custom `protocol://` are engine-blocked on Windows - and the [parity matrix](/docs/migrating/parity) is honest about every cell. Some method-level corners are still being filled in. +It's **alpha**. It genuinely works on **macOS, Linux, and Windows** today - real windows, WebKit rendering on all three (system framework on macOS/Linux, a from-source WinCairo build on Windows), Electron-style IPC (with context isolation on macOS and Linux), menus, tray, dialogs, clipboard (incl. images), `nativeImage`, `safeStorage`, `powerMonitor`, and a CLI that packages real `.app`/`.deb`/`.exe` distributables (plus `.dmg` with a flag). A few APIs differ per platform - `printToPDF` and `capturePage` are macOS + Linux, and those two plus custom `protocol://` are engine-blocked on Windows - and the [parity matrix](/docs/migrating/parity) is honest about every cell. Some method-level corners are still being filled in. If you're evaluating it for production, read the word "alpha" one more time, then keep reading anyway. diff --git a/website/src/content/docs/migrating/parity.md b/website/src/content/docs/migrating/parity.md index bd0f74d0..e7af673b 100644 --- a/website/src/content/docs/migrating/parity.md +++ b/website/src/content/docs/migrating/parity.md @@ -15,7 +15,7 @@ Support is not the same on every platform, and we won't pretend it is. Start wit ## How to read the table -- **Full.** Everything Bunmaska offers in this module works on this OS. A few differences from Electron apply on every OS, such as async clipboard reads, JSON IPC or media keys in `globalShortcut`. The note and the module's section list them. +- **Full.** Everything Bunmaska offers in this module works on this OS. A few differences from Electron apply on every OS, such as async clipboard reads or JSON IPC. The note and the module's section list them. - **Partial.** It works on this OS, with gaps you should plan around. The note and the module's section say exactly which. - **Engine-blocked.** It can't be built on this OS today, because the WebKit build Bunmaska uses there lacks the piece it needs. `printToPDF` and `capturePage` reject with `UnsupportedPlatformError`. `protocol.handle` is the exception: it registers without an error but never serves anything (see [`protocol`](#protocol)). This changes only if WebKit adds the missing piece. See [why](#why-some-things-cant-work-on-an-os). - **Not implemented.** Not built on this OS yet, though nothing in the platform stops it. Calling it throws `UnsupportedPlatformError`, or rejects with it when the method returns a Promise. To fall back, catch it: import `UnsupportedPlatformError` from `bunmaska/main`, or check `err.code === 'ERR_UNSUPPORTED_PLATFORM'`. [Still to do](#still-to-do) says what is planned. @@ -38,7 +38,7 @@ Your users don't set anything. Your main process does, at the top of `main.ts`, | `app` | | | | [Lifecycle, quit, paths and locale work everywhere. Windows has no about panel.](#app) | | `BrowserWindow` | | | | [On Linux your app can't position its windows or tell when the user minimizes one. Windows reports moves and resizes only when a drag ends.](#browserwindow) | | `webContents` (core) | | | | [Loading, navigation, scripts and IPC work everywhere. Windows has no DevTools or pop-up handler yet.](#webcontents-core) | -| `webContents.printToPDF` | | | | [macOS only.](#webcontentsprinttopdf) | +| `webContents.printToPDF` | | | | [macOS and Linux. Engine-blocked on Windows.](#webcontentsprinttopdf) | | `webContents.capturePage` | | | | [macOS and Linux. Not possible on Windows today.](#webcontentscapturepage) | | `webContents.sendInputEvent` | | | | [Windows only, without modifier keys.](#webcontentssendinputevent) | | `ipcMain` / `ipcRenderer` | | | | [Works everywhere. Messages are sent as JSON, so send plain data only.](#ipcmain-and-ipcrenderer) | @@ -46,17 +46,17 @@ Your users don't set anything. Your main process does, at the top of `main.ts`, | `Menu` / `MenuItem` | | | | [Menu keyboard shortcuts work on macOS only.](#menu-and-menuitem) | | `dialog` | | | | [Dialogs never attach to a window. Windows can't show custom button labels.](#dialog) | | `clipboard` | | | | [Text, HTML and images everywhere. Reads return Promises.](#clipboard) | -| `Tray` | | | | [No tray menu on Linux or Windows yet. Linux needs an opt-in switch.](#tray) | -| `Notification` | | | | [macOS needs a packaged `.app`. No `click` event anywhere.](#notification) | +| `Tray` | | | | [Context menus work on all three. Linux needs an opt-in switch; Wayland placement is weak.](#tray) | +| `Notification` | | | | [macOS needs a packaged `.app`. `click` works on all three.](#notification) | | `nativeImage` | | | | [Works everywhere. Windows ignores JPEG quality.](#nativeimage) | | `nativeTheme` | | | | [Forcing light or dark with `themeSource` restyles the page on macOS only.](#nativetheme) | -| `globalShortcut` | | | | [Linux works under X11 only. Media keys don't register anywhere.](#globalshortcut) | +| `globalShortcut` | | | | [Linux prefers X11; Wayland is a best-effort portal. Media keys work on Windows and Linux, not macOS.](#globalshortcut) | | `shell` | | | | [Works everywhere. Linux can't highlight the file in its folder.](#shell) | | `protocol` | | | | [Custom schemes like `app://` serve on macOS and Linux. Not possible on Windows today.](#protocol) | -| `screen` | | | | [No display-change events anywhere. Linux can't read the cursor or work area.](#screen) | -| `powerMonitor` | | | | [Sleep, wake, lock and unlock only. Linux needs an opt-in switch.](#powermonitor) | +| `screen` | | | | [Hot-plug events fire. Linux can't read the cursor or work area.](#screen) | +| `powerMonitor` | | | | [Idle, battery, sleep and lock. Linux idle time is always 0; sleep/lock need an opt-in switch.](#powermonitor) | | `powerSaveBlocker` | | | | [Blocks idle sleep. Linux needs an opt-in switch, and both types do the same thing there.](#powersaveblocker) | -| `safeStorage` | | | | [One key shared by every Bunmaska app. Linux needs an opt-in switch.](#safestorage) | +| `safeStorage` | | | | [One key per `app.getName()`. Linux needs an opt-in switch.](#safestorage) | | `session` | | | | [One default session. Cookies on macOS and Linux only.](#session) | | `autoUpdater` | | | | [Signed updates download, install and relaunch on all three. Unlike Electron, you start the download yourself, and `.deb` installs can't update themselves.](#autoupdater) | | Accelerator strings, `app.getPath` | | | | [Parse and resolve the same on all three.](#accelerator-strings-and-appgetpath) | @@ -97,13 +97,13 @@ On every OS, `BrowserWindow.fromWebContents` and `getFocusedWindow` work, and a - While the user drags or resizes a window, `move` and `resize` arrive when they let go of the mouse, not continuously. - To your code, a closed window behaves as on the other OSes: `closed` fires, and using it throws `Object has been destroyed`. Behind the scenes, Bunmaska only hides the native window and loads a blank page into it, because tearing down a live WebKit view crashes on Windows today. That memory is freed only when the app exits, so an app that opens and closes many windows uses more memory over time. -Parent, child and modal windows are not implemented on any OS. The [BrowserWindow page](/docs/api/browser-window#not-in-bunmaska-yet) lists the rest. +Native parent, child and modal windows (`parent` / `modal` constructor options) are not implemented on any OS. `{ action: 'allow' }` from `setWindowOpenHandler` opens a sibling `BrowserWindow` on macOS and Linux; see [`webContents`](#webcontents-core). The [BrowserWindow page](/docs/api/browser-window#not-in-bunmaska-yet) lists the rest. ### `webContents` (core) Loading pages, navigation events, `executeJavaScript`, zoom, `insertCSS` and `send` work on all three. -Bunmaska can't create child windows yet, so `window.open` and `target="_blank"` links are always blocked, on every OS. On macOS and Linux your `setWindowOpenHandler` handler is still called with the URL. Returning `{ action: 'allow' }` logs a warning and the window stays blocked. The practical pattern: open the URL with `shell.openExternal(url)` and return `{ action: 'deny' }`. +On macOS and Linux, `setWindowOpenHandler` is called for `window.open` and `target="_blank"`. Returning `{ action: 'allow' }` opens a new `BrowserWindow` (a sibling, not a native child view) and loads the URL. You can pass `overrideBrowserWindowOptions`. There is no `did-create-window` event. To send the URL to the browser instead, call `shell.openExternal(url)` and return `{ action: 'deny' }`. - **macOS:** `openDevTools()` opens the Web Inspector through a private WebKit API. If that API is missing, it logs a warning instead of throwing. `alert()`, `confirm()` and file inputs open native sheets. `prompt()` returns `null`, as in Electron. - **Linux:** `openDevTools()` opens the WebKitGTK inspector. @@ -115,7 +115,7 @@ Bunmaska can't create child windows yet, so `window.open` and `target="_blank"` ### `webContents.printToPDF` - **macOS:** works. Resolves to the PDF bytes. Options such as page size and margins are ignored (TypeScript flags them). -- **Linux:** rejects with `UnsupportedPlatformError`. WebKitGTK has no call that hands back PDF bytes, but it can print to a file. Printing to a temporary PDF and reading it back would work. It just isn't wired up yet. +- **Linux:** works. WebKitGTK prints to a temporary PDF file and Bunmaska reads the bytes back. Options are ignored, as on macOS. - **Windows:** engine-blocked. Rejects with `UnsupportedPlatformError`. WinCairo has no PDF export at all. ### `webContents.capturePage` @@ -224,14 +224,14 @@ The Linux selection clipboard, RTF, bookmarks and the combined `write()` are not - **Linux:** off by default. Turn it on with the `BUNMASKA_ENABLE_LINUX_TRAY` [opt-in switch](#linux-opt-in-switches). - When it is off, or the desktop's message bus can't be reached, `new Tray()` still works but shows nothing, so the same code runs on every OS. - When on, the icon uses StatusNotifierItem, the tray standard that KDE, Waybar, swaybar and GNOME (with the AppIndicator extension) draw. - - `click` fires when the desktop activates the icon. `setContextMenu` is accepted, but no menu shows yet. -- **Windows:** icon, tooltip and left-click `click` work. `setContextMenu` is accepted, but no menu shows yet. `setTitle` does nothing, because Windows tray icons have no text. Right-click and double-click are not reported. + - `click` fires when the desktop activates the icon. `setContextMenu` opens a GTK popover on `ContextMenu` / `SecondaryActivate`. The popover is parented to a hidden 1×1 window, so on Wayland it may not sit next to the panel icon. Hosts that only speak dbusmenu will not embed the menu in the panel. +- **Windows:** icon, tooltip, left-click `click` and a right-click context menu (`TrackPopupMenu`) work. `setTitle` does nothing, because Windows tray icons have no text. Double-click is not reported as its own event. On every OS, `click` carries no event, bounds or position. ### `Notification` -`new Notification({ title, body, subtitle, silent }).show()` works on all three. Those four are the only options; others such as `icon`, `actions` and `urgency` are ignored (TypeScript flags them). `silent` is honored everywhere. Changing a property after `show()` doesn't update the notification on screen. `click`, `reply` and `action` events are not delivered on any OS yet. +`new Notification({ title, body, subtitle, silent }).show()` works on all three. Those four are the only options; others such as `icon`, `actions` and `urgency` are ignored (TypeScript flags them). `silent` is honored everywhere. Changing a property after `show()` doesn't update the notification on screen. The `click` event fires when the user activates the banner or balloon. `reply` and `action` are not delivered. - **macOS:** notifications only appear from a packaged `.app`. Under `bunmaska dev` or `bun main.ts`, nothing shows and `Notification.isSupported()` returns `false`, so check it first. The `close` event never fires. - **Linux:** shown through libnotify. `close` fires when the user or the system dismisses the notification. `subtitle` is ignored. @@ -260,8 +260,8 @@ System-wide shortcuts that fire even when your app is not focused. - **macOS:** works, even when the app is not packaged. - **Windows:** works. -- **Linux:** works under X11 only. Linux desktops run on one of two display systems, X11 or Wayland, and Ubuntu and Fedora default to Wayland. Under Wayland, `register` returns `false` and nothing is grabbed, even through XWayland. Supporting Wayland means asking the desktop for permission through its global-shortcuts service, which Bunmaska doesn't do yet. Check the return value of `register` and offer an in-app shortcut as a fallback. Under X11, shortcuts fire regardless of NumLock and CapsLock. -- **Every OS:** media and volume keys (`MediaPlayPause`, `VolumeUp` and friends) parse, but `register` returns `false` for them. The numpad keys and `Insert` work. An accelerator that can't be parsed makes `register` return `false` instead of throwing. +- **Linux:** prefers X11 (`XGrabKey`). Under X11, shortcuts fire regardless of NumLock and CapsLock. On a Wayland session with a session bus, `register` falls back to the `org.freedesktop.portal.GlobalShortcuts` portal: it returns `true` and stores the callback, but the CreateSession handshake is incomplete, so the key may never fire. Check the return value and keep an in-app shortcut as a fallback. +- **Every OS:** media and volume keys (`MediaPlayPause`, `VolumeUp` and friends) parse. Windows (`RegisterHotKey` media VKs) and Linux X11 (`XF86Audio*` keysyms) can grab them. Carbon cannot grab those NX_SYSDEFINED keys, so `register` returns `false` for them on macOS. The numpad keys and `Insert` work. An accelerator that can't be parsed makes `register` return `false` instead of throwing. ### `shell` @@ -294,7 +294,7 @@ On every OS: Listing displays with their bounds, scale factor and multi-monitor positions works on all three. Coordinates start at the top-left corner of the primary display. -On every OS, `screen` emits no events: no `display-added`, `display-removed` or `display-metrics-changed`. It is a plain object, not an `EventEmitter`. Call `getAllDisplays()` again when you need fresh data. +`screen` is an `EventEmitter`. `display-added`, `display-removed` and `display-metrics-changed` fire when the backend notices a change (AppKit screen-parameter notifications, GTK's monitor `items-changed`, Win32 display-change). On Linux, display ids are list indexes, so a plug/unplug can look like every monitor was removed and added, and a scale-only change may not fire. - **macOS:** `getCursorScreenPoint()` and `workArea` (the screen minus the menu bar and Dock) are real, and so are `rotation` and `internal`. - **Windows:** `getCursorScreenPoint()` and `workArea` (the screen minus the taskbar) are real. `rotation` is always `0` and `internal` is always `false`. @@ -308,12 +308,13 @@ On every OS, `screen` emits no events: no `display-added`, `display-removed` or ### `powerMonitor` -The `suspend`, `resume`, `lock-screen` and `unlock-screen` events work on all three. The rest of Electron's `powerMonitor` is missing on every OS: no `getSystemIdleTime` or `getSystemIdleState`, no `isOnBatteryPower` or `on-ac` / `on-battery`, no `shutdown` event and no thermal state. +The `suspend`, `resume`, `lock-screen`, `unlock-screen`, `on-ac` and `on-battery` events work, plus `getSystemIdleTime`, `getSystemIdleState`, `isOnBatteryPower` and the `onBatteryPower` getter. There is still no `shutdown` event and no thermal state. -- **Linux:** off by default. Turn it on with the `BUNMASKA_ENABLE_LINUX_POWER` [opt-in switch](#linux-opt-in-switches). It also needs systemd-logind, Linux's login manager, on the system message bus. With it off, no events fire. +- **Linux:** sleep and lock events are off by default. Turn them on with the `BUNMASKA_ENABLE_LINUX_POWER` [opt-in switch](#linux-opt-in-switches). They also need systemd-logind, Linux's login manager, on the system message bus. With it off, those four stay silent. Battery queries and `on-ac` / `on-battery` read sysfs and do not need the switch. `getSystemIdleTime()` is always `0`; `getSystemIdleState` still reports `'locked'` when logind says the session is locked. - `suspend` is best-effort. Bunmaska doesn't ask the system to wait for it, so the event can arrive after the machine wakes. Don't count on it to finish work before the lid closes. - `lock-screen` and `unlock-screen` fire only when the lock goes through logind, for example `loginctl lock-session`. Lock screens that lock without telling logind don't trigger them, so test on the desktops you target before relying on these events. -- **Windows:** Windows sometimes refuses the lock listener, usually when the app starts right at login. Bunmaska then logs a warning, and `lock-screen` and `unlock-screen` stay silent until the app restarts. +- **Windows:** idle time comes from `GetLastInputInfo`. Battery state comes from `GetSystemPowerStatus`. `on-ac` / `on-battery` fire on `PBT_APMPOWERSTATUSCHANGE`. Windows sometimes refuses the lock listener, usually when the app starts right at login. Bunmaska then logs a warning, and `lock-screen` and `unlock-screen` stay silent until the app restarts. +- **macOS:** idle time comes from CoreGraphics; battery from IOKit. `on-ac` / `on-battery` fire when the power source changes (polled every two seconds, and again on wake). ### `powerSaveBlocker` @@ -327,14 +328,14 @@ The `suspend`, `resume`, `lock-screen` and `unlock-screen` events work on all th `isEncryptionAvailable`, `encryptString` and `decryptString` work. Strings are encrypted with AES-256-GCM, so a tampered blob makes `decryptString` throw instead of returning garbage. - **macOS:** the key lives in the Keychain. -- **Windows:** the key is sealed with DPAPI, Windows' built-in per-user encryption. It is stored as `safestorage.key` in the folder `BUNMASKA_HOME` names, or in `.bunmaska` in the user's home folder when that isn't set. +- **Windows:** the key is sealed with DPAPI, Windows' built-in per-user encryption. It is stored as `safestorage..key` in the folder `BUNMASKA_HOME` names, or in `.bunmaska` in the user's home folder when that isn't set. - **Linux:** off by default. Turn it on with the `BUNMASKA_ENABLE_LINUX_KEYRING` [opt-in switch](#linux-opt-in-switches) to keep the key in the desktop keyring through libsecret. - With it off, or with no keyring, `isEncryptionAvailable()` returns `false` and `encryptString` / `decryptString` throw. - If the keyring is locked, the first `encryptString` or `decryptString` waits for the user to unlock it, and your main process is frozen until they do. Two differences from Electron on every OS: -- **One key is shared by every Bunmaska app of the same user.** Electron keeps one per app. Any other Bunmaska app the same user runs can decrypt your app's data (macOS may ask the user first). Treat `safeStorage` as protection against other users and a stolen disk, not against other apps. A separate key per app is on the [to-do list](#still-to-do). +- **The key is scoped to `app.getName()`.** Two apps that share a name share a key. Blobs sealed by older alpha builds (one shared `master-key` / `safestorage.key`) will not decrypt. - **There is no plaintext fallback.** Without a keyring, Electron falls back to a weak built-in key. Bunmaska refuses and throws instead. Blobs are Bunmaska's own format and can't be read by Electron. ### `session` @@ -348,9 +349,8 @@ There is one session, `session.defaultSession`. Partitions (`fromPartition`, `fr - `cookies.set` defaults `path` to `/`, not the URL's directory. - **Windows:** every `cookies` method rejects with `UnsupportedPlatformError`. WinCairo has no way to read or write a single cookie; it can only delete them all. - **`clearStorageData()`:** - - macOS clears all website data: cookies, caches, local storage, IndexedDB and the rest. Pages that are still open keep their in-memory cache until they reload. + - macOS and Linux clear all website data: cookies, caches, local storage, IndexedDB and the rest. Pages that are still open keep their in-memory cache until they reload. - Windows clears cookies and Cache API storage (`caches`) only, not the HTTP cache, local storage or IndexedDB. - - Linux rejects with `UnsupportedPlatformError`. It is not wired up yet. - On every OS, passing the `origin` or `storages` options rejects rather than quietly clearing everything. - **macOS, in development:** every Bunmaska app you run unpackaged (`bunmaska dev`, `bun main.ts`) shares one cookie jar and one set of web storage, across all your projects, because they all run as the same `bun` process. Logins and `localStorage` from one project show up in another. A packaged `.app` gets its own. @@ -411,41 +411,35 @@ GTK 4 removed the calls that let an app move its own window, and Wayland forbids ## Still to do -Gaps inside modules that already ship. We're filling them. Gaps mentioned above but not listed here, such as `sendInputEvent` on macOS and Linux, parent and child windows, `trashItem`, `MessagePort`, session partitions and `printToPDF` options, have no date yet. +Gaps inside modules that already ship. We're filling them. Gaps mentioned above but not listed here, such as `sendInputEvent` on macOS and Linux, native parent/modal windows, `trashItem`, `MessagePort`, session partitions and `printToPDF` options, have no date yet. **Every OS** -- `getSystemIdleTime` and `isOnBatteryPower` in `powerMonitor`. -- `click`, `reply` and `action` events for notifications. -- Display-change events in `screen`. -- Media and volume keys for `globalShortcut`. -- Child windows, so `setWindowOpenHandler` can `allow`. -- A separate `safeStorage` key per app. +- `reply` and `action` events for notifications. - Richer `webContents` events. **macOS** - The `close` event for notifications. +- Media and volume keys for `globalShortcut` (Carbon cannot grab them). **Linux** -- `session.clearStorageData`. -- `printToPDF`. -- The tray context menu. +- A real `getSystemIdleTime` (today it is always `0`). +- A complete Wayland global-shortcuts portal bind (today `register` may return `true` without the key ever firing). - Menu keyboard shortcuts. - The minimized state, and the `minimize` and `restore` events. - The cursor position and the work area in `screen`. -- Global shortcuts under Wayland. - Your app's name and version in the about dialog. +- A dbusmenu-backed tray menu (today a GTK popover). **Windows** - The `setWindowOpenHandler` callback. -- DevTools. +- DevTools (engine-blocked: no verified WinCairo inspector symbol). - Live dark-mode changes in `nativeTheme`. -- The tray context menu. - Menu keyboard shortcuts. -- An isolated world for the preload. +- An isolated world for the preload (engine-blocked: WinCairo has no content-world API). - JPEG quality in `nativeImage`. - Rich notifications. - Modifier keys, more keys and scaled displays in `sendInputEvent`. @@ -469,10 +463,10 @@ Differences in behavior today, on every OS unless noted. Some are by design, lik - **`clipboard`, `shell` and `nativeImage` work in the main process only.** Call them there and expose what the page needs through IPC. Clipboard reads return Promises. - **`shell.openExternal` resolves `true` or `false`** instead of rejecting on failure. - **`cookies.set` defaults `path` to `/`**, not the URL's directory, and `session.getUserAgent()` returns `''` until you set one. -- **`safeStorage` shares one key across all Bunmaska apps** of a user, on all three OSes, and has no plaintext fallback. +- **`safeStorage` keys off `app.getName()`** and has no plaintext fallback. Older alpha blobs sealed under the shared key will not decrypt. - **`autoUpdater` doesn't download on its own.** You call `downloadUpdate()`, and `before-quit-for-update` is not emitted. - **`MenuItem` properties are read-only** after construction, except `checked`. -- **`screen` is not an `EventEmitter`.** +- **`setWindowOpenHandler` `{ action: 'allow' }` opens a sibling `BrowserWindow`**, not a native child view, and only on macOS and Linux. ## Out of scope by design diff --git a/website/src/content/docs/platforms.md b/website/src/content/docs/platforms.md index 81e6511f..cafad55c 100644 --- a/website/src/content/docs/platforms.md +++ b/website/src/content/docs/platforms.md @@ -34,7 +34,7 @@ A from-scratch Win32 backend on pure `bun:ffi` - native windows + a cooperative - **Architectures:** `x64` today. Upstream WinCairo is x64-only, so **ARM64 is on the roadmap**, not shipping. 32-bit (x86) is not supported, on purpose. - **Engine:** Windows ships no system WebKit, so an app loads a **WinCairo `WebKit2.dll`** - built from WebKit source by us (a clang-cl from-source build, proven end-to-end) and bundled with the app, or resolved from the engine store. The engine directory is placed on the DLL search path so its dependency closure (ICU, libcurl, ANGLE, …) resolves beside it. - **The distribution piece:** you can ship a Windows app **today** by embedding the engine in the build: `engine.embed: true` for a pinned engine you installed from the feed, or `bunmaska build --embed-engine ` for your own build. On a dev machine, `BUNMASKA_WEBKIT_PATH` or a pinned engine in the store also works. With no engine at all, the app refuses to start and tells you which of those to provide. A hosted WinCairo engine is on the feed today; the stable-train build and ARM64 are next. -- **Engine-blocked gaps:** `printToPDF`, `capturePage`, and custom `protocol://` schemes can't be served on Windows - the WinCairo WebKit2 C API simply doesn't expose those entry points (confirmed against the DLL's exports). `printToPDF` and `capturePage` reject with a clear error, and creating a window while custom schemes are registered logs a warning, rather than anything silently no-opping. DevTools, the tray context menu, and a fully isolated content world are follow-ups. Full picture on the [parity matrix](/docs/migrating/parity). +- **Engine-blocked gaps:** `printToPDF`, `capturePage`, and custom `protocol://` schemes can't be served on Windows - the WinCairo WebKit2 C API simply doesn't expose those entry points (confirmed against the DLL's exports). `printToPDF` and `capturePage` reject with a clear error, and creating a window while custom schemes are registered logs a warning, rather than anything silently no-opping. DevTools and a fully isolated preload world are the same class of gap: the DLL has no verified inspector or content-world entry points, so they stay stubbed rather than `dlopen`-guessed. The tray context menu does show (`TrackPopupMenu` on right-click). Full picture on the [parity matrix](/docs/migrating/parity). ## Requirements (all platforms)