sha
stringlengths 40
40
| author
stringclasses 155
values | date
stringlengths 19
19
| commit_message
stringlengths 24
9.22k
| git_diff
stringlengths 110
332k
⌀ | type
stringclasses 9
values |
|---|---|---|---|---|---|
87f2a1d572a78c41da293eeb467966f76da7ba9d
|
Shelley Vohr
|
2023-02-28 23:26:37
|
fix: `BroadcastChannel` initialization location (#37421)
* fix: BroadcastChannel initialization location
* chore: update patches
---------
Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com>
|
diff --git a/patches/node/.patches b/patches/node/.patches
index f7a1dadefe..52928aa248 100644
--- a/patches/node/.patches
+++ b/patches/node/.patches
@@ -35,3 +35,4 @@ enable_crashpad_linux_node_processes.patch
allow_embedder_to_control_codegenerationfromstringscallback.patch
src_allow_optional_isolation_termination_in_node.patch
test_mark_cpu_prof_tests_as_flaky_in_electron.patch
+lib_fix_broadcastchannel_initialization_location.patch
diff --git a/patches/node/lib_fix_broadcastchannel_initialization_location.patch b/patches/node/lib_fix_broadcastchannel_initialization_location.patch
new file mode 100644
index 0000000000..a95e7c9d30
--- /dev/null
+++ b/patches/node/lib_fix_broadcastchannel_initialization_location.patch
@@ -0,0 +1,44 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Shelley Vohr <[email protected]>
+Date: Mon, 27 Feb 2023 12:56:15 +0100
+Subject: lib: fix BroadcastChannel initialization location
+
+Refs https://github.com/nodejs/node/pull/40532.
+
+Fixes a bug in the above, wherein BroadcastChannel should have been
+initialized in bootstrap/browser instead of bootstrap/node. That
+inadvertently made it such that there was incorrect handling of the
+DOM vs Node.js implementations of BroadcastChannel.
+
+This will be upstreamed.
+
+diff --git a/lib/internal/bootstrap/browser.js b/lib/internal/bootstrap/browser.js
+index d0c01ca2a512be549b0fea8a829c05eabbec799a..210a1bb7e929021725b04786bc11d9b3ce09ad04 100644
+--- a/lib/internal/bootstrap/browser.js
++++ b/lib/internal/bootstrap/browser.js
+@@ -12,6 +12,10 @@ const {
+ } = require('internal/util');
+ const config = internalBinding('config');
+
++// Non-standard extensions:
++const { BroadcastChannel } = require('internal/worker/io');
++exposeInterface(globalThis, 'BroadcastChannel', BroadcastChannel);
++
+ // https://console.spec.whatwg.org/#console-namespace
+ exposeNamespace(globalThis, 'console',
+ createGlobalConsole());
+diff --git a/lib/internal/bootstrap/node.js b/lib/internal/bootstrap/node.js
+index 7dd89d5f134b09da2678dd54fa9139466fea179c..f235545b6433c0f1dd335e0bb97cd3dc77616c0f 100644
+--- a/lib/internal/bootstrap/node.js
++++ b/lib/internal/bootstrap/node.js
+@@ -237,10 +237,6 @@ const {
+ queueMicrotask
+ } = require('internal/process/task_queues');
+
+-// Non-standard extensions:
+-const { BroadcastChannel } = require('internal/worker/io');
+-exposeInterface(globalThis, 'BroadcastChannel', BroadcastChannel);
+-
+ defineOperation(globalThis, 'queueMicrotask', queueMicrotask);
+
+ const timers = require('timers');
|
fix
|
abec9ead0645db89e17d81e17b9de50f01f9edc0
|
Milan Burda
|
2023-06-22 16:21:42
|
refactor: use node scheme imports in scripts (#38846)
* refactor: use node scheme imports in script
* refactor: use node scheme imports in build
|
diff --git a/build/.eslintrc.json b/build/.eslintrc.json
new file mode 100644
index 0000000000..dc7dde78dc
--- /dev/null
+++ b/build/.eslintrc.json
@@ -0,0 +1,8 @@
+{
+ "plugins": [
+ "unicorn"
+ ],
+ "rules": {
+ "unicorn/prefer-node-protocol": "error"
+ }
+}
diff --git a/build/webpack/webpack.config.base.js b/build/webpack/webpack.config.base.js
index 7afe880258..bd4ca38e02 100644
--- a/build/webpack/webpack.config.base.js
+++ b/build/webpack/webpack.config.base.js
@@ -1,5 +1,5 @@
-const fs = require('fs');
-const path = require('path');
+const fs = require('node:fs');
+const path = require('node:path');
const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
const WrapperPlugin = require('wrapper-webpack-plugin');
diff --git a/script/.eslintrc.json b/script/.eslintrc.json
new file mode 100644
index 0000000000..dc7dde78dc
--- /dev/null
+++ b/script/.eslintrc.json
@@ -0,0 +1,8 @@
+{
+ "plugins": [
+ "unicorn"
+ ],
+ "rules": {
+ "unicorn/prefer-node-protocol": "error"
+ }
+}
diff --git a/script/check-patch-diff.ts b/script/check-patch-diff.ts
index 8b2bccc26d..b48a5bf914 100644
--- a/script/check-patch-diff.ts
+++ b/script/check-patch-diff.ts
@@ -1,5 +1,5 @@
-import { spawnSync } from 'child_process';
-import * as path from 'path';
+import { spawnSync } from 'node:child_process';
+import * as path from 'node:path';
const srcPath = path.resolve(__dirname, '..', '..', '..');
const patchExportFnPath = path.resolve(__dirname, 'export_all_patches.py');
diff --git a/script/check-symlinks.js b/script/check-symlinks.js
index c68e2ac27e..19c9626025 100644
--- a/script/check-symlinks.js
+++ b/script/check-symlinks.js
@@ -1,5 +1,5 @@
-const fs = require('fs');
-const path = require('path');
+const fs = require('node:fs');
+const path = require('node:path');
const utils = require('./lib/utils');
const branding = require('../shell/app/BRANDING.json');
diff --git a/script/codesign/gen-trust.ts b/script/codesign/gen-trust.ts
index 3f39f0e74b..941db3c865 100644
--- a/script/codesign/gen-trust.ts
+++ b/script/codesign/gen-trust.ts
@@ -1,6 +1,6 @@
-import * as cp from 'child_process';
-import * as fs from 'fs';
-import * as path from 'path';
+import * as cp from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
const certificatePath = process.argv[2];
const outPath = process.argv[3];
diff --git a/script/create-api-json.js b/script/create-api-json.js
index 00a70355c3..4f3b5ecfc2 100644
--- a/script/create-api-json.js
+++ b/script/create-api-json.js
@@ -1,6 +1,6 @@
const { parseDocs } = require('@electron/docs-parser');
-const fs = require('fs');
-const path = require('path');
+const fs = require('node:fs');
+const path = require('node:path');
const { getElectronVersion } = require('./lib/get-version');
diff --git a/script/download-circleci-artifacts.js b/script/download-circleci-artifacts.js
index 118dd4a447..c0593fa01a 100644
--- a/script/download-circleci-artifacts.js
+++ b/script/download-circleci-artifacts.js
@@ -1,8 +1,8 @@
const args = require('minimist')(process.argv.slice(2));
-const fs = require('fs');
+const fs = require('node:fs');
const got = require('got');
-const stream = require('stream');
-const { promisify } = require('util');
+const stream = require('node:stream');
+const { promisify } = require('node:util');
const pipeline = promisify(stream.pipeline);
diff --git a/script/gen-filenames.ts b/script/gen-filenames.ts
index 3e1f41bcc8..b281ea78ef 100644
--- a/script/gen-filenames.ts
+++ b/script/gen-filenames.ts
@@ -1,7 +1,7 @@
-import * as cp from 'child_process';
+import * as cp from 'node:child_process';
import * as fs from 'fs-extra';
-import * as os from 'os';
-import * as path from 'path';
+import * as os from 'node:os';
+import * as path from 'node:path';
const rootPath = path.resolve(__dirname, '..');
const gniPath = path.resolve(__dirname, '../filenames.auto.gni');
diff --git a/script/gen-hunspell-filenames.js b/script/gen-hunspell-filenames.js
index 4e9b9d2a01..336cefec8c 100644
--- a/script/gen-hunspell-filenames.js
+++ b/script/gen-hunspell-filenames.js
@@ -1,5 +1,5 @@
-const fs = require('fs');
-const path = require('path');
+const fs = require('node:fs');
+const path = require('node:path');
const check = process.argv.includes('--check');
diff --git a/script/gen-libc++-filenames.js b/script/gen-libc++-filenames.js
index 0d083c4ea2..c6fbe3347a 100644
--- a/script/gen-libc++-filenames.js
+++ b/script/gen-libc++-filenames.js
@@ -1,5 +1,5 @@
-const fs = require('fs');
-const path = require('path');
+const fs = require('node:fs');
+const path = require('node:path');
const check = process.argv.includes('--check');
diff --git a/script/generate-deps-hash.js b/script/generate-deps-hash.js
index ca22e23ad6..9161da0d6e 100644
--- a/script/generate-deps-hash.js
+++ b/script/generate-deps-hash.js
@@ -1,6 +1,6 @@
-const crypto = require('crypto');
-const fs = require('fs');
-const path = require('path');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
// Fallback to blow away old cache keys
const FALLBACK_HASH_VERSION = 3;
diff --git a/script/generate-version-json.js b/script/generate-version-json.js
index 8a981f8173..76dd8c8049 100644
--- a/script/generate-version-json.js
+++ b/script/generate-version-json.js
@@ -1,5 +1,5 @@
-const fs = require('fs');
-const path = require('path');
+const fs = require('node:fs');
+const path = require('node:path');
const semver = require('semver');
const outputPath = process.argv[2];
diff --git a/script/gn-asar-hash.js b/script/gn-asar-hash.js
index 8aa78c9a3d..ad341cb2cd 100644
--- a/script/gn-asar-hash.js
+++ b/script/gn-asar-hash.js
@@ -1,6 +1,6 @@
const asar = require('@electron/asar');
-const crypto = require('crypto');
-const fs = require('fs');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
const archive = process.argv[2];
const hashFile = process.argv[3];
diff --git a/script/gn-asar.js b/script/gn-asar.js
index 57ef6a8110..f7dd9db2db 100644
--- a/script/gn-asar.js
+++ b/script/gn-asar.js
@@ -1,8 +1,8 @@
const asar = require('@electron/asar');
-const assert = require('assert');
+const assert = require('node:assert');
const fs = require('fs-extra');
-const os = require('os');
-const path = require('path');
+const os = require('node:os');
+const path = require('node:path');
const getArgGroup = (name) => {
const group = [];
diff --git a/script/gn-check.js b/script/gn-check.js
index 12dca3651e..54ba2b5b7d 100644
--- a/script/gn-check.js
+++ b/script/gn-check.js
@@ -4,8 +4,8 @@ Usage:
$ node ./script/gn-check.js [--outDir=dirName]
*/
-const cp = require('child_process');
-const path = require('path');
+const cp = require('node:child_process');
+const path = require('node:path');
const args = require('minimist')(process.argv.slice(2), { string: ['outDir'] });
const { getOutDir } = require('./lib/utils');
diff --git a/script/gn-plist-but-with-hashes.js b/script/gn-plist-but-with-hashes.js
index 16ee734ef9..4eec9581f9 100644
--- a/script/gn-plist-but-with-hashes.js
+++ b/script/gn-plist-but-with-hashes.js
@@ -1,4 +1,4 @@
-const fs = require('fs');
+const fs = require('node:fs');
const [,, plistPath, outputPath, ...keySet] = process.argv;
diff --git a/script/lib/azput.js b/script/lib/azput.js
index 6abd0220db..2c0dab15d4 100644
--- a/script/lib/azput.js
+++ b/script/lib/azput.js
@@ -1,7 +1,7 @@
/* eslint-disable camelcase */
const { BlobServiceClient } = require('@azure/storage-blob');
-const fs = require('fs');
-const path = require('path');
+const fs = require('node:fs');
+const path = require('node:path');
const blobServiceClient = BlobServiceClient.fromConnectionString(process.env.ELECTRON_ARTIFACTS_BLOB_STORAGE);
diff --git a/script/lib/get-version.js b/script/lib/get-version.js
index 45a120482b..3e1cc62acc 100644
--- a/script/lib/get-version.js
+++ b/script/lib/get-version.js
@@ -1,5 +1,5 @@
-const { spawnSync } = require('child_process');
-const path = require('path');
+const { spawnSync } = require('node:child_process');
+const path = require('node:path');
module.exports.getElectronVersion = () => {
// Find the nearest tag to the current HEAD
diff --git a/script/lib/utils.js b/script/lib/utils.js
index 03ac37b649..7e1db46881 100644
--- a/script/lib/utils.js
+++ b/script/lib/utils.js
@@ -1,8 +1,8 @@
const { GitProcess } = require('dugite');
-const fs = require('fs');
+const fs = require('node:fs');
const klaw = require('klaw');
-const os = require('os');
-const path = require('path');
+const os = require('node:os');
+const path = require('node:path');
const ELECTRON_DIR = path.resolve(__dirname, '..', '..');
const SRC_DIR = path.resolve(ELECTRON_DIR, '..');
diff --git a/script/lint.js b/script/lint.js
index 7b6405a4bd..e3508bbb74 100755
--- a/script/lint.js
+++ b/script/lint.js
@@ -1,12 +1,12 @@
#!/usr/bin/env node
-const crypto = require('crypto');
+const crypto = require('node:crypto');
const { GitProcess } = require('dugite');
-const childProcess = require('child_process');
+const childProcess = require('node:child_process');
const { ESLint } = require('eslint');
-const fs = require('fs');
+const fs = require('node:fs');
const minimist = require('minimist');
-const path = require('path');
+const path = require('node:path');
const { chunkFilenames, findMatchingFiles } = require('./lib/utils');
diff --git a/script/nan-spec-runner.js b/script/nan-spec-runner.js
index 85aebb15f6..2889f3290b 100644
--- a/script/nan-spec-runner.js
+++ b/script/nan-spec-runner.js
@@ -1,6 +1,6 @@
-const cp = require('child_process');
-const fs = require('fs');
-const path = require('path');
+const cp = require('node:child_process');
+const fs = require('node:fs');
+const path = require('node:path');
const BASE = path.resolve(__dirname, '../..');
const NAN_DIR = path.resolve(BASE, 'third_party', 'nan');
diff --git a/script/node-spec-runner.js b/script/node-spec-runner.js
index f365886b0a..3d904e9a66 100644
--- a/script/node-spec-runner.js
+++ b/script/node-spec-runner.js
@@ -1,6 +1,6 @@
-const cp = require('child_process');
-const fs = require('fs');
-const path = require('path');
+const cp = require('node:child_process');
+const fs = require('node:fs');
+const path = require('node:path');
const args = require('minimist')(process.argv.slice(2), {
boolean: ['default', 'validateDisabled'],
diff --git a/script/prepare-appveyor.js b/script/prepare-appveyor.js
index 0e15e4eaec..a08ce66e3f 100644
--- a/script/prepare-appveyor.js
+++ b/script/prepare-appveyor.js
@@ -1,9 +1,9 @@
if (!process.env.CI) require('dotenv-safe').load();
-const assert = require('assert');
-const fs = require('fs');
+const assert = require('node:assert');
+const fs = require('node:fs');
const got = require('got');
-const path = require('path');
+const path = require('node:path');
const { handleGitCall, ELECTRON_DIR } = require('./lib/utils.js');
const { Octokit } = require('@octokit/rest');
const octokit = new Octokit();
diff --git a/script/push-patch.js b/script/push-patch.js
index 8f7bc86326..78595bc6e6 100644
--- a/script/push-patch.js
+++ b/script/push-patch.js
@@ -1,5 +1,5 @@
const { appCredentialsFromString, getTokenForRepo } = require('@electron/github-app-auth');
-const cp = require('child_process');
+const cp = require('node:child_process');
if (!process.env.CIRCLE_BRANCH) {
console.error('Not building for a specific branch, can\'t autopush a patch');
diff --git a/script/release/ci-release-build.js b/script/release/ci-release-build.js
index e79dfc9627..8d455c1a5e 100644
--- a/script/release/ci-release-build.js
+++ b/script/release/ci-release-build.js
@@ -1,6 +1,6 @@
if (!process.env.CI) require('dotenv-safe').load();
-const assert = require('assert');
+const assert = require('node:assert');
const got = require('got');
const { Octokit } = require('@octokit/rest');
diff --git a/script/release/get-url-hash.js b/script/release/get-url-hash.js
index ae91fac30e..a4c0966559 100644
--- a/script/release/get-url-hash.js
+++ b/script/release/get-url-hash.js
@@ -1,5 +1,5 @@
const got = require('got');
-const url = require('url');
+const url = require('node:url');
module.exports = async function getUrlHash (targetUrl, algorithm = 'sha256', attempts = 3) {
const options = {
diff --git a/script/release/notes/index.js b/script/release/notes/index.js
index 567135faf8..6dc5454a8f 100755
--- a/script/release/notes/index.js
+++ b/script/release/notes/index.js
@@ -2,7 +2,7 @@
const { GitProcess } = require('dugite');
const minimist = require('minimist');
-const path = require('path');
+const path = require('node:path');
const semver = require('semver');
const { ELECTRON_DIR } = require('../../lib/utils');
diff --git a/script/release/notes/notes.js b/script/release/notes/notes.js
index 7bc3d525d7..1aee04b7ec 100644
--- a/script/release/notes/notes.js
+++ b/script/release/notes/notes.js
@@ -2,8 +2,8 @@
'use strict';
-const fs = require('fs');
-const path = require('path');
+const fs = require('node:fs');
+const path = require('node:path');
const { GitProcess } = require('dugite');
diff --git a/script/release/prepare-release.js b/script/release/prepare-release.js
index be9c430849..e38f93746e 100755
--- a/script/release/prepare-release.js
+++ b/script/release/prepare-release.js
@@ -6,11 +6,11 @@ const args = require('minimist')(process.argv.slice(2), {
});
const ciReleaseBuild = require('./ci-release-build');
const { Octokit } = require('@octokit/rest');
-const { execSync } = require('child_process');
+const { execSync } = require('node:child_process');
const { GitProcess } = require('dugite');
-const path = require('path');
-const readline = require('readline');
+const path = require('node:path');
+const readline = require('node:readline');
const releaseNotesGenerator = require('./notes/index.js');
const { getCurrentBranch, ELECTRON_DIR } = require('../lib/utils.js');
const bumpType = args._[0];
diff --git a/script/release/publish-to-npm.js b/script/release/publish-to-npm.js
index dbf15a9f03..e74cc280c9 100644
--- a/script/release/publish-to-npm.js
+++ b/script/release/publish-to-npm.js
@@ -1,7 +1,7 @@
const temp = require('temp');
-const fs = require('fs');
-const path = require('path');
-const childProcess = require('child_process');
+const fs = require('node:fs');
+const path = require('node:path');
+const childProcess = require('node:child_process');
const got = require('got');
const semver = require('semver');
diff --git a/script/release/release-artifact-cleanup.js b/script/release/release-artifact-cleanup.js
index 0079696c3a..3565125408 100755
--- a/script/release/release-artifact-cleanup.js
+++ b/script/release/release-artifact-cleanup.js
@@ -5,7 +5,7 @@ const args = require('minimist')(process.argv.slice(2), {
string: ['tag', 'releaseID'],
default: { releaseID: '' }
});
-const { execSync } = require('child_process');
+const { execSync } = require('node:child_process');
const { GitProcess } = require('dugite');
const { getCurrentBranch, ELECTRON_DIR } = require('../lib/utils.js');
const { Octokit } = require('@octokit/rest');
diff --git a/script/release/release.js b/script/release/release.js
index b12da0f029..e25cc60286 100755
--- a/script/release/release.js
+++ b/script/release/release.js
@@ -9,13 +9,13 @@ const args = require('minimist')(process.argv.slice(2), {
],
default: { verboseNugget: false }
});
-const fs = require('fs');
-const { execSync } = require('child_process');
+const fs = require('node:fs');
+const { execSync } = require('node:child_process');
const got = require('got');
-const path = require('path');
+const path = require('node:path');
const semver = require('semver');
const temp = require('temp').track();
-const { URL } = require('url');
+const { URL } = require('node:url');
const { BlobServiceClient } = require('@azure/storage-blob');
const { Octokit } = require('@octokit/rest');
diff --git a/script/release/uploaders/upload-to-github.ts b/script/release/uploaders/upload-to-github.ts
index c998e2f42e..218e369fee 100644
--- a/script/release/uploaders/upload-to-github.ts
+++ b/script/release/uploaders/upload-to-github.ts
@@ -1,5 +1,5 @@
import { Octokit } from '@octokit/rest';
-import * as fs from 'fs';
+import * as fs from 'node:fs';
const octokit = new Octokit({
auth: process.env.ELECTRON_GITHUB_TOKEN
diff --git a/script/release/version-utils.js b/script/release/version-utils.js
index 85e8f8f15a..d50fdedaa0 100644
--- a/script/release/version-utils.js
+++ b/script/release/version-utils.js
@@ -1,8 +1,8 @@
-const path = require('path');
-const fs = require('fs');
+const path = require('node:path');
+const fs = require('node:fs');
const semver = require('semver');
const { GitProcess } = require('dugite');
-const { promisify } = require('util');
+const { promisify } = require('node:util');
const { ELECTRON_DIR } = require('../lib/utils');
diff --git a/script/run-clang-tidy.ts b/script/run-clang-tidy.ts
index ab1aa5eba5..6a5ba9c2c7 100644
--- a/script/run-clang-tidy.ts
+++ b/script/run-clang-tidy.ts
@@ -1,8 +1,8 @@
-import * as childProcess from 'child_process';
-import * as fs from 'fs';
+import * as childProcess from 'node:child_process';
+import * as fs from 'node:fs';
import * as minimist from 'minimist';
-import * as os from 'os';
-import * as path from 'path';
+import * as os from 'node:os';
+import * as path from 'node:path';
import * as streamChain from 'stream-chain';
import * as streamJson from 'stream-json';
import { ignore as streamJsonIgnore } from 'stream-json/filters/Ignore';
diff --git a/script/run-if-exists.js b/script/run-if-exists.js
index 93e2252fc9..9ffe732bc6 100644
--- a/script/run-if-exists.js
+++ b/script/run-if-exists.js
@@ -1,5 +1,5 @@
-const cp = require('child_process');
-const fs = require('fs');
+const cp = require('node:child_process');
+const fs = require('node:fs');
const checkPath = process.argv[2];
const command = process.argv.slice(3);
diff --git a/script/spec-runner.js b/script/spec-runner.js
index 1b828713f0..f8a32423b7 100755
--- a/script/spec-runner.js
+++ b/script/spec-runner.js
@@ -1,12 +1,12 @@
#!/usr/bin/env node
const { ElectronVersions, Installer } = require('@electron/fiddle-core');
-const childProcess = require('child_process');
-const crypto = require('crypto');
+const childProcess = require('node:child_process');
+const crypto = require('node:crypto');
const fs = require('fs-extra');
const { hashElement } = require('folder-hash');
-const os = require('os');
-const path = require('path');
+const os = require('node:os');
+const path = require('node:path');
const unknownFlags = [];
require('colors');
diff --git a/script/start.js b/script/start.js
index 94ecfeac87..6c081a0ccd 100644
--- a/script/start.js
+++ b/script/start.js
@@ -1,4 +1,4 @@
-const cp = require('child_process');
+const cp = require('node:child_process');
const utils = require('./lib/utils');
const electronPath = utils.getAbsoluteElectronExec();
diff --git a/script/yarn.js b/script/yarn.js
index 353a183244..3638802ccd 100644
--- a/script/yarn.js
+++ b/script/yarn.js
@@ -1,6 +1,6 @@
-const cp = require('child_process');
-const fs = require('fs');
-const path = require('path');
+const cp = require('node:child_process');
+const fs = require('node:fs');
+const path = require('node:path');
const YARN_VERSION = /'yarn_version': '(.+?)'/.exec(fs.readFileSync(path.resolve(__dirname, '../DEPS'), 'utf8'))[1];
const NPX_CMD = process.platform === 'win32' ? 'npx.cmd' : 'npx';
|
refactor
|
93a6f3e60739a58dedb5b50563e0cb8e7ed46e29
|
Charles Kerr
|
2024-08-20 14:34:59
|
refactor: NodeBindings::Create() returns a unique_ptr (#43361)
* refactor: NodeBindings::Create() returns a unique_ptr
* empty commit
|
diff --git a/shell/common/node_bindings.h b/shell/common/node_bindings.h
index bb25287dd3..ad55645422 100644
--- a/shell/common/node_bindings.h
+++ b/shell/common/node_bindings.h
@@ -84,7 +84,7 @@ class NodeBindings {
public:
enum class BrowserEnvironment { kBrowser, kRenderer, kUtility, kWorker };
- static NodeBindings* Create(BrowserEnvironment browser_env);
+ static std::unique_ptr<NodeBindings> Create(BrowserEnvironment browser_env);
static void RegisterBuiltinBindings();
static bool IsInitialized();
diff --git a/shell/common/node_bindings_linux.cc b/shell/common/node_bindings_linux.cc
index ad598105c9..7af0b151e6 100644
--- a/shell/common/node_bindings_linux.cc
+++ b/shell/common/node_bindings_linux.cc
@@ -33,8 +33,8 @@ void NodeBindingsLinux::PollEvents() {
}
// static
-NodeBindings* NodeBindings::Create(BrowserEnvironment browser_env) {
- return new NodeBindingsLinux(browser_env);
+std::unique_ptr<NodeBindings> NodeBindings::Create(BrowserEnvironment env) {
+ return std::make_unique<NodeBindingsLinux>(env);
}
} // namespace electron
diff --git a/shell/common/node_bindings_mac.cc b/shell/common/node_bindings_mac.cc
index e50afcdf6a..b6a92c54a0 100644
--- a/shell/common/node_bindings_mac.cc
+++ b/shell/common/node_bindings_mac.cc
@@ -41,8 +41,8 @@ void NodeBindingsMac::PollEvents() {
}
// static
-NodeBindings* NodeBindings::Create(BrowserEnvironment browser_env) {
- return new NodeBindingsMac(browser_env);
+std::unique_ptr<NodeBindings> NodeBindings::Create(BrowserEnvironment env) {
+ return std::make_unique<NodeBindingsMac>(env);
}
} // namespace electron
diff --git a/shell/common/node_bindings_win.cc b/shell/common/node_bindings_win.cc
index e6efce987d..6c2aeffb27 100644
--- a/shell/common/node_bindings_win.cc
+++ b/shell/common/node_bindings_win.cc
@@ -50,8 +50,8 @@ void NodeBindingsWin::PollEvents() {
}
// static
-NodeBindings* NodeBindings::Create(BrowserEnvironment browser_env) {
- return new NodeBindingsWin(browser_env);
+std::unique_ptr<NodeBindings> NodeBindings::Create(BrowserEnvironment env) {
+ return std::make_unique<NodeBindingsWin>(env);
}
} // namespace electron
|
refactor
|
f2b32af1f6d13f3bcd4d0ff32584720c8a575064
|
Charles Kerr
|
2023-07-19 09:54:30
|
perf: small perf changes in HidChooserController (#39057)
* perf: avoid string temporary in HidChooserController::PhysicalDeviceIdFromDeviceInfo()
return a const ref instead of a new string
* perf: avoid second map lookup in HidChooserController::AddDeviceInfo()
|
diff --git a/shell/browser/hid/hid_chooser_controller.cc b/shell/browser/hid/hid_chooser_controller.cc
index 6dd372ad1c..28c15f86dc 100644
--- a/shell/browser/hid/hid_chooser_controller.cc
+++ b/shell/browser/hid/hid_chooser_controller.cc
@@ -106,7 +106,7 @@ HidChooserController::~HidChooserController() {
}
// static
-std::string HidChooserController::PhysicalDeviceIdFromDeviceInfo(
+const std::string& HidChooserController::PhysicalDeviceIdFromDeviceInfo(
const device::mojom::HidDeviceInfo& device) {
// A single physical device may expose multiple HID interfaces, each
// represented by a HidDeviceInfo object. When a device exposes multiple
@@ -148,11 +148,10 @@ void HidChooserController::OnDeviceAdded(
void HidChooserController::OnDeviceRemoved(
const device::mojom::HidDeviceInfo& device) {
- auto id = PhysicalDeviceIdFromDeviceInfo(device);
- if (!base::Contains(items_, id))
+ if (!base::Contains(items_, PhysicalDeviceIdFromDeviceInfo(device)))
return;
- api::Session* session = GetSession();
- if (session) {
+
+ if (api::Session* session = GetSession(); session != nullptr) {
auto* rfh = content::RenderFrameHost::FromID(render_frame_host_id_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
@@ -306,21 +305,20 @@ bool HidChooserController::IsExcluded(
bool HidChooserController::AddDeviceInfo(
const device::mojom::HidDeviceInfo& device) {
- auto id = PhysicalDeviceIdFromDeviceInfo(device);
- auto find_it = device_map_.find(id);
- if (find_it != device_map_.end()) {
- find_it->second.push_back(device.Clone());
- return false;
- }
- // A new device was connected. Append it to the end of the chooser list.
- device_map_[id].push_back(device.Clone());
- items_.push_back(id);
- return true;
+ const auto& id = PhysicalDeviceIdFromDeviceInfo(device);
+ auto [iter, is_new_physical_device] = device_map_.try_emplace(id);
+ iter->second.emplace_back(device.Clone());
+
+ // append new devices to the chooser list
+ if (is_new_physical_device)
+ items_.emplace_back(id);
+
+ return is_new_physical_device;
}
bool HidChooserController::RemoveDeviceInfo(
const device::mojom::HidDeviceInfo& device) {
- auto id = PhysicalDeviceIdFromDeviceInfo(device);
+ const auto& id = PhysicalDeviceIdFromDeviceInfo(device);
auto find_it = device_map_.find(id);
DCHECK(find_it != device_map_.end());
auto& device_infos = find_it->second;
@@ -338,7 +336,7 @@ bool HidChooserController::RemoveDeviceInfo(
void HidChooserController::UpdateDeviceInfo(
const device::mojom::HidDeviceInfo& device) {
- auto id = PhysicalDeviceIdFromDeviceInfo(device);
+ const auto& id = PhysicalDeviceIdFromDeviceInfo(device);
auto physical_device_it = device_map_.find(id);
DCHECK(physical_device_it != device_map_.end());
auto& device_infos = physical_device_it->second;
diff --git a/shell/browser/hid/hid_chooser_controller.h b/shell/browser/hid/hid_chooser_controller.h
index f437437162..39756b7621 100644
--- a/shell/browser/hid/hid_chooser_controller.h
+++ b/shell/browser/hid/hid_chooser_controller.h
@@ -54,7 +54,7 @@ class HidChooserController
~HidChooserController() override;
// static
- static std::string PhysicalDeviceIdFromDeviceInfo(
+ static const std::string& PhysicalDeviceIdFromDeviceInfo(
const device::mojom::HidDeviceInfo& device);
// HidChooserContext::DeviceObserver:
|
perf
|
97132ece33bd32660a5f26612a14232875f4fbdf
|
Charles Kerr
|
2023-06-19 03:33:09
|
refactor: use constexpr lookup tables in gin helper (#38818)
* feat: add gin_helper::FromV8WithLookup()
feat: add gin_helper::FromV8WithLowerLookup()
* refactor: use constexpr lookup table in gin Converters
|
diff --git a/shell/browser/api/electron_api_app.cc b/shell/browser/api/electron_api_app.cc
index 818d5bace4..14018f86fe 100644
--- a/shell/browser/api/electron_api_app.cc
+++ b/shell/browser/api/electron_api_app.cc
@@ -141,40 +141,25 @@ struct Converter<JumpListItem::Type> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
JumpListItem::Type* out) {
- std::string item_type;
- if (!ConvertFromV8(isolate, val, &item_type))
- return false;
-
- if (item_type == "task")
- *out = JumpListItem::Type::kTask;
- else if (item_type == "separator")
- *out = JumpListItem::Type::kSeparator;
- else if (item_type == "file")
- *out = JumpListItem::Type::kFile;
- else
- return false;
-
- return true;
+ return FromV8WithLookup(isolate, val, Lookup, out);
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
JumpListItem::Type val) {
- std::string item_type;
- switch (val) {
- case JumpListItem::Type::kTask:
- item_type = "task";
- break;
-
- case JumpListItem::Type::kSeparator:
- item_type = "separator";
- break;
+ for (const auto& [name, item_val] : Lookup)
+ if (item_val == val)
+ return gin::ConvertToV8(isolate, name);
- case JumpListItem::Type::kFile:
- item_type = "file";
- break;
- }
- return gin::ConvertToV8(isolate, item_type);
+ return gin::ConvertToV8(isolate, "");
}
+
+ private:
+ static constexpr auto Lookup =
+ base::MakeFixedFlatMapSorted<base::StringPiece, JumpListItem::Type>({
+ {"file", JumpListItem::Type::kFile},
+ {"separator", JumpListItem::Type::kSeparator},
+ {"task", JumpListItem::Type::kTask},
+ });
};
template <>
@@ -247,46 +232,26 @@ struct Converter<JumpListCategory::Type> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
JumpListCategory::Type* out) {
- std::string category_type;
- if (!ConvertFromV8(isolate, val, &category_type))
- return false;
-
- if (category_type == "tasks")
- *out = JumpListCategory::Type::kTasks;
- else if (category_type == "frequent")
- *out = JumpListCategory::Type::kFrequent;
- else if (category_type == "recent")
- *out = JumpListCategory::Type::kRecent;
- else if (category_type == "custom")
- *out = JumpListCategory::Type::kCustom;
- else
- return false;
-
- return true;
+ return FromV8WithLookup(isolate, val, Lookup, out);
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
JumpListCategory::Type val) {
- std::string category_type;
- switch (val) {
- case JumpListCategory::Type::kTasks:
- category_type = "tasks";
- break;
+ for (const auto& [name, type_val] : Lookup)
+ if (type_val == val)
+ return gin::ConvertToV8(isolate, name);
- case JumpListCategory::Type::kFrequent:
- category_type = "frequent";
- break;
-
- case JumpListCategory::Type::kRecent:
- category_type = "recent";
- break;
-
- case JumpListCategory::Type::kCustom:
- category_type = "custom";
- break;
- }
- return gin::ConvertToV8(isolate, category_type);
+ return gin::ConvertToV8(isolate, "");
}
+
+ private:
+ static constexpr auto Lookup =
+ base::MakeFixedFlatMapSorted<base::StringPiece, JumpListCategory::Type>({
+ {"custom", JumpListCategory::Type::kCustom},
+ {"frequent", JumpListCategory::Type::kFrequent},
+ {"recent", JumpListCategory::Type::kRecent},
+ {"tasks", JumpListCategory::Type::kTasks},
+ });
};
template <>
@@ -440,20 +405,13 @@ struct Converter<net::SecureDnsMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
net::SecureDnsMode* out) {
- std::string s;
- if (!ConvertFromV8(isolate, val, &s))
- return false;
- if (s == "off") {
- *out = net::SecureDnsMode::kOff;
- return true;
- } else if (s == "automatic") {
- *out = net::SecureDnsMode::kAutomatic;
- return true;
- } else if (s == "secure") {
- *out = net::SecureDnsMode::kSecure;
- return true;
- }
- return false;
+ static constexpr auto Lookup =
+ base::MakeFixedFlatMapSorted<base::StringPiece, net::SecureDnsMode>({
+ {"automatic", net::SecureDnsMode::kAutomatic},
+ {"off", net::SecureDnsMode::kOff},
+ {"secure", net::SecureDnsMode::kSecure},
+ });
+ return FromV8WithLookup(isolate, val, Lookup, out);
}
};
} // namespace gin
diff --git a/shell/browser/api/electron_api_url_loader.cc b/shell/browser/api/electron_api_url_loader.cc
index d5885c9797..0944a4dfd5 100644
--- a/shell/browser/api/electron_api_url_loader.cc
+++ b/shell/browser/api/electron_api_url_loader.cc
@@ -62,20 +62,16 @@ struct Converter<network::mojom::CredentialsMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
network::mojom::CredentialsMode* out) {
- std::string mode;
- if (!ConvertFromV8(isolate, val, &mode))
- return false;
- if (mode == "omit")
- *out = network::mojom::CredentialsMode::kOmit;
- else if (mode == "include")
- *out = network::mojom::CredentialsMode::kInclude;
- else if (mode == "same-origin")
- // Note: This only makes sense if the request specifies the "origin"
- // option.
- *out = network::mojom::CredentialsMode::kSameOrigin;
- else
- return false;
- return true;
+ using Val = network::mojom::CredentialsMode;
+ static constexpr auto Lookup =
+ base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
+ {"include", Val::kInclude},
+ {"omit", Val::kOmit},
+ // Note: This only makes sense if the request
+ // specifies the "origin" option.
+ {"same-origin", Val::kSameOrigin},
+ });
+ return FromV8WithLookup(isolate, val, Lookup, out);
}
};
@@ -84,25 +80,17 @@ struct Converter<blink::mojom::FetchCacheMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
blink::mojom::FetchCacheMode* out) {
- std::string cache;
- if (!ConvertFromV8(isolate, val, &cache))
- return false;
- if (cache == "default") {
- *out = blink::mojom::FetchCacheMode::kDefault;
- } else if (cache == "no-store") {
- *out = blink::mojom::FetchCacheMode::kNoStore;
- } else if (cache == "reload") {
- *out = blink::mojom::FetchCacheMode::kBypassCache;
- } else if (cache == "no-cache") {
- *out = blink::mojom::FetchCacheMode::kValidateCache;
- } else if (cache == "force-cache") {
- *out = blink::mojom::FetchCacheMode::kForceCache;
- } else if (cache == "only-if-cached") {
- *out = blink::mojom::FetchCacheMode::kOnlyIfCached;
- } else {
- return false;
- }
- return true;
+ using Val = blink::mojom::FetchCacheMode;
+ static constexpr auto Lookup =
+ base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
+ {"default", Val::kDefault},
+ {"force-cache", Val::kForceCache},
+ {"no-cache", Val::kValidateCache},
+ {"no-store", Val::kNoStore},
+ {"only-if-cached", Val::kOnlyIfCached},
+ {"reload", Val::kBypassCache},
+ });
+ return FromV8WithLookup(isolate, val, Lookup, out);
}
};
@@ -111,42 +99,24 @@ struct Converter<net::ReferrerPolicy> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
net::ReferrerPolicy* out) {
- std::string referrer_policy;
- if (!ConvertFromV8(isolate, val, &referrer_policy))
- return false;
- if (base::CompareCaseInsensitiveASCII(referrer_policy, "no-referrer") ==
- 0) {
- *out = net::ReferrerPolicy::NO_REFERRER;
- } else if (base::CompareCaseInsensitiveASCII(
- referrer_policy, "no-referrer-when-downgrade") == 0) {
- *out = net::ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE;
- } else if (base::CompareCaseInsensitiveASCII(referrer_policy, "origin") ==
- 0) {
- *out = net::ReferrerPolicy::ORIGIN;
- } else if (base::CompareCaseInsensitiveASCII(
- referrer_policy, "origin-when-cross-origin") == 0) {
- *out = net::ReferrerPolicy::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN;
- } else if (base::CompareCaseInsensitiveASCII(referrer_policy,
- "unsafe-url") == 0) {
- *out = net::ReferrerPolicy::NEVER_CLEAR;
- } else if (base::CompareCaseInsensitiveASCII(referrer_policy,
- "same-origin") == 0) {
- *out = net::ReferrerPolicy::CLEAR_ON_TRANSITION_CROSS_ORIGIN;
- } else if (base::CompareCaseInsensitiveASCII(referrer_policy,
- "strict-origin") == 0) {
- *out = net::ReferrerPolicy::
- ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE;
- } else if (referrer_policy == "" ||
- base::CompareCaseInsensitiveASCII(
- referrer_policy, "strict-origin-when-cross-origin") == 0) {
- *out = net::ReferrerPolicy::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN;
- } else {
- return false;
- }
- return true;
+ using Val = net::ReferrerPolicy;
+ // clang-format off
+ static constexpr auto Lookup =
+ base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
+ {"", Val::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN},
+ {"no-referrer", Val::NO_REFERRER},
+ {"no-referrer-when-downgrade", Val::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE},
+ {"origin", Val::ORIGIN},
+ {"origin-when-cross-origin", Val::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN},
+ {"same-origin", Val::CLEAR_ON_TRANSITION_CROSS_ORIGIN},
+ {"strict-origin", Val:: ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE},
+ {"strict-origin-when-cross-origin", Val::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN},
+ {"unsafe-url", Val::NEVER_CLEAR},
+ });
+ // clang-format on
+ return FromV8WithLowerLookup(isolate, val, Lookup, out);
}
};
-
} // namespace gin
namespace electron::api {
diff --git a/shell/browser/api/electron_api_web_request.cc b/shell/browser/api/electron_api_web_request.cc
index 82c4e8fee8..28fc9426e7 100644
--- a/shell/browser/api/electron_api_web_request.cc
+++ b/shell/browser/api/electron_api_web_request.cc
@@ -9,6 +9,7 @@
#include <utility>
#include "base/containers/contains.h"
+#include "base/containers/fixed_flat_map.h"
#include "base/memory/raw_ptr.h"
#include "base/stl_util.h"
#include "base/task/sequenced_task_runner.h"
@@ -31,54 +32,34 @@
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
+static constexpr auto ResourceTypes =
+ base::MakeFixedFlatMapSorted<base::StringPiece,
+ extensions::WebRequestResourceType>({
+ {"cspReport", extensions::WebRequestResourceType::CSP_REPORT},
+ {"font", extensions::WebRequestResourceType::FONT},
+ {"image", extensions::WebRequestResourceType::IMAGE},
+ {"mainFrame", extensions::WebRequestResourceType::MAIN_FRAME},
+ {"media", extensions::WebRequestResourceType::MEDIA},
+ {"object", extensions::WebRequestResourceType::OBJECT},
+ {"ping", extensions::WebRequestResourceType::PING},
+ {"script", extensions::WebRequestResourceType::SCRIPT},
+ {"stylesheet", extensions::WebRequestResourceType::STYLESHEET},
+ {"subFrame", extensions::WebRequestResourceType::SUB_FRAME},
+ {"webSocket", extensions::WebRequestResourceType::WEB_SOCKET},
+ {"xhr", extensions::WebRequestResourceType::XHR},
+ });
+
namespace gin {
template <>
struct Converter<extensions::WebRequestResourceType> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
extensions::WebRequestResourceType type) {
- const char* result;
- switch (type) {
- case extensions::WebRequestResourceType::MAIN_FRAME:
- result = "mainFrame";
- break;
- case extensions::WebRequestResourceType::SUB_FRAME:
- result = "subFrame";
- break;
- case extensions::WebRequestResourceType::STYLESHEET:
- result = "stylesheet";
- break;
- case extensions::WebRequestResourceType::SCRIPT:
- result = "script";
- break;
- case extensions::WebRequestResourceType::IMAGE:
- result = "image";
- break;
- case extensions::WebRequestResourceType::FONT:
- result = "font";
- break;
- case extensions::WebRequestResourceType::OBJECT:
- result = "object";
- break;
- case extensions::WebRequestResourceType::XHR:
- result = "xhr";
- break;
- case extensions::WebRequestResourceType::PING:
- result = "ping";
- break;
- case extensions::WebRequestResourceType::CSP_REPORT:
- result = "cspReport";
- break;
- case extensions::WebRequestResourceType::MEDIA:
- result = "media";
- break;
- case extensions::WebRequestResourceType::WEB_SOCKET:
- result = "webSocket";
- break;
- default:
- result = "other";
- }
- return StringToV8(isolate, result);
+ for (const auto& [name, val] : ResourceTypes)
+ if (type == val)
+ return StringToV8(isolate, name);
+
+ return StringToV8(isolate, "other");
}
};
@@ -96,34 +77,11 @@ struct UserData : public base::SupportsUserData::Data {
raw_ptr<WebRequest> data;
};
-extensions::WebRequestResourceType ParseResourceType(const std::string& value) {
- if (value == "mainFrame") {
- return extensions::WebRequestResourceType::MAIN_FRAME;
- } else if (value == "subFrame") {
- return extensions::WebRequestResourceType::SUB_FRAME;
- } else if (value == "stylesheet") {
- return extensions::WebRequestResourceType::STYLESHEET;
- } else if (value == "script") {
- return extensions::WebRequestResourceType::SCRIPT;
- } else if (value == "image") {
- return extensions::WebRequestResourceType::IMAGE;
- } else if (value == "font") {
- return extensions::WebRequestResourceType::FONT;
- } else if (value == "object") {
- return extensions::WebRequestResourceType::OBJECT;
- } else if (value == "xhr") {
- return extensions::WebRequestResourceType::XHR;
- } else if (value == "ping") {
- return extensions::WebRequestResourceType::PING;
- } else if (value == "cspReport") {
- return extensions::WebRequestResourceType::CSP_REPORT;
- } else if (value == "media") {
- return extensions::WebRequestResourceType::MEDIA;
- } else if (value == "webSocket") {
- return extensions::WebRequestResourceType::WEB_SOCKET;
- } else {
- return extensions::WebRequestResourceType::OTHER;
- }
+extensions::WebRequestResourceType ParseResourceType(base::StringPiece value) {
+ if (const auto* iter = ResourceTypes.find(value); iter != ResourceTypes.end())
+ return iter->second;
+
+ return extensions::WebRequestResourceType::OTHER;
}
// Convert HttpResponseHeaders to V8.
diff --git a/shell/common/gin_converters/blink_converter.cc b/shell/common/gin_converters/blink_converter.cc
index 36ca46d717..75054b1b55 100644
--- a/shell/common/gin_converters/blink_converter.cc
+++ b/shell/common/gin_converters/blink_converter.cc
@@ -8,12 +8,14 @@
#include <string>
#include <vector>
+#include "base/containers/fixed_flat_map.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "gin/converter.h"
#include "gin/data_object_builder.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
+#include "shell/common/gin_converters/std_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/keyboard_util.h"
@@ -130,86 +132,77 @@ struct Converter<blink::WebMouseEvent::Button> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
blink::WebMouseEvent::Button* out) {
- std::string button = base::ToLowerASCII(gin::V8ToString(isolate, val));
- if (button == "left")
- *out = blink::WebMouseEvent::Button::kLeft;
- else if (button == "middle")
- *out = blink::WebMouseEvent::Button::kMiddle;
- else if (button == "right")
- *out = blink::WebMouseEvent::Button::kRight;
- else
- return false;
- return true;
+ using Val = blink::WebMouseEvent::Button;
+ static constexpr auto Lookup =
+ base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
+ {"left", Val::kLeft},
+ {"middle", Val::kMiddle},
+ {"right", Val::kRight},
+ });
+ return FromV8WithLowerLookup(isolate, val, Lookup, out);
}
};
+// clang-format off
+
+// these are the modifier names we both accept and return
+static constexpr auto Modifiers =
+ base::MakeFixedFlatMapSorted<base::StringPiece, blink::WebInputEvent::Modifiers>({
+ {"alt", blink::WebInputEvent::Modifiers::kAltKey},
+ {"capslock", blink::WebInputEvent::Modifiers::kCapsLockOn},
+ {"control", blink::WebInputEvent::Modifiers::kControlKey},
+ {"isautorepeat", blink::WebInputEvent::Modifiers::kIsAutoRepeat},
+ {"iskeypad", blink::WebInputEvent::Modifiers::kIsKeyPad},
+ {"left", blink::WebInputEvent::Modifiers::kIsLeft},
+ {"leftbuttondown", blink::WebInputEvent::Modifiers::kLeftButtonDown},
+ {"meta", blink::WebInputEvent::Modifiers::kMetaKey},
+ {"middlebuttondown", blink::WebInputEvent::Modifiers::kMiddleButtonDown},
+ {"numlock", blink::WebInputEvent::Modifiers::kNumLockOn},
+ {"right", blink::WebInputEvent::Modifiers::kIsRight},
+ {"rightbuttondown", blink::WebInputEvent::Modifiers::kRightButtonDown},
+ {"shift", blink::WebInputEvent::Modifiers::kShiftKey},
+ // TODO(nornagon): the rest of the modifiers
+});
+
+// these are the modifier names we accept but do not return
+static constexpr auto ModifierAliases =
+ base::MakeFixedFlatMapSorted<base::StringPiece, blink::WebInputEvent::Modifiers>({
+ {"cmd", blink::WebInputEvent::Modifiers::kMetaKey},
+ {"command", blink::WebInputEvent::Modifiers::kMetaKey},
+ {"ctrl", blink::WebInputEvent::Modifiers::kControlKey},
+});
+
+static constexpr auto ReferrerPolicies =
+ base::MakeFixedFlatMapSorted<base::StringPiece, network::mojom::ReferrerPolicy>({
+ {"default", network::mojom::ReferrerPolicy::kDefault},
+ {"no-referrer", network::mojom::ReferrerPolicy::kNever},
+ {"no-referrer-when-downgrade", network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade},
+ {"origin", network::mojom::ReferrerPolicy::kOrigin},
+ {"same-origin", network::mojom::ReferrerPolicy::kSameOrigin},
+ {"strict-origin", network::mojom::ReferrerPolicy::kStrictOrigin},
+ {"strict-origin-when-cross-origin", network::mojom::ReferrerPolicy::kStrictOriginWhenCrossOrigin},
+ {"unsafe-url", network::mojom::ReferrerPolicy::kAlways},
+ });
+
+// clang-format on
+
template <>
struct Converter<blink::WebInputEvent::Modifiers> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
blink::WebInputEvent::Modifiers* out) {
- std::string modifier = base::ToLowerASCII(gin::V8ToString(isolate, val));
- if (modifier == "shift")
- *out = blink::WebInputEvent::Modifiers::kShiftKey;
- else if (modifier == "control" || modifier == "ctrl")
- *out = blink::WebInputEvent::Modifiers::kControlKey;
- else if (modifier == "alt")
- *out = blink::WebInputEvent::Modifiers::kAltKey;
- else if (modifier == "meta" || modifier == "command" || modifier == "cmd")
- *out = blink::WebInputEvent::Modifiers::kMetaKey;
- else if (modifier == "iskeypad")
- *out = blink::WebInputEvent::Modifiers::kIsKeyPad;
- else if (modifier == "isautorepeat")
- *out = blink::WebInputEvent::Modifiers::kIsAutoRepeat;
- else if (modifier == "leftbuttondown")
- *out = blink::WebInputEvent::Modifiers::kLeftButtonDown;
- else if (modifier == "middlebuttondown")
- *out = blink::WebInputEvent::Modifiers::kMiddleButtonDown;
- else if (modifier == "rightbuttondown")
- *out = blink::WebInputEvent::Modifiers::kRightButtonDown;
- else if (modifier == "capslock")
- *out = blink::WebInputEvent::Modifiers::kCapsLockOn;
- else if (modifier == "numlock")
- *out = blink::WebInputEvent::Modifiers::kNumLockOn;
- else if (modifier == "left")
- *out = blink::WebInputEvent::Modifiers::kIsLeft;
- else if (modifier == "right")
- *out = blink::WebInputEvent::Modifiers::kIsRight;
- // TODO(nornagon): the rest of the modifiers
- return true;
+ return FromV8WithLowerLookup(isolate, val, Modifiers, out) ||
+ FromV8WithLowerLookup(isolate, val, ModifierAliases, out);
}
};
std::vector<base::StringPiece> ModifiersToArray(int modifiers) {
- using Modifiers = blink::WebInputEvent::Modifiers;
std::vector<base::StringPiece> modifier_strings;
- if (modifiers & Modifiers::kShiftKey)
- modifier_strings.push_back("shift");
- if (modifiers & Modifiers::kControlKey)
- modifier_strings.push_back("control");
- if (modifiers & Modifiers::kAltKey)
- modifier_strings.push_back("alt");
- if (modifiers & Modifiers::kMetaKey)
- modifier_strings.push_back("meta");
- if (modifiers & Modifiers::kIsKeyPad)
- modifier_strings.push_back("iskeypad");
- if (modifiers & Modifiers::kIsAutoRepeat)
- modifier_strings.push_back("isautorepeat");
- if (modifiers & Modifiers::kLeftButtonDown)
- modifier_strings.push_back("leftbuttondown");
- if (modifiers & Modifiers::kMiddleButtonDown)
- modifier_strings.push_back("middlebuttondown");
- if (modifiers & Modifiers::kRightButtonDown)
- modifier_strings.push_back("rightbuttondown");
- if (modifiers & Modifiers::kCapsLockOn)
- modifier_strings.push_back("capslock");
- if (modifiers & Modifiers::kNumLockOn)
- modifier_strings.push_back("numlock");
- if (modifiers & Modifiers::kIsLeft)
- modifier_strings.push_back("left");
- if (modifiers & Modifiers::kIsRight)
- modifier_strings.push_back("right");
- // TODO(nornagon): the rest of the modifiers
+
+ for (const auto& [name, mask] : Modifiers)
+ if (mask & modifiers)
+ modifier_strings.emplace_back(name);
+
return modifier_strings;
}
@@ -553,26 +546,11 @@ v8::Local<v8::Value> Converter<blink::WebCacheResourceTypeStats>::ToV8(
v8::Local<v8::Value> Converter<network::mojom::ReferrerPolicy>::ToV8(
v8::Isolate* isolate,
const network::mojom::ReferrerPolicy& in) {
- switch (in) {
- case network::mojom::ReferrerPolicy::kDefault:
- return StringToV8(isolate, "default");
- case network::mojom::ReferrerPolicy::kAlways:
- return StringToV8(isolate, "unsafe-url");
- case network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade:
- return StringToV8(isolate, "no-referrer-when-downgrade");
- case network::mojom::ReferrerPolicy::kNever:
- return StringToV8(isolate, "no-referrer");
- case network::mojom::ReferrerPolicy::kOrigin:
- return StringToV8(isolate, "origin");
- case network::mojom::ReferrerPolicy::kStrictOriginWhenCrossOrigin:
- return StringToV8(isolate, "strict-origin-when-cross-origin");
- case network::mojom::ReferrerPolicy::kSameOrigin:
- return StringToV8(isolate, "same-origin");
- case network::mojom::ReferrerPolicy::kStrictOrigin:
- return StringToV8(isolate, "strict-origin");
- default:
- return StringToV8(isolate, "no-referrer");
- }
+ for (const auto& [name, val] : ReferrerPolicies)
+ if (val == in)
+ return StringToV8(isolate, name);
+
+ return StringToV8(isolate, "no-referrer");
}
// static
@@ -580,26 +558,7 @@ bool Converter<network::mojom::ReferrerPolicy>::FromV8(
v8::Isolate* isolate,
v8::Handle<v8::Value> val,
network::mojom::ReferrerPolicy* out) {
- std::string policy = base::ToLowerASCII(gin::V8ToString(isolate, val));
- if (policy == "default")
- *out = network::mojom::ReferrerPolicy::kDefault;
- else if (policy == "unsafe-url")
- *out = network::mojom::ReferrerPolicy::kAlways;
- else if (policy == "no-referrer-when-downgrade")
- *out = network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade;
- else if (policy == "no-referrer")
- *out = network::mojom::ReferrerPolicy::kNever;
- else if (policy == "origin")
- *out = network::mojom::ReferrerPolicy::kOrigin;
- else if (policy == "strict-origin-when-cross-origin")
- *out = network::mojom::ReferrerPolicy::kStrictOriginWhenCrossOrigin;
- else if (policy == "same-origin")
- *out = network::mojom::ReferrerPolicy::kSameOrigin;
- else if (policy == "strict-origin")
- *out = network::mojom::ReferrerPolicy::kStrictOrigin;
- else
- return false;
- return true;
+ return FromV8WithLowerLookup(isolate, val, ReferrerPolicies, out);
}
// static
diff --git a/shell/common/gin_converters/net_converter.cc b/shell/common/gin_converters/net_converter.cc
index 695635495b..be1bc50416 100644
--- a/shell/common/gin_converters/net_converter.cc
+++ b/shell/common/gin_converters/net_converter.cc
@@ -689,57 +689,28 @@ v8::Local<v8::Value> Converter<net::IPEndPoint>::ToV8(
bool Converter<net::DnsQueryType>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
net::DnsQueryType* out) {
- std::string query_type;
- if (!ConvertFromV8(isolate, val, &query_type))
- return false;
-
- if (query_type == "A") {
- *out = net::DnsQueryType::A;
- return true;
- }
-
- if (query_type == "AAAA") {
- *out = net::DnsQueryType::AAAA;
- return true;
- }
-
- return false;
+ static constexpr auto Lookup =
+ base::MakeFixedFlatMapSorted<base::StringPiece, net::DnsQueryType>({
+ {"A", net::DnsQueryType::A},
+ {"AAAA", net::DnsQueryType::AAAA},
+ });
+ return FromV8WithLookup(isolate, val, Lookup, out);
}
// static
bool Converter<net::HostResolverSource>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
net::HostResolverSource* out) {
- std::string query_type;
- if (!ConvertFromV8(isolate, val, &query_type))
- return false;
-
- if (query_type == "any") {
- *out = net::HostResolverSource::ANY;
- return true;
- }
-
- if (query_type == "system") {
- *out = net::HostResolverSource::SYSTEM;
- return true;
- }
-
- if (query_type == "dns") {
- *out = net::HostResolverSource::DNS;
- return true;
- }
-
- if (query_type == "mdns") {
- *out = net::HostResolverSource::MULTICAST_DNS;
- return true;
- }
-
- if (query_type == "localOnly") {
- *out = net::HostResolverSource::LOCAL_ONLY;
- return true;
- }
-
- return false;
+ using Val = net::HostResolverSource;
+ static constexpr auto Lookup =
+ base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
+ {"any", Val::ANY},
+ {"dns", Val::DNS},
+ {"localOnly", Val::LOCAL_ONLY},
+ {"mdns", Val::MULTICAST_DNS},
+ {"system", Val::SYSTEM},
+ });
+ return FromV8WithLookup(isolate, val, Lookup, out);
}
// static
@@ -747,26 +718,14 @@ bool Converter<network::mojom::ResolveHostParameters::CacheUsage>::FromV8(
v8::Isolate* isolate,
v8::Local<v8::Value> val,
network::mojom::ResolveHostParameters::CacheUsage* out) {
- std::string query_type;
- if (!ConvertFromV8(isolate, val, &query_type))
- return false;
-
- if (query_type == "allowed") {
- *out = network::mojom::ResolveHostParameters::CacheUsage::ALLOWED;
- return true;
- }
-
- if (query_type == "staleAllowed") {
- *out = network::mojom::ResolveHostParameters::CacheUsage::STALE_ALLOWED;
- return true;
- }
-
- if (query_type == "disallowed") {
- *out = network::mojom::ResolveHostParameters::CacheUsage::DISALLOWED;
- return true;
- }
-
- return false;
+ using Val = network::mojom::ResolveHostParameters::CacheUsage;
+ static constexpr auto Lookup =
+ base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
+ {"allowed", Val::ALLOWED},
+ {"disallowed", Val::DISALLOWED},
+ {"staleAllowed", Val::STALE_ALLOWED},
+ });
+ return FromV8WithLookup(isolate, val, Lookup, out);
}
// static
@@ -774,21 +733,13 @@ bool Converter<network::mojom::SecureDnsPolicy>::FromV8(
v8::Isolate* isolate,
v8::Local<v8::Value> val,
network::mojom::SecureDnsPolicy* out) {
- std::string query_type;
- if (!ConvertFromV8(isolate, val, &query_type))
- return false;
-
- if (query_type == "allow") {
- *out = network::mojom::SecureDnsPolicy::ALLOW;
- return true;
- }
-
- if (query_type == "disable") {
- *out = network::mojom::SecureDnsPolicy::DISABLE;
- return true;
- }
-
- return false;
+ using Val = network::mojom::SecureDnsPolicy;
+ static constexpr auto Lookup =
+ base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
+ {"allow", Val::ALLOW},
+ {"disable", Val::DISABLE},
+ });
+ return FromV8WithLookup(isolate, val, Lookup, out);
}
// static
diff --git a/shell/common/gin_converters/std_converter.h b/shell/common/gin_converters/std_converter.h
index 27020ee578..eb6d4c1874 100644
--- a/shell/common/gin_converters/std_converter.h
+++ b/shell/common/gin_converters/std_converter.h
@@ -5,12 +5,16 @@
#ifndef ELECTRON_SHELL_COMMON_GIN_CONVERTERS_STD_CONVERTER_H_
#define ELECTRON_SHELL_COMMON_GIN_CONVERTERS_STD_CONVERTER_H_
+#include <cstddef>
+#include <functional>
#include <map>
#include <set>
+#include <type_traits>
#include <utility>
#include "gin/converter.h"
+#include "base/strings/string_util.h"
#if BUILDFLAG(IS_WIN)
#include "base/strings/string_util_win.h"
#endif
@@ -210,6 +214,61 @@ struct Converter<std::wstring> {
};
#endif
+namespace detail {
+
+// Get a key from `key_val` and check `lookup` for a matching entry.
+// Return true iff a match is found, and set `*out` to the entry's value.
+template <typename KeyType, typename Out, typename Map>
+bool FromV8WithLookup(v8::Isolate* isolate,
+ v8::Local<v8::Value> key_val,
+ const Map& table,
+ Out* out,
+ std::function<void(KeyType&)> key_transform = {}) {
+ static_assert(std::is_same_v<typename Map::mapped_type, Out>);
+
+ auto key = KeyType{};
+ if (!ConvertFromV8(isolate, key_val, &key))
+ return false;
+
+ if (key_transform)
+ key_transform(key);
+
+ if (const auto* iter = table.find(key); iter != table.end()) {
+ *out = iter->second;
+ return true;
+ }
+
+ return false;
+}
+
+} // namespace detail
+
+// Convert `key_val to a string key and check `lookup` for a matching entry.
+// Return true iff a match is found, and set `*out` to the entry's value.
+template <typename Out, typename Map>
+bool FromV8WithLookup(v8::Isolate* isolate,
+ v8::Local<v8::Value> key_val,
+ const Map& table,
+ Out* out) {
+ return detail::FromV8WithLookup<std::string>(isolate, key_val, table, out);
+}
+
+// Convert `key_val` to a lowercase string key and check `lookup` for a matching
+// entry. Return true iff a match is found, and set `*out` to the entry's value.
+template <typename Out, typename Map>
+bool FromV8WithLowerLookup(v8::Isolate* isolate,
+ v8::Local<v8::Value> key_val,
+ const Map& table,
+ Out* out) {
+ static constexpr auto to_lower_ascii_inplace = [](std::string& str) {
+ for (auto& ch : str)
+ ch = base::ToLowerASCII(ch);
+ };
+
+ return detail::FromV8WithLookup<std::string>(isolate, key_val, table, out,
+ to_lower_ascii_inplace);
+}
+
} // namespace gin
#endif // ELECTRON_SHELL_COMMON_GIN_CONVERTERS_STD_CONVERTER_H_
|
refactor
|
d8bb17231814b85df0ff492e8198522efa830da3
|
Samuel Attard
|
2022-11-14 10:12:16
|
fix: abort ShipIt installation attempt at the final mile if the app is running (#36130)
* fix: abort ShipIt installation attempt at the final mile if the app is running
* chore: remove only
* Update patches/squirrel.mac/fix_abort_installation_attempt_at_the_final_mile_if_the_app_is.patch
Co-authored-by: Jeremy Rose <[email protected]>
* chore: update patches
* spec: make the ShipIt process lister helper more resilient
Co-authored-by: Jeremy Rose <[email protected]>
Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com>
|
diff --git a/patches/squirrel.mac/.patches b/patches/squirrel.mac/.patches
index 53f27f11a9..1a2a44222c 100644
--- a/patches/squirrel.mac/.patches
+++ b/patches/squirrel.mac/.patches
@@ -3,3 +3,4 @@ fix_ensure_that_self_is_retained_until_the_racsignal_is_complete.patch
fix_use_kseccschecknestedcode_kseccsstrictvalidate_in_the_sec.patch
feat_add_new_squirrel_mac_bundle_installation_method_behind_flag.patch
refactor_use_posix_spawn_instead_of_nstask_so_we_can_disclaim_the.patch
+fix_abort_installation_attempt_at_the_final_mile_if_the_app_is.patch
diff --git a/patches/squirrel.mac/fix_abort_installation_attempt_at_the_final_mile_if_the_app_is.patch b/patches/squirrel.mac/fix_abort_installation_attempt_at_the_final_mile_if_the_app_is.patch
new file mode 100644
index 0000000000..febb0650db
--- /dev/null
+++ b/patches/squirrel.mac/fix_abort_installation_attempt_at_the_final_mile_if_the_app_is.patch
@@ -0,0 +1,75 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Samuel Attard <[email protected]>
+Date: Tue, 25 Oct 2022 13:09:55 -0700
+Subject: fix: abort installation attempt at the final mile if the app is
+ running
+
+There is a race condition between ShipIt launching and it performing an atomic rename to "install" the app bundle. This fixes the race by checking the list of running apps immediately before performing the rename.
+
+diff --git a/Squirrel/SQRLInstaller.h b/Squirrel/SQRLInstaller.h
+index 2de1c384aae200f41de429cc35313e4c2ba9d0de..35a0c99129478f09526667d73c9544c3bfe14706 100644
+--- a/Squirrel/SQRLInstaller.h
++++ b/Squirrel/SQRLInstaller.h
+@@ -37,6 +37,9 @@ extern const NSInteger SQRLInstallerErrorMovingAcrossVolumes;
+ // There was an error changing the file permissions of the update.
+ extern const NSInteger SQRLInstallerErrorChangingPermissions;
+
++// There was a running instance of the app just prior to the update attempt
++extern const NSInteger SQRLInstallerErrorAppStillRunning;
++
+ @class RACCommand;
+
+ // Performs the installation of an update, saving its intermediate state to user
+diff --git a/Squirrel/SQRLInstaller.m b/Squirrel/SQRLInstaller.m
+index c1f328fa8c3689218ef260347cb8f9d30b789efe..f502df2f88424ea902a061adfeb30358daf212e4 100644
+--- a/Squirrel/SQRLInstaller.m
++++ b/Squirrel/SQRLInstaller.m
+@@ -36,6 +36,7 @@
+ const NSInteger SQRLInstallerErrorInvalidState = -6;
+ const NSInteger SQRLInstallerErrorMovingAcrossVolumes = -7;
+ const NSInteger SQRLInstallerErrorChangingPermissions = -8;
++const NSInteger SQRLInstallerErrorAppStillRunning = -9;
+
+ NSString * const SQRLShipItInstallationAttemptsKey = @"SQRLShipItInstallationAttempts";
+ NSString * const SQRLInstallerOwnedBundleKey = @"SQRLInstallerOwnedBundle";
+@@ -286,6 +287,19 @@ - (RACSignal *)installRequest:(SQRLShipItRequest *)request {
+ return [[[[self
+ renameIfNeeded:request updateBundleURL:updateBundleURL]
+ flattenMap:^(SQRLShipItRequest *request) {
++ // Final validation that the application is not running again;
++ NSArray *apps = [[NSRunningApplication runningApplicationsWithBundleIdentifier:request.bundleIdentifier] filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSRunningApplication *app, NSDictionary *bindings) {
++ return [[[app bundleURL] URLByStandardizingPath] isEqual:request.targetBundleURL];
++ }]];
++ if ([apps count] != 0) {
++ NSLog(@"Aborting update attempt because there are %lu running instances of the target app", [apps count]);
++ NSDictionary *errorInfo = @{
++ NSLocalizedDescriptionKey: NSLocalizedString(@"App Still Running Error", nil),
++ NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"All instances of the target application should be quit during the update process", nil),
++ };
++ return [RACSignal error:[NSError errorWithDomain:SQRLInstallerErrorDomain code:SQRLInstallerErrorAppStillRunning userInfo:errorInfo]];
++ }
++
+ return [[self acquireTargetBundleURLForRequest:request] concat:[RACSignal return:request]];
+ }]
+ flattenMap:^(SQRLShipItRequest *request) {
+diff --git a/Squirrel/ShipIt-main.m b/Squirrel/ShipIt-main.m
+index 2c515ffdd67052a08ee8155c0e46b57e9721a0e5..5f3e29642012d04fc506b730a4e87fba861df250 100644
+--- a/Squirrel/ShipIt-main.m
++++ b/Squirrel/ShipIt-main.m
+@@ -201,8 +201,14 @@ static void installRequest(RACSignal *readRequestSignal, NSString *applicationId
+ return action;
+ }]
+ subscribeError:^(NSError *error) {
+- NSLog(@"Installation error: %@", error);
+- exit(EXIT_FAILURE);
++ if ([[error domain] isEqual:SQRLInstallerErrorDomain] && [error code] == SQRLInstallerErrorAppStillRunning) {
++ NSLog(@"Installation cancelled: %@", error);
++ clearInstallationAttempts(applicationIdentifier);
++ exit(EXIT_SUCCESS);
++ } else {
++ NSLog(@"Installation error: %@", error);
++ exit(EXIT_FAILURE);
++ }
+ } completed:^{
+ exit(EXIT_SUCCESS);
+ }];
diff --git a/spec/api-autoupdater-darwin-spec.ts b/spec/api-autoupdater-darwin-spec.ts
index 18c075f0c7..0ea8674f3d 100644
--- a/spec/api-autoupdater-darwin-spec.ts
+++ b/spec/api-autoupdater-darwin-spec.ts
@@ -5,6 +5,7 @@ import * as express from 'express';
import * as fs from 'fs-extra';
import * as os from 'os';
import * as path from 'path';
+import * as psList from 'ps-list';
import { AddressInfo } from 'net';
import { ifdescribe, ifit } from './spec-helpers';
import * as uuid from 'uuid';
@@ -95,6 +96,16 @@ ifdescribe(process.platform === 'darwin' && !(process.env.CI && process.arch ===
return spawn(path.resolve(appPath, 'Contents/MacOS/Electron'), args);
};
+ const spawnAppWithHandle = (appPath: string, args: string[] = []) => {
+ return cp.spawn(path.resolve(appPath, 'Contents/MacOS/Electron'), args);
+ };
+
+ const getRunningShipIts = async (appPath: string) => {
+ const processes = await psList();
+ const activeShipIts = processes.filter(p => p.cmd?.includes('Squirrel.framework/Resources/ShipIt com.github.Electron.ShipIt') && p.cmd!.startsWith(appPath));
+ return activeShipIts;
+ };
+
const withTempDirectory = async (fn: (dir: string) => Promise<void>, autoCleanUp = true) => {
const dir = await fs.mkdtemp(path.resolve(os.tmpdir(), 'electron-update-spec-'));
try {
@@ -323,6 +334,71 @@ ifdescribe(process.platform === 'darwin' && !(process.env.CI && process.arch ===
});
});
+ it('should abort the update if the application is still running when ShipIt kicks off', async () => {
+ await withUpdatableApp({
+ nextVersion: '2.0.0',
+ startFixture: 'update',
+ endFixture: 'update'
+ }, async (appPath, updateZipPath) => {
+ server.get('/update-file', (req, res) => {
+ res.download(updateZipPath);
+ });
+ server.get('/update-check', (req, res) => {
+ res.json({
+ url: `http://localhost:${port}/update-file`,
+ name: 'My Release Name',
+ notes: 'Theses are some release notes innit',
+ pub_date: (new Date()).toString()
+ });
+ });
+
+ enum FlipFlop {
+ INITIAL,
+ FLIPPED,
+ FLOPPED,
+ }
+
+ const shipItFlipFlopPromise = new Promise<void>((resolve) => {
+ let state = FlipFlop.INITIAL;
+ const checker = setInterval(async () => {
+ const running = await getRunningShipIts(appPath);
+ switch (state) {
+ case FlipFlop.INITIAL: {
+ if (running.length) state = FlipFlop.FLIPPED;
+ break;
+ }
+ case FlipFlop.FLIPPED: {
+ if (!running.length) state = FlipFlop.FLOPPED;
+ break;
+ }
+ }
+ if (state === FlipFlop.FLOPPED) {
+ clearInterval(checker);
+ resolve();
+ }
+ }, 500);
+ });
+
+ const launchResult = await launchApp(appPath, [`http://localhost:${port}/update-check`]);
+ const retainerHandle = spawnAppWithHandle(appPath, ['remain-open']);
+ logOnError(launchResult, () => {
+ expect(launchResult).to.have.property('code', 0);
+ expect(launchResult.out).to.include('Update Downloaded');
+ expect(requests).to.have.lengthOf(2);
+ expect(requests[0]).to.have.property('url', '/update-check');
+ expect(requests[1]).to.have.property('url', '/update-file');
+ expect(requests[0].header('user-agent')).to.include('Electron/');
+ expect(requests[1].header('user-agent')).to.include('Electron/');
+ });
+
+ await shipItFlipFlopPromise;
+ expect(requests).to.have.lengthOf(2, 'should not have relaunched the updated app');
+ expect(JSON.parse(await fs.readFile(path.resolve(appPath, 'Contents/Resources/app/package.json'), 'utf8')).version).to.equal('1.0.0', 'should still be the old version on disk');
+
+ retainerHandle.kill('SIGINT');
+ });
+ });
+
describe('with SquirrelMacEnableDirectContentsWrite enabled', () => {
let previousValue: any;
diff --git a/spec/fixtures/auto-update/update/index.js b/spec/fixtures/auto-update/update/index.js
index e391362f12..b15dc7dc72 100644
--- a/spec/fixtures/auto-update/update/index.js
+++ b/spec/fixtures/auto-update/update/index.js
@@ -15,28 +15,34 @@ autoUpdater.on('error', (err) => {
const urlPath = path.resolve(__dirname, '../../../../url.txt');
let feedUrl = process.argv[1];
-if (!feedUrl || !feedUrl.startsWith('http')) {
- feedUrl = `${fs.readFileSync(urlPath, 'utf8')}/${app.getVersion()}`;
+
+if (feedUrl === 'remain-open') {
+ // Hold the event loop
+ setInterval(() => {});
} else {
- fs.writeFileSync(urlPath, `${feedUrl}/updated`);
+ if (!feedUrl || !feedUrl.startsWith('http')) {
+ feedUrl = `${fs.readFileSync(urlPath, 'utf8')}/${app.getVersion()}`;
+ } else {
+ fs.writeFileSync(urlPath, `${feedUrl}/updated`);
+ }
+
+ autoUpdater.setFeedURL({
+ url: feedUrl
+ });
+
+ autoUpdater.checkForUpdates();
+
+ autoUpdater.on('update-available', () => {
+ console.log('Update Available');
+ });
+
+ autoUpdater.on('update-downloaded', () => {
+ console.log('Update Downloaded');
+ autoUpdater.quitAndInstall();
+ });
+
+ autoUpdater.on('update-not-available', () => {
+ console.error('No update available');
+ process.exit(1);
+ });
}
-
-autoUpdater.setFeedURL({
- url: feedUrl
-});
-
-autoUpdater.checkForUpdates();
-
-autoUpdater.on('update-available', () => {
- console.log('Update Available');
-});
-
-autoUpdater.on('update-downloaded', () => {
- console.log('Update Downloaded');
- autoUpdater.quitAndInstall();
-});
-
-autoUpdater.on('update-not-available', () => {
- console.error('No update available');
- process.exit(1);
-});
diff --git a/spec/package.json b/spec/package.json
index ff20598a49..c1860f1fb1 100644
--- a/spec/package.json
+++ b/spec/package.json
@@ -23,6 +23,7 @@
"mocha-junit-reporter": "^1.18.0",
"mocha-multi-reporters": "^1.1.7",
"pdfjs-dist": "^2.2.228",
+ "ps-list": "^7.0.0",
"q": "^1.5.1",
"send": "^0.16.2",
"sinon": "^9.0.1",
diff --git a/spec/yarn.lock b/spec/yarn.lock
index 48f47862c2..757f5e98c6 100644
--- a/spec/yarn.lock
+++ b/spec/yarn.lock
@@ -73,10 +73,9 @@
dependencies:
"@types/node" "*"
-abstract-socket@^2.0.0:
- version "2.1.1"
- resolved "https://registry.yarnpkg.com/abstract-socket/-/abstract-socket-2.1.1.tgz#243a7e6e6ff65bb9eab16a22fa90699b91e528f7"
- integrity sha512-YZJizsvS1aBua5Gd01woe4zuyYBGgSMeqDOB6/ChwdTI904KP6QGtJswXl4hcqWxbz86hQBe++HWV0hF1aGUtA==
+"abstract-socket@github:saghul/node-abstractsocket#35b1b1491fabc04899bde5be3428abf5cf9cd528":
+ version "2.1.0"
+ resolved "https://codeload.github.com/saghul/node-abstractsocket/tar.gz/35b1b1491fabc04899bde5be3428abf5cf9cd528"
dependencies:
bindings "^1.2.1"
nan "^2.12.1"
@@ -303,7 +302,7 @@ dashdash@^1.12.0:
safe-buffer "^5.1.1"
xml2js "^0.4.17"
optionalDependencies:
- abstract-socket "^2.0.0"
+ abstract-socket "github:saghul/node-abstractsocket#35b1b1491fabc04899bde5be3428abf5cf9cd528"
[email protected], debug@^2.2.0:
version "2.6.9"
@@ -937,6 +936,11 @@ performance-now@^2.1.0:
resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b"
integrity sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=
+ps-list@^7.0.0:
+ version "7.2.0"
+ resolved "https://registry.yarnpkg.com/ps-list/-/ps-list-7.2.0.tgz#3d110e1de8249a4b178c9b1cf2a215d1e4e42fc0"
+ integrity sha512-v4Bl6I3f2kJfr5o80ShABNHAokIgY+wFDTQfE+X3zWYgSGQOCBeYptLZUpoOALBqO5EawmDN/tjTldJesd0ujQ==
+
psl@^1.1.24:
version "1.9.0"
resolved "https://registry.yarnpkg.com/psl/-/psl-1.9.0.tgz#d0df2a137f00794565fcaf3b2c00cd09f8d5a5a7"
|
fix
|
a7d664e3a3d06a4d3f059cb51a375ee3155a23d6
|
Shelley Vohr
|
2024-03-06 12:43:39
|
fix: `user-did-{resign|become}-active` events on macOS (#41506)
fix: user-did-{resign|become}-active events on macOS
|
diff --git a/shell/browser/api/electron_api_power_monitor_mac.mm b/shell/browser/api/electron_api_power_monitor_mac.mm
index ef38f17515..347d0d17d7 100644
--- a/shell/browser/api/electron_api_power_monitor_mac.mm
+++ b/shell/browser/api/electron_api_power_monitor_mac.mm
@@ -22,41 +22,45 @@
- (id)init {
if ((self = [super init])) {
- NSDistributedNotificationCenter* distCenter =
+ NSDistributedNotificationCenter* distributed_center =
[NSDistributedNotificationCenter defaultCenter];
// A notification that the screen was locked.
- [distCenter addObserver:self
- selector:@selector(onScreenLocked:)
- name:@"com.apple.screenIsLocked"
- object:nil];
+ [distributed_center addObserver:self
+ selector:@selector(onScreenLocked:)
+ name:@"com.apple.screenIsLocked"
+ object:nil];
// A notification that the screen was unlocked by the user.
- [distCenter addObserver:self
- selector:@selector(onScreenUnlocked:)
- name:@"com.apple.screenIsUnlocked"
- object:nil];
+ [distributed_center addObserver:self
+ selector:@selector(onScreenUnlocked:)
+ name:@"com.apple.screenIsUnlocked"
+ object:nil];
// A notification that the workspace posts before the machine goes to sleep.
- [distCenter addObserver:self
- selector:@selector(isSuspending:)
- name:NSWorkspaceWillSleepNotification
- object:nil];
+ [distributed_center addObserver:self
+ selector:@selector(isSuspending:)
+ name:NSWorkspaceWillSleepNotification
+ object:nil];
// A notification that the workspace posts when the machine wakes from
// sleep.
- [distCenter addObserver:self
- selector:@selector(isResuming:)
- name:NSWorkspaceDidWakeNotification
- object:nil];
+ [distributed_center addObserver:self
+ selector:@selector(isResuming:)
+ name:NSWorkspaceDidWakeNotification
+ object:nil];
+
+ NSNotificationCenter* shared_center =
+ [[NSWorkspace sharedWorkspace] notificationCenter];
+
// A notification that the workspace posts when the user session becomes
// active.
- [distCenter addObserver:self
- selector:@selector(onUserDidBecomeActive:)
- name:NSWorkspaceSessionDidBecomeActiveNotification
- object:nil];
+ [shared_center addObserver:self
+ selector:@selector(onUserDidBecomeActive:)
+ name:NSWorkspaceSessionDidBecomeActiveNotification
+ object:nil];
// A notification that the workspace posts when the user session becomes
// inactive.
- [distCenter addObserver:self
- selector:@selector(onUserDidResignActive:)
- name:NSWorkspaceSessionDidResignActiveNotification
- object:nil];
+ [shared_center addObserver:self
+ selector:@selector(onUserDidResignActive:)
+ name:NSWorkspaceSessionDidResignActiveNotification
+ object:nil];
}
return self;
}
|
fix
|
2a16c73834358f85ef20c07e50dfb5178c30bb1e
|
Samuel Attard
|
2023-05-16 15:21:22
|
chore: cherry-pick e6e23ba00379 from chromium (#38323)
* chore: cherry-pick e6e23ba00379 from chromium
* make it work
|
diff --git a/patches/chromium/.patches b/patches/chromium/.patches
index 627b4cde97..711b02be73 100644
--- a/patches/chromium/.patches
+++ b/patches/chromium/.patches
@@ -125,3 +125,5 @@ chore_patch_out_profile_methods_in_profile_selections_cc.patch
add_gin_converter_support_for_arraybufferview.patch
chore_defer_usb_service_getdevices_request_until_usb_service_is.patch
fix_remove_profiles_from_spellcheck_service.patch
+cherry-pick-48a136e77e6d.patch
+cherry-pick-e6e23ba00379.patch
diff --git a/patches/chromium/cherry-pick-48a136e77e6d.patch b/patches/chromium/cherry-pick-48a136e77e6d.patch
new file mode 100644
index 0000000000..351872e5d3
--- /dev/null
+++ b/patches/chromium/cherry-pick-48a136e77e6d.patch
@@ -0,0 +1,232 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Christopher Cameron <[email protected]>
+Date: Mon, 15 May 2023 23:09:29 +0000
+Subject: ui::Compositor: Propagate display ID
+
+The display ID originates in BrowserCompositorMac (for things like
+ContentShell) or in NativeWidgetMacNSWindowHost (for views).
+
+Add it as a parameter to RecyclableCompositorMac::UpdateSurface and
+use this to propagate it to ui::Compositor.
+
+Ensure that its initial value is propagated correctly in
+ui::Compositor::SetLayerTreeFrameSink.
+
+Remove use of base::LazyInstance from BrowserCompositorMac (it is
+long deprecated, and touching the file triggered presubmit failures).
+
+Bug: 1404797
+Change-Id: Ib39addd1ac2a3b2f42e1958d7ab7c6c4750224f8
+Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/4517539
+Commit-Queue: ccameron chromium <[email protected]>
+Reviewed-by: Maggie Chen <[email protected]>
+Cr-Commit-Position: refs/heads/main@{#1144438}
+
+diff --git a/content/browser/renderer_host/browser_compositor_view_mac.mm b/content/browser/renderer_host/browser_compositor_view_mac.mm
+index 323548d3ed7be2e2572c0048dbf5f0fa464016dc..b7311c83633746855b1e7086b6824879c1870b28 100644
+--- a/content/browser/renderer_host/browser_compositor_view_mac.mm
++++ b/content/browser/renderer_host/browser_compositor_view_mac.mm
+@@ -12,7 +12,7 @@
+
+ #include "base/command_line.h"
+ #include "base/containers/circular_deque.h"
+-#include "base/lazy_instance.h"
++#include "base/no_destructor.h"
+ #include "base/trace_event/trace_event.h"
+ #include "components/viz/common/features.h"
+ #include "components/viz/common/surfaces/local_surface_id.h"
+@@ -38,8 +38,10 @@
+ // signals to shut down will come in very late, long after things that the
+ // ui::Compositor depend on have been destroyed).
+ // https://crbug.com/805726
+-base::LazyInstance<std::set<BrowserCompositorMac*>>::Leaky
+- g_browser_compositors;
++std::set<BrowserCompositorMac*>& GetBrowserCompositors() {
++ static base::NoDestructor<std::set<BrowserCompositorMac*>> instance;
++ return *instance.get();
++}
+
+ } // namespace
+
+@@ -54,7 +56,7 @@
+ : client_(client),
+ accelerated_widget_mac_ns_view_(accelerated_widget_mac_ns_view),
+ weak_factory_(this) {
+- g_browser_compositors.Get().insert(this);
++ GetBrowserCompositors().insert(this);
+
+ root_layer_ = std::make_unique<ui::Layer>(ui::LAYER_SOLID_COLOR);
+ // Ensure that this layer draws nothing when it does not not have delegated
+@@ -75,7 +77,7 @@
+ delegated_frame_host_.reset();
+ root_layer_.reset();
+
+- size_t num_erased = g_browser_compositors.Get().erase(this);
++ size_t num_erased = GetBrowserCompositors().erase(this);
+ DCHECK_EQ(1u, num_erased);
+ }
+
+@@ -138,9 +140,9 @@
+ }
+
+ if (recyclable_compositor_) {
+- recyclable_compositor_->UpdateSurface(dfh_size_pixels_,
+- current.device_scale_factor,
+- current.display_color_spaces);
++ recyclable_compositor_->UpdateSurface(
++ dfh_size_pixels_, current.device_scale_factor,
++ current.display_color_spaces, current.display_id);
+ }
+ }
+
+@@ -160,9 +162,9 @@
+ dfh_device_scale_factor_ = new_device_scale_factor;
+ root_layer_->SetBounds(gfx::Rect(dfh_size_dip_));
+ if (recyclable_compositor_) {
+- recyclable_compositor_->UpdateSurface(dfh_size_pixels_,
+- current.device_scale_factor,
+- current.display_color_spaces);
++ recyclable_compositor_->UpdateSurface(
++ dfh_size_pixels_, current.device_scale_factor,
++ current.display_color_spaces, current.display_id);
+ }
+ }
+ delegated_frame_host_->EmbedSurface(
+@@ -252,9 +254,9 @@
+ recyclable_compositor_ = std::make_unique<ui::RecyclableCompositorMac>(
+ content::GetContextFactory());
+ display::ScreenInfo current = client_->GetCurrentScreenInfo();
+- recyclable_compositor_->UpdateSurface(dfh_size_pixels_,
+- current.device_scale_factor,
+- current.display_color_spaces);
++ recyclable_compositor_->UpdateSurface(
++ dfh_size_pixels_, current.device_scale_factor,
++ current.display_color_spaces, current.display_id);
+ recyclable_compositor_->compositor()->SetRootLayer(root_layer_.get());
+ recyclable_compositor_->compositor()->SetBackgroundColor(background_color_);
+ recyclable_compositor_->widget()->SetNSView(
+@@ -273,9 +275,8 @@
+ // Ensure that the client has destroyed its BrowserCompositorViewMac before
+ // it dependencies are destroyed.
+ // https://crbug.com/805726
+- while (!g_browser_compositors.Get().empty()) {
+- BrowserCompositorMac* browser_compositor =
+- *g_browser_compositors.Get().begin();
++ while (!GetBrowserCompositors().empty()) {
++ BrowserCompositorMac* browser_compositor = *GetBrowserCompositors().begin();
+ browser_compositor->client_->DestroyCompositorForShutdown();
+ }
+ }
+diff --git a/ui/compositor/compositor.cc b/ui/compositor/compositor.cc
+index c652c0dfd2e6c464c91e3522902ee96dd19b0287..e52e5b74146d0709925e87c6f4d5dc551ec8eec8 100644
+--- a/ui/compositor/compositor.cc
++++ b/ui/compositor/compositor.cc
+@@ -347,6 +347,9 @@ void Compositor::SetLayerTreeFrameSink(
+ display_private_->SetDisplayColorMatrix(
+ gfx::SkM44ToTransform(display_color_matrix_));
+ display_private_->SetOutputIsSecure(output_is_secure_);
++#if BUILDFLAG(IS_MAC)
++ display_private_->SetVSyncDisplayID(display_id_);
++#endif
+ if (has_vsync_params_) {
+ display_private_->SetDisplayVSyncParameters(vsync_timebase_,
+ vsync_interval_);
+diff --git a/ui/compositor/recyclable_compositor_mac.cc b/ui/compositor/recyclable_compositor_mac.cc
+index 0e30e781760d38778ec0e741ddae250e96c6d671..0c57b17778872702f887e5fe9d95dc8ad98d654f 100644
+--- a/ui/compositor/recyclable_compositor_mac.cc
++++ b/ui/compositor/recyclable_compositor_mac.cc
+@@ -12,6 +12,7 @@
+ #include "ui/compositor/compositor.h"
+ #include "ui/compositor/compositor_observer.h"
+ #include "ui/compositor/compositor_switches.h"
++#include "ui/display/types/display_constants.h"
+
+ namespace ui {
+
+@@ -65,7 +66,8 @@ void RecyclableCompositorMac::Unsuspend() {
+ void RecyclableCompositorMac::UpdateSurface(
+ const gfx::Size& size_pixels,
+ float scale_factor,
+- const gfx::DisplayColorSpaces& display_color_spaces) {
++ const gfx::DisplayColorSpaces& display_color_spaces,
++ int64_t display_id) {
+ if (size_pixels != size_pixels_ || scale_factor != scale_factor_) {
+ size_pixels_ = size_pixels;
+ scale_factor_ = scale_factor;
+@@ -75,21 +77,19 @@ void RecyclableCompositorMac::UpdateSurface(
+ compositor()->SetScaleAndSize(scale_factor_, size_pixels_,
+ local_surface_id);
+ }
+- if (display_color_spaces != display_color_spaces_) {
+- display_color_spaces_ = display_color_spaces;
+- compositor()->SetDisplayColorSpaces(display_color_spaces_);
+- }
++ compositor()->SetDisplayColorSpaces(display_color_spaces);
++ compositor()->SetVSyncDisplayID(display_id);
+ }
+
+ void RecyclableCompositorMac::InvalidateSurface() {
+ size_pixels_ = gfx::Size();
+ scale_factor_ = 1.f;
+ local_surface_id_allocator_.Invalidate();
+- display_color_spaces_ = gfx::DisplayColorSpaces();
+ compositor()->SetScaleAndSize(
+ scale_factor_, size_pixels_,
+ local_surface_id_allocator_.GetCurrentLocalSurfaceId());
+ compositor()->SetDisplayColorSpaces(gfx::DisplayColorSpaces());
++ compositor()->SetVSyncDisplayID(display::kInvalidDisplayId);
+ }
+
+ void RecyclableCompositorMac::OnCompositingDidCommit(
+diff --git a/ui/compositor/recyclable_compositor_mac.h b/ui/compositor/recyclable_compositor_mac.h
+index 891204a715de65bce5103b85490bb66de401ba0e..778842bee9395101c6f8b2c182e4b6de7a8a039e 100644
+--- a/ui/compositor/recyclable_compositor_mac.h
++++ b/ui/compositor/recyclable_compositor_mac.h
+@@ -49,7 +49,8 @@ class COMPOSITOR_EXPORT RecyclableCompositorMac
+ // Update the compositor's surface information, if needed.
+ void UpdateSurface(const gfx::Size& size_pixels,
+ float scale_factor,
+- const gfx::DisplayColorSpaces& display_color_spaces);
++ const gfx::DisplayColorSpaces& display_color_spaces,
++ int64_t display_id);
+
+ private:
+ // Invalidate the compositor's surface information.
+@@ -63,7 +64,6 @@ class COMPOSITOR_EXPORT RecyclableCompositorMac
+ viz::ParentLocalSurfaceIdAllocator local_surface_id_allocator_;
+ gfx::Size size_pixels_;
+ float scale_factor_ = 1.f;
+- gfx::DisplayColorSpaces display_color_spaces_;
+
+ std::unique_ptr<ui::AcceleratedWidgetMac> accelerated_widget_mac_;
+ ui::Compositor compositor_;
+diff --git a/ui/views/cocoa/native_widget_mac_ns_window_host.mm b/ui/views/cocoa/native_widget_mac_ns_window_host.mm
+index c6a33c2a85206295426292406291af670ce65ab0..f1f25bf0e19a918c3fcc7b7610ecf2924a880ff4 100644
+--- a/ui/views/cocoa/native_widget_mac_ns_window_host.mm
++++ b/ui/views/cocoa/native_widget_mac_ns_window_host.mm
+@@ -617,7 +617,7 @@ void HandleAccelerator(const ui::Accelerator& accelerator,
+ content_bounds_in_screen_.size(), display_.device_scale_factor()));
+ compositor_->UpdateSurface(content_bounds_in_pixels,
+ display_.device_scale_factor(),
+- display_.color_spaces());
++ display_.color_spaces(), display_.id());
+ }
+
+ void NativeWidgetMacNSWindowHost::DestroyCompositor() {
+@@ -1173,7 +1173,7 @@ void HandleAccelerator(const ui::Accelerator& accelerator,
+ content_bounds_in_screen_.size(), display_.device_scale_factor()));
+ compositor_->UpdateSurface(content_bounds_in_pixels,
+ display_.device_scale_factor(),
+- display_.color_spaces());
++ display_.color_spaces(), display_.id());
+ }
+
+ if (display_id_changed) {
+@@ -1187,7 +1187,6 @@ void HandleAccelerator(const ui::Accelerator& accelerator,
+
+ if (compositor_) {
+ RequestVSyncParametersUpdate();
+- compositor_->compositor()->SetVSyncDisplayID(display_.id());
+ }
+ }
+ }
diff --git a/patches/chromium/cherry-pick-e6e23ba00379.patch b/patches/chromium/cherry-pick-e6e23ba00379.patch
new file mode 100644
index 0000000000..bc52f235dc
--- /dev/null
+++ b/patches/chromium/cherry-pick-e6e23ba00379.patch
@@ -0,0 +1,430 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Christopher Cameron <[email protected]>
+Date: Mon, 15 May 2023 15:30:36 +0200
+Subject: Use ExternalBeginFrameSourceMac on macOS
+
+Change ExternalBeginFrameSourceMac from being a
+SyntheticBeginFrameSource to being an ExternalBeginFrameSource.
+
+Move all of the code that is responsible for updating the VSync
+parameters every 10 seconds from NativeWidgetMacNSWindowHost to
+ExternalBeginFrameSourceMac.
+
+Wire up ExternalBeginFrameSourceMac::SetVSyncDisplayID to create
+the DisplayLinkMac (that was previously created in
+NativeWidgetMacNSWindowHost). Set the VSyncCallbackMac callback in
+ExternalBeginFrameSourceMac to update the timer based VSync
+parameters the same way that was done in SyntheticBeginFrameSource.
+
+Make RootCompositorFrameSinkImpl create a ExternalBeginFrameSourceMac
+instead of creating a DelayBasedBeginFrameSource.
+
+Bug: 1404797
+Change-Id: I288497d94cc66356586e8da34852d53d05cf42f3
+
+diff --git a/components/viz/service/BUILD.gn b/components/viz/service/BUILD.gn
+index 5b0a12d8b69c0b79fefcb9194e0f3fb88c4c7051..8ebcf88eadb7fbc3ce781b9094ec88f6d23134c1 100644
+--- a/components/viz/service/BUILD.gn
++++ b/components/viz/service/BUILD.gn
+@@ -323,6 +323,12 @@ viz_component("service") {
+ frameworks += [ "CoreGraphics.framework" ]
+ }
+ configs = ["//electron/build/config:mas_build"]
++ if (is_mac) {
++ sources += [
++ "frame_sinks/external_begin_frame_source_mac.cc",
++ "frame_sinks/external_begin_frame_source_mac.h",
++ ]
++ }
+ }
+
+ if (is_android || use_ozone) {
+diff --git a/components/viz/service/frame_sinks/DEPS b/components/viz/service/frame_sinks/DEPS
+index 163224a3cdb78d1eee055491c2daa7ca09fe4baa..c0e240ec70f7b7d4da92b497ac607e73d1168923 100644
+--- a/components/viz/service/frame_sinks/DEPS
++++ b/components/viz/service/frame_sinks/DEPS
+@@ -26,4 +26,8 @@ specific_include_rules = {
+ "external_begin_frame_source_android.cc": [
+ "+components/viz/service/service_jni_headers/ExternalBeginFrameSourceAndroid_jni.h",
+ ],
++ "external_begin_frame_source_mac.h": [
++ "+ui/display/mac/display_link_mac.h",
++ "+ui/display/types/display_constants.h",
++ ],
+ }
+diff --git a/components/viz/service/frame_sinks/external_begin_frame_source_mac.cc b/components/viz/service/frame_sinks/external_begin_frame_source_mac.cc
+new file mode 100644
+index 0000000000000000000000000000000000000000..f5bd62e7c486b8e6bb58d59984f363867015486c
+--- /dev/null
++++ b/components/viz/service/frame_sinks/external_begin_frame_source_mac.cc
+@@ -0,0 +1,97 @@
++// Copyright 2023 The Chromium Authors
++// Use of this source code is governed by a BSD-style license that can be
++// found in the LICENSE file.
++
++#include "components/viz/service/frame_sinks/external_begin_frame_source_mac.h"
++
++#include <algorithm>
++#include <memory>
++#include <utility>
++
++#include "base/containers/contains.h"
++#include "base/trace_event/trace_event.h"
++
++namespace viz {
++
++ExternalBeginFrameSourceMac::ExternalBeginFrameSourceMac(
++ std::unique_ptr<DelayBasedTimeSource> time_source,
++ uint32_t restart_id)
++ : ExternalBeginFrameSource(this, restart_id),
++ time_source_(std::move(time_source)) {
++ time_source_->SetClient(this);
++}
++
++ExternalBeginFrameSourceMac::~ExternalBeginFrameSourceMac() = default;
++
++void ExternalBeginFrameSourceMac::SetDynamicBeginFrameDeadlineOffsetSource(
++ DynamicBeginFrameDeadlineOffsetSource*
++ dynamic_begin_frame_deadline_offset_source) {
++ begin_frame_args_generator_.set_dynamic_begin_frame_deadline_offset_source(
++ dynamic_begin_frame_deadline_offset_source);
++}
++
++void ExternalBeginFrameSourceMac::SetVSyncDisplayID(int64_t display_id) {
++ if (display_id_ == display_id) {
++ return;
++ }
++
++ display_id_ = display_id;
++ display_link_ = ui::DisplayLinkMac::GetForDisplay(
++ base::checked_cast<CGDirectDisplayID>(display_id_));
++ time_source_next_update_time_ = base::TimeTicks();
++ RequestTimeSourceParamsUpdate();
++}
++
++void ExternalBeginFrameSourceMac::OnNeedsBeginFrames(bool needs_begin_frames) {
++ if (needs_begin_frames_ == needs_begin_frames) {
++ return;
++ }
++ needs_begin_frames_ = needs_begin_frames;
++
++ DCHECK_NE(time_source_->Active(), needs_begin_frames_);
++ time_source_->SetActive(needs_begin_frames_);
++}
++
++void ExternalBeginFrameSourceMac::OnTimerTick() {
++ // The VSync parameters skew over time (astonishingly quickly -- 0.1 msec per
++ // second). If too much time has elapsed since the last time the vsync
++ // parameters were calculated, re-calculate them.
++ if (base::TimeTicks::Now() >= time_source_next_update_time_) {
++ RequestTimeSourceParamsUpdate();
++ }
++
++ // See comments in DelayBasedBeginFrameSource::OnTimerTick regarding the
++ // computation of `frame_time`.
++ base::TimeTicks frame_time =
++ std::max(time_source_->LastTickTime(),
++ time_source_->NextTickTime() - time_source_->Interval());
++ OnBeginFrame(begin_frame_args_generator_.GenerateBeginFrameArgs(
++ source_id(), frame_time, time_source_->NextTickTime(),
++ time_source_->Interval()));
++}
++
++void ExternalBeginFrameSourceMac::RequestTimeSourceParamsUpdate() {
++ if (!display_link_ || time_source_updater_) {
++ return;
++ }
++ time_source_updater_ = display_link_->RegisterCallback(base::BindRepeating(
++ &ExternalBeginFrameSourceMac::OnTimeSourceParamsUpdate,
++ weak_factory_.GetWeakPtr()));
++}
++
++void ExternalBeginFrameSourceMac::OnTimeSourceParamsUpdate(
++ ui::VSyncParamsMac params) {
++ time_source_next_update_time_ = base::TimeTicks::Now() + base::Seconds(10);
++ time_source_updater_ = nullptr;
++
++ if (params.display_times_valid) {
++ time_source_->SetTimebaseAndInterval(params.display_timebase,
++ params.display_interval);
++ last_timebase_ = params.display_timebase;
++ } else {
++ time_source_->SetTimebaseAndInterval(last_timebase_,
++ BeginFrameArgs::DefaultInterval());
++ }
++}
++
++} // namespace viz
+diff --git a/components/viz/service/frame_sinks/external_begin_frame_source_mac.h b/components/viz/service/frame_sinks/external_begin_frame_source_mac.h
+new file mode 100644
+index 0000000000000000000000000000000000000000..4753f86371d97ec0470e355258bae17e10e77dcf
+--- /dev/null
++++ b/components/viz/service/frame_sinks/external_begin_frame_source_mac.h
+@@ -0,0 +1,74 @@
++// Copyright 2023 The Chromium Authors
++// Use of this source code is governed by a BSD-style license that can be
++// found in the LICENSE file.
++
++#ifndef COMPONENTS_VIZ_SERVICE_FRAME_SINKS_EXTERNAL_BEGIN_FRAME_SOURCE_MAC_H_
++#define COMPONENTS_VIZ_SERVICE_FRAME_SINKS_EXTERNAL_BEGIN_FRAME_SOURCE_MAC_H_
++
++#include <memory>
++
++#include "components/viz/common/frame_sinks/begin_frame_source.h"
++#include "components/viz/service/viz_service_export.h"
++#include "ui/display/mac/display_link_mac.h"
++#include "ui/display/types/display_constants.h"
++
++namespace viz {
++
++// A begin frame source for use on macOS. This behaves like a
++// DelayBasedBeginFrameSource, but, instead of being informed externally of its
++// timebase and interval, it is informed externally of its display::DisplayId
++// and uses that to query its timebase and interval from a DisplayLinkMac.
++class VIZ_COMMON_EXPORT ExternalBeginFrameSourceMac
++ : public ExternalBeginFrameSource,
++ public ExternalBeginFrameSourceClient,
++ public DelayBasedTimeSourceClient {
++ public:
++ ExternalBeginFrameSourceMac(std::unique_ptr<DelayBasedTimeSource> time_source,
++ uint32_t restart_id);
++
++ ExternalBeginFrameSourceMac(const ExternalBeginFrameSourceMac&) = delete;
++ ExternalBeginFrameSourceMac& operator=(const ExternalBeginFrameSourceMac&) =
++ delete;
++ ~ExternalBeginFrameSourceMac() override;
++
++ // BeginFrameSource implementation.
++ void SetDynamicBeginFrameDeadlineOffsetSource(
++ DynamicBeginFrameDeadlineOffsetSource*
++ dynamic_begin_frame_deadline_offset_source) override;
++ void SetVSyncDisplayID(int64_t display_id) override;
++
++ // ExternalBeginFrameSourceClient implementation.
++ void OnNeedsBeginFrames(bool needs_begin_frames) override;
++
++ // DelayBasedTimeSourceClient implementation.
++ void OnTimerTick() override;
++
++ private:
++ // Request a callback from DisplayLinkMac, and the callback function.
++ void RequestTimeSourceParamsUpdate();
++ void OnTimeSourceParamsUpdate(ui::VSyncParamsMac params);
++
++ BeginFrameArgsGenerator begin_frame_args_generator_;
++
++ bool needs_begin_frames_ = false;
++
++ // CVDisplayLink and related structures to set timer parameters.
++ int64_t display_id_ = display::kInvalidDisplayId;
++ scoped_refptr<ui::DisplayLinkMac> display_link_;
++
++ // Timer used to drive callbacks.
++ // TODO(https://crbug.com/1404797): Only use this when it is not possible or
++ // efficient to use `display_link_`.
++ std::unique_ptr<DelayBasedTimeSource> time_source_;
++ base::TimeTicks last_timebase_;
++
++ // The callback that is used to update `time_source_`.
++ base::TimeTicks time_source_next_update_time_;
++ std::unique_ptr<ui::VSyncCallbackMac> time_source_updater_;
++
++ base::WeakPtrFactory<ExternalBeginFrameSourceMac> weak_factory_{this};
++};
++
++} // namespace viz
++
++#endif // COMPONENTS_VIZ_SERVICE_FRAME_SINKS_EXTERNAL_BEGIN_FRAME_SOURCE_MAC_H_
+diff --git a/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc b/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc
+index 13962687d262434de77f76c1c5a0f39f0fd9fb43..4d07b897a158bf39d9b29e3ac90920aee3050ce0 100644
+--- a/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc
++++ b/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc
+@@ -36,6 +36,10 @@
+ #include "components/viz/service/frame_sinks/external_begin_frame_source_ios.h"
+ #endif
+
++#if BUILDFLAG(IS_MAC)
++#include "components/viz/service/frame_sinks/external_begin_frame_source_mac.h"
++#endif
++
+ namespace viz {
+
+ class RootCompositorFrameSinkImpl::StandaloneBeginFrameObserver
+@@ -140,6 +144,11 @@ RootCompositorFrameSinkImpl::Create(
+ hw_support_for_multiple_refresh_rates = true;
+ external_begin_frame_source =
+ std::make_unique<ExternalBeginFrameSourceIOS>(restart_id);
++#elif BUILDFLAG(IS_MAC)
++ external_begin_frame_source = std::make_unique<ExternalBeginFrameSourceMac>(
++ std::make_unique<DelayBasedTimeSource>(
++ base::SingleThreadTaskRunner::GetCurrentDefault().get()),
++ restart_id);
+ #else
+ if (params->disable_frame_rate_limit) {
+ synthetic_begin_frame_source =
+diff --git a/ui/display/mac/screen_mac.mm b/ui/display/mac/screen_mac.mm
+index 0d5ef8c48f08b1eb5ed878ab8934f2ecd04083fa..30f72b9655e790d864fc7e28983b6a37074448a5 100644
+--- a/ui/display/mac/screen_mac.mm
++++ b/ui/display/mac/screen_mac.mm
+@@ -9,6 +9,7 @@
+ #import <Cocoa/Cocoa.h>
+ #include <IOKit/IOKitLib.h>
+ #include <IOKit/graphics/IOGraphicsLib.h>
++#include <QuartzCore/CVDisplayLink.h>
+ #include <stdint.h>
+
+ #include <map>
+@@ -27,7 +28,6 @@
+ #include "base/trace_event/trace_event.h"
+ #include "ui/display/display.h"
+ #include "ui/display/display_change_notifier.h"
+-#include "ui/display/mac/display_link_mac.h"
+ #include "ui/display/util/display_util.h"
+ #include "ui/gfx/geometry/point.h"
+ #include "ui/gfx/icc_profile.h"
+@@ -280,8 +280,22 @@ DisplayMac BuildDisplayForScreen(NSScreen* screen) {
+ display.set_is_monochrome(CGDisplayUsesForceToGray());
+ #endif
+
+- if (auto display_link = ui::DisplayLinkMac::GetForDisplay(display_id))
+- display.set_display_frequency(display_link->GetRefreshRate());
++ // Query the display's referesh rate.
++ {
++ CVDisplayLinkRef display_link = nullptr;
++ if (CVDisplayLinkCreateWithCGDisplay(display_id, &display_link) ==
++ kCVReturnSuccess) {
++ DCHECK(display_link);
++ CVTime cv_time =
++ CVDisplayLinkGetNominalOutputVideoRefreshPeriod(display_link);
++ if (!(cv_time.flags & kCVTimeIsIndefinite)) {
++ double refresh_rate = (static_cast<double>(cv_time.timeScale) /
++ static_cast<double>(cv_time.timeValue));
++ display.set_display_frequency(refresh_rate);
++ }
++ CVDisplayLinkRelease(display_link);
++ }
++ }
+
+ // CGDisplayRotation returns a double. Display::SetRotationAsDegree will
+ // handle the unexpected situations were the angle is not a multiple of 90.
+diff --git a/ui/views/cocoa/native_widget_mac_ns_window_host.h b/ui/views/cocoa/native_widget_mac_ns_window_host.h
+index e63b249a9bdc23545121a513156bfa32e92fec0b..e21c2df5d19bf01271bee91f792a3dbae29c55b7 100644
+--- a/ui/views/cocoa/native_widget_mac_ns_window_host.h
++++ b/ui/views/cocoa/native_widget_mac_ns_window_host.h
+@@ -24,7 +24,6 @@
+ #include "ui/accelerated_widget_mac/accelerated_widget_mac.h"
+ #include "ui/base/cocoa/accessibility_focus_overrider.h"
+ #include "ui/compositor/layer_owner.h"
+-#include "ui/display/mac/display_link_mac.h"
+ #include "ui/views/cocoa/drag_drop_client_mac.h"
+ #include "ui/views/cocoa/native_widget_mac_event_monitor.h"
+ #include "ui/views/views_export.h"
+@@ -421,12 +420,6 @@ class VIEWS_EXPORT NativeWidgetMacNSWindowHost
+ // ui::AcceleratedWidgetMacNSView:
+ void AcceleratedWidgetCALayerParamsUpdated() override;
+
+- // If `display_link_` is valid and `display_link_updater_` does not exist,
+- // create it. It will call back to OnVSyncParametersUpdated with new VSync
+- // parameters.
+- void RequestVSyncParametersUpdate();
+- void OnVSyncParametersUpdated(ui::VSyncParamsMac params);
+-
+ // The id that this bridge may be looked up from.
+ const uint64_t widget_id_;
+ const raw_ptr<views::NativeWidgetMac>
+@@ -494,15 +487,6 @@ class VIEWS_EXPORT NativeWidgetMacNSWindowHost
+ // The display that the window is currently on.
+ display::Display display_;
+
+- // Display link for getting vsync info for `display_`, and VSyncCallbackMac to
+- // use for callbacks.
+- scoped_refptr<ui::DisplayLinkMac> display_link_;
+- std::unique_ptr<ui::VSyncCallbackMac> display_link_updater_;
+-
+- // Updating VSync parameters can be expensive, so set this to the next time
+- // when we should update VSync parameters.
+- base::TimeTicks display_link_next_update_time_;
+-
+ // The geometry of the window and its contents view, in screen coordinates.
+ gfx::Rect window_bounds_in_screen_;
+ gfx::Rect content_bounds_in_screen_;
+diff --git a/ui/views/cocoa/native_widget_mac_ns_window_host.mm b/ui/views/cocoa/native_widget_mac_ns_window_host.mm
+index f1f25bf0e19a918c3fcc7b7610ecf2924a880ff4..a0c9f71c5eb97091941ba7d9955854af74bd67d5 100644
+--- a/ui/views/cocoa/native_widget_mac_ns_window_host.mm
++++ b/ui/views/cocoa/native_widget_mac_ns_window_host.mm
+@@ -1163,32 +1163,19 @@ void HandleAccelerator(const ui::Accelerator& accelerator,
+
+ void NativeWidgetMacNSWindowHost::OnWindowDisplayChanged(
+ const display::Display& new_display) {
+- bool display_id_changed = display_.id() != new_display.id();
+ display_ = new_display;
+- if (compositor_) {
+- // Mac device scale factor is always an integer so the result here is an
+- // integer pixel size.
+- gfx::Size content_bounds_in_pixels =
+- gfx::ToRoundedSize(gfx::ConvertSizeToPixels(
+- content_bounds_in_screen_.size(), display_.device_scale_factor()));
+- compositor_->UpdateSurface(content_bounds_in_pixels,
+- display_.device_scale_factor(),
+- display_.color_spaces(), display_.id());
++ if (!compositor_) {
++ return;
+ }
+
+- if (display_id_changed) {
+- display_link_ = ui::DisplayLinkMac::GetForDisplay(
+- base::checked_cast<CGDirectDisplayID>(display_.id()));
+- if (!display_link_) {
+- // Note that on some headless systems, the display link will fail to be
+- // created, so this should not be a fatal error.
+- LOG(ERROR) << "Failed to create display link.";
+- }
+-
+- if (compositor_) {
+- RequestVSyncParametersUpdate();
+- }
+- }
++ // Mac device scale factor is always an integer so the result here is an
++ // integer pixel size.
++ gfx::Size content_bounds_in_pixels =
++ gfx::ToRoundedSize(gfx::ConvertSizeToPixels(
++ content_bounds_in_screen_.size(), display_.device_scale_factor()));
++ compositor_->UpdateSurface(content_bounds_in_pixels,
++ display_.device_scale_factor(),
++ display_.color_spaces(), display_.id());
+ }
+
+ void NativeWidgetMacNSWindowHost::OnWindowWillClose() {
+@@ -1619,32 +1606,6 @@ void HandleAccelerator(const ui::Accelerator& accelerator,
+ void NativeWidgetMacNSWindowHost::AcceleratedWidgetCALayerParamsUpdated() {
+ if (const auto* ca_layer_params = compositor_->widget()->GetCALayerParams())
+ GetNSWindowMojo()->SetCALayerParams(*ca_layer_params);
+-
+- // The VSync parameters skew over time (astonishingly quickly -- 0.1 msec per
+- // second). If too much time has elapsed since the last time the vsync
+- // parameters were calculated, re-calculate them.
+- if (base::TimeTicks::Now() >= display_link_next_update_time_) {
+- RequestVSyncParametersUpdate();
+- }
+-}
+-
+-void NativeWidgetMacNSWindowHost::RequestVSyncParametersUpdate() {
+- if (!display_link_ || display_link_updater_) {
+- return;
+- }
+- display_link_updater_ = display_link_->RegisterCallback(base::BindRepeating(
+- &NativeWidgetMacNSWindowHost::OnVSyncParametersUpdated,
+- weak_factory_for_vsync_update_.GetWeakPtr()));
+-}
+-
+-void NativeWidgetMacNSWindowHost::OnVSyncParametersUpdated(
+- ui::VSyncParamsMac params) {
+- if (compositor_ && params.display_times_valid) {
+- compositor_->compositor()->SetDisplayVSyncParameters(
+- params.display_timebase, params.display_interval);
+- display_link_next_update_time_ = base::TimeTicks::Now() + base::Seconds(10);
+- }
+- display_link_updater_ = nullptr;
+ }
+
+ } // namespace views
|
chore
|
2222920429b37248ecc9fa3ebb0d1171b7f39196
|
Sam Maddock
|
2024-12-02 23:32:24
|
feat: WebFrameMain.collectJavaScriptCallStack() (#44204)
* feat: WebFrameMain.unresponsiveDocumentJSCallStack
* Revert "feat: WebFrameMain.unresponsiveDocumentJSCallStack"
This reverts commit e0612bc1a00a5282cba5df97da3c9c90e96ef244.
* feat: frame.collectJavaScriptCallStack()
* feat: frame.collectJavaScriptCallStack()
* Update web-frame-main.md
|
diff --git a/docs/api/web-frame-main.md b/docs/api/web-frame-main.md
index 87d35051f0..45b01d5b25 100644
--- a/docs/api/web-frame-main.md
+++ b/docs/api/web-frame-main.md
@@ -142,6 +142,29 @@ ipcRenderer.on('port', (e, msg) => {
})
```
+#### `frame.collectJavaScriptCallStack()` _Experimental_
+
+Returns `Promise<string> | Promise<void>` - A promise that resolves with the currently running JavaScript call
+stack. If no JavaScript runs in the frame, the promise will never resolve. In cases where the call stack is
+otherwise unable to be collected, it will return `undefined`.
+
+This can be useful to determine why the frame is unresponsive in cases where there's long-running JavaScript.
+For more information, see the [proposed Crash Reporting API.](https://wicg.github.io/crash-reporting/)
+
+```js
+const { app } = require('electron')
+
+app.commandLine.appendSwitch('enable-features', 'DocumentPolicyIncludeJSCallStacksInCrashReports')
+
+app.on('web-contents-created', (_, webContents) => {
+ webContents.on('unresponsive', async () => {
+ // Interrupt execution and collect call stack from unresponsive renderer
+ const callStack = await webContents.mainFrame.collectJavaScriptCallStack()
+ console.log('Renderer unresponsive\n', callStack)
+ })
+})
+```
+
### Instance Properties
#### `frame.ipc` _Readonly_
diff --git a/shell/browser/api/electron_api_web_frame_main.cc b/shell/browser/api/electron_api_web_frame_main.cc
index 6415e3019f..7ced5e5763 100644
--- a/shell/browser/api/electron_api_web_frame_main.cc
+++ b/shell/browser/api/electron_api_web_frame_main.cc
@@ -9,9 +9,11 @@
#include <utility>
#include <vector>
+#include "base/feature_list.h"
#include "base/logging.h"
#include "base/no_destructor.h"
#include "content/browser/renderer_host/render_frame_host_impl.h" // nogncheck
+#include "content/browser/renderer_host/render_process_host_impl.h" // nogncheck
#include "content/public/browser/frame_tree_node_id.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/common/isolated_world_ids.h"
@@ -429,6 +431,61 @@ std::vector<content::RenderFrameHost*> WebFrameMain::FramesInSubtree() const {
return frame_hosts;
}
+v8::Local<v8::Promise> WebFrameMain::CollectDocumentJSCallStack(
+ gin::Arguments* args) {
+ gin_helper::Promise<base::Value> promise(args->isolate());
+ v8::Local<v8::Promise> handle = promise.GetHandle();
+
+ if (render_frame_disposed_) {
+ promise.RejectWithErrorMessage(
+ "Render frame was disposed before WebFrameMain could be accessed");
+ return handle;
+ }
+
+ if (!base::FeatureList::IsEnabled(
+ blink::features::kDocumentPolicyIncludeJSCallStacksInCrashReports)) {
+ promise.RejectWithErrorMessage(
+ "DocumentPolicyIncludeJSCallStacksInCrashReports is not enabled");
+ return handle;
+ }
+
+ content::RenderProcessHostImpl* rph_impl =
+ static_cast<content::RenderProcessHostImpl*>(render_frame_->GetProcess());
+
+ rph_impl->GetJavaScriptCallStackGeneratorInterface()
+ ->CollectJavaScriptCallStack(
+ base::BindOnce(&WebFrameMain::CollectedJavaScriptCallStack,
+ weak_factory_.GetWeakPtr(), std::move(promise)));
+
+ return handle;
+}
+
+void WebFrameMain::CollectedJavaScriptCallStack(
+ gin_helper::Promise<base::Value> promise,
+ const std::string& untrusted_javascript_call_stack,
+ const std::optional<blink::LocalFrameToken>& remote_frame_token) {
+ if (render_frame_disposed_) {
+ promise.RejectWithErrorMessage(
+ "Render frame was disposed before call stack was received");
+ return;
+ }
+
+ const blink::LocalFrameToken& frame_token = render_frame_->GetFrameToken();
+ if (remote_frame_token == frame_token) {
+ base::Value base_value(untrusted_javascript_call_stack);
+ promise.Resolve(base_value);
+ } else if (!remote_frame_token) {
+ // Failed to collect call stack. See logic in:
+ // third_party/blink/renderer/controller/javascript_call_stack_collector.cc
+ promise.Resolve(base::Value());
+ } else {
+ // Requests for call stacks can be initiated on an old RenderProcessHost
+ // then be received after a frame swap.
+ LOG(ERROR) << "Received call stack from old RPH";
+ promise.Resolve(base::Value());
+ }
+}
+
void WebFrameMain::DOMContentLoaded() {
Emit("dom-ready");
}
@@ -461,6 +518,8 @@ void WebFrameMain::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin_helper::ObjectTemplateBuilder(isolate, templ)
.SetMethod("executeJavaScript", &WebFrameMain::ExecuteJavaScript)
+ .SetMethod("collectJavaScriptCallStack",
+ &WebFrameMain::CollectDocumentJSCallStack)
.SetMethod("reload", &WebFrameMain::Reload)
.SetMethod("isDestroyed", &WebFrameMain::IsDestroyed)
.SetMethod("_send", &WebFrameMain::Send)
diff --git a/shell/browser/api/electron_api_web_frame_main.h b/shell/browser/api/electron_api_web_frame_main.h
index 5f765dca48..07d50afb8c 100644
--- a/shell/browser/api/electron_api_web_frame_main.h
+++ b/shell/browser/api/electron_api_web_frame_main.h
@@ -36,6 +36,11 @@ template <typename T>
class Handle;
} // namespace gin
+namespace gin_helper {
+template <typename T>
+class Promise;
+} // namespace gin_helper
+
namespace electron::api {
class WebContents;
@@ -128,6 +133,12 @@ class WebFrameMain final : public gin::Wrappable<WebFrameMain>,
std::vector<content::RenderFrameHost*> Frames() const;
std::vector<content::RenderFrameHost*> FramesInSubtree() const;
+ v8::Local<v8::Promise> CollectDocumentJSCallStack(gin::Arguments* args);
+ void CollectedJavaScriptCallStack(
+ gin_helper::Promise<base::Value> promise,
+ const std::string& untrusted_javascript_call_stack,
+ const std::optional<blink::LocalFrameToken>& remote_frame_token);
+
void DOMContentLoaded();
mojo::Remote<mojom::ElectronRenderer> renderer_api_;
diff --git a/spec/api-web-frame-main-spec.ts b/spec/api-web-frame-main-spec.ts
index 9d1c9edae7..6a1a5873db 100644
--- a/spec/api-web-frame-main-spec.ts
+++ b/spec/api-web-frame-main-spec.ts
@@ -21,8 +21,16 @@ describe('webFrameMain module', () => {
type Server = { server: http.Server, url: string, crossOriginUrl: string }
/** Creates an HTTP server whose handler embeds the given iframe src. */
- const createServer = async (): Promise<Server> => {
+ const createServer = async (options: {
+ headers?: Record<string, string>
+ } = {}): Promise<Server> => {
const server = http.createServer((req, res) => {
+ if (options.headers) {
+ for (const [k, v] of Object.entries(options.headers)) {
+ res.setHeader(k, v);
+ }
+ }
+
const params = new URLSearchParams(new URL(req.url || '', `http://${req.headers.host}`).search || '');
if (params.has('frameSrc')) {
res.end(`<iframe src="${params.get('frameSrc')}"></iframe>`);
@@ -444,6 +452,29 @@ describe('webFrameMain module', () => {
});
});
+ describe('webFrameMain.collectJavaScriptCallStack', () => {
+ let server: Server;
+ before(async () => {
+ server = await createServer({
+ headers: {
+ 'Document-Policy': 'include-js-call-stacks-in-crash-reports'
+ }
+ });
+ });
+ after(() => {
+ server.server.close();
+ });
+
+ it('collects call stack during JS execution', async () => {
+ const w = new BrowserWindow({ show: false });
+ await w.loadURL(server.url);
+ const callStackPromise = w.webContents.mainFrame.collectJavaScriptCallStack();
+ w.webContents.mainFrame.executeJavaScript('"run a lil js"');
+ const callStack = await callStackPromise;
+ expect(callStack).to.be.a('string');
+ });
+ });
+
describe('"frame-created" event', () => {
it('emits when the main frame is created', async () => {
const w = new BrowserWindow({ show: false });
diff --git a/spec/index.js b/spec/index.js
index 344b006156..985d0b43ae 100644
--- a/spec/index.js
+++ b/spec/index.js
@@ -33,6 +33,12 @@ app.commandLine.appendSwitch('host-resolver-rules', [
'MAP notfound.localhost2 ~NOTFOUND'
].join(', '));
+// Enable features required by tests.
+app.commandLine.appendSwitch('enable-features', [
+ // spec/api-web-frame-main-spec.ts
+ 'DocumentPolicyIncludeJSCallStacksInCrashReports'
+].join(','));
+
global.standardScheme = 'app';
global.zoomScheme = 'zoom';
global.serviceWorkerScheme = 'sw';
|
feat
|
f56a26c4f70dca6e9468ba15a82007d4a9ad53d6
|
Shelley Vohr
|
2023-01-09 19:16:58
|
build: fix broken stale issues workflow (#36843)
|
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
index 47333e4954..b9a1248bf1 100644
--- a/.github/workflows/stale.yml
+++ b/.github/workflows/stale.yml
@@ -24,6 +24,7 @@ jobs:
exempt-issue-labels: "discussion,security \U0001F512,enhancement :sparkles:"
only-pr-labels: not-a-real-label
pending-repro:
+ runs-on: ubuntu-latest
steps:
- uses: actions/stale@3de2653986ebd134983c79fe2be5d45cc3d9f4e1
with:
|
build
|
41ab5f327f8ab820e8559334f0ac0e6208f59d7e
|
Charles Kerr
|
2023-06-16 00:44:19
|
refactor: remove unused InspectableWebContentsView::GetWebView() (#38799)
|
diff --git a/shell/browser/ui/inspectable_web_contents_view.h b/shell/browser/ui/inspectable_web_contents_view.h
index d2c9cc54c9..fb10cbf5d4 100644
--- a/shell/browser/ui/inspectable_web_contents_view.h
+++ b/shell/browser/ui/inspectable_web_contents_view.h
@@ -44,10 +44,6 @@ class InspectableWebContentsView {
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
// Returns the container control, which has devtools view attached.
virtual views::View* GetView() = 0;
-
- // Returns the web view control, which can be used by the
- // GetInitiallyFocusedView() to set initial focus to web view.
- virtual views::View* GetWebView() = 0;
#else
virtual gfx::NativeView GetNativeView() const = 0;
#endif
diff --git a/shell/browser/ui/views/inspectable_web_contents_view_views.cc b/shell/browser/ui/views/inspectable_web_contents_view_views.cc
index 6ddc8bcb43..b9def2941a 100644
--- a/shell/browser/ui/views/inspectable_web_contents_view_views.cc
+++ b/shell/browser/ui/views/inspectable_web_contents_view_views.cc
@@ -108,10 +108,6 @@ views::View* InspectableWebContentsViewViews::GetView() {
return this;
}
-views::View* InspectableWebContentsViewViews::GetWebView() {
- return contents_web_view_;
-}
-
void InspectableWebContentsViewViews::ShowDevTools(bool activate) {
if (devtools_visible_)
return;
diff --git a/shell/browser/ui/views/inspectable_web_contents_view_views.h b/shell/browser/ui/views/inspectable_web_contents_view_views.h
index c30de470c6..f3c364b196 100644
--- a/shell/browser/ui/views/inspectable_web_contents_view_views.h
+++ b/shell/browser/ui/views/inspectable_web_contents_view_views.h
@@ -31,7 +31,6 @@ class InspectableWebContentsViewViews : public InspectableWebContentsView,
// InspectableWebContentsView:
views::View* GetView() override;
- views::View* GetWebView() override;
void ShowDevTools(bool activate) override;
void CloseDevTools() override;
bool IsDevToolsViewShowing() override;
|
refactor
|
be45614f6f0928dfac6248efaa042a5e5bf8322d
|
Dani Haro
|
2023-06-08 08:51:49
|
docs: indicate `app.setBadgeCount()` needs notifications permission to work (#38648)
docs: match docs for `app.badgeCount` and `app.setBadgeCount()`
|
diff --git a/docs/api/app.md b/docs/api/app.md
index 35b6da350e..23cf19e5f4 100755
--- a/docs/api/app.md
+++ b/docs/api/app.md
@@ -1276,6 +1276,9 @@ On macOS, it shows on the dock icon. On Linux, it only works for Unity launcher.
**Note:** Unity launcher requires a `.desktop` file to work. For more information,
please read the [Unity integration documentation][unity-requirement].
+**Note:** On macOS, you need to ensure that your application has the permission
+to display notifications for this method to work.
+
### `app.getBadgeCount()` _Linux_ _macOS_
Returns `Integer` - The current value displayed in the counter badge.
|
docs
|
73d480d40171b101e37ad04d7195893f01c72052
|
John Kleinschmidt
|
2024-09-05 04:08:27
|
build: fix telemetry error when using autoninja (#43563)
|
diff --git a/appveyor-woa.yml b/appveyor-woa.yml
index 39c61f327f..1c630ba059 100644
--- a/appveyor-woa.yml
+++ b/appveyor-woa.yml
@@ -95,6 +95,8 @@ for:
- git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git
- ps: New-Item -Name depot_tools\.disable_auto_update -ItemType File
- depot_tools\bootstrap\win_tools.bat
+ - ps: |
+ Set-Content -Path $pwd\depot_tools\build_telemetry.cfg -Value '{"user": "[email protected]", "status": "opt-out", "countdown": 10, "version": 1}'
- ps: $env:PATH="$pwd\depot_tools;$env:PATH"
- ps: >-
if (Test-Path -Path "$pwd\src\electron") {
diff --git a/appveyor.yml b/appveyor.yml
index d92636c360..9fcf286b21 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -93,6 +93,8 @@ for:
- git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git
- ps: New-Item -Name depot_tools\.disable_auto_update -ItemType File
- depot_tools\bootstrap\win_tools.bat
+ - ps: |
+ Set-Content -Path $pwd\depot_tools\build_telemetry.cfg -Value '{"user": "[email protected]", "status": "opt-out", "countdown": 10, "version": 1}'
- ps: $env:PATH="$pwd\depot_tools;$env:PATH"
- ps: >-
if (Test-Path -Path "$pwd\src\electron") {
|
build
|
ae0c55c0b19fc317708e573d30d6d10ea9777a13
|
Charles Kerr
|
2024-05-29 13:07:02
|
refactor: inherit Observer classes privately, pt. 2 (#42237)
* refactor: use private inheritance in PushNotifications
* refactor: use private inheritance in electron::api::App
* refactor: use private inheritance in electron::api::BrowserWindow
* refactor: use private inheritance in electron::api::NativeTheme
* refactor: use private inheritance in electron::api::Tray
* refactor: use private inheritance in electron::api::Session
* refactor: use private inheritance in electron::api::WebContents
* refactor: use private inheritance in electron::api::DownloadItem
* refactor: use private inheritance in electron::api::MenuBar
* refactor: use private inheritance in ClearDataOperation
* refactor: use private inheritance in electron::api::Screen
* refactor: use private inheritance in electron::ElectronDesktopWindowTreeHostLinux
* refactor: use private inheritance in SpellCheckerHolder
* refactor: use private inheritance in electron::api::PowerMonitor
* refactor: use private inheritance in electron::api::BaseWindow
* refactor: use private inheritance in electron::api::AutoUpdater
* refactor: use private inheritance in electron::api::Menu
* refactor: use private inheritance in electron::api::NativeWindowViews
* refactor: use private inheritance in electron::ElectronBrowserClient
* refactor: use private inheritance in electron::AutofillPopupView
* refactor: use private inheritance in GtkMessageBox
* refactor: use private inheritance in electron::OffScreenRenderWidgetHostView
* refactor: use private inheritance in electron::InspectableWebContents
* refactor: use private inheritance in electron::ElectronUsbDelegate
* refactor: use private inheritance in electron::LoginHandler
* refactor: use private inheritance in WebFrameRenderer
* refactor: use private inheritance in electron::ElectronSerialDelegate
* refactor: use private inheritance in electron::ClientFrameViewLinux
* refactor: use private inheritance in electron::ElectronHidDelegate
* refactor: use private inheritance in IPCRenderer
* refactor: use private inheritance in electron::WinCaptionButtonContainer
* refactor: use private inheritance in electron::ElectronApiIPCHandlerImpl
* refactor: use private inheritance in electron::api::ServiceWorkerContext
* refactor: use private inheritance in ui::FileSelectHelper
* refactor: use private inheritance in electron::api::WebContentsView
* refactor: use private inheritance in electron::api::SimpleURLLoaderWrapper
* refactor: use private inheritance in electron::api::InAppPurchase
* refactor: use private inheritance in electron::api::Debugger
* refactor: use private inheritance in electron::ElectronWebContentsUtilityHandlerImpl
* refactor: use private inheritance in electron::OffScreenWebContentsView
|
diff --git a/shell/browser/api/electron_api_app.h b/shell/browser/api/electron_api_app.h
index 96f47b273a..f03fc96d85 100644
--- a/shell/browser/api/electron_api_app.h
+++ b/shell/browser/api/electron_api_app.h
@@ -50,9 +50,9 @@ namespace api {
class App : public ElectronBrowserClient::Delegate,
public gin::Wrappable<App>,
public gin_helper::EventEmitterMixin<App>,
- public BrowserObserver,
- public content::GpuDataManagerObserver,
- public content::BrowserChildProcessObserver {
+ private BrowserObserver,
+ private content::GpuDataManagerObserver,
+ private content::BrowserChildProcessObserver {
public:
using FileIconCallback =
base::RepeatingCallback<void(v8::Local<v8::Value>, const gfx::Image&)>;
diff --git a/shell/browser/api/electron_api_auto_updater.h b/shell/browser/api/electron_api_auto_updater.h
index aadbd7543c..50c771fddb 100644
--- a/shell/browser/api/electron_api_auto_updater.h
+++ b/shell/browser/api/electron_api_auto_updater.h
@@ -18,7 +18,7 @@ namespace electron::api {
class AutoUpdater : public gin::Wrappable<AutoUpdater>,
public gin_helper::EventEmitterMixin<AutoUpdater>,
public auto_updater::Delegate,
- public WindowListObserver {
+ private WindowListObserver {
public:
static gin::Handle<AutoUpdater> Create(v8::Isolate* isolate);
diff --git a/shell/browser/api/electron_api_base_window.h b/shell/browser/api/electron_api_base_window.h
index 46043f284f..c4bd0a8799 100644
--- a/shell/browser/api/electron_api_base_window.h
+++ b/shell/browser/api/electron_api_base_window.h
@@ -26,7 +26,7 @@ namespace electron::api {
class View;
class BaseWindow : public gin_helper::TrackableObject<BaseWindow>,
- public NativeWindowObserver {
+ private NativeWindowObserver {
public:
static gin_helper::WrappableBase* New(gin_helper::Arguments* args);
diff --git a/shell/browser/api/electron_api_browser_window.h b/shell/browser/api/electron_api_browser_window.h
index e752d1ed59..2ad029bc03 100644
--- a/shell/browser/api/electron_api_browser_window.h
+++ b/shell/browser/api/electron_api_browser_window.h
@@ -16,8 +16,8 @@
namespace electron::api {
class BrowserWindow : public BaseWindow,
- public content::WebContentsObserver,
- public ExtendedWebContentsObserver {
+ private content::WebContentsObserver,
+ private ExtendedWebContentsObserver {
public:
static gin_helper::WrappableBase* New(gin_helper::ErrorThrower thrower,
gin::Arguments* args);
diff --git a/shell/browser/api/electron_api_debugger.h b/shell/browser/api/electron_api_debugger.h
index 7429961948..deda78c6cd 100644
--- a/shell/browser/api/electron_api_debugger.h
+++ b/shell/browser/api/electron_api_debugger.h
@@ -28,7 +28,7 @@ namespace electron::api {
class Debugger : public gin::Wrappable<Debugger>,
public gin_helper::EventEmitterMixin<Debugger>,
public content::DevToolsAgentHostClient,
- public content::WebContentsObserver {
+ private content::WebContentsObserver {
public:
static gin::Handle<Debugger> Create(v8::Isolate* isolate,
content::WebContents* web_contents);
diff --git a/shell/browser/api/electron_api_download_item.h b/shell/browser/api/electron_api_download_item.h
index 7b240aa10a..f04953a8d3 100644
--- a/shell/browser/api/electron_api_download_item.h
+++ b/shell/browser/api/electron_api_download_item.h
@@ -24,7 +24,7 @@ namespace electron::api {
class DownloadItem : public gin::Wrappable<DownloadItem>,
public gin_helper::Pinnable<DownloadItem>,
public gin_helper::EventEmitterMixin<DownloadItem>,
- public download::DownloadItem::Observer {
+ private download::DownloadItem::Observer {
public:
static gin::Handle<DownloadItem> FromOrCreate(v8::Isolate* isolate,
download::DownloadItem* item);
diff --git a/shell/browser/api/electron_api_in_app_purchase.h b/shell/browser/api/electron_api_in_app_purchase.h
index 4b64641054..e89a7ca691 100644
--- a/shell/browser/api/electron_api_in_app_purchase.h
+++ b/shell/browser/api/electron_api_in_app_purchase.h
@@ -20,7 +20,7 @@ namespace electron::api {
class InAppPurchase : public gin::Wrappable<InAppPurchase>,
public gin_helper::EventEmitterMixin<InAppPurchase>,
- public in_app_purchase::TransactionObserver {
+ private in_app_purchase::TransactionObserver {
public:
static gin::Handle<InAppPurchase> Create(v8::Isolate* isolate);
diff --git a/shell/browser/api/electron_api_menu.h b/shell/browser/api/electron_api_menu.h
index 697fbd950f..c12fda7e93 100644
--- a/shell/browser/api/electron_api_menu.h
+++ b/shell/browser/api/electron_api_menu.h
@@ -24,7 +24,7 @@ class Menu : public gin::Wrappable<Menu>,
public gin_helper::Constructible<Menu>,
public gin_helper::Pinnable<Menu>,
public ElectronMenuModel::Delegate,
- public ElectronMenuModel::Observer {
+ private ElectronMenuModel::Observer {
public:
// gin_helper::Constructible
static gin::Handle<Menu> New(gin::Arguments* args);
diff --git a/shell/browser/api/electron_api_native_theme.h b/shell/browser/api/electron_api_native_theme.h
index 6be9c008e0..a1f7798014 100644
--- a/shell/browser/api/electron_api_native_theme.h
+++ b/shell/browser/api/electron_api_native_theme.h
@@ -16,7 +16,7 @@ namespace electron::api {
class NativeTheme : public gin::Wrappable<NativeTheme>,
public gin_helper::EventEmitterMixin<NativeTheme>,
- public ui::NativeThemeObserver {
+ private ui::NativeThemeObserver {
public:
static gin::Handle<NativeTheme> Create(v8::Isolate* isolate);
diff --git a/shell/browser/api/electron_api_power_monitor.h b/shell/browser/api/electron_api_power_monitor.h
index 01f3aced32..436fd9c0f8 100644
--- a/shell/browser/api/electron_api_power_monitor.h
+++ b/shell/browser/api/electron_api_power_monitor.h
@@ -20,9 +20,9 @@ namespace electron::api {
class PowerMonitor : public gin::Wrappable<PowerMonitor>,
public gin_helper::EventEmitterMixin<PowerMonitor>,
public gin_helper::Pinnable<PowerMonitor>,
- public base::PowerStateObserver,
- public base::PowerSuspendObserver,
- public base::PowerThermalObserver {
+ private base::PowerStateObserver,
+ private base::PowerSuspendObserver,
+ private base::PowerThermalObserver {
public:
static v8::Local<v8::Value> Create(v8::Isolate* isolate);
diff --git a/shell/browser/api/electron_api_push_notifications.h b/shell/browser/api/electron_api_push_notifications.h
index 19f29d83d5..6f1e9f1215 100644
--- a/shell/browser/api/electron_api_push_notifications.h
+++ b/shell/browser/api/electron_api_push_notifications.h
@@ -21,7 +21,7 @@ class PushNotifications
: public ElectronBrowserClient::Delegate,
public gin::Wrappable<PushNotifications>,
public gin_helper::EventEmitterMixin<PushNotifications>,
- public BrowserObserver {
+ private BrowserObserver {
public:
static PushNotifications* Get();
static gin::Handle<PushNotifications> Create(v8::Isolate* isolate);
diff --git a/shell/browser/api/electron_api_screen.h b/shell/browser/api/electron_api_screen.h
index ca29a79f5d..19ce4d40db 100644
--- a/shell/browser/api/electron_api_screen.h
+++ b/shell/browser/api/electron_api_screen.h
@@ -24,7 +24,7 @@ namespace electron::api {
class Screen : public gin::Wrappable<Screen>,
public gin_helper::EventEmitterMixin<Screen>,
- public display::DisplayObserver {
+ private display::DisplayObserver {
public:
static v8::Local<v8::Value> Create(gin_helper::ErrorThrower error_thrower);
diff --git a/shell/browser/api/electron_api_service_worker_context.h b/shell/browser/api/electron_api_service_worker_context.h
index 9a6a6cd671..52f617e59e 100644
--- a/shell/browser/api/electron_api_service_worker_context.h
+++ b/shell/browser/api/electron_api_service_worker_context.h
@@ -21,7 +21,7 @@ namespace api {
class ServiceWorkerContext
: public gin::Wrappable<ServiceWorkerContext>,
public gin_helper::EventEmitterMixin<ServiceWorkerContext>,
- public content::ServiceWorkerContextObserver {
+ private content::ServiceWorkerContextObserver {
public:
static gin::Handle<ServiceWorkerContext> Create(
v8::Isolate* isolate,
diff --git a/shell/browser/api/electron_api_session.cc b/shell/browser/api/electron_api_session.cc
index 69e10b10f7..191f632e75 100644
--- a/shell/browser/api/electron_api_session.cc
+++ b/shell/browser/api/electron_api_session.cc
@@ -262,7 +262,7 @@ class ClearDataTask {
// of a full |ClearDataTask|. This class manages its own lifetime, cleaning
// itself up after the operation completes and notifies the task of the
// result.
- class ClearDataOperation : public BrowsingDataRemover::Observer {
+ class ClearDataOperation : private BrowsingDataRemover::Observer {
public:
static void Run(std::shared_ptr<ClearDataTask> task,
BrowsingDataRemover* remover,
diff --git a/shell/browser/api/electron_api_session.h b/shell/browser/api/electron_api_session.h
index 1efe2296fa..0af8a72f0c 100644
--- a/shell/browser/api/electron_api_session.h
+++ b/shell/browser/api/electron_api_session.h
@@ -65,12 +65,12 @@ class Session : public gin::Wrappable<Session>,
public gin_helper::EventEmitterMixin<Session>,
public gin_helper::CleanedUpAtExit,
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
- public SpellcheckHunspellDictionary::Observer,
+ private SpellcheckHunspellDictionary::Observer,
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
- public extensions::ExtensionRegistryObserver,
+ private extensions::ExtensionRegistryObserver,
#endif
- public content::DownloadManager::Observer {
+ private content::DownloadManager::Observer {
public:
// Gets or creates Session from the |browser_context|.
static gin::Handle<Session> CreateFrom(
diff --git a/shell/browser/api/electron_api_tray.h b/shell/browser/api/electron_api_tray.h
index 26429e9ee8..9eaebb5066 100644
--- a/shell/browser/api/electron_api_tray.h
+++ b/shell/browser/api/electron_api_tray.h
@@ -39,7 +39,7 @@ class Tray : public gin::Wrappable<Tray>,
public gin_helper::Constructible<Tray>,
public gin_helper::CleanedUpAtExit,
public gin_helper::Pinnable<Tray>,
- public TrayIconObserver {
+ private TrayIconObserver {
public:
// gin_helper::Constructible
static gin::Handle<Tray> New(gin_helper::ErrorThrower thrower,
diff --git a/shell/browser/api/electron_api_web_contents.h b/shell/browser/api/electron_api_web_contents.h
index a34a4bbe80..07fd3ad8da 100644
--- a/shell/browser/api/electron_api_web_contents.h
+++ b/shell/browser/api/electron_api_web_contents.h
@@ -111,7 +111,7 @@ class WebContents : public ExclusiveAccessContext,
public gin_helper::CleanedUpAtExit,
public content::WebContentsObserver,
public content::WebContentsDelegate,
- public content::RenderWidgetHost::InputEventObserver,
+ private content::RenderWidgetHost::InputEventObserver,
public content::JavaScriptDialogManager,
public InspectableWebContentsDelegate,
public InspectableWebContentsViewDelegate,
diff --git a/shell/browser/api/electron_api_web_contents_view.h b/shell/browser/api/electron_api_web_contents_view.h
index 353086427b..b02c3a460d 100644
--- a/shell/browser/api/electron_api_web_contents_view.h
+++ b/shell/browser/api/electron_api_web_contents_view.h
@@ -21,7 +21,7 @@ namespace electron::api {
class WebContents;
class WebContentsView : public View,
- public content::WebContentsObserver,
+ private content::WebContentsObserver,
public DraggableRegionProvider {
public:
// Create a new instance of WebContentsView.
diff --git a/shell/browser/electron_api_ipc_handler_impl.h b/shell/browser/electron_api_ipc_handler_impl.h
index 1a0ad3a013..96e9a620eb 100644
--- a/shell/browser/electron_api_ipc_handler_impl.h
+++ b/shell/browser/electron_api_ipc_handler_impl.h
@@ -20,7 +20,7 @@ class RenderFrameHost;
namespace electron {
class ElectronApiIPCHandlerImpl : public mojom::ElectronApiIPC,
- public content::WebContentsObserver {
+ private content::WebContentsObserver {
public:
explicit ElectronApiIPCHandlerImpl(
content::RenderFrameHost* render_frame_host,
diff --git a/shell/browser/electron_browser_client.h b/shell/browser/electron_browser_client.h
index 9f3f7fe8df..39e6b90c72 100644
--- a/shell/browser/electron_browser_client.h
+++ b/shell/browser/electron_browser_client.h
@@ -43,7 +43,7 @@ class PlatformNotificationService;
class ElectronWebAuthenticationDelegate;
class ElectronBrowserClient : public content::ContentBrowserClient,
- public content::RenderProcessHostObserver {
+ private content::RenderProcessHostObserver {
public:
static ElectronBrowserClient* Get();
static void SetApplicationLocale(const std::string& locale);
diff --git a/shell/browser/electron_web_contents_utility_handler_impl.h b/shell/browser/electron_web_contents_utility_handler_impl.h
index 79bca6b664..2f0f07d007 100644
--- a/shell/browser/electron_web_contents_utility_handler_impl.h
+++ b/shell/browser/electron_web_contents_utility_handler_impl.h
@@ -21,7 +21,7 @@ class RenderFrameHost;
namespace electron {
class ElectronWebContentsUtilityHandlerImpl
: public mojom::ElectronWebContentsUtility,
- public content::WebContentsObserver {
+ private content::WebContentsObserver {
public:
explicit ElectronWebContentsUtilityHandlerImpl(
content::RenderFrameHost* render_frame_host,
diff --git a/shell/browser/file_select_helper.h b/shell/browser/file_select_helper.h
index 27a2dbb0b2..7ade0b04d3 100644
--- a/shell/browser/file_select_helper.h
+++ b/shell/browser/file_select_helper.h
@@ -41,7 +41,7 @@ class FileSelectHelper : public base::RefCountedThreadSafe<
FileSelectHelper,
content::BrowserThread::DeleteOnUIThread>,
public ui::SelectFileDialog::Listener,
- public content::WebContentsObserver,
+ private content::WebContentsObserver,
private net::DirectoryLister::DirectoryListerDelegate {
public:
// disable copy
diff --git a/shell/browser/hid/electron_hid_delegate.cc b/shell/browser/hid/electron_hid_delegate.cc
index 10aa32c41d..91a174ab2c 100644
--- a/shell/browser/hid/electron_hid_delegate.cc
+++ b/shell/browser/hid/electron_hid_delegate.cc
@@ -41,7 +41,7 @@ namespace electron {
// Manages the HidDelegate observers for a single browser context.
class ElectronHidDelegate::ContextObservation
- : public HidChooserContext::DeviceObserver {
+ : private HidChooserContext::DeviceObserver {
public:
ContextObservation(ElectronHidDelegate* parent,
content::BrowserContext* browser_context)
diff --git a/shell/browser/login_handler.h b/shell/browser/login_handler.h
index 0e513f8c98..1f229baaa3 100644
--- a/shell/browser/login_handler.h
+++ b/shell/browser/login_handler.h
@@ -22,7 +22,7 @@ namespace electron {
// Handles HTTP basic auth.
class LoginHandler : public content::LoginDelegate,
- public content::WebContentsObserver {
+ private content::WebContentsObserver {
public:
LoginHandler(const net::AuthChallengeInfo& auth_info,
content::WebContents* web_contents,
diff --git a/shell/browser/native_window_views.h b/shell/browser/native_window_views.h
index e5683cecf0..81c39adfc0 100644
--- a/shell/browser/native_window_views.h
+++ b/shell/browser/native_window_views.h
@@ -38,8 +38,8 @@ gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds);
#endif
class NativeWindowViews : public NativeWindow,
- public views::WidgetObserver,
- public ui::EventHandler {
+ private views::WidgetObserver,
+ private ui::EventHandler {
public:
NativeWindowViews(const gin_helper::Dictionary& options,
NativeWindow* parent);
diff --git a/shell/browser/osr/osr_render_widget_host_view.h b/shell/browser/osr/osr_render_widget_host_view.h
index b674f7cfbc..2ce5204d97 100644
--- a/shell/browser/osr/osr_render_widget_host_view.h
+++ b/shell/browser/osr/osr_render_widget_host_view.h
@@ -61,9 +61,9 @@ typedef base::RepeatingCallback<void(const gfx::Rect&)> OnPopupPaintCallback;
class OffScreenRenderWidgetHostView
: public content::RenderWidgetHostViewBase,
- public content::RenderFrameMetadataProvider::Observer,
+ private content::RenderFrameMetadataProvider::Observer,
public ui::CompositorDelegate,
- public OffscreenViewProxyObserver {
+ private OffscreenViewProxyObserver {
public:
OffScreenRenderWidgetHostView(bool transparent,
bool painting,
diff --git a/shell/browser/osr/osr_web_contents_view.h b/shell/browser/osr/osr_web_contents_view.h
index 18587533ba..89bf556c08 100644
--- a/shell/browser/osr/osr_web_contents_view.h
+++ b/shell/browser/osr/osr_web_contents_view.h
@@ -28,7 +28,7 @@ namespace electron {
class OffScreenWebContentsView : public content::WebContentsView,
public content::RenderViewHostDelegateView,
- public NativeWindowObserver {
+ private NativeWindowObserver {
public:
OffScreenWebContentsView(bool transparent, const OnPaintCallback& callback);
~OffScreenWebContentsView() override;
diff --git a/shell/browser/serial/electron_serial_delegate.h b/shell/browser/serial/electron_serial_delegate.h
index dd12e4484e..986fa28a57 100644
--- a/shell/browser/serial/electron_serial_delegate.h
+++ b/shell/browser/serial/electron_serial_delegate.h
@@ -20,7 +20,7 @@ namespace electron {
class SerialChooserController;
class ElectronSerialDelegate : public content::SerialDelegate,
- public SerialChooserContext::PortObserver {
+ private SerialChooserContext::PortObserver {
public:
ElectronSerialDelegate();
~ElectronSerialDelegate() override;
diff --git a/shell/browser/ui/electron_desktop_window_tree_host_linux.h b/shell/browser/ui/electron_desktop_window_tree_host_linux.h
index 27f81d4a99..29bc4254a4 100644
--- a/shell/browser/ui/electron_desktop_window_tree_host_linux.h
+++ b/shell/browser/ui/electron_desktop_window_tree_host_linux.h
@@ -23,8 +23,8 @@ namespace electron {
class ElectronDesktopWindowTreeHostLinux
: public views::DesktopWindowTreeHostLinux,
- public ui::NativeThemeObserver,
- public ui::DeviceScaleFactorObserver {
+ private ui::NativeThemeObserver,
+ private ui::DeviceScaleFactorObserver {
public:
ElectronDesktopWindowTreeHostLinux(
NativeWindowViews* native_window_view,
diff --git a/shell/browser/ui/inspectable_web_contents.h b/shell/browser/ui/inspectable_web_contents.h
index fb4d2adbe4..89d0d965ff 100644
--- a/shell/browser/ui/inspectable_web_contents.h
+++ b/shell/browser/ui/inspectable_web_contents.h
@@ -34,7 +34,7 @@ class InspectableWebContentsView;
class InspectableWebContents
: public content::DevToolsAgentHostClient,
- public content::WebContentsObserver,
+ private content::WebContentsObserver,
public content::WebContentsDelegate,
public DevToolsEmbedderMessageDispatcher::Delegate {
public:
diff --git a/shell/browser/ui/message_box_gtk.cc b/shell/browser/ui/message_box_gtk.cc
index 51bb743b0d..c882be2aaa 100644
--- a/shell/browser/ui/message_box_gtk.cc
+++ b/shell/browser/ui/message_box_gtk.cc
@@ -47,7 +47,7 @@ base::flat_map<int, GtkWidget*>& GetDialogsMap() {
return *dialogs;
}
-class GtkMessageBox : public NativeWindowObserver {
+class GtkMessageBox : private NativeWindowObserver {
public:
explicit GtkMessageBox(const MessageBoxSettings& settings)
: id_(settings.id),
diff --git a/shell/browser/ui/views/autofill_popup_view.h b/shell/browser/ui/views/autofill_popup_view.h
index 88420bb4cd..cabc1182d5 100644
--- a/shell/browser/ui/views/autofill_popup_view.h
+++ b/shell/browser/ui/views/autofill_popup_view.h
@@ -58,8 +58,8 @@ class AutofillPopupChildView : public views::View {
};
class AutofillPopupView : public views::WidgetDelegateView,
- public views::WidgetFocusChangeListener,
- public views::WidgetObserver,
+ private views::WidgetFocusChangeListener,
+ private views::WidgetObserver,
public views::DragController {
public:
explicit AutofillPopupView(AutofillPopup* popup,
diff --git a/shell/browser/ui/views/client_frame_view_linux.h b/shell/browser/ui/views/client_frame_view_linux.h
index ce60e43c57..05d5b5454f 100644
--- a/shell/browser/ui/views/client_frame_view_linux.h
+++ b/shell/browser/ui/views/client_frame_view_linux.h
@@ -29,8 +29,8 @@
namespace electron {
class ClientFrameViewLinux : public FramelessView,
- public ui::NativeThemeObserver,
- public ui::WindowButtonOrderObserver {
+ private ui::NativeThemeObserver,
+ private ui::WindowButtonOrderObserver {
METADATA_HEADER(ClientFrameViewLinux, FramelessView)
public:
diff --git a/shell/browser/ui/views/menu_bar.h b/shell/browser/ui/views/menu_bar.h
index 0db03ae310..b2e1860ea2 100644
--- a/shell/browser/ui/views/menu_bar.h
+++ b/shell/browser/ui/views/menu_bar.h
@@ -21,8 +21,8 @@ class MenuButton;
namespace electron {
class MenuBar : public views::AccessiblePaneView,
- public MenuDelegate::Observer,
- public NativeWindowObserver {
+ private MenuDelegate::Observer,
+ private NativeWindowObserver {
METADATA_HEADER(MenuBar, views::AccessiblePaneView)
public:
diff --git a/shell/browser/ui/views/win_caption_button_container.h b/shell/browser/ui/views/win_caption_button_container.h
index f4568016af..308f35ca53 100644
--- a/shell/browser/ui/views/win_caption_button_container.h
+++ b/shell/browser/ui/views/win_caption_button_container.h
@@ -27,7 +27,7 @@ class WinCaptionButton;
// frame and browser window as needed. When extended horizontally, becomes a
// grab bar for moving the window.
class WinCaptionButtonContainer : public views::View,
- public views::WidgetObserver {
+ private views::WidgetObserver {
METADATA_HEADER(WinCaptionButtonContainer, views::View)
public:
diff --git a/shell/browser/usb/electron_usb_delegate.cc b/shell/browser/usb/electron_usb_delegate.cc
index a90896e0fe..0e2e5c549c 100644
--- a/shell/browser/usb/electron_usb_delegate.cc
+++ b/shell/browser/usb/electron_usb_delegate.cc
@@ -88,7 +88,7 @@ namespace electron {
// Manages the UsbDelegate observers for a single browser context.
class ElectronUsbDelegate::ContextObservation
- : public UsbChooserContext::DeviceObserver {
+ : private UsbChooserContext::DeviceObserver {
public:
ContextObservation(ElectronUsbDelegate* parent,
content::BrowserContext* browser_context)
diff --git a/shell/common/api/electron_api_url_loader.h b/shell/common/api/electron_api_url_loader.h
index b0da4a727b..8b9f1f9134 100644
--- a/shell/common/api/electron_api_url_loader.h
+++ b/shell/common/api/electron_api_url_loader.h
@@ -46,8 +46,8 @@ namespace electron::api {
class SimpleURLLoaderWrapper
: public gin::Wrappable<SimpleURLLoaderWrapper>,
public gin_helper::EventEmitterMixin<SimpleURLLoaderWrapper>,
- public network::SimpleURLLoaderStreamConsumer,
- public network::mojom::URLLoaderNetworkServiceObserver {
+ private network::SimpleURLLoaderStreamConsumer,
+ private network::mojom::URLLoaderNetworkServiceObserver {
public:
~SimpleURLLoaderWrapper() override;
static gin::Handle<SimpleURLLoaderWrapper> Create(gin::Arguments* args);
diff --git a/shell/renderer/api/electron_api_ipc_renderer.cc b/shell/renderer/api/electron_api_ipc_renderer.cc
index 317b933687..7eceed45bd 100644
--- a/shell/renderer/api/electron_api_ipc_renderer.cc
+++ b/shell/renderer/api/electron_api_ipc_renderer.cc
@@ -42,7 +42,7 @@ RenderFrame* GetCurrentRenderFrame() {
}
class IPCRenderer : public gin::Wrappable<IPCRenderer>,
- public content::RenderFrameObserver {
+ private content::RenderFrameObserver {
public:
static gin::WrapperInfo kWrapperInfo;
diff --git a/shell/renderer/api/electron_api_web_frame.cc b/shell/renderer/api/electron_api_web_frame.cc
index ceb5608ab7..64dd277ae8 100644
--- a/shell/renderer/api/electron_api_web_frame.cc
+++ b/shell/renderer/api/electron_api_web_frame.cc
@@ -272,7 +272,7 @@ class FrameSetSpellChecker : public content::RenderFrameVisitor {
content::RenderFrame* main_frame_;
};
-class SpellCheckerHolder final : public content::RenderFrameObserver {
+class SpellCheckerHolder final : private content::RenderFrameObserver {
public:
// Find existing holder for the |render_frame|.
static SpellCheckerHolder* FromRenderFrame(
@@ -330,7 +330,7 @@ class SpellCheckerHolder final : public content::RenderFrameObserver {
} // namespace
class WebFrameRenderer : public gin::Wrappable<WebFrameRenderer>,
- public content::RenderFrameObserver {
+ private content::RenderFrameObserver {
public:
static gin::WrapperInfo kWrapperInfo;
|
refactor
|
0672f59f2648df29294d507e3789ca6a87877b8a
|
Keeley Hammond
|
2024-01-04 07:01:40
|
chore: add disclaimer to release timeline (#40717)
* chore: add disclaimer to release timeline
* Update docs/tutorial/electron-timelines.md
Co-authored-by: David Sanders <[email protected]>
---------
Co-authored-by: Shelley Vohr <[email protected]>
Co-authored-by: David Sanders <[email protected]>
|
diff --git a/docs/tutorial/electron-timelines.md b/docs/tutorial/electron-timelines.md
index 3f991f2cd1..645d7c7ad7 100644
--- a/docs/tutorial/electron-timelines.md
+++ b/docs/tutorial/electron-timelines.md
@@ -38,6 +38,19 @@ check out our [Electron Versioning](./electron-versioning.md) doc.
| 3.0.0 | -- | 2018-Jun-21 | 2018-Sep-18 | 2019-Jul-30 | M66 | v10.2 | 🚫 |
| 2.0.0 | -- | 2018-Feb-21 | 2018-May-01 | 2019-Apr-23 | M61 | v8.9 | 🚫 |
+:::info Official support dates may change
+
+Electron's official support policy is the latest 3 stable releases. Our stable
+release and end-of-life dates are determined by Chromium, and may be subject to
+change. While we try to keep our planned release and end-of-life dates frequently
+updated here, future dates may change if affected by upstream scheduling changes,
+and may not always be accurately reflected.
+
+ See [Chromium's public release schedule](https://chromiumdash.appspot.com/schedule) for
+ definitive information about Chromium's scheduled release dates.
+
+ :::
+
**Notes:**
* The `-alpha.1`, `-beta.1`, and `stable` dates are our solid release dates.
@@ -49,20 +62,10 @@ check out our [Electron Versioning](./electron-versioning.md) doc.
* Since Electron 5, Electron has been publicizing its release dates ([see blog post](https://www.electronjs.org/blog/electron-5-0-timeline)).
* Since Electron 6, Electron major versions have been targeting every other Chromium major version. Each Electron stable should happen on the same day as Chrome stable ([see blog post](https://www.electronjs.org/blog/12-week-cadence)).
* Since Electron 16, Electron has been releasing major versions on an 8-week cadence in accordance to Chrome's change to a 4-week release cadence ([see blog post](https://www.electronjs.org/blog/8-week-cadence)).
+* Electron temporarily extended support for Electron 22 until October 10, 2023, to support an extended end-of-life for Windows 7/8/8.1
## Version support policy
-:::info
-
-The Electron team will temporarily support Electron 22 until October 10, 2023.
-This extended support is intended to help Electron developers who still need
-support for Windows 7/8/8.1, which ended support in Electron 23. The October
-support date follows the extended support dates from both Chromium and Microsoft.
-On October 11, the Electron team will drop support back to the latest three
-stable major versions.
-
-:::
-
The latest three _stable_ major versions are supported by the Electron team.
For example, if the latest release is 6.1.x, then the 5.0.x as well
as the 4.2.x series are supported. We only support the latest minor release
|
chore
|
86cf60c3f1e7c992b7bf4269fc1eb2919890625d
|
Shelley Vohr
|
2024-06-18 10:51:37
|
chore: improve error message on failed SMApp register/unregister (#42526)
|
diff --git a/shell/common/platform_util_mac.mm b/shell/common/platform_util_mac.mm
index ad9b51a576..370eccd45b 100644
--- a/shell/common/platform_util_mac.mm
+++ b/shell/common/platform_util_mac.mm
@@ -111,7 +111,7 @@ std::string GetLaunchStringForError(NSError* error) {
return "The specified path doesn't exist or the helper tool at the "
"specified path isn't valid";
default:
- return "Failed to register the login item";
+ return base::SysNSStringToUTF8([error localizedDescription]);
}
}
|
chore
|
5773a2dce6fbcad34dc4f94a9c41b100fcd3cbaf
|
Charles Kerr
|
2024-07-17 23:30:09
|
fix: dangling raw_ptr NodeBindings::uv_env_ (#42933)
|
diff --git a/shell/browser/electron_browser_main_parts.cc b/shell/browser/electron_browser_main_parts.cc
index 0b89745111..ee0f1feb7b 100644
--- a/shell/browser/electron_browser_main_parts.cc
+++ b/shell/browser/electron_browser_main_parts.cc
@@ -604,6 +604,7 @@ void ElectronBrowserMainParts::PostMainMessageLoopRun() {
node_env_->set_trace_sync_io(false);
js_env_->DestroyMicrotasksRunner();
node::Stop(node_env_.get(), node::StopFlags::kDoNotTerminateIsolate);
+ node_bindings_->set_uv_env(nullptr);
node_env_.reset();
auto default_context_key = ElectronBrowserContext::PartitionKey("", false);
diff --git a/shell/browser/electron_browser_main_parts.h b/shell/browser/electron_browser_main_parts.h
index 41d69716f1..fdcfb6c062 100644
--- a/shell/browser/electron_browser_main_parts.h
+++ b/shell/browser/electron_browser_main_parts.h
@@ -155,10 +155,10 @@ class ElectronBrowserMainParts : public content::BrowserMainParts {
// Before then, we just exit() without any intermediate steps.
std::optional<int> exit_code_;
- std::unique_ptr<NodeBindings> node_bindings_;
+ const std::unique_ptr<NodeBindings> node_bindings_;
// depends-on: node_bindings_
- std::unique_ptr<ElectronBindings> electron_bindings_;
+ const std::unique_ptr<ElectronBindings> electron_bindings_;
// depends-on: node_bindings_
std::unique_ptr<JavascriptEnvironment> js_env_;
|
fix
|
b16318723556c70d6d407f271e5ad1b7d2402cc9
|
Milan Burda
|
2023-11-01 13:46:25
|
docs: avoid leaking the `IpcRendererEvent` in `contextBridge` examples (#40321)
* docs: avoid leaking the `IpcRendererEvent` in `contextBridge` examples
* Update docs/fiddles/ipc/pattern-3/preload.js
Co-authored-by: David Sanders <[email protected]>
* Update docs/tutorial/ipc.md
Co-authored-by: David Sanders <[email protected]>
* Update docs/tutorial/ipc.md
Co-authored-by: David Sanders <[email protected]>
---------
Co-authored-by: David Sanders <[email protected]>
|
diff --git a/docs/fiddles/ipc/pattern-3/preload.js b/docs/fiddles/ipc/pattern-3/preload.js
index 1df2941caa..b8d2756507 100644
--- a/docs/fiddles/ipc/pattern-3/preload.js
+++ b/docs/fiddles/ipc/pattern-3/preload.js
@@ -1,5 +1,6 @@
const { contextBridge, ipcRenderer } = require('electron/renderer')
contextBridge.exposeInMainWorld('electronAPI', {
- handleCounter: (callback) => ipcRenderer.on('update-counter', () => callback())
+ onUpdateCounter: (callback) => ipcRenderer.on('update-counter', (_event, value) => callback(value)),
+ counterValue: (value) => ipcRenderer.send('counter-value', value)
})
diff --git a/docs/fiddles/ipc/pattern-3/renderer.js b/docs/fiddles/ipc/pattern-3/renderer.js
index d7316a5d87..c1d97a8483 100644
--- a/docs/fiddles/ipc/pattern-3/renderer.js
+++ b/docs/fiddles/ipc/pattern-3/renderer.js
@@ -1,8 +1,8 @@
const counter = document.getElementById('counter')
-window.electronAPI.handleCounter((event, value) => {
+window.electronAPI.onUpdateCounter((value) => {
const oldValue = Number(counter.innerText)
const newValue = oldValue + value
- counter.innerText = newValue
- event.sender.send('counter-value', newValue)
+ counter.innerText = newValue.toString()
+ window.electronAPI.counterValue(newValue)
})
diff --git a/docs/tutorial/ipc.md b/docs/tutorial/ipc.md
index 73b5723aeb..bbd139e81a 100644
--- a/docs/tutorial/ipc.md
+++ b/docs/tutorial/ipc.md
@@ -429,7 +429,7 @@ modules in the preload script to expose IPC functionality to the renderer proces
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {
- onUpdateCounter: (callback) => ipcRenderer.on('update-counter', callback)
+ onUpdateCounter: (callback) => ipcRenderer.on('update-counter', (_event, value) => callback(value))
})
```
@@ -439,6 +439,8 @@ After loading the preload script, your renderer process should have access to th
:::caution Security warning
We don't directly expose the whole `ipcRenderer.on` API for [security reasons][]. Make sure to
limit the renderer's access to Electron APIs as much as possible.
+Also don't just pass the callback to `ipcRenderer.on` as this will leak `ipcRenderer` via `event.sender`.
+Use a custom handler that invoke the `callback` only with the desired arguments.
:::
:::info
@@ -486,10 +488,10 @@ To tie it all together, we'll create an interface in the loaded HTML file that c
Finally, to make the values update in the HTML document, we'll add a few lines of DOM manipulation
so that the value of the `#counter` element is updated whenever we fire an `update-counter` event.
-```javascript title='renderer.js (Renderer Process)' @ts-window-type={electronAPI:{onUpdateCounter:(callback:(event:Electron.IpcRendererEvent,value:number)=>void)=>void}}
+```javascript title='renderer.js (Renderer Process)' @ts-window-type={electronAPI:{onUpdateCounter:(callback:(value:number)=>void)=>void}}
const counter = document.getElementById('counter')
-window.electronAPI.onUpdateCounter((_event, value) => {
+window.electronAPI.onUpdateCounter((value) => {
const oldValue = Number(counter.innerText)
const newValue = oldValue + value
counter.innerText = newValue.toString()
@@ -506,17 +508,26 @@ There's no equivalent for `ipcRenderer.invoke` for main-to-renderer IPC. Instead
send a reply back to the main process from within the `ipcRenderer.on` callback.
We can demonstrate this with slight modifications to the code from the previous example. In the
-renderer process, use the `event` parameter to send a reply back to the main process through the
+renderer process, expose another API to send a reply back to the main process through the
`counter-value` channel.
-```javascript title='renderer.js (Renderer Process)' @ts-window-type={electronAPI:{onUpdateCounter:(callback:(event:Electron.IpcRendererEvent,value:number)=>void)=>void}}
+```javascript title='preload.js (Preload Script)'
+const { contextBridge, ipcRenderer } = require('electron')
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ onUpdateCounter: (callback) => ipcRenderer.on('update-counter', (_event, value) => callback(value)),
+ counterValue: (value) => ipcRenderer.send('counter-value', value)
+})
+```
+
+```javascript title='renderer.js (Renderer Process)' @ts-window-type={electronAPI:{onUpdateCounter:(callback:(value:number)=>void)=>void,counterValue:(value:number)=>void}}
const counter = document.getElementById('counter')
-window.electronAPI.onUpdateCounter((event, value) => {
+window.electronAPI.onUpdateCounter((value) => {
const oldValue = Number(counter.innerText)
const newValue = oldValue + value
counter.innerText = newValue.toString()
- event.sender.send('counter-value', newValue)
+ window.electronAPI.counterValue(newValue)
})
```
|
docs
|
0b5fceb50ea18102411950106037636834e0f7d2
|
Alex Browne
|
2023-11-21 22:19:39
|
docs: update quick-start.md (#40556)
Updates the Quick Start guide to specify _where_ JavaScript code is supposed to be added. This is more descriptive than just "your file".
|
diff --git a/docs/tutorial/quick-start.md b/docs/tutorial/quick-start.md
index abb2629cb3..b40dd8d110 100644
--- a/docs/tutorial/quick-start.md
+++ b/docs/tutorial/quick-start.md
@@ -155,7 +155,7 @@ need two Electron modules:
windows.
Because the main process runs Node.js, you can import these as [CommonJS][commonjs]
-modules at the top of your file:
+modules at the top of your `main.js` file:
```js
const { app, BrowserWindow } = require('electron')
|
docs
|
095f9067a7f9fa9edca0379acccb26d244e23f75
|
Erick Zhao
|
2023-03-16 17:05:15
|
docs: delete synopsis.md (#37580)
* docs: delete synopsis.md
* remove code references to doc
|
diff --git a/docs/README.md b/docs/README.md
index 30306ecb0e..d86583f97e 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -90,7 +90,6 @@ These individual tutorials expand on topics discussed in the guide above.
## API References
-* [Synopsis](api/synopsis.md)
* [Process Object](api/process.md)
* [Supported Command Line Switches](api/command-line-switches.md)
* [Environment Variables](api/environment-variables.md)
diff --git a/docs/api/synopsis.md b/docs/api/synopsis.md
deleted file mode 100644
index 667c1dcd35..0000000000
--- a/docs/api/synopsis.md
+++ /dev/null
@@ -1,93 +0,0 @@
-# Synopsis
-
-> How to use Node.js and Electron APIs.
-
-All of [Node.js's built-in modules](https://nodejs.org/api/) are available in
-Electron and third-party node modules also fully supported as well (including
-the [native modules](../tutorial/using-native-node-modules.md)).
-
-Electron also provides some extra built-in modules for developing native
-desktop applications. Some modules are only available in the main process, some
-are only available in the renderer process (web page), and some can be used in
-either process type.
-
-The basic rule is: if a module is [GUI][gui] or low-level system related, then
-it should be only available in the main process. You need to be familiar with
-the concept of main process vs. renderer process
-scripts to be able to use those modules.
-
-The main process script is like a normal Node.js script:
-
-```javascript
-const { app, BrowserWindow } = require('electron')
-let win = null
-
-app.whenReady().then(() => {
- win = new BrowserWindow({ width: 800, height: 600 })
- win.loadURL('https://github.com')
-})
-```
-
-The renderer process is no different than a normal web page, except for the
-extra ability to use node modules if `nodeIntegration` is enabled:
-
-```html
-<!DOCTYPE html>
-<html>
-<body>
-<script>
- const fs = require('fs')
- console.log(fs.readFileSync(__filename, 'utf8'))
-</script>
-</body>
-</html>
-```
-
-## Destructuring assignment
-
-As of 0.37, you can use
-[destructuring assignment][destructuring-assignment] to make it easier to use
-built-in modules.
-
-```javascript
-const { app, BrowserWindow } = require('electron')
-
-let win
-
-app.whenReady().then(() => {
- win = new BrowserWindow()
- win.loadURL('https://github.com')
-})
-```
-
-If you need the entire `electron` module, you can require it and then using
-destructuring to access the individual modules from `electron`.
-
-```javascript
-const electron = require('electron')
-const { app, BrowserWindow } = electron
-
-let win
-
-app.whenReady().then(() => {
- win = new BrowserWindow()
- win.loadURL('https://github.com')
-})
-```
-
-This is equivalent to the following code:
-
-```javascript
-const electron = require('electron')
-const app = electron.app
-const BrowserWindow = electron.BrowserWindow
-let win
-
-app.whenReady().then(() => {
- win = new BrowserWindow()
- win.loadURL('https://github.com')
-})
-```
-
-[gui]: https://en.wikipedia.org/wiki/Graphical_user_interface
-[destructuring-assignment]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
diff --git a/filenames.auto.gni b/filenames.auto.gni
index fdbd7f0dfd..c29eebcb20 100644
--- a/filenames.auto.gni
+++ b/filenames.auto.gni
@@ -49,7 +49,6 @@ auto_filenames = {
"docs/api/share-menu.md",
"docs/api/shell.md",
"docs/api/structures",
- "docs/api/synopsis.md",
"docs/api/system-preferences.md",
"docs/api/touch-bar-button.md",
"docs/api/touch-bar-color-picker.md",
diff --git a/spec/ts-smoke/electron/main.ts b/spec/ts-smoke/electron/main.ts
index 09519f83c2..468d16df7f 100644
--- a/spec/ts-smoke/electron/main.ts
+++ b/spec/ts-smoke/electron/main.ts
@@ -331,9 +331,6 @@ ipcMain.on('online-status-changed', (event, status: any) => {
console.log(status);
});
-// Synopsis
-// https://github.com/electron/electron/blob/main/docs/api/synopsis.md
-
app.whenReady().then(() => {
window = new BrowserWindow({
width: 800,
|
docs
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 4