Skip to content

Commit

Permalink
refactor: simplify events (electron#37099)
Browse files Browse the repository at this point in the history
  • Loading branch information
nornagon authored Feb 13, 2023
1 parent 8b3e498 commit 71944f2
Show file tree
Hide file tree
Showing 32 changed files with 290 additions and 409 deletions.
3 changes: 0 additions & 3 deletions docs/api/structures/event.md

This file was deleted.

4 changes: 2 additions & 2 deletions docs/api/web-contents.md
Original file line number Diff line number Diff line change
Expand Up @@ -831,7 +831,7 @@ Emitted when the preload script `preloadPath` throws an unhandled exception `err

Returns:

* `event` Event
* `event` [IpcMainEvent](structures/ipc-main-event.md)
* `channel` string
* `...args` any[]

Expand All @@ -843,7 +843,7 @@ See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain

Returns:

* `event` Event
* `event` [IpcMainEvent](structures/ipc-main-event.md)
* `channel` string
* `...args` any[]

Expand Down
1 change: 0 additions & 1 deletion filenames.auto.gni
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ auto_filenames = {
"docs/api/structures/custom-scheme.md",
"docs/api/structures/desktop-capturer-source.md",
"docs/api/structures/display.md",
"docs/api/structures/event.md",
"docs/api/structures/extension-info.md",
"docs/api/structures/extension.md",
"docs/api/structures/file-filter.md",
Expand Down
9 changes: 4 additions & 5 deletions filenames.gni
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,6 @@ filenames = {
"shell/browser/api/electron_api_dialog.cc",
"shell/browser/api/electron_api_download_item.cc",
"shell/browser/api/electron_api_download_item.h",
"shell/browser/api/electron_api_event.cc",
"shell/browser/api/electron_api_event_emitter.cc",
"shell/browser/api/electron_api_event_emitter.h",
"shell/browser/api/electron_api_global_shortcut.cc",
Expand Down Expand Up @@ -320,8 +319,6 @@ filenames = {
"shell/browser/api/electron_api_web_request.cc",
"shell/browser/api/electron_api_web_request.h",
"shell/browser/api/electron_api_web_view_manager.cc",
"shell/browser/api/event.cc",
"shell/browser/api/event.h",
"shell/browser/api/frame_subscriber.cc",
"shell/browser/api/frame_subscriber.h",
"shell/browser/api/gpu_info_enumerator.cc",
Expand Down Expand Up @@ -382,7 +379,6 @@ filenames = {
"shell/browser/electron_web_contents_utility_handler_impl.h",
"shell/browser/electron_web_ui_controller_factory.cc",
"shell/browser/electron_web_ui_controller_factory.h",
"shell/browser/event_emitter_mixin.cc",
"shell/browser/event_emitter_mixin.h",
"shell/browser/extended_web_contents_observer.h",
"shell/browser/feature_list.cc",
Expand Down Expand Up @@ -606,10 +602,13 @@ filenames = {
"shell/common/gin_helper/dictionary.h",
"shell/common/gin_helper/error_thrower.cc",
"shell/common/gin_helper/error_thrower.h",
"shell/common/gin_helper/event_emitter.cc",
"shell/common/gin_helper/event.cc",
"shell/common/gin_helper/event.h",
"shell/common/gin_helper/event_emitter.h",
"shell/common/gin_helper/event_emitter_caller.cc",
"shell/common/gin_helper/event_emitter_caller.h",
"shell/common/gin_helper/event_emitter_template.cc",
"shell/common/gin_helper/event_emitter_template.h",
"shell/common/gin_helper/function_template.cc",
"shell/common/gin_helper/function_template.h",
"shell/common/gin_helper/function_template_extensions.h",
Expand Down
9 changes: 4 additions & 5 deletions lib/browser/api/browser-window.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BaseWindow, WebContents, Event, BrowserView, TouchBar } from 'electron/main';
import { BaseWindow, WebContents, BrowserView, TouchBar } from 'electron/main';
import type { BrowserWindow as BWT } from 'electron/main';
import * as deprecate from '@electron/internal/common/deprecate';
const { BrowserWindow } = process._linkedBinding('electron_browser_window') as { BrowserWindow: typeof BWT };
Expand All @@ -22,10 +22,10 @@ BrowserWindow.prototype._init = function (this: BWT) {
};

// Redirect focus/blur event to app instance too.
this.on('blur', (event: Event) => {
this.on('blur', (event: Electron.Event) => {
app.emit('browser-window-blur', event, this);
});
this.on('focus', (event: Event) => {
this.on('focus', (event: Electron.Event) => {
app.emit('browser-window-focus', event, this);
});

Expand Down Expand Up @@ -68,8 +68,7 @@ BrowserWindow.prototype._init = function (this: BWT) {
});

// Notify the creation of the window.
const event = process._linkedBinding('electron_browser_event').createEmpty();
app.emit('browser-window-created', event, this);
app.emit('browser-window-created', { preventDefault () {} }, this);

Object.defineProperty(this, 'devToolsWebContents', {
enumerable: true,
Expand Down
4 changes: 2 additions & 2 deletions lib/browser/api/menu-item.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as roles from '@electron/internal/browser/api/menu-item-roles';
import { Menu, Event, BrowserWindow, WebContents } from 'electron/main';
import { Menu, BrowserWindow, WebContents, KeyboardEvent } from 'electron/main';

let nextCommandId = 0;

Expand Down Expand Up @@ -53,7 +53,7 @@ const MenuItem = function (this: any, options: any) {
});

const click = options.click;
this.click = (event: Event, focusedWindow: BrowserWindow, focusedWebContents: WebContents) => {
this.click = (event: KeyboardEvent, focusedWindow: BrowserWindow, focusedWebContents: WebContents) => {
// Manually flip the checked flags when clicked.
if (!roles.shouldOverrideCheckStatus(this.role) &&
(this.type === 'checkbox' || this.type === 'radio')) {
Expand Down
47 changes: 26 additions & 21 deletions lib/browser/api/web-contents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,8 @@ const addReplyToEvent = (event: Electron.IpcMainEvent) => {
};
};

const addSenderFrameToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => {
const addSenderToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent, sender: Electron.WebContents) => {
event.sender = sender;
const { processId, frameId } = event;
Object.defineProperty(event, 'senderFrame', {
get: () => webFrameMain.fromId(processId, frameId)
Expand All @@ -533,7 +534,7 @@ const addSenderFrameToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainIn

const addReturnValueToEvent = (event: Electron.IpcMainEvent) => {
Object.defineProperty(event, 'returnValue', {
set: (value) => event.sendReply(value),
set: (value) => event._replyChannel.sendReply(value),
get: () => {}
});
};
Expand Down Expand Up @@ -574,7 +575,7 @@ WebContents.prototype._init = function () {

// Dispatch IPC messages to the ipc module.
this.on('-ipc-message' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
addSenderFrameToEvent(event);
addSenderToEvent(event, this);
if (internal) {
ipcMainInternal.emit(channel, event, ...args);
} else {
Expand All @@ -587,25 +588,30 @@ WebContents.prototype._init = function () {
}
});

this.on('-ipc-invoke' as any, function (event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) {
addSenderFrameToEvent(event);
event._reply = (result: any) => event.sendReply({ result });
event._throw = (error: Error) => {
this.on('-ipc-invoke' as any, async function (this: Electron.WebContents, event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
const replyWithResult = (result: any) => event._replyChannel.sendReply({ result });
const replyWithError = (error: Error) => {
console.error(`Error occurred in handler for '${channel}':`, error);
event.sendReply({ error: error.toString() });
event._replyChannel.sendReply({ error: error.toString() });
};
const maybeWebFrame = getWebFrameForEvent(event);
const targets: (ElectronInternal.IpcMainInternal| undefined)[] = internal ? [ipcMainInternal] : [maybeWebFrame?.ipc, ipc, ipcMain];
const target = targets.find(target => target && (target as any)._invokeHandlers.has(channel));
if (target) {
(target as any)._invokeHandlers.get(channel)(event, ...args);
const handler = (target as any)._invokeHandlers.get(channel);
try {
replyWithResult(await Promise.resolve(handler(event, ...args)));
} catch (err) {
replyWithError(err as Error);
}
} else {
event._throw(`No handler registered for '${channel}'`);
replyWithError(new Error(`No handler registered for '${channel}'`));
}
});

this.on('-ipc-message-sync' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
addSenderFrameToEvent(event);
addSenderToEvent(event, this);
addReturnValueToEvent(event);
if (internal) {
ipcMainInternal.emit(channel, event, ...args);
Expand All @@ -622,8 +628,8 @@ WebContents.prototype._init = function () {
}
});

this.on('-ipc-ports' as any, function (event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) {
addSenderFrameToEvent(event);
this.on('-ipc-ports' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) {
addSenderToEvent(event, this);
event.ports = ports.map(p => new MessagePortMain(p));
const maybeWebFrame = getWebFrameForEvent(event);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, message);
Expand Down Expand Up @@ -651,7 +657,7 @@ WebContents.prototype._init = function () {

if (this.getType() !== 'remote') {
// Make new windows requested by links behave like "window.open".
this.on('-new-window' as any, (event: ElectronInternal.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'],
this.on('-new-window' as any, (event: Electron.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'],
rawFeatures: string, referrer: Electron.Referrer, postData: PostData) => {
const postBody = postData ? {
data: postData,
Expand All @@ -677,7 +683,7 @@ WebContents.prototype._init = function () {
const options = result.browserWindowConstructorOptions;
if (!event.defaultPrevented) {
openGuestWindow({
embedder: event.sender,
embedder: this,
disposition,
referrer,
postData,
Expand All @@ -690,7 +696,7 @@ WebContents.prototype._init = function () {

let windowOpenOverriddenOptions: BrowserWindowConstructorOptions | null = null;
let windowOpenOutlivesOpenerOption: boolean = false;
this.on('-will-add-new-contents' as any, (event: ElectronInternal.Event, url: string, frameName: string, rawFeatures: string, disposition: Electron.HandlerDetails['disposition'], referrer: Electron.Referrer, postData: PostData) => {
this.on('-will-add-new-contents' as any, (event: Electron.Event, url: string, frameName: string, rawFeatures: string, disposition: Electron.HandlerDetails['disposition'], referrer: Electron.Referrer, postData: PostData) => {
const postBody = postData ? {
data: postData,
...parseContentTypeFormat(postData)
Expand Down Expand Up @@ -725,7 +731,7 @@ WebContents.prototype._init = function () {
} : undefined;
const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures);
const webPreferences = makeWebPreferences({
embedder: event.sender,
embedder: this,
insecureParsedWebPreferences: parsedWebPreferences,
secureOverrideWebPreferences
});
Expand All @@ -738,7 +744,7 @@ WebContents.prototype._init = function () {
});

// Create a new browser window for "window.open"
this.on('-add-new-contents' as any, (event: ElectronInternal.Event, webContents: Electron.WebContents, disposition: string,
this.on('-add-new-contents' as any, (event: Electron.Event, webContents: Electron.WebContents, disposition: string,
_userGesture: boolean, _left: number, _top: number, _width: number, _height: number, url: string, frameName: string,
referrer: Electron.Referrer, rawFeatures: string, postData: PostData) => {
const overriddenOptions = windowOpenOverriddenOptions || undefined;
Expand All @@ -754,7 +760,7 @@ WebContents.prototype._init = function () {
}

openGuestWindow({
embedder: event.sender,
embedder: this,
guest: webContents,
overrideBrowserWindowOptions: overriddenOptions,
disposition,
Expand Down Expand Up @@ -791,8 +797,7 @@ WebContents.prototype._init = function () {
}
});

const event = process._linkedBinding('electron_browser_event').createEmpty();
app.emit('web-contents-created', event, this);
app.emit('web-contents-created', { sender: this, preventDefault () {}, get defaultPrevented () { return false; } }, this);

// Properties

Expand Down
9 changes: 7 additions & 2 deletions lib/browser/guest-view-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ interface GuestInstance {
}

const webViewManager = process._linkedBinding('electron_browser_web_view_manager');
const eventBinding = process._linkedBinding('electron_browser_event');
const netBinding = process._linkedBinding('electron_browser_net');

const supportedWebViewEvents = Object.keys(webViewEvents);
Expand Down Expand Up @@ -82,7 +81,13 @@ function makeLoadURLOptions (params: Record<string, any>) {
// Create a new guest instance.
const createGuest = function (embedder: Electron.WebContents, embedderFrameId: number, elementInstanceId: number, params: Record<string, any>) {
const webPreferences = makeWebPreferences(embedder, params);
const event = eventBinding.createWithSender(embedder);
const event = {
sender: embedder,
preventDefault () {
this.defaultPrevented = true;
},
defaultPrevented: false
};

const { instanceId } = params;

Expand Down
8 changes: 1 addition & 7 deletions lib/browser/ipc-main-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,7 @@ export class IpcMainImpl extends EventEmitter {
if (typeof fn !== 'function') {
throw new Error(`Expected handler to be a function, but found type '${typeof fn}'`);
}
this._invokeHandlers.set(method, async (e, ...args) => {
try {
e._reply(await Promise.resolve(fn(e, ...args)));
} catch (err) {
e._throw(err as Error);
}
});
this._invokeHandlers.set(method, fn);
}

handleOnce: Electron.IpcMain['handleOnce'] = (method, fn) => {
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
"@azure/storage-blob": "^12.9.0",
"@dsanders11/vscode-markdown-languageservice": "^0.3.0-alpha.4",
"@electron/asar": "^3.2.1",
"@electron/docs-parser": "^1.0.0",
"@electron/docs-parser": "^1.1.0",
"@electron/fiddle-core": "^1.0.4",
"@electron/github-app-auth": "^1.5.0",
"@electron/typescript-definitions": "^8.10.0",
"@electron/typescript-definitions": "^8.14.0",
"@octokit/rest": "^19.0.7",
"@primer/octicons": "^10.0.0",
"@types/basic-auth": "^1.1.3",
Expand Down
28 changes: 0 additions & 28 deletions shell/browser/api/electron_api_event.cc

This file was deleted.

3 changes: 1 addition & 2 deletions shell/browser/api/electron_api_session.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1178,8 +1178,7 @@ gin::Handle<Session> Session::CreateFrom(
// to use partition strings, instead of using the Session object directly.
handle->Pin(isolate);

App::Get()->EmitCustomEvent("session-created",
handle.ToV8().As<v8::Object>());
App::Get()->EmitWithoutEvent("session-created", handle);

return handle;
}
Expand Down
Loading

0 comments on commit 71944f2

Please sign in to comment.