Skip to content
Draft
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
24 changes: 24 additions & 0 deletions biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,30 @@
}
}
},
{
"includes": ["src/main/platform/cef/**"],
"linter": {
"rules": {
"style": {
"noRestrictedImports": {
"level": "error",
"options": {
"patterns": [
{
"group": ["../api/**", "../../api/**", "**/bootstrap", "**/native-app"],
"message": "D024: platform/ never imports api/; contracts live in platform/services.ts and native.ts."
},
{
"group": ["**/linux/**", "**/windows/**"],
"message": "D024: the Blink backend reuses only the macOS window code (D048); share the rest through a platform/ root file."
}
]
}
}
}
}
}
},
{
"includes": ["src/main/platform/windows/**"],
"linter": {
Expand Down
19 changes: 17 additions & 2 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
configChannel,
rendererOutDir,
} from '../common/config-schema';
import { parseEngineId } from '../common/engine-id';
import { type Arch, currentArch, currentPlatform, type Platform } from '../common/platform';
import { BUNMASKA_VERSION } from '../common/version';
import { buildLinuxApp, resolveBuildEngineId } from './build-linux';
Expand Down Expand Up @@ -218,10 +219,15 @@ const resolveProjectEngine = (
return { engineId, embed: config.engine?.embed === true };
};

/** dev and run must forward the pin, or on Windows the app launches with no engine. */
/**
* dev and run must forward the pin, or on Windows the app launches with no engine. Both
* names: an inherited BUNMASKA_ENGINE_ID would otherwise outrank the alias.
*/
const launchEngineEnv = (config: BunmaskaConfig, command: string): Record<string, string> => {
const { engineId } = resolveProjectEngine(config, command);
return engineId === 'system' ? {} : { BUNMASKA_WEBKIT_ID: engineId };
return engineId === 'system'
? {}
: { BUNMASKA_ENGINE_ID: engineId, BUNMASKA_WEBKIT_ID: engineId };
};

const runBuild = async (
Expand All @@ -243,6 +249,15 @@ const runBuild = async (
);
return 1;
}
const macPin = resolveBuildEngineId(config.engine?.webkit, { os: 'macos', arch: currentArch() });
if (target === 'macos' && macPin !== 'system' && parseEngineId(macPin).engine === 'cef') {
// ponytail: packaged Blink waits on helper signing + the entitlements audit (D048 phase 2).
err(
`bunmaska build: the Blink engine ${macPin} runs under dev and run only so far; the .app ` +
'would ship the system WebKit instead. Remove the pin to build.',
);
return 1;
}
const macOnly: readonly [string, boolean, string][] = [
['--sign', command.options.sign !== undefined, 'codesign'],
['--notarize', command.options.notarize === true, 'notarytool'],
Expand Down
9 changes: 6 additions & 3 deletions src/common/engine-id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ import { InvalidArgumentError } from './errors';
import { compareVersions } from './manifest';
import type { Arch } from './platform';

/** Which web-engine family a build belongs to (`webkit` covers WinCairo + macOS; D044). */
export type EngineFamily = 'webkitgtk' | 'webkit';
/**
* `webkit` covers WinCairo + macOS (D044). `cef` is the opt-in Blink engine (D048): its `api`
* is the CEF version and its `upstream` the Chromium version.
*/
export type EngineFamily = 'webkitgtk' | 'webkit' | 'cef';

export type EngineOs = 'linux' | 'macos' | 'windows';

Expand All @@ -26,7 +29,7 @@ export type EngineRef = {
/** The reserved sentinel meaning "use the OS WebView" (the default). */
export const SYSTEM_ENGINE = 'system';

const ENGINE_FAMILIES: ReadonlySet<string> = new Set(['webkitgtk', 'webkit']);
const ENGINE_FAMILIES: ReadonlySet<string> = new Set(['webkitgtk', 'webkit', 'cef']);
const ENGINE_OSES: ReadonlySet<string> = new Set(['linux', 'macos', 'windows']);
const ENGINE_ARCHES: ReadonlySet<string> = new Set(['x64', 'arm64']);

Expand Down
2 changes: 1 addition & 1 deletion src/main/api/web-contents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ export class WebContents extends EventEmitter {
return this.#userAgent;
}

/** Delivers an `isTrusted` event through the engine; Windows only, macOS and Linux throw. */
/** An `isTrusted` event via the engine: Windows and Blink; WebKit on macOS and Linux throws. */
sendInputEvent(event: NativeInputEvent): void {
// Validate at the boundary (Electron throws on a bad event): an unknown type
// must not silently no-op, and non-finite coordinates must not coerce to a
Expand Down
1 change: 1 addition & 0 deletions src/main/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export const ensureNativeStarted = (): void => {
native.onQuitRequest?.(() => {
setTimeout(() => app.quit(), 0);
});
native.setUserDataPath?.(app.getPath('userData'));
try {
native.start();
} catch (error) {
Expand Down
18 changes: 15 additions & 3 deletions src/main/engine/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@

import { existsSync, readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { type EngineRef, isSystemEngine, parseEngineId } from '../../common/engine-id';
import {
type EngineFamily,
type EngineRef,
isSystemEngine,
parseEngineId,
} from '../../common/engine-id';
import { isBunCli } from '../../common/preload-bundle';
import { type Arch, currentArch, currentPlatform, type Platform } from '../../common/platform';
import {
Expand All @@ -16,6 +21,8 @@ import {
/** The resolved engine decision for the current process. */
export type EngineResolution = {
readonly mode: 'system' | 'pinned';
/** The pinned engine's family (store pins only); `cef` selects the Blink backend (D048). */
readonly family?: EngineFamily;
/** The pinned engine's `lib/` dir (absolute). Absent in system mode. */
readonly libDir?: string;
/** The resolved engine-id (store pins only; absent for an explicit-dir pin/system). */
Expand Down Expand Up @@ -73,7 +80,12 @@ export const resolveEngineWith = (deps: ResolveDeps = {}): EngineResolution => {
}

const readBakedId = deps.readBakedId ?? (() => defaultReadBakedId(env));
const id = env['BUNMASKA_WEBKIT_ID']?.trim() || readBakedId()?.trim() || 'system';
// BUNMASKA_ENGINE_ID is the family-neutral name; BUNMASKA_WEBKIT_ID stays as its alias.
const id =
env['BUNMASKA_ENGINE_ID']?.trim() ||
env['BUNMASKA_WEBKIT_ID']?.trim() ||
readBakedId()?.trim() ||
'system';

if (isSystemEngine(id)) {
return { mode: 'system', warnings: [] };
Expand Down Expand Up @@ -113,7 +125,7 @@ export const resolveEngineWith = (deps: ResolveDeps = {}): EngineResolution => {
],
};
}
return { mode: 'pinned', libDir: join(dir, 'lib'), id, root, warnings: [] };
return { mode: 'pinned', family: ref.engine, libDir: join(dir, 'lib'), id, root, warnings: [] };
};

const cache: { value: EngineResolution | undefined } = { value: undefined };
Expand Down
159 changes: 159 additions & 0 deletions src/main/platform/cef/cef-backend.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import { homedir } from 'node:os';
import { join } from 'node:path';
import { UnsupportedPlatformError } from '../../../common/errors';
import { createLogger } from '../../../common/logger';
import { currentPlatform } from '../../../common/platform';
import { createMacOSApplication, createMacOSWindow } from '../macos/cocoa-backend';
import { withAutoreleasePool } from '../macos/cocoa-run-loop';
import { cocoa } from '../macos/cocoa-runtime';
import type { NativeAppKit, NativeApplication, NativeWindow, NativeWindowOptions } from '../native';
import { loadCef } from './cef-ffi';
import {
cefLibraryPath,
createCefBrowser,
doCefWork,
flushCookies,
initializeCef,
installCefApplicationClass,
} from './cef-runtime';
import { CefWebContents } from './cef-web-contents';

const log = createLogger('cef-backend');

const QUIT_CLOSE_TIMEOUT_MS = 2_000;
const FLUSH_GRACE_MS = 200;

/**
* The opt-in Blink engine (D048): CEF browsers inside the macOS backend's own NSWindows,
* so every window, menu, tray, dialog and app operation is the OS backend's and only the
* web contents are Chromium.
*/
class CefApplication implements NativeApplication {
readonly #libDir: string;
readonly #host: NativeApplication;
readonly #live = new Set<CefWebContents>();
#readyCallbacks: Array<() => void> = [];
#userDataPath = join(homedir(), '.bunmaska', 'blink-profile');
#cefRunning = false;
#started = false;
#startError: unknown;
readonly appKit?: NativeAppKit;

constructor(libDir: string) {
this.#libDir = libDir;
this.#host = createMacOSApplication(() => {
if (this.#cefRunning) {
doCefWork();
}
});
if (this.#host.appKit !== undefined) {
this.appKit = this.#host.appKit;
}
}

setUserDataPath(path: string): void {
this.#userDataPath = path;
}

/** A failed start rethrows its error forever: cef_initialize cannot run twice in a process. */
start(): void {
if (this.#startError !== undefined) {
throw this.#startError;
}
if (this.#started) {
return;
}
this.#started = true;
try {
loadCef(cefLibraryPath(this.#libDir));
installCefApplicationClass();
this.#host.start();
initializeCef({ libDir: this.#libDir, userDataPath: this.#userDataPath });
} catch (error) {
this.#startError = error;
throw error;
}
this.#cefRunning = true;
const callbacks = this.#readyCallbacks;
this.#readyCallbacks = [];
for (const callback of callbacks) {
callback();
}
}

onReady(callback: () => void): void {
if (this.#cefRunning) {
callback();
} else {
this.#readyCallbacks.push(callback);
}
}

onActivate(callback: (hasVisibleWindows: boolean) => void): void {
this.#host.onActivate?.(callback);
}

onOpenUrl(callback: (url: string) => void): void {
this.#host.onOpenUrl?.(callback);
}

onOpenFile(callback: (path: string) => void): void {
this.#host.onOpenFile?.(callback);
}

onQuitRequest(callback: () => void): void {
this.#host.onQuitRequest?.(callback);
}

showAboutPanel(): void {
this.#host.showAboutPanel?.();
}

createWindow(options: NativeWindowOptions): NativeWindow {
const schemes = options.protocol?.schemes ?? [];
if (schemes.length > 0) {
// ponytail: needs the phase 2 native scheme-handler bridge in the glue (D048).
log.warn(
`protocol.handle schemes are not served by the Blink engine yet: ${schemes.join(', ')}`,
);
}
return withAutoreleasePool(() =>
createMacOSWindow(options, (window, _options, emit) => {
const rt = cocoa();
const contentView = rt.msgSend(window, rt.selectors.get('contentView'));
const browser = createCefBrowser(contentView, options.width, options.height);
const contents = new CefWebContents(browser, options, () => emit('ready-to-show'));
this.#live.add(contents);
void contents.closed.then(() => this.#live.delete(contents));
// do_close returns 1: the browser is destroyed when CEF's host view deallocs with the
// window, which needs the drain's rolling autorelease pool.
return { contents, teardown: () => contents.close(), release: () => undefined };
}),
);
}

/** Close every browser and flush cookies while the pump still runs, then stop it. */
async quit(): Promise<void> {
if (this.#cefRunning) {
const closing = [...this.#live].map((contents) => {
contents.close();
return contents.closed;
});
await Promise.race([Promise.all(closing), Bun.sleep(QUIT_CLOSE_TIMEOUT_MS)]);
flushCookies();
await Bun.sleep(FLUSH_GRACE_MS);
// ponytail: no cef_shutdown - it blocks forever on a Mach wait under the Bun pump, so the
// helpers exit with us and DOM storage can lose its last few seconds; fix with a symbolized CEF.
this.#cefRunning = false;
}
await this.#host.quit();
}
}

/** The Blink backend over the CEF engine in `libDir` (an installed engine's `lib/`). macOS only. */
export const createCefApplication = (libDir: string): NativeApplication => {
if (currentPlatform() !== 'macos') {
throw new UnsupportedPlatformError('The Blink (cef) engine runs on macOS only so far');
}
return new CefApplication(libDir);
};
Loading
Loading