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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/main/api/browser-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
/**
Expand Down Expand Up @@ -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);
});
5 changes: 4 additions & 1 deletion src/main/api/notification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -52,6 +52,9 @@ export class Notification extends EventEmitter {
handle.onClosed(() => {
this.emit('close');
});
handle.onClick?.(() => {
this.emit('click');
});
this.emit('show');
}

Expand Down
50 changes: 44 additions & 6 deletions src/main/api/power-monitor.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;
};
3 changes: 2 additions & 1 deletion src/main/api/safe-storage.ts
Original file line number Diff line number Diff line change
@@ -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';

/**
Expand Down Expand Up @@ -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}`,
Expand Down
118 changes: 112 additions & 6 deletions src/main/api/screen.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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();
};
4 changes: 2 additions & 2 deletions src/main/api/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/main/api/tray.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
42 changes: 38 additions & 4 deletions src/main/api/web-contents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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');

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

Expand Down
2 changes: 2 additions & 0 deletions src/main/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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);
Expand Down
19 changes: 19 additions & 0 deletions src/main/platform/idle-state.ts
Original file line number Diff line number Diff line change
@@ -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';
};
Loading