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
85bebfb18073d623f1963f8c5a6d9b24295d691d
Sam Maddock
2024-01-31 04:29:17
test: draggable region allows moving window (#41127) * chore: add nut.js * test: dragging window updates position * instantly move mouse position * limit platforms to run drag tests on * defer loading nut-js
diff --git a/spec/api-browser-window-spec.ts b/spec/api-browser-window-spec.ts index bc7cc52208..b7bb9833e9 100644 --- a/spec/api-browser-window-spec.ts +++ b/spec/api-browser-window-spec.ts @@ -11,7 +11,7 @@ import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersLi import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; -import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; +import { areColorsSimilar, captureScreen, HexColors, getPixelColor, hasCapturableScreen } from './lib/screen-helpers'; import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; import { setTimeout as syncSetTimeout } from 'node:timers'; @@ -6599,4 +6599,51 @@ describe('BrowserWindow module', () => { expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); + + describe('draggable regions', () => { + afterEach(closeAllWindows); + + ifit(hasCapturableScreen())('should allow the window to be dragged when enabled', async () => { + // WOA fails to load libnut so we're using require to defer loading only + // on supported platforms. + // "@nut-tree\libnut-win32\build\Release\libnut.node is not a valid Win32 application." + const { mouse, straightTo, centerOf, Region, Button } = require('@nut-tree/nut-js') as typeof import('@nut-tree/nut-js'); + + const display = screen.getPrimaryDisplay(); + + const w = new BrowserWindow({ + x: 0, + y: 0, + width: display.bounds.width / 2, + height: display.bounds.height / 2, + frame: false, + titleBarStyle: 'hidden' + }); + + const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); + w.loadFile(overlayHTML); + await once(w, 'ready-to-show'); + + const winBounds = w.getBounds(); + const titleBarHeight = 30; + const titleBarRegion = new Region(winBounds.x, winBounds.y, winBounds.width, titleBarHeight); + const screenRegion = new Region(display.bounds.x, display.bounds.y, display.bounds.width, display.bounds.height); + + const startPos = w.getPosition(); + + await mouse.setPosition(await centerOf(titleBarRegion)); + await mouse.pressButton(Button.LEFT); + await mouse.drag(straightTo(centerOf(screenRegion))); + + // Wait for move to complete + await Promise.race([ + once(w, 'move'), + setTimeout(100) // fallback for possible race condition + ]); + + const endPos = w.getPosition(); + + expect(startPos).to.not.deep.equal(endPos); + }); + }); }); diff --git a/spec/lib/screen-helpers.ts b/spec/lib/screen-helpers.ts index 9407f012a9..3c6f855f8d 100644 --- a/spec/lib/screen-helpers.ts +++ b/spec/lib/screen-helpers.ts @@ -91,3 +91,16 @@ export const areColorsSimilar = ( const distance = colorDistance(hexColorA, hexColorB); return distance <= distanceThreshold; }; + +/** + * Whether the current VM has a valid screen which can be used to capture. + * + * This is specific to Electron's CI test runners. + * - Linux: virtual screen display is 0x0 + * - Win32 arm64 (WOA): virtual screen display is 0x0 + * - Win32 ia32: skipped + */ +export const hasCapturableScreen = () => { + return process.platform === 'darwin' || + (process.platform === 'win32' && process.arch === 'x64'); +}; diff --git a/spec/package.json b/spec/package.json index 65bd1fd8d8..3dd7e83bb0 100644 --- a/spec/package.json +++ b/spec/package.json @@ -11,6 +11,7 @@ "@electron-ci/is-valid-window": "file:./is-valid-window", "@electron-ci/uv-dlopen": "file:./fixtures/native-addon/uv-dlopen/", "@marshallofsound/mocha-appveyor-reporter": "^0.4.3", + "@nut-tree/nut-js": "^3.1.2", "@types/sinon": "^9.0.4", "@types/ws": "^7.2.0", "basic-auth": "^2.0.1", diff --git a/spec/yarn.lock b/spec/yarn.lock index 46fbcec7d1..0bb27e497c 100644 --- a/spec/yarn.lock +++ b/spec/yarn.lock @@ -2,6 +2,13 @@ # yarn lockfile v1 +"@babel/runtime@^7.7.2": + version "7.23.9" + resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.23.9.tgz#47791a15e4603bb5f905bc0753801cf21d6345f7" + integrity sha512-0CX6F+BI2s9dkUqr08KFrAIZgNFj75rdBU/DjCyYLIaV/quFjkk6T+EJ2LkZHyZTbEV4L5p97mNkUsHl2wLFAw== + dependencies: + regenerator-runtime "^0.14.0" + "@electron-ci/echo@file:./fixtures/native-addon/echo": version "0.0.1" @@ -13,6 +20,296 @@ "@electron-ci/uv-dlopen@file:./fixtures/native-addon/uv-dlopen": version "0.0.1" +"@jimp/bmp@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/bmp/-/bmp-0.16.13.tgz#57ffa5b17417b5a181f6f184bdabc8218e8448ef" + integrity sha512-9edAxu7N2FX7vzkdl5Jo1BbACfycUtBQX+XBMcHA2bk62P8R0otgkHg798frgAk/WxQIzwxqOH6wMiCwrlAzdQ== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + bmp-js "^0.1.0" + +"@jimp/core@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/core/-/core-0.16.13.tgz#7171745a912b5b847f8bf53e70b0672c5ca92744" + integrity sha512-qXpA1tzTnlkTku9yqtuRtS/wVntvE6f3m3GNxdTdtmc+O+Wcg9Xo2ABPMh7Nc0AHbMKzwvwgB2JnjZmlmJEObg== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + any-base "^1.1.0" + buffer "^5.2.0" + exif-parser "^0.1.12" + file-type "^16.5.4" + load-bmfont "^1.3.1" + mkdirp "^0.5.1" + phin "^2.9.1" + pixelmatch "^4.0.2" + tinycolor2 "^1.4.1" + +"@jimp/custom@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/custom/-/custom-0.16.13.tgz#2e4ed447b7410b81fe9103682b4166af904daf84" + integrity sha512-LTATglVUPGkPf15zX1wTMlZ0+AU7cGEGF6ekVF1crA8eHUWsGjrYTB+Ht4E3HTrCok8weQG+K01rJndCp/l4XA== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/core" "^0.16.13" + +"@jimp/gif@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/gif/-/gif-0.16.13.tgz#fa72f35d8ad67d6ce3a3d7ef6c8d04a462afaaf9" + integrity sha512-yFAMZGv3o+YcjXilMWWwS/bv1iSqykFahFMSO169uVMtfQVfa90kt4/kDwrXNR6Q9i6VHpFiGZMlF2UnHClBvg== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + gifwrap "^0.9.2" + omggif "^1.0.9" + +"@jimp/jpeg@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/jpeg/-/jpeg-0.16.13.tgz#e1c128a591bd7f8a26c8731fd0bc65d32d4ba32a" + integrity sha512-BJHlDxzTlCqP2ThqP8J0eDrbBfod7npWCbJAcfkKqdQuFk0zBPaZ6KKaQKyKxmWJ87Z6ohANZoMKEbtvrwz1AA== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + jpeg-js "^0.4.2" + +"@jimp/plugin-blit@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-blit/-/plugin-blit-0.16.13.tgz#370303edef02b75aa3e316726c5a3aac3e92f5d0" + integrity sha512-8Z1k96ZFxlhK2bgrY1JNWNwvaBeI/bciLM0yDOni2+aZwfIIiC7Y6PeWHTAvjHNjphz+XCt01WQmOYWCn0ML6g== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-blur@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-blur/-/plugin-blur-0.16.13.tgz#27b82295a3dee88d6e029d4d62f5de8118b845e6" + integrity sha512-PvLrfa8vkej3qinlebyhLpksJgCF5aiysDMSVhOZqwH5nQLLtDE9WYbnsofGw4r0VVpyw3H/ANCIzYTyCtP9Cg== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-circle@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-circle/-/plugin-circle-0.16.13.tgz#d7af61a95b17e67c7fd4361cd1d588e00b58b6b6" + integrity sha512-RNave7EFgZrb5V5EpdvJGAEHMnDAJuwv05hKscNfIYxf0kR3KhViBTDy+MoTnMlIvaKFULfwIgaZWzyhuINMzA== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-color@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-color/-/plugin-color-0.16.13.tgz#825227e7e6f32d227740ad1bd97c389083c1d0d1" + integrity sha512-xW+9BtEvoIkkH/Wde9ql4nAFbYLkVINhpgAE7VcBUsuuB34WUbcBl/taOuUYQrPEFQJ4jfXiAJZ2H/rvKjCVnQ== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + tinycolor2 "^1.4.1" + +"@jimp/plugin-contain@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-contain/-/plugin-contain-0.16.13.tgz#7a42ed1ce580bf910f812ba2f35e0fa2cfe501ac" + integrity sha512-QayTXw4tXMwU6q6acNTQrTTFTXpNRBe+MgTGMDU0lk+23PjlFCO/9sacflelG8lsp7vNHhAxFeHptDMAksEYzg== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-cover@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-cover/-/plugin-cover-0.16.13.tgz#9c964be05b163e0f0e06866a9afcebe775dff246" + integrity sha512-BSsP71GTNaqWRcvkbWuIVH+zK7b3TSNebbhDkFK0fVaUTzHuKMS/mgY4hDZIEVt7Rf5FjadAYtsujHN9w0iSYA== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-crop@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-crop/-/plugin-crop-0.16.13.tgz#80c6ae4d401a8de6cc11b265f3cdecd80425b9a9" + integrity sha512-WEl2tPVYwzYL8OKme6Go2xqiWgKsgxlMwyHabdAU4tXaRwOCnOI7v4021gCcBb9zn/oWwguHuKHmK30Fw2Z/PA== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-displace@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-displace/-/plugin-displace-0.16.13.tgz#fd72aa93b3fe97a1c3da729e6b26399661ce8ce5" + integrity sha512-qt9WKq8vWrcjySa9DyQ0x/RBMHQeiVjdVSY1SJsMjssPUf0pS74qorcuAkGi89biN3YoGUgPkpqECnAWnYwgGA== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-dither@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-dither/-/plugin-dither-0.16.13.tgz#430750f73d528df7ebe21bb508fb80f9f515305d" + integrity sha512-5/N3yJggbWQTlGZHQYJPmQXEwR52qaXjEzkp1yRBbtdaekXE3BG/suo0fqeoV/csf8ooI78sJzYmIrxNoWVtgQ== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-fisheye@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-fisheye/-/plugin-fisheye-0.16.13.tgz#caf69851ab25c44d13c952880a8e43c928abd3f1" + integrity sha512-2rZmTdFbT/cF9lEZIkXCYO0TsT114Q27AX5IAo0Sju6jVQbvIk1dFUTnwLDadTo8wkJlFzGqMQ24Cs8cHWOliA== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-flip@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-flip/-/plugin-flip-0.16.13.tgz#3dd167e14d03d62410c519990728ac3c247c0692" + integrity sha512-EmcgAA74FTc5u7Z+hUO/sRjWwfPPLuOQP5O64x5g4j0T12Bd29IgsYZxoutZo/rb3579+JNa/3wsSEmyVv1EpA== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-gaussian@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-gaussian/-/plugin-gaussian-0.16.13.tgz#79879d9371aff3e1714c54be0771418573ac2954" + integrity sha512-A1XKfGQD0iDdIiKqFYi8nZMv4dDVYdxbrmgR7y/CzUHhSYdcmoljLIIsZZM3Iks/Wa353W3vtvkWLuDbQbch1w== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-invert@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-invert/-/plugin-invert-0.16.13.tgz#7449283d5b0f405ce2cd1b93a6d79169c970e431" + integrity sha512-xFMrIn7czEZbdbMzZWuaZFnlLGJDVJ82y5vlsKsXRTG2kcxRsMPXvZRWHV57nSs1YFsNqXSbrC8B98n0E32njQ== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-mask@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-mask/-/plugin-mask-0.16.13.tgz#70b4bef4a598e41571f9a3e0c33fcc730eeae24d" + integrity sha512-wLRYKVBXql2GAYgt6FkTnCfE+q5NomM7Dlh0oIPGAoMBWDyTx0eYutRK6PlUrRK2yMHuroAJCglICTbxqGzowQ== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-normalize@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-normalize/-/plugin-normalize-0.16.13.tgz#fd7c802c3f6be8d34abf0dbeadfe1d783e531d67" + integrity sha512-3tfad0n9soRna4IfW9NzQdQ2Z3ijkmo21DREHbE6CGcMIxOSvfRdSvf1qQPApxjTSo8LTU4MCi/fidx/NZ0GqQ== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-print@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-print/-/plugin-print-0.16.13.tgz#595fb6db6677ac3d2b6bfe7144658019791bf288" + integrity sha512-0m6i3p01PGRkGAK9r53hDYrkyMq+tlhLOIbsSTmZyh6HLshUKlTB7eXskF5OpVd5ZUHoltlNc6R+ggvKIzxRFw== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + load-bmfont "^1.4.0" + +"@jimp/plugin-resize@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-resize/-/plugin-resize-0.16.13.tgz#6267087f724d47e7bb8824c5b842d9315f50b8e7" + integrity sha512-qoqtN8LDknm3fJm9nuPygJv30O3vGhSBD2TxrsCnhtOsxKAqVPJtFVdGd/qVuZ8nqQANQmTlfqTiK9mVWQ7MiQ== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-rotate@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-rotate/-/plugin-rotate-0.16.13.tgz#9981f24631b1a0ad486d2b75a0163918ff912491" + integrity sha512-Ev+Jjmj1nHYw897z9C3R9dYsPv7S2/nxdgfFb/h8hOwK0Ovd1k/+yYS46A0uj/JCKK0pQk8wOslYBkPwdnLorw== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-scale@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-scale/-/plugin-scale-0.16.13.tgz#36b1b7d70819591901339926a91dae4864cc1b92" + integrity sha512-05POQaEJVucjTiSGMoH68ZiELc7QqpIpuQlZ2JBbhCV+WCbPFUBcGSmE7w4Jd0E2GvCho/NoMODLwgcVGQA97A== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-shadow@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-shadow/-/plugin-shadow-0.16.13.tgz#f5b58122c0a6e1307efcddfc165ce1291415d553" + integrity sha512-nmu5VSZ9hsB1JchTKhnnCY+paRBnwzSyK5fhkhtQHHoFD5ArBQ/5wU8y6tCr7k/GQhhGq1OrixsECeMjPoc8Zw== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugin-threshold@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugin-threshold/-/plugin-threshold-0.16.13.tgz#8de7500b03342b251201bc0feb84955dd3e410f0" + integrity sha512-+3zArBH0OE3Rhjm4HyAokMsZlIq5gpQec33CncyoSwxtRBM2WAhUVmCUKuBo+Lr/2/4ISoY4BWpHKhMLDix6cA== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + +"@jimp/plugins@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/plugins/-/plugins-0.16.13.tgz#cf441ee13204dd9474bc0e67e41c50afc910de4f" + integrity sha512-CJLdqODEhEVs4MgWCxpWL5l95sCBlkuSLz65cxEm56X5akIsn4LOlwnKoSEZioYcZUBvHhCheH67AyPTudfnQQ== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/plugin-blit" "^0.16.13" + "@jimp/plugin-blur" "^0.16.13" + "@jimp/plugin-circle" "^0.16.13" + "@jimp/plugin-color" "^0.16.13" + "@jimp/plugin-contain" "^0.16.13" + "@jimp/plugin-cover" "^0.16.13" + "@jimp/plugin-crop" "^0.16.13" + "@jimp/plugin-displace" "^0.16.13" + "@jimp/plugin-dither" "^0.16.13" + "@jimp/plugin-fisheye" "^0.16.13" + "@jimp/plugin-flip" "^0.16.13" + "@jimp/plugin-gaussian" "^0.16.13" + "@jimp/plugin-invert" "^0.16.13" + "@jimp/plugin-mask" "^0.16.13" + "@jimp/plugin-normalize" "^0.16.13" + "@jimp/plugin-print" "^0.16.13" + "@jimp/plugin-resize" "^0.16.13" + "@jimp/plugin-rotate" "^0.16.13" + "@jimp/plugin-scale" "^0.16.13" + "@jimp/plugin-shadow" "^0.16.13" + "@jimp/plugin-threshold" "^0.16.13" + timm "^1.6.1" + +"@jimp/png@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/png/-/png-0.16.13.tgz#8b130cc5e1e754c074c42fa3fe2609897cefdf7c" + integrity sha512-8cGqINvbWJf1G0Her9zbq9I80roEX0A+U45xFby3tDWfzn+Zz8XKDF1Nv9VUwVx0N3zpcG1RPs9hfheG4Cq2kg== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/utils" "^0.16.13" + pngjs "^3.3.3" + +"@jimp/tiff@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/tiff/-/tiff-0.16.13.tgz#9cf8d19f2b0b0c46758e81acfc7d656835ee6da1" + integrity sha512-oJY8d9u95SwW00VPHuCNxPap6Q1+E/xM5QThb9Hu+P6EGuu6lIeLaNBMmFZyblwFbwrH+WBOZlvIzDhi4Dm/6Q== + dependencies: + "@babel/runtime" "^7.7.2" + utif "^2.0.1" + +"@jimp/types@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/types/-/types-0.16.13.tgz#39be1886cbfa4fb5e77e17441a046a1f961d3046" + integrity sha512-mC0yVNUobFDjoYLg4hoUwzMKgNlxynzwt3cDXzumGvRJ7Kb8qQGOWJQjQFo5OxmGExqzPphkirdbBF88RVLBCg== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/bmp" "^0.16.13" + "@jimp/gif" "^0.16.13" + "@jimp/jpeg" "^0.16.13" + "@jimp/png" "^0.16.13" + "@jimp/tiff" "^0.16.13" + timm "^1.6.1" + +"@jimp/utils@^0.16.13": + version "0.16.13" + resolved "https://registry.yarnpkg.com/@jimp/utils/-/utils-0.16.13.tgz#afde41b9c6cdadfb45d83cb5e16deb65f369bf99" + integrity sha512-VyCpkZzFTHXtKgVO35iKN0sYR10psGpV6SkcSeV4oF7eSYlR8Bl6aQLCzVeFjvESF7mxTmIiI3/XrMobVrtxDA== + dependencies: + "@babel/runtime" "^7.7.2" + regenerator-runtime "^0.13.3" + "@marshallofsound/mocha-appveyor-reporter@^0.4.3": version "0.4.3" resolved "https://registry.yarnpkg.com/@marshallofsound/mocha-appveyor-reporter/-/mocha-appveyor-reporter-0.4.3.tgz#a9225224391a90e3c6bb48415d5015de895a7114" @@ -25,6 +322,60 @@ resolved "https://registry.yarnpkg.com/@nornagon/put/-/put-0.0.8.tgz#9d497ec46c9364acc3f8b59aa3cf8ee4134ae337" integrity sha512-ugvXJjwF5ldtUpa7D95kruNJ41yFQDEKyF5CW4TgKJnh+W/zmlBzXXeKTyqIgwMFrkePN2JqOBqcF0M0oOunow== +"@nut-tree/[email protected]": + version "2.5.2" + resolved "https://registry.yarnpkg.com/@nut-tree/libnut-darwin/-/libnut-darwin-2.5.2.tgz#83f091969912bf0d808ecebbab40423f6d30a660" + integrity sha512-OKqCgpBbZj2oNQkLM+mM7TyiLBAQsRyN7Q5UXVKbyXnzcQTU1FZBJ1mLGvdfzzspajznL3Mkl08AQE+xYYbTMw== + dependencies: + bindings "1.5.0" + optionalDependencies: + "@nut-tree/node-mac-permissions" "2.2.1" + +"@nut-tree/[email protected]": + version "2.5.2" + resolved "https://registry.yarnpkg.com/@nut-tree/libnut-linux/-/libnut-linux-2.5.2.tgz#37bf6f875a82f68570c13fda6435c0722c1af532" + integrity sha512-uY6XDuNE8soYRUhV23g6KQN5BRR43MYNLyPnrrQa5Wtfgm6oW9kBRu6JtkWz6Fn6trAWrVAKnbPoTiEgHuGz9w== + dependencies: + bindings "1.5.0" + optionalDependencies: + "@nut-tree/node-mac-permissions" "2.2.1" + +"@nut-tree/[email protected]": + version "2.5.2" + resolved "https://registry.yarnpkg.com/@nut-tree/libnut-win32/-/libnut-win32-2.5.2.tgz#6ae816544d9aa7e795910ef37c5ea07078315dd0" + integrity sha512-cnNAQ0pzUMH7hrSjTWRiFfXid3sbSZ78jpv1rA154dlka3wqo6m1OtaX4PLVQK4irZl5REz74iPdHcjeTy9rtg== + dependencies: + bindings "1.5.0" + optionalDependencies: + "@nut-tree/node-mac-permissions" "2.2.1" + +"@nut-tree/[email protected]": + version "2.5.2" + resolved "https://registry.yarnpkg.com/@nut-tree/libnut/-/libnut-2.5.2.tgz#0e410c108bee31c57ca5923e409762ff223d70de" + integrity sha512-IwlGgalGQjjCrbPq52HTLtsR6MRsGJ6c4GhgHmgwJPD/yBVCzsU5EA2rwDgjKSgK+jiLOpykySDZQ+owhyd1zw== + dependencies: + "@nut-tree/libnut-darwin" "2.5.2" + "@nut-tree/libnut-linux" "2.5.2" + "@nut-tree/libnut-win32" "2.5.2" + +"@nut-tree/[email protected]": + version "2.2.1" + resolved "https://registry.yarnpkg.com/@nut-tree/node-mac-permissions/-/node-mac-permissions-2.2.1.tgz#925597509cb4492d2567dd04607f58c531b3584e" + integrity sha512-yoijwCqt2yS9UFTv7THGUwZgy2D2TorN703QpYNOergbTJ6vEmeG379pIZDfBuvf56n24RMzKJVoSqr9WIq/Yw== + dependencies: + bindings "1.5.0" + node-addon-api "5.0.0" + +"@nut-tree/nut-js@^3.1.2": + version "3.1.2" + resolved "https://registry.yarnpkg.com/@nut-tree/nut-js/-/nut-js-3.1.2.tgz#33f3fafd89f48230264c569289d82c99b974b915" + integrity sha512-hi7DBZz9O/t4goeQu3hKeauQbb0PcBmurScl3/t5L3I1pub3ibV24sft8KNSS3INKnGCj7I3Ma5iNHQ24g+95g== + dependencies: + "@nut-tree/libnut" "2.5.2" + clipboardy "2.3.0" + jimp "0.16.13" + node-abort-controller "2.0.0" + "@sindresorhus/is@^4.0.0": version "4.6.0" resolved "https://registry.yarnpkg.com/@sindresorhus/is/-/is-4.6.0.tgz#3c7c9c46e678feefe7a2e5bb609d3dbd665ffb3f" @@ -73,6 +424,11 @@ dependencies: defer-to-connect "^2.0.0" +"@tokenizer/token@^0.3.0": + version "0.3.0" + resolved "https://registry.yarnpkg.com/@tokenizer/token/-/token-0.3.0.tgz#fe98a93fe789247e998c75e74e9c7c63217aa276" + integrity sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A== + "@types/cacheable-request@^6.0.1": version "6.0.3" resolved "https://registry.yarnpkg.com/@types/cacheable-request/-/cacheable-request-6.0.3.tgz#a430b3260466ca7b5ca5bfd735693b36e7a9d183" @@ -100,6 +456,11 @@ resolved "https://registry.yarnpkg.com/@types/node/-/node-13.7.0.tgz#b417deda18cf8400f278733499ad5547ed1abec4" integrity sha512-GnZbirvmqZUzMgkFn70c74OQpTTUcCzlhQliTzYjQMqg+hVKcDnxdL19Ne3UdYzdMA/+W3eb646FWn/ZaT1NfQ== +"@types/[email protected]": + version "16.9.1" + resolved "https://registry.yarnpkg.com/@types/node/-/node-16.9.1.tgz#0611b37db4246c937feef529ddcc018cf8e35708" + integrity sha512-QpLcX9ZSsq3YYUUnD3nFDY8H7wctAhQj/TFKL8Ya8v5fMm3CFXxo8zStsLAl780ltoYoo1WvKUVGBQK+1ifr7g== + "@types/responselike@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/responselike/-/responselike-1.0.0.tgz#251f4fe7d154d2bad125abe1b429b23afd262e29" @@ -156,6 +517,11 @@ ansi-styles@^4.0.0, ansi-styles@^4.1.0: dependencies: color-convert "^2.0.1" +any-base@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/any-base/-/any-base-1.1.0.tgz#ae101a62bc08a597b4c9ab5b7089d456630549fe" + integrity sha512-uMgjozySS8adZZYePpaWs8cxB9/kdzmpX6SgJZ+wbz1K5eYk5QMYDVJaZKhxyIHUdnnJkfR7SVgStgH7LkGUyg== + anymatch@~3.1.2: version "3.1.3" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.3.tgz#790c58b19ba1720a84205b57c618d5ad8524973e" @@ -164,6 +530,11 @@ anymatch@~3.1.2: normalize-path "^3.0.0" picomatch "^2.0.4" +arch@^2.1.1: + version "2.2.0" + resolved "https://registry.yarnpkg.com/arch/-/arch-2.2.0.tgz#1bc47818f305764f23ab3306b0bfc086c5a29d11" + integrity sha512-Of/R0wqp83cgHozfIYLbBMnej79U/SVGOOyuB3VVFv1NRM/PSFMK12x9KVtiYzJqmnU5WR2qp0Z5rHb7sWGnFQ== + argparse@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" @@ -179,6 +550,11 @@ balanced-match@^1.0.0: resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== +base64-js@^1.3.1: + version "1.5.1" + resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" + integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA== + basic-auth@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/basic-auth/-/basic-auth-2.0.1.tgz#b998279bf47ce38344b4f3cf916d4679bbf51e3a" @@ -191,13 +567,18 @@ binary-extensions@^2.0.0: resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.2.0.tgz#75f502eeaf9ffde42fc98829645be4ea76bd9e2d" integrity sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA== -bindings@^1.2.1: [email protected], bindings@^1.2.1: version "1.5.0" resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.5.0.tgz#10353c9e945334bc0511a6d90b38fbc7c9c504df" integrity sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ== dependencies: file-uri-to-path "1.0.0" +bmp-js@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/bmp-js/-/bmp-js-0.1.0.tgz#e05a63f796a6c1ff25f4771ec7adadc148c07233" + integrity sha512-vHdS19CnY3hwiNdkaqk93DvjVLfbEcI8mys4UjuWrlX1haDmroo8o4xCzh4wD6DGV6HxRCyauwhHRqMTfERtjw== + brace-expansion@^1.1.7: version "1.1.11" resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" @@ -225,6 +606,19 @@ [email protected]: resolved "https://registry.yarnpkg.com/browser-stdout/-/browser-stdout-1.3.1.tgz#baa559ee14ced73452229bad7326467c61fabd60" integrity sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw== [email protected]: + version "0.0.1" + resolved "https://registry.yarnpkg.com/buffer-equal/-/buffer-equal-0.0.1.tgz#91bc74b11ea405bc916bc6aa908faafa5b4aac4b" + integrity sha512-RgSV6InVQ9ODPdLWJ5UAqBqJBOg370Nz6ZQtRzpt6nUjc8v0St97uJ4PYC6NztqIScrAXafKM3mZPMygSe1ggA== + +buffer@^5.2.0: + version "5.7.1" + resolved "https://registry.yarnpkg.com/buffer/-/buffer-5.7.1.tgz#ba62e7c13133053582197160851a8f648e99eed0" + integrity sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ== + dependencies: + base64-js "^1.3.1" + ieee754 "^1.1.13" + busboy@^1.6.0: version "1.6.0" resolved "https://registry.yarnpkg.com/busboy/-/busboy-1.6.0.tgz#966ea36a9502e43cdb9146962523b92f531f6893" @@ -308,6 +702,15 @@ [email protected]: optionalDependencies: fsevents "~2.3.2" [email protected]: + version "2.3.0" + resolved "https://registry.yarnpkg.com/clipboardy/-/clipboardy-2.3.0.tgz#3c2903650c68e46a91b388985bc2774287dba290" + integrity sha512-mKhiIL2DrQIsuXMgBgnfEHOZOryC7kY7YO//TN6c63wlEm3NG5tz+YgY5rVi29KCmq/QQjKYvM7a19+MDOTHOQ== + dependencies: + arch "^2.1.1" + execa "^1.0.0" + is-wsl "^2.1.1" + cliui@^7.0.2: version "7.0.4" resolved "https://registry.yarnpkg.com/cliui/-/cliui-7.0.4.tgz#a0265ee655476fc807aea9df3df8df7783808b4f" @@ -346,6 +749,17 @@ [email protected]: resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg== +cross-spawn@^6.0.0: + version "6.0.5" + resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-6.0.5.tgz#4a5ec7c64dfae22c3a14124dbacdee846d80cbc4" + integrity sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ== + dependencies: + nice-try "^1.0.4" + path-key "^2.0.1" + semver "^5.5.0" + shebang-command "^1.2.0" + which "^1.2.9" + [email protected]: version "0.0.2" resolved "https://registry.yarnpkg.com/crypt/-/crypt-0.0.2.tgz#88d7ff7ec0dfb86f713dc87bbb42d044d3e6c41b" @@ -428,6 +842,11 @@ dirty-chai@^2.0.1: resolved "https://registry.yarnpkg.com/dirty-chai/-/dirty-chai-2.0.1.tgz#6b2162ef17f7943589da840abc96e75bda01aff3" integrity sha512-ys79pWKvDMowIDEPC6Fig8d5THiC0DJ2gmTeGzVAoEH18J8OzLud0Jh7I9IWg3NSk8x2UocznUuFmfHCXYZx9w== +dom-walk@^0.1.0: + version "0.1.2" + resolved "https://registry.yarnpkg.com/dom-walk/-/dom-walk-0.1.2.tgz#0c548bef048f4d1f2a97249002236060daa3fd84" + integrity sha512-6QvTW9mrGeIegrFXdtQi9pk7O/nSK6lSdXW2eqUspN5LWD7UTji2Fqw5V2YLjBpHEoU9Xl/eUWNpDeZvoyOv2w== + dommatrix@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/dommatrix/-/dommatrix-1.0.3.tgz#e7c18e8d6f3abdd1fef3dd4aa74c4d2e620a0525" @@ -493,6 +912,33 @@ event-stream@^4.0.0: stream-combiner "^0.2.2" through "^2.3.8" +execa@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/execa/-/execa-1.0.0.tgz#c6236a5bb4df6d6f15e88e7f017798216749ddd8" + integrity sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA== + dependencies: + cross-spawn "^6.0.0" + get-stream "^4.0.0" + is-stream "^1.1.0" + npm-run-path "^2.0.0" + p-finally "^1.0.0" + signal-exit "^3.0.0" + strip-eof "^1.0.0" + +exif-parser@^0.1.12: + version "0.1.12" + resolved "https://registry.yarnpkg.com/exif-parser/-/exif-parser-0.1.12.tgz#58a9d2d72c02c1f6f02a0ef4a9166272b7760922" + integrity sha512-c2bQfLNbMzLPmzQuOr8fy0csy84WmwnER81W88DzTp9CYNPJ6yzOj2EZAh9pywYpqHnshVLHQJ8WzldAyfY+Iw== + +file-type@^16.5.4: + version "16.5.4" + resolved "https://registry.yarnpkg.com/file-type/-/file-type-16.5.4.tgz#474fb4f704bee427681f98dd390058a172a6c2fd" + integrity sha512-/yFHK0aGjFEgDJjEKP0pWCplsPFPhwyfwevf/pVxiN0tmE4L9LmwWxWukdJSHdoCli4VgQLehjJtwQBnqmsKcw== + dependencies: + readable-web-to-node-stream "^3.0.0" + strtok3 "^6.2.4" + token-types "^4.1.1" + [email protected]: version "1.0.0" resolved "https://registry.yarnpkg.com/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz#553a7b8446ff6f684359c445f1e37a05dacc33dd" @@ -548,6 +994,13 @@ get-func-name@^2.0.0: resolved "https://registry.yarnpkg.com/get-func-name/-/get-func-name-2.0.2.tgz#0d7cf20cd13fda808669ffa88f4ffc7a3943fc41" integrity sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ== +get-stream@^4.0.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-4.1.0.tgz#c1b255575f3dc21d59bfc79cd3d2b46b1c3a54b5" + integrity sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w== + dependencies: + pump "^3.0.0" + get-stream@^5.1.0: version "5.2.0" resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-5.2.0.tgz#4966a1795ee5ace65e706c4b7beb71257d6e22d3" @@ -555,6 +1008,14 @@ get-stream@^5.1.0: dependencies: pump "^3.0.0" +gifwrap@^0.9.2: + version "0.9.4" + resolved "https://registry.yarnpkg.com/gifwrap/-/gifwrap-0.9.4.tgz#f4eb6169ba027d61df64aafbdcb1f8ae58ccc0c5" + integrity sha512-MDMwbhASQuVeD4JKd1fKgNgCRL3fGqMM4WaqpNhWO0JiMOAjbQdumbs4BbBZEy9/M00EHEjKN3HieVhCUlwjeQ== + dependencies: + image-q "^4.0.0" + omggif "^1.0.10" + glob-parent@~5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4" @@ -586,6 +1047,14 @@ glob@^7.1.3: once "^1.3.0" path-is-absolute "^1.0.0" +global@~4.4.0: + version "4.4.0" + resolved "https://registry.yarnpkg.com/global/-/global-4.4.0.tgz#3e7b105179006a323ed71aafca3e9c57a5cc6406" + integrity sha512-wv/LAoHdRE3BeTGz53FAamhGlPLhlssK45usmGFThIi4XqnBmjKQ16u+RNbP7WvigRZDxUsM0J3gcQ5yicaL0w== + dependencies: + min-document "^2.19.0" + process "^0.11.10" + got@^11.8.6: version "11.8.6" resolved "https://registry.yarnpkg.com/got/-/got-11.8.6.tgz#276e827ead8772eddbcfc97170590b841823233a" @@ -646,6 +1115,18 @@ http2-wrapper@^1.0.0-beta.5.2: quick-lru "^5.1.1" resolve-alpn "^1.0.0" +ieee754@^1.1.13, ieee754@^1.2.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" + integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA== + +image-q@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/image-q/-/image-q-4.0.0.tgz#31e075be7bae3c1f42a85c469b4732c358981776" + integrity sha512-PfJGVgIfKQJuq3s0tTDOKtztksibuUEbJQIYT3by6wctQo+Rdlh7ef4evJ5NCdxY4CfMbvFkocEwbl4BF8RlJw== + dependencies: + "@types/node" "16.9.1" + inflight@^1.0.4: version "1.0.6" resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" @@ -654,7 +1135,7 @@ inflight@^1.0.4: once "^1.3.0" wrappy "1" -inherits@2: +inherits@2, inherits@^2.0.3: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== @@ -676,6 +1157,11 @@ is-buffer@~1.1.6: resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be" integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w== +is-docker@^2.0.0: + version "2.2.1" + resolved "https://registry.yarnpkg.com/is-docker/-/is-docker-2.2.1.tgz#33eeabe23cfe86f14bde4408a02c0cfb853acdaa" + integrity sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ== + is-extglob@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" @@ -686,6 +1172,11 @@ is-fullwidth-code-point@^3.0.0: resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== +is-function@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-function/-/is-function-1.0.2.tgz#4f097f30abf6efadac9833b17ca5dc03f8144e08" + integrity sha512-lw7DUp0aWXYg+CBCN+JKkcE0Q2RayZnSvnZBlwgxHBQhqt5pZNVy4Ri7H9GmmXkdu7LUthszM+Tor1u/2iBcpQ== + is-glob@^4.0.1, is-glob@~4.0.1: version "4.0.3" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.3.tgz#64f61e42cbbb2eec2071a9dac0b28ba1e65d5084" @@ -703,16 +1194,49 @@ is-plain-obj@^2.1.0: resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-2.1.0.tgz#45e42e37fccf1f40da8e5f76ee21515840c09287" integrity sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA== +is-stream@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-1.1.0.tgz#12d4a3dd4e68e0b79ceb8dbc84173ae80d91ca44" + integrity sha512-uQPm8kcs47jx38atAcWTVxyltQYoPT68y9aWYdV6yWXSyW8mzSat0TL6CiWdZeCdF3KrAvpVtnHbTv4RN+rqdQ== + is-unicode-supported@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz#3f26c76a809593b52bfa2ecb5710ed2779b522a7" integrity sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw== +is-wsl@^2.1.1: + version "2.2.0" + resolved "https://registry.yarnpkg.com/is-wsl/-/is-wsl-2.2.0.tgz#74a4c76e77ca9fd3f932f290c17ea326cd157271" + integrity sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww== + dependencies: + is-docker "^2.0.0" + [email protected]: version "0.0.1" resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf" integrity sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8= +isexe@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" + integrity sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw== + [email protected]: + version "0.16.13" + resolved "https://registry.yarnpkg.com/jimp/-/jimp-0.16.13.tgz#944b6368183235afc5d077429e2a7f34834acb18" + integrity sha512-Bxz8q7V4rnCky9A0ktTNGA9SkNFVWRHodddI/DaAWZJzF7sVUlFYKQ60y9JGqrKpi48ECA/TnfMzzc5C70VByA== + dependencies: + "@babel/runtime" "^7.7.2" + "@jimp/custom" "^0.16.13" + "@jimp/plugins" "^0.16.13" + "@jimp/types" "^0.16.13" + regenerator-runtime "^0.13.3" + +jpeg-js@^0.4.2: + version "0.4.4" + resolved "https://registry.yarnpkg.com/jpeg-js/-/jpeg-js-0.4.4.tgz#a9f1c6f1f9f0fa80cdb3484ed9635054d28936aa" + integrity sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg== + [email protected]: version "4.1.0" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.1.0.tgz#c1fb65f8f5017901cdd2c951864ba18458a10602" @@ -737,6 +1261,20 @@ keyv@^4.0.0: dependencies: json-buffer "3.0.1" +load-bmfont@^1.3.1, load-bmfont@^1.4.0: + version "1.4.1" + resolved "https://registry.yarnpkg.com/load-bmfont/-/load-bmfont-1.4.1.tgz#c0f5f4711a1e2ccff725a7b6078087ccfcddd3e9" + integrity sha512-8UyQoYmdRDy81Brz6aLAUhfZLwr5zV0L3taTQ4hju7m6biuwiWiJXjPhBJxbUQJA8PrkvJ/7Enqmwk2sM14soA== + dependencies: + buffer-equal "0.0.1" + mime "^1.3.4" + parse-bmfont-ascii "^1.0.3" + parse-bmfont-binary "^1.0.5" + parse-bmfont-xml "^1.1.4" + phin "^2.9.1" + xhr "^2.0.1" + xtend "^4.0.0" + locate-path@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-6.0.0.tgz#55321eb309febbc59c4801d931a72452a681d286" @@ -798,6 +1336,11 @@ [email protected]: resolved "https://registry.yarnpkg.com/mime/-/mime-1.4.1.tgz#121f9ebc49e3766f311a76e1fa1c8003c4b03aa6" integrity sha512-KI1+qOZu5DcW6wayYHSzR/tXKCDC5Om4s1z2QJjDULzLcmf3DvzS7oluY4HCTrc+9FiKmWUgeNLg7W3uIQvxtQ== +mime@^1.3.4: + version "1.6.0" + resolved "https://registry.yarnpkg.com/mime/-/mime-1.6.0.tgz#32cd9e5c64553bd58d19a568af452acff04981b1" + integrity sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg== + mimic-response@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-1.0.1.tgz#4923538878eef42063cb8a3e3b0798781487ab1b" @@ -808,6 +1351,13 @@ mimic-response@^3.1.0: resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-3.1.0.tgz#2d1d59af9c1b129815accc2c46a022a5ce1fa3c9" integrity sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ== +min-document@^2.19.0: + version "2.19.0" + resolved "https://registry.yarnpkg.com/min-document/-/min-document-2.19.0.tgz#7bd282e3f5842ed295bb748cdd9f1ffa2c824685" + integrity sha512-9Wy1B3m3f66bPPmU5hdA4DR4PB2OfDU/+GS3yAB7IQozE3tqXaVv2zOjgla7MEGSRv95+ILmOuvhLkOK6wJtCQ== + dependencies: + dom-walk "^0.1.0" + [email protected]: version "5.0.1" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.0.1.tgz#fb9022f7528125187c92bd9e9b6366be1cf3415b" @@ -895,15 +1445,19 @@ [email protected]: resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== [email protected], nan@^2.12.1, nan@nodejs/nan#e14bdcd1f72d62bca1d541b66da43130384ec213: [email protected], nan@^2.12.1, "nan@file:../../third_party/nan": version "2.18.0" - resolved "https://codeload.github.com/nodejs/nan/tar.gz/e14bdcd1f72d62bca1d541b66da43130384ec213" [email protected]: version "3.3.3" resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.3.tgz#fd8e8b7aa761fe807dba2d1b98fb7241bb724a25" integrity sha512-p1sjXuopFs0xg+fPASzQ28agW1oHD7xDsd9Xkf3T15H3c/cifrFHVwrh74PdoklAPi+i7MdRsE47vm2r6JoB+w== +nice-try@^1.0.4: + version "1.0.5" + resolved "https://registry.yarnpkg.com/nice-try/-/nice-try-1.0.5.tgz#a3378a7696ce7d223e88fc9b764bd7ef1089e366" + integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ== + nise@^4.0.1: version "4.0.3" resolved "https://registry.yarnpkg.com/nise/-/nise-4.0.3.tgz#9f79ff02fa002ed5ffbc538ad58518fa011dc913" @@ -915,6 +1469,16 @@ nise@^4.0.1: just-extend "^4.0.2" path-to-regexp "^1.7.0" [email protected]: + version "2.0.0" + resolved "https://registry.yarnpkg.com/node-abort-controller/-/node-abort-controller-2.0.0.tgz#800e0d250d3b977175e48df4f74c2d3960076a79" + integrity sha512-L8RfEgjBTHAISTuagw51PprVAqNZoG6KSB6LQ6H1bskMVkFs5E71IyjauLBv3XbuomJlguWF/VnRHdJ1gqiAqA== + [email protected]: + version "5.0.0" + resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-5.0.0.tgz#7d7e6f9ef89043befdb20c1989c905ebde18c501" + integrity sha512-CvkDw2OEnme7ybCykJpVcKH+uAOLV2qLqiyla128dN9TkEWfrYmxG6C2boDe5KcNQqZF3orkqzGgOMvZ/JNekA== + normalize-path@^3.0.0, normalize-path@~3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" @@ -925,6 +1489,18 @@ normalize-url@^6.0.1: resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-6.1.0.tgz#40d0885b535deffe3f3147bec877d05fe4c5668a" integrity sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A== +npm-run-path@^2.0.0: + version "2.0.2" + resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-2.0.2.tgz#35a9232dfa35d7067b4cb2ddf2357b1871536c5f" + integrity sha512-lJxZYlT4DW/bRUtFh1MQIWqmLwQfAxnqWG4HhEdjMlkrJYnJn0Jrr2u3mgxqaWsdiBc76TYkTG/mhrnYTuzfHw== + dependencies: + path-key "^2.0.0" + +omggif@^1.0.10, omggif@^1.0.9: + version "1.0.10" + resolved "https://registry.yarnpkg.com/omggif/-/omggif-1.0.10.tgz#ddaaf90d4a42f532e9e7cb3a95ecdd47f17c7b19" + integrity sha512-LMJTtvgc/nugXj0Vcrrs68Mn2D1r0zf630VNtqtpI1FEO7e+O9FP4gqs9AcnBaSEeoHIPm28u6qgPR0oyEpGSw== + on-finished@~2.3.0: version "2.3.0" resolved "https://registry.yarnpkg.com/on-finished/-/on-finished-2.3.0.tgz#20f1336481b083cd75337992a16971aa2d906947" @@ -952,6 +1528,11 @@ p-cancelable@^2.0.0: resolved "https://registry.yarnpkg.com/p-cancelable/-/p-cancelable-2.1.1.tgz#aab7fbd416582fa32a3db49859c122487c5ed2cf" integrity sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg== +p-finally@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/p-finally/-/p-finally-1.0.0.tgz#3fbcfb15b899a44123b34b6dcc18b724336a2cae" + integrity sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow== + p-limit@^3.0.2: version "3.1.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-3.1.0.tgz#e1daccbe78d0d1388ca18c64fea38e3e57e3706b" @@ -966,6 +1547,34 @@ p-locate@^5.0.0: dependencies: p-limit "^3.0.2" +pako@^1.0.5: + version "1.0.11" + resolved "https://registry.yarnpkg.com/pako/-/pako-1.0.11.tgz#6c9599d340d54dfd3946380252a35705a6b992bf" + integrity sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw== + +parse-bmfont-ascii@^1.0.3: + version "1.0.6" + resolved "https://registry.yarnpkg.com/parse-bmfont-ascii/-/parse-bmfont-ascii-1.0.6.tgz#11ac3c3ff58f7c2020ab22769079108d4dfa0285" + integrity sha512-U4RrVsUFCleIOBsIGYOMKjn9PavsGOXxbvYGtMOEfnId0SVNsgehXh1DxUdVPLoxd5mvcEtvmKs2Mmf0Mpa1ZA== + +parse-bmfont-binary@^1.0.5: + version "1.0.6" + resolved "https://registry.yarnpkg.com/parse-bmfont-binary/-/parse-bmfont-binary-1.0.6.tgz#d038b476d3e9dd9db1e11a0b0e53a22792b69006" + integrity sha512-GxmsRea0wdGdYthjuUeWTMWPqm2+FAd4GI8vCvhgJsFnoGhTrLhXDDupwTo7rXVAgaLIGoVHDZS9p/5XbSqeWA== + +parse-bmfont-xml@^1.1.4: + version "1.1.4" + resolved "https://registry.yarnpkg.com/parse-bmfont-xml/-/parse-bmfont-xml-1.1.4.tgz#015319797e3e12f9e739c4d513872cd2fa35f389" + integrity sha512-bjnliEOmGv3y1aMEfREMBJ9tfL3WR0i0CKPj61DnSLaoxWR3nLrsQrEbCId/8rF4NyRF0cCqisSVXyQYWM+mCQ== + dependencies: + xml-parse-from-string "^1.0.0" + xml2js "^0.4.5" + +parse-headers@^2.0.0: + version "2.0.5" + resolved "https://registry.yarnpkg.com/parse-headers/-/parse-headers-2.0.5.tgz#069793f9356a54008571eb7f9761153e6c770da9" + integrity sha512-ft3iAoLOB/MlwbNXgzy43SWGP6sQki2jQvAyBg/zDFAgr9bfNWZIUj42Kw2eJIl8kEi4PbgE6U1Zau/HwI75HA== + path-exists@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" @@ -976,6 +1585,11 @@ path-is-absolute@^1.0.0: resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" integrity sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg== +path-key@^2.0.0, path-key@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/path-key/-/path-key-2.0.1.tgz#411cadb574c5a140d3a4b1910d40d80cc9f40b40" + integrity sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw== + path-to-regexp@^1.7.0: version "1.8.0" resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-1.8.0.tgz#887b3ba9d84393e87a0a0b9f4cb756198b53548a" @@ -1003,11 +1617,38 @@ pdfjs-dist@^2.16.105: dommatrix "^1.0.3" web-streams-polyfill "^3.2.1" +peek-readable@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/peek-readable/-/peek-readable-4.1.0.tgz#4ece1111bf5c2ad8867c314c81356847e8a62e72" + integrity sha512-ZI3LnwUv5nOGbQzD9c2iDG6toheuXSZP5esSHBjopsXH4dg19soufvpUGA3uohi5anFtGb2lhAVdHzH6R/Evvg== + +phin@^2.9.1: + version "2.9.3" + resolved "https://registry.yarnpkg.com/phin/-/phin-2.9.3.tgz#f9b6ac10a035636fb65dfc576aaaa17b8743125c" + integrity sha512-CzFr90qM24ju5f88quFC/6qohjC144rehe5n6DH900lgXmUe86+xCKc10ev56gRKC4/BkHUoG4uSiQgBiIXwDA== + picomatch@^2.0.4, picomatch@^2.2.1: version "2.3.1" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA== +pixelmatch@^4.0.2: + version "4.0.2" + resolved "https://registry.yarnpkg.com/pixelmatch/-/pixelmatch-4.0.2.tgz#8f47dcec5011b477b67db03c243bc1f3085e8854" + integrity sha512-J8B6xqiO37sU/gkcMglv6h5Jbd9xNER7aHzpfRdNmV4IbQBzBpe4l9XmbG+xPF/znacgu2jfEw+wHffaq/YkXA== + dependencies: + pngjs "^3.0.0" + +pngjs@^3.0.0, pngjs@^3.3.3: + version "3.4.0" + resolved "https://registry.yarnpkg.com/pngjs/-/pngjs-3.4.0.tgz#99ca7d725965fb655814eaf65f38f12bbdbf555f" + integrity sha512-NCrCHhWmnQklfH4MtJMRjZ2a8c80qXeMlQMv2uVp9ISJMTt562SbGd6n2oq0PaPgKm7Z6pL9E2UlLIhC+SHL3w== + +process@^0.11.10: + version "0.11.10" + resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182" + integrity sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A== + ps-list@^7.0.0: version "7.2.0" resolved "https://registry.yarnpkg.com/ps-list/-/ps-list-7.2.0.tgz#3d110e1de8249a4b178c9b1cf2a215d1e4e42fc0" @@ -1043,6 +1684,22 @@ range-parser@~1.2.0: resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.1.tgz#3cf37023d199e1c24d1a55b84800c2f3e6468031" integrity sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg== +readable-stream@^3.6.0: + version "3.6.2" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.2.tgz#56a9b36ea965c00c5a93ef31eb111a0f11056967" + integrity sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA== + dependencies: + inherits "^2.0.3" + string_decoder "^1.1.1" + util-deprecate "^1.0.1" + +readable-web-to-node-stream@^3.0.0: + version "3.0.2" + resolved "https://registry.yarnpkg.com/readable-web-to-node-stream/-/readable-web-to-node-stream-3.0.2.tgz#5d52bb5df7b54861fd48d015e93a2cb87b3ee0bb" + integrity sha512-ePeK6cc1EcKLEhJFt/AebMCLL+GgSKhuygrZ/GLaKZYEecIgIECf4UaUuaByiGtzckwR4ain9VzUh95T1exYGw== + dependencies: + readable-stream "^3.6.0" + readdirp@~3.6.0: version "3.6.0" resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.6.0.tgz#74a370bd857116e245b29cc97340cd431a02a6c7" @@ -1050,6 +1707,16 @@ readdirp@~3.6.0: dependencies: picomatch "^2.2.1" +regenerator-runtime@^0.13.3: + version "0.13.11" + resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz#f6dca3e7ceec20590d07ada785636a90cdca17f9" + integrity sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg== + +regenerator-runtime@^0.14.0: + version "0.14.1" + resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz#356ade10263f685dda125100cd862c1db895327f" + integrity sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw== + require-directory@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" @@ -1079,7 +1746,7 @@ [email protected]: resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== -safe-buffer@^5.1.0, safe-buffer@^5.1.1: +safe-buffer@^5.1.0, safe-buffer@^5.1.1, safe-buffer@~5.2.0: version "5.2.1" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== @@ -1089,6 +1756,11 @@ sax@>=0.6.0: resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9" integrity sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw== +semver@^5.5.0: + version "5.7.2" + resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.2.tgz#48d55db737c3287cd4835e17fa13feace1c41ef8" + integrity sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g== + send@^0.16.2: version "0.16.2" resolved "https://registry.yarnpkg.com/send/-/send-0.16.2.tgz#6ecca1e0f8c156d141597559848df64730a6bbc1" @@ -1120,6 +1792,23 @@ [email protected]: resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.1.0.tgz#d0bd85536887b6fe7c0d818cb962d9d91c54e656" integrity sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ== +shebang-command@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea" + integrity sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg== + dependencies: + shebang-regex "^1.0.0" + +shebang-regex@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3" + integrity sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ== + +signal-exit@^3.0.0: + version "3.0.7" + resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.7.tgz#a9a1767f8af84155114eaabd73f99273c8f59ad9" + integrity sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ== + sinon@^9.0.1: version "9.0.2" resolved "https://registry.yarnpkg.com/sinon/-/sinon-9.0.2.tgz#b9017e24633f4b1c98dfb6e784a5f0509f5fd85d" @@ -1172,6 +1861,13 @@ string-width@^4.1.0, string-width@^4.2.0: is-fullwidth-code-point "^3.0.0" strip-ansi "^6.0.1" +string_decoder@^1.1.1: + version "1.3.0" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e" + integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA== + dependencies: + safe-buffer "~5.2.0" + strip-ansi@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-4.0.0.tgz#a8479022eb1ac368a871389b635262c505ee368f" @@ -1186,11 +1882,24 @@ strip-ansi@^6.0.0, strip-ansi@^6.0.1: dependencies: ansi-regex "^5.0.1" +strip-eof@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/strip-eof/-/strip-eof-1.0.0.tgz#bb43ff5598a6eb05d89b59fcd129c983313606bf" + integrity sha512-7FCwGGmx8mD5xQd3RPUvnSpUXHM3BWuzjtpD4TXsfcZ9EL4azvVVUscFYwD9nx8Kh+uCBC00XBtAykoMHwTh8Q== + [email protected]: version "3.1.1" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== +strtok3@^6.2.4: + version "6.3.0" + resolved "https://registry.yarnpkg.com/strtok3/-/strtok3-6.3.0.tgz#358b80ffe6d5d5620e19a073aa78ce947a90f9a0" + integrity sha512-fZtbhtvI9I48xDSywd/somNqgUHl2L2cstmXCCif0itOf96jeW18MBSyrLuNicYQVkvpOxkZtkzujiTJ9LW5Jw== + dependencies: + "@tokenizer/token" "^0.3.0" + peek-readable "^4.1.0" + [email protected]: version "8.1.1" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-8.1.1.tgz#cd6fc17e28500cff56c1b86c0a7fd4a54a73005c" @@ -1218,6 +1927,16 @@ through@2, through@^2.3.8, through@~2.3, through@~2.3.4: resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" integrity sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg== +timm@^1.6.1: + version "1.7.1" + resolved "https://registry.yarnpkg.com/timm/-/timm-1.7.1.tgz#96bab60c7d45b5a10a8a4d0f0117c6b7e5aff76f" + integrity sha512-IjZc9KIotudix8bMaBW6QvMuq64BrJWFs1+4V0lXwWGQZwH+LnX87doAYhem4caOEusRP9/g6jVDQmZ8XOk1nw== + +tinycolor2@^1.4.1: + version "1.6.0" + resolved "https://registry.yarnpkg.com/tinycolor2/-/tinycolor2-1.6.0.tgz#f98007460169b0263b97072c5ae92484ce02d09e" + integrity sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw== + to-regex-range@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" @@ -1225,11 +1944,31 @@ to-regex-range@^5.0.1: dependencies: is-number "^7.0.0" +token-types@^4.1.1: + version "4.2.1" + resolved "https://registry.yarnpkg.com/token-types/-/token-types-4.2.1.tgz#0f897f03665846982806e138977dbe72d44df753" + integrity sha512-6udB24Q737UD/SDsKAHI9FCRP7Bqc9D/MQUV02ORQg5iskjtLJlZJNdN4kKtcdtwCeWIwIHDGaUsTsCCAa8sFQ== + dependencies: + "@tokenizer/token" "^0.3.0" + ieee754 "^1.2.1" + [email protected], type-detect@^4.0.0, type-detect@^4.0.5, type-detect@^4.0.8: version "4.0.8" resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c" integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g== +utif@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/utif/-/utif-2.0.1.tgz#9e1582d9bbd20011a6588548ed3266298e711759" + integrity sha512-Z/S1fNKCicQTf375lIP9G8Sa1H/phcysstNrrSdZKj1f9g58J4NMgb5IgiEZN9/nLMPDwF0W7hdOe9Qq2IYoLg== + dependencies: + pako "^1.0.5" + +util-deprecate@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" + integrity sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw== + uuid@^3.3.3: version "3.4.0" resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.4.0.tgz#b23e4358afa8a202fe7a100af1f5f883f02007ee" @@ -1245,6 +1984,13 @@ web-streams-polyfill@^3.2.1: resolved "https://registry.yarnpkg.com/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz#71c2718c52b45fd49dbeee88634b3a60ceab42a6" integrity sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q== +which@^1.2.9: + version "1.3.1" + resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" + integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ== + dependencies: + isexe "^2.0.0" + winreg@^1.2.4: version "1.2.4" resolved "https://registry.yarnpkg.com/winreg/-/winreg-1.2.4.tgz#ba065629b7a925130e15779108cf540990e98d1b" @@ -1279,6 +2025,21 @@ ws@^7.4.6: resolved "https://registry.yarnpkg.com/ws/-/ws-7.4.6.tgz#5654ca8ecdeee47c33a9a4bf6d28e2be2980377c" integrity sha512-YmhHDO4MzaDLB+M9ym/mDA5z0naX8j7SIlT8f8z+I0VtzsRbekxEutHSme7NPS2qE8StCYQNUnfWdXta/Yu85A== +xhr@^2.0.1: + version "2.6.0" + resolved "https://registry.yarnpkg.com/xhr/-/xhr-2.6.0.tgz#b69d4395e792b4173d6b7df077f0fc5e4e2b249d" + integrity sha512-/eCGLb5rxjx5e3mF1A7s+pLlR6CGyqWN91fv1JgER5mVWg1MZmlhBvy9kjcsOdRk8RrIujotWyJamfyrp+WIcA== + dependencies: + global "~4.4.0" + is-function "^1.0.1" + parse-headers "^2.0.0" + xtend "^4.0.0" + +xml-parse-from-string@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/xml-parse-from-string/-/xml-parse-from-string-1.0.1.tgz#a9029e929d3dbcded169f3c6e28238d95a5d5a28" + integrity sha512-ErcKwJTF54uRzzNMXq2X5sMIy88zJvfN2DmdoQvy7PAFJ+tPRU6ydWuOKNMyfmOjdyBQTFREi60s0Y0SyI0G0g== + [email protected], xml2js@^0.4.17: version "0.5.0" resolved "https://registry.yarnpkg.com/xml2js/-/xml2js-0.5.0.tgz#d9440631fbb2ed800203fad106f2724f62c493b7" @@ -1287,6 +2048,14 @@ [email protected], xml2js@^0.4.17: sax ">=0.6.0" xmlbuilder "~11.0.0" +xml2js@^0.4.5: + version "0.4.23" + resolved "https://registry.yarnpkg.com/xml2js/-/xml2js-0.4.23.tgz#a0c69516752421eb2ac758ee4d4ccf58843eac66" + integrity sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug== + dependencies: + sax ">=0.6.0" + xmlbuilder "~11.0.0" + xml@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/xml/-/xml-1.0.1.tgz#78ba72020029c5bc87b8a81a3cfcd74b4a2fc1e5" @@ -1297,6 +2066,11 @@ xmlbuilder@~11.0.0: resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-11.0.1.tgz#be9bae1c8a046e76b31127726347d0ad7002beb3" integrity sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA== +xtend@^4.0.0: + version "4.0.2" + resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54" + integrity sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ== + y18n@^5.0.5: version "5.0.8" resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55"
test
50ce448556b870f42f98d6567159576b8d0f0495
Shelley Vohr
2024-08-22 20:13:30
fix: menu should allow focused `BaseWindow` where possible (#43404) fix: menu should allow focused BaseWindow
diff --git a/docs/api/menu-item.md b/docs/api/menu-item.md index 3ad0c8e87c..0bc80b2bd3 100644 --- a/docs/api/menu-item.md +++ b/docs/api/menu-item.md @@ -10,9 +10,9 @@ See [`Menu`](menu.md) for examples. * `options` Object * `click` Function (optional) - Will be called with - `click(menuItem, browserWindow, event)` when the menu item is clicked. + `click(menuItem, window, event)` when the menu item is clicked. * `menuItem` MenuItem - * `browserWindow` [BrowserWindow](browser-window.md) | undefined - This will not be defined if no window is open. + * `window` [BaseWindow](base-window.md) | undefined - This will not be defined if no window is open. * `event` [KeyboardEvent](structures/keyboard-event.md) * `role` string (optional) - Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `reload`, `forceReload`, `toggleDevTools`, `resetZoom`, `zoomIn`, `zoomOut`, `toggleSpellChecker`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`, `showSubstitutions`, `toggleSmartQuotes`, `toggleSmartDashes`, `toggleTextReplacement`, `startSpeaking`, `stopSpeaking`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu`, `shareMenu`, `recentDocuments`, `toggleTabBar`, `selectNextTab`, `selectPreviousTab`, `showAllTabs`, `mergeAllWindows`, `clearRecentDocuments`, `moveTabToNewWindow` or `windowMenu` - Define the action of the menu item, when specified the `click` property will be ignored. See [roles](#roles). @@ -146,7 +146,7 @@ A `Function` that is fired when the MenuItem receives a click event. It can be called with `menuItem.click(event, focusedWindow, focusedWebContents)`. * `event` [KeyboardEvent](structures/keyboard-event.md) -* `focusedWindow` [BrowserWindow](browser-window.md) +* `focusedWindow` [BaseWindow](browser-window.md) * `focusedWebContents` [WebContents](web-contents.md) #### `menuItem.submenu` diff --git a/lib/browser/api/menu-item-roles.ts b/lib/browser/api/menu-item-roles.ts index 8fcc528271..1fa02345cb 100644 --- a/lib/browser/api/menu-item-roles.ts +++ b/lib/browser/api/menu-item-roles.ts @@ -1,4 +1,4 @@ -import { app, BrowserWindow, session, webContents, WebContents, MenuItemConstructorOptions } from 'electron/main'; +import { app, BaseWindow, BrowserWindow, session, webContents, WebContents, MenuItemConstructorOptions } from 'electron/main'; const isMac = process.platform === 'darwin'; const isWindows = process.platform === 'win32'; @@ -13,7 +13,7 @@ interface Role { label: string; accelerator?: string; checked?: boolean; - windowMethod?: ((window: BrowserWindow) => void); + windowMethod?: ((window: BaseWindow) => void); webContentsMethod?: ((webContents: WebContents) => void); appMethod?: () => void; registerAccelerator?: boolean; @@ -53,8 +53,10 @@ export const roleList: Record<RoleId, Role> = { label: 'Force Reload', accelerator: 'Shift+CmdOrCtrl+R', nonNativeMacOSRole: true, - windowMethod: (window: BrowserWindow) => { - window.webContents.reloadIgnoringCache(); + windowMethod: (window: BaseWindow) => { + if (window instanceof BrowserWindow) { + window.webContents.reloadIgnoringCache(); + } } }, front: { @@ -110,7 +112,11 @@ export const roleList: Record<RoleId, Role> = { label: 'Reload', accelerator: 'CmdOrCtrl+R', nonNativeMacOSRole: true, - windowMethod: w => w.reload() + windowMethod: (w: BaseWindow) => { + if (w instanceof BrowserWindow) { + w.reload(); + } + } }, resetzoom: { label: 'Actual Size', @@ -164,7 +170,7 @@ export const roleList: Record<RoleId, Role> = { togglefullscreen: { label: 'Toggle Full Screen', accelerator: isMac ? 'Control+Command+F' : 'F11', - windowMethod: (window: BrowserWindow) => { + windowMethod: (window: BaseWindow) => { window.setFullScreen(!window.isFullScreen()); } }, @@ -361,7 +367,7 @@ export function getDefaultSubmenu (role: RoleId) { return submenu; } -export function execute (role: RoleId, focusedWindow: BrowserWindow, focusedWebContents: WebContents) { +export function execute (role: RoleId, focusedWindow: BaseWindow, focusedWebContents: WebContents) { if (!canExecuteRole(role)) return false; const { appMethod, webContentsMethod, windowMethod } = roleList[role]; diff --git a/lib/browser/api/menu-item.ts b/lib/browser/api/menu-item.ts index ae1c2ea5a2..ae74948064 100644 --- a/lib/browser/api/menu-item.ts +++ b/lib/browser/api/menu-item.ts @@ -1,5 +1,5 @@ import * as roles from '@electron/internal/browser/api/menu-item-roles'; -import { Menu, BrowserWindow, WebContents, KeyboardEvent } from 'electron/main'; +import { Menu, BaseWindow, WebContents, KeyboardEvent } from 'electron/main'; let nextCommandId = 0; @@ -53,7 +53,7 @@ const MenuItem = function (this: any, options: any) { }); const click = options.click; - this.click = (event: KeyboardEvent, focusedWindow: BrowserWindow, focusedWebContents: WebContents) => { + this.click = (event: KeyboardEvent, focusedWindow: BaseWindow, focusedWebContents: WebContents) => { // Manually flip the checked flags when clicked. if (!roles.shouldOverrideCheckStatus(this.role) && (this.type === 'checkbox' || this.type === 'radio')) { diff --git a/lib/browser/api/menu.ts b/lib/browser/api/menu.ts index abdf50bf6d..48a7f475b1 100644 --- a/lib/browser/api/menu.ts +++ b/lib/browser/api/menu.ts @@ -1,4 +1,4 @@ -import { BaseWindow, MenuItem, webContents, Menu as MenuType, BrowserWindow, MenuItemConstructorOptions } from 'electron/main'; +import { BaseWindow, MenuItem, webContents, Menu as MenuType, MenuItemConstructorOptions } from 'electron/main'; import { sortMenuItems } from '@electron/internal/browser/api/menu-utils'; import { setApplicationMenuWasSet } from '@electron/internal/browser/default-menu'; @@ -54,7 +54,7 @@ Menu.prototype._executeCommand = function (event, id) { const command = this.commandsMap[id]; if (!command) return; const focusedWindow = BaseWindow.getFocusedWindow(); - command.click(event, focusedWindow instanceof BrowserWindow ? focusedWindow : undefined, webContents.getFocusedWebContents()); + command.click(event, focusedWindow, webContents.getFocusedWebContents()); }; Menu.prototype._menuWillShow = function () { diff --git a/spec/ts-smoke/electron/main.ts b/spec/ts-smoke/electron/main.ts index 2a8c13ac87..278fef29a5 100644 --- a/spec/ts-smoke/electron/main.ts +++ b/spec/ts-smoke/electron/main.ts @@ -717,7 +717,7 @@ const template = <Electron.MenuItemConstructorOptions[]> [ label: 'Reload', accelerator: 'Command+R', click: (item, focusedWindow) => { - if (focusedWindow) { + if (focusedWindow instanceof BrowserWindow) { focusedWindow.webContents.reloadIgnoringCache(); } } @@ -726,7 +726,7 @@ const template = <Electron.MenuItemConstructorOptions[]> [ label: 'Toggle DevTools', accelerator: 'Alt+Command+I', click: (item, focusedWindow) => { - if (focusedWindow) { + if (focusedWindow instanceof BrowserWindow) { focusedWindow.webContents.toggleDevTools(); } } @@ -738,7 +738,7 @@ const template = <Electron.MenuItemConstructorOptions[]> [ label: 'Actual Size', accelerator: 'CmdOrCtrl+0', click: (item, focusedWindow) => { - if (focusedWindow) { + if (focusedWindow instanceof BrowserWindow) { focusedWindow.webContents.zoomLevel = 0; } } @@ -747,7 +747,7 @@ const template = <Electron.MenuItemConstructorOptions[]> [ label: 'Zoom In', accelerator: 'CmdOrCtrl+Plus', click: (item, focusedWindow) => { - if (focusedWindow) { + if (focusedWindow instanceof BrowserWindow) { const { webContents } = focusedWindow; webContents.zoomLevel += 0.5; } @@ -757,7 +757,7 @@ const template = <Electron.MenuItemConstructorOptions[]> [ label: 'Zoom Out', accelerator: 'CmdOrCtrl+-', click: (item, focusedWindow) => { - if (focusedWindow) { + if (focusedWindow instanceof BrowserWindow) { const { webContents } = focusedWindow; webContents.zoomLevel -= 0.5; }
fix
1252f92431add122d7ab5f0947f7cf2f634c9fb8
Shelley Vohr
2024-03-10 18:18:56
chore: remove 8088 from codespaces port forwarding (#41557)
diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 3743ea60ae..88c851c937 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -4,12 +4,8 @@ "onCreateCommand": ".devcontainer/on-create-command.sh", "updateContentCommand": ".devcontainer/update-content-command.sh", "workspaceFolder": "/workspaces/gclient/src/electron", - "forwardPorts": [8088, 6080, 5901], + "forwardPorts": [6080, 5901], "portsAttributes": { - "8088": { - "label": "Goma Control Panel", - "onAutoForward": "silent" - }, "6080": { "label": "VNC web client (noVNC)", "onAutoForward": "silent"
chore
6caf9f06f3fe3a93d63ab3b4a02f3feb6c1810ff
Shelley Vohr
2024-06-12 10:59:04
fix: don't observe WebUSB for in-memory partitions (#42443)
diff --git a/shell/browser/hid/electron_hid_delegate.cc b/shell/browser/hid/electron_hid_delegate.cc index 91a174ab2c..8cd163dbb2 100644 --- a/shell/browser/hid/electron_hid_delegate.cc +++ b/shell/browser/hid/electron_hid_delegate.cc @@ -46,8 +46,8 @@ class ElectronHidDelegate::ContextObservation ContextObservation(ElectronHidDelegate* parent, content::BrowserContext* browser_context) : parent_(parent), browser_context_(browser_context) { - auto* chooser_context = GetChooserContext(browser_context_); - device_observation_.Observe(chooser_context); + if (auto* chooser_context = GetChooserContext(browser_context_)) + device_observation_.Observe(chooser_context); } ContextObservation(ContextObservation&) = delete; diff --git a/shell/browser/usb/electron_usb_delegate.cc b/shell/browser/usb/electron_usb_delegate.cc index e396863e0d..4e15d1954a 100644 --- a/shell/browser/usb/electron_usb_delegate.cc +++ b/shell/browser/usb/electron_usb_delegate.cc @@ -94,7 +94,8 @@ class ElectronUsbDelegate::ContextObservation content::BrowserContext* browser_context) : parent_(parent), browser_context_(browser_context) { auto* chooser_context = GetChooserContext(browser_context_); - device_observation_.Observe(chooser_context); + if (chooser_context) + device_observation_.Observe(chooser_context); } ContextObservation(ContextObservation&) = delete; ContextObservation& operator=(ContextObservation&) = delete;
fix
7e241eef7c2e77edd882c25ccc6c38d1f29367ea
David Sanders
2024-02-14 02:13:03
ci: update GitHub actions workflow dependencies (#41321)
diff --git a/.github/workflows/branch-created.yml b/.github/workflows/branch-created.yml index 2a0bf85694..8ca6388a9c 100644 --- a/.github/workflows/branch-created.yml +++ b/.github/workflows/branch-created.yml @@ -73,7 +73,7 @@ jobs: org: electron - name: Generate Release Project Board Metadata if: ${{ steps.check-major-version.outputs.MAJOR }} - uses: actions/github-script@d7906e4ad0b1822421a7e6a35d5ca353c962f410 # v6.4.1 + uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1 id: generate-project-metadata with: script: | @@ -92,7 +92,7 @@ jobs: })) - name: Create Release Project Board if: ${{ steps.check-major-version.outputs.MAJOR }} - uses: dsanders11/project-actions/copy-project@3a81985616963f32fae17d1d1b406c631f3201a1 # v1.1.0 + uses: dsanders11/project-actions/copy-project@82e99438bd44a14ad18d92d036dbc25cbfb9a8c4 # v1.2.0 id: create-release-board with: drafts: true @@ -112,14 +112,14 @@ jobs: GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }} - name: Find Previous Release Project Board if: ${{ steps.check-major-version.outputs.MAJOR }} - uses: dsanders11/project-actions/find-project@3a81985616963f32fae17d1d1b406c631f3201a1 # v1.1.0 + uses: dsanders11/project-actions/find-project@82e99438bd44a14ad18d92d036dbc25cbfb9a8c4 # v1.2.0 id: find-prev-release-board with: title: ${{ steps.generate-project-metadata.outputs.prev-prev-major }}-x-y token: ${{ steps.generate-token.outputs.token }} - name: Close Previous Release Project Board if: ${{ steps.check-major-version.outputs.MAJOR }} - uses: dsanders11/project-actions/close-project@3a81985616963f32fae17d1d1b406c631f3201a1 # v1.1.0 + uses: dsanders11/project-actions/close-project@82e99438bd44a14ad18d92d036dbc25cbfb9a8c4 # v1.2.0 with: project-number: ${{ steps.find-prev-release-board.outputs.number }} token: ${{ steps.generate-token.outputs.token }} diff --git a/.github/workflows/issue-commented.yml b/.github/workflows/issue-commented.yml index d21f6a3ec4..f17254858b 100644 --- a/.github/workflows/issue-commented.yml +++ b/.github/workflows/issue-commented.yml @@ -14,7 +14,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Generate GitHub App token - uses: electron/github-app-auth-action@cc6751b3b5e4edc5b9a4ad0a021ac455653b6dc8 # v1.0.0 + uses: electron/github-app-auth-action@384fd19694fe7b6dcc9a684746c6976ad78228ae # v1.1.1 id: generate-token with: creds: ${{ secrets.ISSUE_TRIAGE_GH_APP_CREDS }} diff --git a/.github/workflows/issue-labeled.yml b/.github/workflows/issue-labeled.yml index 20205f0128..e92b46739c 100644 --- a/.github/workflows/issue-labeled.yml +++ b/.github/workflows/issue-labeled.yml @@ -14,13 +14,13 @@ jobs: runs-on: ubuntu-latest steps: - name: Generate GitHub App token - uses: electron/github-app-auth-action@cc6751b3b5e4edc5b9a4ad0a021ac455653b6dc8 # v1.0.0 + uses: electron/github-app-auth-action@384fd19694fe7b6dcc9a684746c6976ad78228ae # v1.1.1 id: generate-token with: creds: ${{ secrets.ISSUE_TRIAGE_GH_APP_CREDS }} org: electron - name: Set status - uses: dsanders11/project-actions/edit-item@a24415515fa60a22f71f9d9d00e36ca82660cde9 # v1.0.1 + uses: dsanders11/project-actions/edit-item@82e99438bd44a14ad18d92d036dbc25cbfb9a8c4 # v1.2.0 with: token: ${{ steps.generate-token.outputs.token }} project-number: 90 @@ -46,7 +46,7 @@ jobs: fi - name: Generate GitHub App token if: ${{ steps.check-for-comment.outputs.SHOULD_COMMENT }} - uses: electron/github-app-auth-action@cc6751b3b5e4edc5b9a4ad0a021ac455653b6dc8 # v1.0.0 + uses: electron/github-app-auth-action@384fd19694fe7b6dcc9a684746c6976ad78228ae # v1.1.1 id: generate-token with: creds: ${{ secrets.ISSUE_TRIAGE_GH_APP_CREDS }} diff --git a/.github/workflows/issue-opened.yml b/.github/workflows/issue-opened.yml index 7883ea6ea0..b739983f1c 100644 --- a/.github/workflows/issue-opened.yml +++ b/.github/workflows/issue-opened.yml @@ -19,7 +19,7 @@ jobs: creds: ${{ secrets.ISSUE_TRIAGE_GH_APP_CREDS }} org: electron - name: Add to Issue Triage - uses: dsanders11/project-actions/add-item@a24415515fa60a22f71f9d9d00e36ca82660cde9 # v1.0.1 + uses: dsanders11/project-actions/add-item@82e99438bd44a14ad18d92d036dbc25cbfb9a8c4 # v1.2.0 with: field: Reporter field-value: ${{ github.event.issue.user.login }} diff --git a/.github/workflows/issue-unlabeled.yml b/.github/workflows/issue-unlabeled.yml index 6de3d7c83f..03f2e0cc3b 100644 --- a/.github/workflows/issue-unlabeled.yml +++ b/.github/workflows/issue-unlabeled.yml @@ -23,14 +23,14 @@ jobs: fi - name: Generate GitHub App token if: ${{ steps.check-for-blocked-labels.outputs.NOT_BLOCKED }} - uses: electron/github-app-auth-action@cc6751b3b5e4edc5b9a4ad0a021ac455653b6dc8 # v1.0.0 + uses: electron/github-app-auth-action@384fd19694fe7b6dcc9a684746c6976ad78228ae # v1.1.1 id: generate-token with: creds: ${{ secrets.ISSUE_TRIAGE_GH_APP_CREDS }} org: electron - name: Set status if: ${{ steps.check-for-blocked-labels.outputs.NOT_BLOCKED }} - uses: dsanders11/project-actions/edit-item@a24415515fa60a22f71f9d9d00e36ca82660cde9 # v1.0.1 + uses: dsanders11/project-actions/edit-item@82e99438bd44a14ad18d92d036dbc25cbfb9a8c4 # v1.2.0 with: token: ${{ steps.generate-token.outputs.token }} project-number: 90 diff --git a/.github/workflows/pull-request-labeled.yml b/.github/workflows/pull-request-labeled.yml index 6b339a7ea1..3462f0005b 100644 --- a/.github/workflows/pull-request-labeled.yml +++ b/.github/workflows/pull-request-labeled.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Trigger Slack workflow - uses: slackapi/slack-github-action@e28cf165c92ffef168d23c5c9000cffc8a25e117 # v1.24.0 + uses: slackapi/slack-github-action@6c661ce58804a1a20f6dc5fbee7f0381b469e001 # v1.25.0 with: payload: | { @@ -27,13 +27,13 @@ jobs: runs-on: ubuntu-latest steps: - name: Generate GitHub App token - uses: electron/github-app-auth-action@cc6751b3b5e4edc5b9a4ad0a021ac455653b6dc8 # v1.0.0 + uses: electron/github-app-auth-action@384fd19694fe7b6dcc9a684746c6976ad78228ae # v1.1.1 id: generate-token with: creds: ${{ secrets.RELEASE_BOARD_GH_APP_CREDS }} org: electron - name: Set status - uses: dsanders11/project-actions/edit-item@a24415515fa60a22f71f9d9d00e36ca82660cde9 # v1.0.1 + uses: dsanders11/project-actions/edit-item@82e99438bd44a14ad18d92d036dbc25cbfb9a8c4 # v1.2.0 with: token: ${{ steps.generate-token.outputs.token }} project-number: 94 diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 532734c542..27130c16ff 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -22,12 +22,13 @@ jobs: steps: - name: "Checkout code" - uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # tag=v3.1.0 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 with: persist-credentials: false + # This is a pre-submit / pre-release. - name: "Run analysis" - uses: ossf/scorecard-action@e38b1902ae4f44df626f11ba0734b14fb91f8f86 # tag=v2.1.2 + uses: ossf/scorecard-action@0864cf19026789058feabb7e87baa5f140aac736 # v2.3.1 with: results_file: results.sarif results_format: sarif @@ -41,7 +42,7 @@ jobs: # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF # format to the repository Actions tab. - name: "Upload artifact" - uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # tag=v3.1.2 + uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1 with: name: SARIF file path: results.sarif @@ -49,6 +50,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@959cbb7472c4d4ad70cdfe6f4976053fe48ab394 # tag=v2.1.27 + uses: github/codeql-action/upload-sarif@e8893c57a1f3a2b659b6b55564fdfdbbd2982911 # v3.24.0 with: sarif_file: results.sarif diff --git a/.github/workflows/semantic.yml b/.github/workflows/semantic.yml index 031902020f..1a7dad3e18 100644 --- a/.github/workflows/semantic.yml +++ b/.github/workflows/semantic.yml @@ -19,7 +19,7 @@ jobs: runs-on: ubuntu-latest steps: - name: semantic-pull-request - uses: amannn/action-semantic-pull-request@01d5fd8a8ebb9aafe902c40c53f0f4744f7381eb # tag: v5 + uses: amannn/action-semantic-pull-request@e9fabac35e210fea40ca5b14c0da95a099eff26f # v5.4.0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: diff --git a/.github/workflows/stable-prep-items.yml b/.github/workflows/stable-prep-items.yml index b5ec575b9f..74dabd23a5 100644 --- a/.github/workflows/stable-prep-items.yml +++ b/.github/workflows/stable-prep-items.yml @@ -27,7 +27,7 @@ jobs: PROJECT_NUMBER=$(gh project list --owner electron --format json | jq -r '.projects | map(select(.title | test("^[0-9]+-x-y$"))) | max_by(.number) | .number') echo "PROJECT_NUMBER=$PROJECT_NUMBER" >> "$GITHUB_OUTPUT" - name: Update Completed Stable Prep Items - uses: dsanders11/project-actions/completed-by@a24415515fa60a22f71f9d9d00e36ca82660cde9 # v1.0.1 + uses: dsanders11/project-actions/completed-by@82e99438bd44a14ad18d92d036dbc25cbfb9a8c4 # v1.2.0 with: field: Prep Status field-value: ✅ Complete diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index a0102ad488..400e393b3c 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -12,11 +12,11 @@ jobs: runs-on: ubuntu-latest steps: - name: Generate GitHub App token - uses: electron/github-app-auth-action@cc6751b3b5e4edc5b9a4ad0a021ac455653b6dc8 # v1.0.0 + uses: electron/github-app-auth-action@384fd19694fe7b6dcc9a684746c6976ad78228ae # v1.1.1 id: generate-token with: creds: ${{ secrets.ISSUE_TRIAGE_GH_APP_CREDS }} - - uses: actions/stale@5ebf00ea0e4c1561e9b43a292ed34424fb1d4578 # tag: v6.0.1 + - uses: actions/stale@28ca1036281a5e5922ead5184a1bbf96e5fc984e # tag: v9.0.0 with: repo-token: ${{ steps.generate-token.outputs.token }} days-before-stale: 90 @@ -35,11 +35,11 @@ jobs: needs: stale steps: - name: Generate GitHub App token - uses: electron/github-app-auth-action@cc6751b3b5e4edc5b9a4ad0a021ac455653b6dc8 # v1.0.0 + uses: electron/github-app-auth-action@384fd19694fe7b6dcc9a684746c6976ad78228ae # v1.1.1 id: generate-token with: creds: ${{ secrets.ISSUE_TRIAGE_GH_APP_CREDS }} - - uses: actions/stale@5ebf00ea0e4c1561e9b43a292ed34424fb1d4578 # tag: v6.0.1 + - uses: actions/stale@28ca1036281a5e5922ead5184a1bbf96e5fc984e # tag: v9.0.0 with: repo-token: ${{ steps.generate-token.outputs.token }} days-before-stale: -1 diff --git a/.github/workflows/update_appveyor_image.yml b/.github/workflows/update_appveyor_image.yml index bb09408eaa..5eba50527a 100644 --- a/.github/workflows/update_appveyor_image.yml +++ b/.github/workflows/update_appveyor_image.yml @@ -19,7 +19,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # v3.1.0 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 with: fetch-depth: 0 - name: Yarn install @@ -38,7 +38,7 @@ jobs: fi - name: (Optionally) Update Appveyor Image if: ${{ env.APPVEYOR_IMAGE_VERSION }} - uses: mikefarah/yq@1c7dc0e88aad311c89889bc5ce5d8f96931a1bd0 # v4.27.2 + uses: mikefarah/yq@bb66c9c872a7a4cf3d6846c2ff6d182c66ec3f77 # v4.40.7 with: cmd: | yq '.image = "${{ env.APPVEYOR_IMAGE_VERSION }}"' "appveyor.yml" > "appveyor2.yml" @@ -57,7 +57,7 @@ jobs: rm appveyor-woa2.yml appveyor-woa.diff - name: (Optionally) Commit and Pull Request if: ${{ env.APPVEYOR_IMAGE_VERSION }} - uses: peter-evans/create-pull-request@2b011faafdcbc9ceb11414d64d0573f37c774b04 # v4.2.3 + uses: peter-evans/create-pull-request@b1ddad2c994a25fbc81a28b3ec0e368bb2021c50 # v6.0.0 with: token: ${{ secrets.GITHUB_TOKEN }} commit-message: 'build: update appveyor image to latest version'
ci
1a9f99b3ed4f8fcde707bafe1bb0f5f1621891ec
John Kleinschmidt
2024-07-09 16:20:18
chore: speed up azcopy on src cache (#42742)
diff --git a/.github/actions/restore-cache-azcopy/action.yml b/.github/actions/restore-cache-azcopy/action.yml index 643585272a..0d23a5f8c6 100644 --- a/.github/actions/restore-cache-azcopy/action.yml +++ b/.github/actions/restore-cache-azcopy/action.yml @@ -23,7 +23,7 @@ runs: # or it was uploaded in the checkout job for a previous commit. uses: nick-fields/retry@7152eba30c6575329ac0576536151aca5a72780e # v3.0.0 with: - timeout_minutes: 20 + timeout_minutes: 30 max_attempts: 3 retry_on: error command: | @@ -32,7 +32,7 @@ runs: echo "SAS Token not found; exiting src cache download early..." exit 1 fi - azcopy copy \ + azcopy copy --log-level=ERROR \ "https://${{ env.AZURE_AKS_CACHE_STORAGE_ACCOUNT }}.file.core.windows.net/${{ env.AZURE_AKS_CACHE_SHARE_NAME }}/${{ env.CACHE_PATH }}?$sas_token" $DEPSHASH.tar - name: Clean SAS Key shell: bash
chore
d8f8560b1c427a9047f762019f4b6ca1379f8599
Shelley Vohr
2024-04-23 11:30:47
refactor: address changes and fix errors in `chrome://accessibility` (#41911) refactor: address changes and fix errors in chrome://accessibility
diff --git a/patches/chromium/.patches b/patches/chromium/.patches index 66d5646f8a..1e3a430f36 100644 --- a/patches/chromium/.patches +++ b/patches/chromium/.patches @@ -52,7 +52,7 @@ crash_allow_setting_more_options.patch upload_list_add_loadsync_method.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch -fix_patch_out_profile_refs_in_accessibility_ui.patch +adjust_accessibility_ui_for_electron.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch diff --git a/patches/chromium/fix_patch_out_profile_refs_in_accessibility_ui.patch b/patches/chromium/adjust_accessibility_ui_for_electron.patch similarity index 63% rename from patches/chromium/fix_patch_out_profile_refs_in_accessibility_ui.patch rename to patches/chromium/adjust_accessibility_ui_for_electron.patch index 457f9a250a..ce6ea4d48c 100644 --- a/patches/chromium/fix_patch_out_profile_refs_in_accessibility_ui.patch +++ b/patches/chromium/adjust_accessibility_ui_for_electron.patch @@ -1,47 +1,27 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Mon, 6 Jul 2020 13:46:06 -0700 -Subject: fix: patch out Profile refs in accessibility_ui +Subject: Adjust accessibility_ui for Electron This tweaks Chrome's Accessibility support at chrome://accessibility -to make it usable from Electron by removing Profile references. +to make it usable from Electron by replacing use of the Profile PrefService +with Electron's own PrefService in ElectronBrowserContext. It also removes +usage of BrowserList and Browser as we subclass related methods and use our +WindowList. diff --git a/chrome/browser/ui/webui/accessibility/accessibility_ui.cc b/chrome/browser/ui/webui/accessibility/accessibility_ui.cc -index 45b085ebb5096b2cdd083337371539a249c7a0a8..404a0a8d99eb68a35c0c06fe1b1dbfa3086e8794 100644 +index 45b085ebb5096b2cdd083337371539a249c7a0a8..9a0a6cb8b37c60641c2c51aa489fbf22cdb123cb 100644 --- a/chrome/browser/ui/webui/accessibility/accessibility_ui.cc +++ b/chrome/browser/ui/webui/accessibility/accessibility_ui.cc -@@ -23,7 +23,10 @@ - #include "base/trace_event/trace_event.h" - #include "build/build_config.h" - #include "build/chromeos_buildflags.h" -+#if 0 - #include "chrome/browser/profiles/profile.h" -+#endif -+#include "chrome/common/chrome_features.h" - #include "chrome/common/pref_names.h" - #include "chrome/common/webui_url_constants.h" - #include "chrome/grit/accessibility_resources.h" -@@ -33,6 +36,7 @@ - #include "content/public/browser/ax_event_notification_details.h" - #include "content/public/browser/ax_inspect_factory.h" - #include "content/public/browser/browser_accessibility_state.h" -+#include "content/public/browser/browser_context.h" - #include "content/public/browser/browser_thread.h" - #include "content/public/browser/favicon_status.h" - #include "content/public/browser/navigation_entry.h" -@@ -52,9 +56,11 @@ - #include "ui/views/accessibility/view_accessibility.h" - - #if !BUILDFLAG(IS_ANDROID) -+#if 0 - #include "chrome/browser/ui/browser.h" - #include "chrome/browser/ui/browser_list.h" - #include "chrome/browser/ui/browser_window.h" -+#endif - #include "ui/views/accessibility/widget_ax_tree_id_map.h" - #include "ui/views/widget/widget.h" - #include "ui/views/widget/widget_delegate.h" -@@ -169,7 +175,7 @@ base::Value::Dict BuildTargetDescriptor(content::RenderViewHost* rvh) { +@@ -44,6 +44,7 @@ + #include "content/public/browser/web_contents.h" + #include "content/public/browser/web_contents_delegate.h" + #include "content/public/browser/web_ui_data_source.h" ++#include "electron/shell/browser/electron_browser_context.h" + #include "ui/accessibility/accessibility_features.h" + #include "ui/accessibility/platform/ax_platform_node.h" + #include "ui/accessibility/platform/ax_platform_node_delegate.h" +@@ -169,7 +170,7 @@ base::Value::Dict BuildTargetDescriptor(content::RenderViewHost* rvh) { accessibility_mode); } @@ -50,27 +30,25 @@ index 45b085ebb5096b2cdd083337371539a249c7a0a8..404a0a8d99eb68a35c0c06fe1b1dbfa3 base::Value::Dict BuildTargetDescriptor(Browser* browser) { base::Value::Dict target_data; target_data.Set(kSessionIdField, browser->session_id().id()); -@@ -203,7 +209,9 @@ void HandleAccessibilityRequestCallback( +@@ -203,7 +204,7 @@ void HandleAccessibilityRequestCallback( DCHECK(ShouldHandleAccessibilityRequestCallback(path)); base::Value::Dict data; -+#if 0 - PrefService* pref = Profile::FromBrowserContext(current_context)->GetPrefs(); -+#endif +- PrefService* pref = Profile::FromBrowserContext(current_context)->GetPrefs(); ++ PrefService* pref = static_cast<electron::ElectronBrowserContext*>(current_context)->prefs(); ui::AXMode mode = content::BrowserAccessibilityState::GetInstance()->GetAccessibilityMode(); bool is_native_enabled = content::BrowserAccessibilityState::GetInstance() -@@ -235,8 +243,7 @@ void HandleAccessibilityRequestCallback( - // enabled. +@@ -236,7 +237,7 @@ void HandleAccessibilityRequestCallback( data.Set(kViewsAccessibility, features::IsAccessibilityTreeForViewsEnabled()); -- std::string pref_api_type = + std::string pref_api_type = - pref->GetString(prefs::kShownAccessibilityApiType); -+ std::string pref_api_type = "blink"; ++ std::string(pref->GetString(prefs::kShownAccessibilityApiType)); bool pref_api_type_supported = false; std::vector<ui::AXApiType::Type> supported_api_types = -@@ -303,11 +310,11 @@ void HandleAccessibilityRequestCallback( +@@ -303,11 +304,11 @@ void HandleAccessibilityRequestCallback( data.Set(kPagesField, std::move(page_list)); base::Value::List browser_list; @@ -80,36 +58,31 @@ index 45b085ebb5096b2cdd083337371539a249c7a0a8..404a0a8d99eb68a35c0c06fe1b1dbfa3 browser_list.Append(BuildTargetDescriptor(browser)); } -#endif // !BUILDFLAG(IS_ANDROID) -+#endif // !BUILDFLAG(IS_ANDROID) ++#endif data.Set(kBrowsersField, std::move(browser_list)); base::Value::List widgets_list; -@@ -647,8 +654,10 @@ void AccessibilityUIMessageHandler::SetGlobalString( +@@ -647,7 +648,8 @@ void AccessibilityUIMessageHandler::SetGlobalString( const std::string value = CheckJSValue(data.FindString(kValueField)); if (string_name == kApiTypeField) { -+#if 0 - PrefService* pref = Profile::FromWebUI(web_ui())->GetPrefs(); +- PrefService* pref = Profile::FromWebUI(web_ui())->GetPrefs(); ++ PrefService* pref = static_cast<electron::ElectronBrowserContext*>( ++ web_ui()->GetWebContents()->GetBrowserContext())->prefs(); pref->SetString(prefs::kShownAccessibilityApiType, value); -+#endif } } - -@@ -700,9 +709,13 @@ void AccessibilityUIMessageHandler::RequestWebContentsTree( +@@ -700,7 +702,8 @@ void AccessibilityUIMessageHandler::RequestWebContentsTree( AXPropertyFilter::ALLOW_EMPTY); AddPropertyFilters(property_filters, deny, AXPropertyFilter::DENY); -+#if 0 - PrefService* pref = Profile::FromWebUI(web_ui())->GetPrefs(); +- PrefService* pref = Profile::FromWebUI(web_ui())->GetPrefs(); ++ PrefService* pref = static_cast<electron::ElectronBrowserContext*>( ++ web_contents->GetBrowserContext())->prefs(); ui::AXApiType::Type api_type = ui::AXApiType::From(pref->GetString(prefs::kShownAccessibilityApiType)); -+#else -+ ui::AXApiType::Type api_type = ui::AXApiType::kBlink; -+#endif std::string accessibility_contents = - web_contents->DumpAccessibilityTree(api_type, property_filters); - result.Set(kTreeField, accessibility_contents); -@@ -727,6 +740,7 @@ void AccessibilityUIMessageHandler::RequestNativeUITree( +@@ -727,6 +730,7 @@ void AccessibilityUIMessageHandler::RequestNativeUITree( AXPropertyFilter::ALLOW_EMPTY); AddPropertyFilters(property_filters, deny, AXPropertyFilter::DENY); @@ -117,7 +90,7 @@ index 45b085ebb5096b2cdd083337371539a249c7a0a8..404a0a8d99eb68a35c0c06fe1b1dbfa3 for (Browser* browser : *BrowserList::GetInstance()) { if (browser->session_id().id() == session_id) { base::Value::Dict result = BuildTargetDescriptor(browser); -@@ -739,6 +753,7 @@ void AccessibilityUIMessageHandler::RequestNativeUITree( +@@ -739,6 +743,7 @@ void AccessibilityUIMessageHandler::RequestNativeUITree( return; } } @@ -125,25 +98,24 @@ index 45b085ebb5096b2cdd083337371539a249c7a0a8..404a0a8d99eb68a35c0c06fe1b1dbfa3 #endif // !BUILDFLAG(IS_ANDROID) // No browser with the specified |session_id| was found. base::Value::Dict result; -@@ -807,11 +822,15 @@ void AccessibilityUIMessageHandler::StopRecording( +@@ -807,11 +812,13 @@ void AccessibilityUIMessageHandler::StopRecording( } ui::AXApiType::Type AccessibilityUIMessageHandler::GetRecordingApiType() { -+#if 0 - PrefService* pref = Profile::FromWebUI(web_ui())->GetPrefs(); +- PrefService* pref = Profile::FromWebUI(web_ui())->GetPrefs(); - const std::vector<ui::AXApiType::Type> supported_types = - content::AXInspectFactory::SupportedApis(); ++ PrefService* pref = static_cast<electron::ElectronBrowserContext*>( ++ web_ui()->GetWebContents()->GetBrowserContext())->prefs(); ui::AXApiType::Type api_type = ui::AXApiType::From(pref->GetString(prefs::kShownAccessibilityApiType)); -+#else -+ ui::AXApiType::Type api_type = ui::AXApiType::kBlink; -+#endif ++ + const std::vector<ui::AXApiType::Type> supported_types = + content::AXInspectFactory::SupportedApis(); // Check to see if it is in the supported types list. if (std::find(supported_types.begin(), supported_types.end(), api_type) == supported_types.end()) { -@@ -881,8 +900,11 @@ void AccessibilityUIMessageHandler::RequestAccessibilityEvents( +@@ -881,8 +888,11 @@ void AccessibilityUIMessageHandler::RequestAccessibilityEvents( // static void AccessibilityUIMessageHandler::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { diff --git a/shell/browser/electron_browser_context.cc b/shell/browser/electron_browser_context.cc index 6a0bf13c12..c085a69ece 100644 --- a/shell/browser/electron_browser_context.cc +++ b/shell/browser/electron_browser_context.cc @@ -50,6 +50,7 @@ #include "shell/browser/protocol_registry.h" #include "shell/browser/special_storage_policy.h" #include "shell/browser/ui/inspectable_web_contents.h" +#include "shell/browser/ui/webui/accessibility_ui.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/zoom_level_delegate.h" @@ -413,6 +414,7 @@ void ElectronBrowserContext::InitPrefs() { MediaDeviceIDSalt::RegisterPrefs(registry.get()); ZoomLevelDelegate::RegisterPrefs(registry.get()); PrefProxyConfigTrackerImpl::RegisterPrefs(registry.get()); + ElectronAccessibilityUIMessageHandler::RegisterPrefs(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) extensions::ExtensionPrefs::RegisterProfilePrefs(registry.get()); diff --git a/shell/browser/electron_browser_context.h b/shell/browser/electron_browser_context.h index e3d6f4e2e7..33d18cc051 100644 --- a/shell/browser/electron_browser_context.h +++ b/shell/browser/electron_browser_context.h @@ -20,11 +20,11 @@ #include "content/public/browser/media_stream_request.h" #include "content/public/browser/resource_context.h" #include "electron/buildflags/buildflags.h" +#include "electron/shell/browser/media/media_device_id_salt.h" #include "gin/arguments.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/network/public/mojom/network_context.mojom.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" -#include "shell/browser/media/media_device_id_salt.h" #include "third_party/blink/public/common/permissions/permission_utils.h" class PrefService; diff --git a/shell/browser/ui/webui/accessibility_ui.cc b/shell/browser/ui/webui/accessibility_ui.cc index ad05cb1cb6..f2573738f5 100644 --- a/shell/browser/ui/webui/accessibility_ui.cc +++ b/shell/browser/ui/webui/accessibility_ui.cc @@ -19,7 +19,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "build/build_config.h" -#include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "chrome/common/webui_url_constants.h" #include "chrome/grit/accessibility_resources.h" // nogncheck @@ -40,11 +39,17 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_ui_data_source.h" +#include "shell/browser/electron_browser_context.h" #include "shell/browser/native_window.h" #include "shell/browser/window_list.h" +#include "ui/accessibility/accessibility_features.h" #include "ui/accessibility/platform/ax_platform_node.h" #include "ui/accessibility/platform/ax_platform_node_delegate.h" #include "ui/base/webui/web_ui_util.h" +#include "ui/views/accessibility/view_accessibility.h" +#include "ui/views/accessibility/widget_ax_tree_id_map.h" +#include "ui/views/widget/widget.h" +#include "ui/views/widget/widget_delegate.h" namespace { @@ -57,26 +62,34 @@ static const char kFaviconUrlField[] = "faviconUrl"; static const char kNameField[] = "name"; static const char kPagesField[] = "pages"; static const char kPidField[] = "pid"; -static const char kSessionIdField[] = "sessionId"; static const char kProcessIdField[] = "processId"; static const char kRequestTypeField[] = "requestType"; static const char kRoutingIdField[] = "routingId"; +static const char kSessionIdField[] = "sessionId"; +static const char kSupportedApiTypesField[] = "supportedApiTypes"; +static const char kTreeField[] = "tree"; static const char kTypeField[] = "type"; static const char kUrlField[] = "url"; -static const char kTreeField[] = "tree"; +static const char kWidgetsField[] = "widgets"; +static const char kApiTypeField[] = "apiType"; + +#if defined(USE_AURA) +static const char kWidgetIdField[] = "widgetId"; +static const char kWidget[] = "widget"; +#endif // Global flags static const char kBrowser[] = "browser"; static const char kCopyTree[] = "copyTree"; static const char kHTML[] = "html"; -static const char kInternal[] = "internal"; -static const char kLabelImages[] = "labelImages"; +static const char kLocked[] = "locked"; static const char kNative[] = "native"; static const char kPage[] = "page"; -static const char kPDF[] = "pdf"; +static const char kPDFPrinting[] = "pdfPrinting"; static const char kScreenReader[] = "screenreader"; static const char kShowOrRefreshTree[] = "showOrRefreshTree"; static const char kText[] = "text"; +static const char kViewsAccessibility[] = "viewsAccessibility"; static const char kWeb[] = "web"; // Possible global flag values @@ -141,73 +154,21 @@ base::Value::Dict BuildTargetDescriptor(electron::NativeWindow* window) { return target_data; } -bool ShouldHandleAccessibilityRequestCallback(const std::string& path) { - return path == kTargetsDataFile; -} +#if defined(USE_AURA) +base::Value::Dict BuildTargetDescriptor(views::Widget* widget) { + base::Value::Dict widget_data; + widget_data.Set(kNameField, widget->widget_delegate()->GetWindowTitle()); + widget_data.Set(kTypeField, kWidget); -// Add property filters to the property_filters vector for the given property -// filter type. The attributes are passed in as a string with each attribute -// separated by a space. -void AddPropertyFilters(std::vector<ui::AXPropertyFilter>* property_filters, - const std::string& attributes, - ui::AXPropertyFilter::Type type) { - for (const std::string& attribute : base::SplitString( - attributes, " ", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) { - property_filters->emplace_back(attribute, type); - } -} - -bool MatchesPropertyFilters( - const std::vector<ui::AXPropertyFilter>& property_filters, - const std::string& text) { - bool allow = false; - for (const auto& filter : property_filters) { - if (base::MatchPattern(text, filter.match_str)) { - switch (filter.type) { - case ui::AXPropertyFilter::ALLOW_EMPTY: - case ui::AXPropertyFilter::SCRIPT: - allow = true; - break; - case ui::AXPropertyFilter::ALLOW: - allow = (!base::MatchPattern(text, "*=''")); - break; - case ui::AXPropertyFilter::DENY: - allow = false; - break; - } - } - } - return allow; + // Use the Widget's root view ViewAccessibility's unique ID for lookup. + int id = widget->GetRootView()->GetViewAccessibility().GetUniqueId().Get(); + widget_data.Set(kWidgetIdField, id); + return widget_data; } +#endif // defined(USE_AURA) -std::string RecursiveDumpAXPlatformNodeAsString( - const ui::AXPlatformNode* node, - int indent, - const std::vector<ui::AXPropertyFilter>& property_filters) { - if (!node) - return ""; - std::string str(2 * indent, '+'); - const std::string line = node->GetDelegate()->GetData().ToString(); - const std::vector<std::string> attributes = base::SplitString( - line, " ", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY); - for (const std::string& attribute : attributes) { - if (MatchesPropertyFilters(property_filters, attribute)) { - str += attribute + " "; - } - } - str += "\n"; - for (size_t i = 0; i < node->GetDelegate()->GetChildCount(); i++) { - gfx::NativeViewAccessible child = node->GetDelegate()->ChildAtIndex(i); - const ui::AXPlatformNode* child_node = - ui::AXPlatformNode::FromNativeViewAccessible(child); - str += RecursiveDumpAXPlatformNodeAsString(child_node, indent + 1, - property_filters); - } - return str; -} - -bool IsValidJSValue(const std::string* str) { - return str && str->length() < 5000U; +bool ShouldHandleAccessibilityRequestCallback(const std::string& path) { + return path == kTargetsDataFile; } void HandleAccessibilityRequestCallback( @@ -217,6 +178,8 @@ void HandleAccessibilityRequestCallback( DCHECK(ShouldHandleAccessibilityRequestCallback(path)); base::Value::Dict data; + PrefService* pref = + static_cast<electron::ElectronBrowserContext*>(current_context)->prefs(); ui::AXMode mode = content::BrowserAccessibilityState::GetInstance()->GetAccessibilityMode(); bool is_native_enabled = content::BrowserAccessibilityState::GetInstance() @@ -226,7 +189,7 @@ void HandleAccessibilityRequestCallback( bool text = mode.has_mode(ui::AXMode::kInlineTextBoxes); bool screenreader = mode.has_mode(ui::AXMode::kScreenReader); bool html = mode.has_mode(ui::AXMode::kHTML); - bool pdf = mode.has_mode(ui::AXMode::kPDFPrinting); + bool pdf_printing = mode.has_mode(ui::AXMode::kPDFPrinting); // The "native" and "web" flags are disabled if // --disable-renderer-accessibility is set. @@ -241,73 +204,161 @@ void HandleAccessibilityRequestCallback( is_web_enabled ? (screenreader ? kOn : kOff) : kDisabled); data.Set(kHTML, is_web_enabled ? (html ? kOn : kOff) : kDisabled); - // TODO(codebytere): enable use of this flag. - // - // The "labelImages" flag works only if "web" is enabled, the current profile - // has the kAccessibilityImageLabelsEnabled preference set and the appropriate - // command line switch has been used. Since this is so closely tied into user - // prefs and causes bugs, we're disabling it for now. - bool are_accessibility_image_labels_enabled = is_web_enabled; - data.Set(kLabelImages, kDisabled); + // The "pdfPrinting" flag is independent of the others. + data.Set(kPDFPrinting, pdf_printing ? kOn : kOff); + + // The "Top Level Widgets" section is only relevant if views accessibility is + // enabled. + data.Set(kViewsAccessibility, features::IsAccessibilityTreeForViewsEnabled()); + + std::string pref_api_type = + std::string(pref->GetString(prefs::kShownAccessibilityApiType)); + bool pref_api_type_supported = false; + + std::vector<ui::AXApiType::Type> supported_api_types = + content::AXInspectFactory::SupportedApis(); + base::Value::List supported_api_list; + supported_api_list.reserve(supported_api_types.size()); + for (ui::AXApiType::Type type : supported_api_types) { + supported_api_list.Append(std::string_view(type)); + if (type == ui::AXApiType::From(pref_api_type)) { + pref_api_type_supported = true; + } + } + data.Set(kSupportedApiTypesField, std::move(supported_api_list)); - // The "pdf" flag is independent of the others. - data.Set(kPDF, pdf ? kOn : kOff); + // If the saved API type is not supported, use the default platform formatter + // API type. + if (!pref_api_type_supported) { + pref_api_type = std::string_view( + content::AXInspectFactory::DefaultPlatformFormatterType()); + } + data.Set(kApiTypeField, pref_api_type); - // Always dump the Accessibility tree. - data.Set(kInternal, kOn); + bool is_mode_locked = !content::BrowserAccessibilityState::GetInstance() + ->IsAXModeChangeAllowed(); + data.Set(kLocked, is_mode_locked ? kOn : kOff); - base::Value::List rvh_list; - std::unique_ptr<content::RenderWidgetHostIterator> widgets( + base::Value::List page_list; + std::unique_ptr<content::RenderWidgetHostIterator> widget_iter( content::RenderWidgetHost::GetRenderWidgetHosts()); - while (content::RenderWidgetHost* widget = widgets->GetNextHost()) { + while (content::RenderWidgetHost* widget = widget_iter->GetNextHost()) { // Ignore processes that don't have a connection, such as crashed tabs. - if (!widget->GetProcess()->IsInitializedAndNotDead()) + if (!widget->GetProcess()->IsInitializedAndNotDead()) { continue; + } content::RenderViewHost* rvh = content::RenderViewHost::From(widget); - if (!rvh) + if (!rvh) { continue; + } content::WebContents* web_contents = content::WebContents::FromRenderViewHost(rvh); content::WebContentsDelegate* delegate = web_contents->GetDelegate(); - if (!delegate) + if (!delegate) { + continue; + } + if (web_contents->GetPrimaryMainFrame()->GetRenderViewHost() != rvh) { continue; + } // Ignore views that are never user-visible, like background pages. - if (delegate->IsNeverComposited(web_contents)) + if (delegate->IsNeverComposited(web_contents)) { continue; + } content::BrowserContext* context = rvh->GetProcess()->GetBrowserContext(); - if (context != current_context) + if (context != current_context) { continue; + } base::Value::Dict descriptor = BuildTargetDescriptor(rvh); descriptor.Set(kNative, is_native_enabled); + descriptor.Set(kScreenReader, is_web_enabled && screenreader); descriptor.Set(kWeb, is_web_enabled); - descriptor.Set(kLabelImages, are_accessibility_image_labels_enabled); - rvh_list.Append(std::move(descriptor)); + page_list.Append(std::move(descriptor)); } - - data.Set(kPagesField, std::move(rvh_list)); + data.Set(kPagesField, std::move(page_list)); base::Value::List window_list; for (auto* window : electron::WindowList::GetWindows()) { window_list.Append(BuildTargetDescriptor(window)); } - data.Set(kBrowsersField, std::move(window_list)); + base::Value::List widgets_list; +#if defined(USE_AURA) + if (features::IsAccessibilityTreeForViewsEnabled()) { + views::WidgetAXTreeIDMap& manager_map = + views::WidgetAXTreeIDMap::GetInstance(); + const std::vector<views::Widget*> widgets = manager_map.GetWidgets(); + for (views::Widget* widget : widgets) { + widgets_list.Append(BuildTargetDescriptor(widget)); + } + } +#endif // defined(USE_AURA) + data.Set(kWidgetsField, std::move(widgets_list)); + std::move(callback).Run(base::MakeRefCounted<base::RefCountedString>( base::WriteJson(data).value_or(""))); } +std::string RecursiveDumpAXPlatformNodeAsString( + ui::AXPlatformNode* node, + int indent, + const std::vector<ui::AXPropertyFilter>& property_filters) { + if (!node) { + return ""; + } + std::string str(2 * indent, '+'); + std::string line = node->GetDelegate()->GetData().ToString(); + std::vector<std::string> attributes = base::SplitString( + line, " ", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY); + for (std::string attribute : attributes) { + if (ui::AXTreeFormatter::MatchesPropertyFilters(property_filters, attribute, + false)) { + str += attribute + " "; + } + } + str += "\n"; + for (size_t i = 0; i < node->GetDelegate()->GetChildCount(); i++) { + gfx::NativeViewAccessible child = node->GetDelegate()->ChildAtIndex(i); + ui::AXPlatformNode* child_node = + ui::AXPlatformNode::FromNativeViewAccessible(child); + str += RecursiveDumpAXPlatformNodeAsString(child_node, indent + 1, + property_filters); + } + return str; +} + +// Add property filters to the property_filters vector for the given property +// filter type. The attributes are passed in as a string with each attribute +// separated by a space. +void AddPropertyFilters(std::vector<ui::AXPropertyFilter>& property_filters, + const std::string& attributes, + ui::AXPropertyFilter::Type type) { + for (const std::string& attribute : base::SplitString( + attributes, " ", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) { + property_filters.emplace_back(attribute, type); + } +} + +bool IsValidJSValue(const std::string* str) { + return str && str->length() < 5000U; +} + +const std::string& CheckJSValue(const std::string* str) { + CHECK(IsValidJSValue(str)); + return *str; +} + } // namespace ElectronAccessibilityUI::ElectronAccessibilityUI(content::WebUI* web_ui) : content::WebUIController(web_ui) { + auto* const browser_context = web_ui->GetWebContents()->GetBrowserContext(); // Set up the chrome://accessibility source. content::WebUIDataSource* html_source = content::WebUIDataSource::CreateAndAdd( - web_ui->GetWebContents()->GetBrowserContext(), - chrome::kChromeUIAccessibilityHost); + browser_context, chrome::kChromeUIAccessibilityHost); // Add required resources. html_source->UseStringsJs(); @@ -317,8 +368,7 @@ ElectronAccessibilityUI::ElectronAccessibilityUI(content::WebUI* web_ui) html_source->SetRequestFilter( base::BindRepeating(&ShouldHandleAccessibilityRequestCallback), base::BindRepeating(&HandleAccessibilityRequestCallback, - web_ui->GetWebContents()->GetBrowserContext())); - + browser_context)); html_source->OverrideContentSecurityPolicy( network::mojom::CSPDirectiveName::TrustedTypes, "trusted-types parse-html-subset sanitize-inner-html;"); @@ -332,33 +382,35 @@ ElectronAccessibilityUI::~ElectronAccessibilityUI() = default; ElectronAccessibilityUIMessageHandler::ElectronAccessibilityUIMessageHandler() = default; +void ElectronAccessibilityUIMessageHandler::GetRequestTypeAndFilters( + const base::Value::Dict& data, + std::string& request_type, + std::string& allow, + std::string& allow_empty, + std::string& deny) { + request_type = CheckJSValue(data.FindString(kRequestTypeField)); + CHECK(request_type == kShowOrRefreshTree || request_type == kCopyTree); + allow = CheckJSValue(data.FindStringByDottedPath("filters.allow")); + allow_empty = CheckJSValue(data.FindStringByDottedPath("filters.allowEmpty")); + deny = CheckJSValue(data.FindStringByDottedPath("filters.deny")); +} + void ElectronAccessibilityUIMessageHandler::RequestNativeUITree( const base::Value::List& args) { const base::Value::Dict& data = args.front().GetDict(); - const int window_id = *data.FindInt(kSessionIdField); - const std::string* const request_type_p = data.FindString(kRequestTypeField); - CHECK(IsValidJSValue(request_type_p)); - std::string request_type = *request_type_p; - CHECK(request_type == kShowOrRefreshTree || request_type == kCopyTree); - request_type = "accessibility." + request_type; + std::string request_type, allow, allow_empty, deny; + GetRequestTypeAndFilters(data, request_type, allow, allow_empty, deny); - const std::string* const allow_p = - data.FindStringByDottedPath("filters.allow"); - CHECK(IsValidJSValue(allow_p)); - const std::string* const allow_empty_p = - data.FindStringByDottedPath("filters.allowEmpty"); - CHECK(IsValidJSValue(allow_empty_p)); - const std::string* const deny_p = data.FindStringByDottedPath("filters.deny"); - CHECK(IsValidJSValue(deny_p)); + int window_id = *data.FindInt(kSessionIdField); AllowJavascript(); std::vector<ui::AXPropertyFilter> property_filters; - AddPropertyFilters(&property_filters, *allow_p, ui::AXPropertyFilter::ALLOW); - AddPropertyFilters(&property_filters, *allow_empty_p, + AddPropertyFilters(property_filters, allow, ui::AXPropertyFilter::ALLOW); + AddPropertyFilters(property_filters, allow_empty, ui::AXPropertyFilter::ALLOW_EMPTY); - AddPropertyFilters(&property_filters, *deny_p, ui::AXPropertyFilter::DENY); + AddPropertyFilters(property_filters, deny, ui::AXPropertyFilter::DENY); for (auto* window : electron::WindowList::GetWindows()) { if (window->window_id() == window_id) { @@ -366,9 +418,9 @@ void ElectronAccessibilityUIMessageHandler::RequestNativeUITree( gfx::NativeWindow native_window = window->GetNativeWindow(); ui::AXPlatformNode* node = ui::AXPlatformNode::FromNativeWindow(native_window); - result.Set(kTreeField, base::Value(RecursiveDumpAXPlatformNodeAsString( - node, 0, property_filters))); - CallJavascriptFunction(request_type, base::Value(std::move(result))); + result.Set(kTreeField, RecursiveDumpAXPlatformNodeAsString( + node, 0, property_filters)); + FireWebUIListener(request_type, result); return; } } @@ -378,7 +430,7 @@ void ElectronAccessibilityUIMessageHandler::RequestNativeUITree( result.Set(kSessionIdField, window_id); result.Set(kTypeField, kBrowser); result.Set(kErrorField, "Window no longer exists."); - CallJavascriptFunction(request_type, base::Value(std::move(result))); + FireWebUIListener(request_type, result); } void ElectronAccessibilityUIMessageHandler::RegisterMessages() { @@ -393,6 +445,10 @@ void ElectronAccessibilityUIMessageHandler::RegisterMessages() { "setGlobalFlag", base::BindRepeating(&AccessibilityUIMessageHandler::SetGlobalFlag, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "setGlobalString", + base::BindRepeating(&AccessibilityUIMessageHandler::SetGlobalString, + base::Unretained(this))); web_ui()->RegisterMessageCallback( "requestWebContentsTree", base::BindRepeating( @@ -403,9 +459,24 @@ void ElectronAccessibilityUIMessageHandler::RegisterMessages() { base::BindRepeating( &ElectronAccessibilityUIMessageHandler::RequestNativeUITree, base::Unretained(this))); +#if defined(USE_AURA) + web_ui()->RegisterMessageCallback( + "requestWidgetsTree", + base::BindRepeating(&AccessibilityUIMessageHandler::RequestWidgetsTree, + base::Unretained(this))); +#endif web_ui()->RegisterMessageCallback( "requestAccessibilityEvents", base::BindRepeating( &AccessibilityUIMessageHandler::RequestAccessibilityEvents, base::Unretained(this))); } + +// static +void ElectronAccessibilityUIMessageHandler::RegisterPrefs( + user_prefs::PrefRegistrySyncable* registry) { + const std::string_view default_api_type = + std::string_view(ui::AXApiType::Type(ui::AXApiType::kBlink)); + registry->RegisterStringPref(prefs::kShownAccessibilityApiType, + std::string(default_api_type)); +} diff --git a/shell/browser/ui/webui/accessibility_ui.h b/shell/browser/ui/webui/accessibility_ui.h index f7ed34e42b..79dedf30c3 100644 --- a/shell/browser/ui/webui/accessibility_ui.h +++ b/shell/browser/ui/webui/accessibility_ui.h @@ -31,7 +31,14 @@ class ElectronAccessibilityUIMessageHandler void RegisterMessages() final; + static void RegisterPrefs(user_prefs::PrefRegistrySyncable* registry); + private: + void GetRequestTypeAndFilters(const base::Value::Dict& data, + std::string& request_type, + std::string& allow, + std::string& allow_empty, + std::string& deny); void RequestNativeUITree(const base::Value::List& args); };
refactor
8c837fda4f2d68d8568889cd68da801f833c862c
MAPGarrett
2022-12-20 18:06:25
docs: Fix incorrect highlight in an example snippet (#36700) Fix incorrect highlight in an example snippet At the moment, the "Communicating between processes" `main.js` snippet highlights the line containing `})` when the relevant line is `ipcMain.handle('ping', () => 'pong')`.
diff --git a/docs/tutorial/tutorial-3-preload.md b/docs/tutorial/tutorial-3-preload.md index 251d13aa43..9804b0e1dc 100644 --- a/docs/tutorial/tutorial-3-preload.md +++ b/docs/tutorial/tutorial-3-preload.md @@ -202,7 +202,7 @@ Then, set up your `handle` listener in the main process. We do this _before_ loading the HTML file so that the handler is guaranteed to be ready before you send out the `invoke` call from the renderer. -```js {1,11} title="main.js" +```js {1,12} title="main.js" const { app, BrowserWindow, ipcMain } = require('electron') const path = require('path')
docs
9199d5c610c399d612dd938c87e2a92de56ec68c
Shelley Vohr
2025-02-07 21:00:36
fix: window maximizing with Mica (#45456) * fix: window maximizing with Mica * Fix rounded corners after restore
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc index e5320308a2..44de6c197f 100644 --- a/shell/browser/native_window_views.cc +++ b/shell/browser/native_window_views.cc @@ -642,8 +642,22 @@ void NativeWindowViews::SetEnabledInternal(bool enable) { #endif } -#if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { +#if BUILDFLAG(IS_WIN) + if (IsTranslucent()) { + // If a window is translucent but not transparent on Windows, + // that means it must have a backgroundMaterial set. + if (!transparent()) + SetRoundedCorners(false); + restore_bounds_ = GetBounds(); + auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( + GetNativeWindow()); + SetBounds(display.work_area(), false); + NotifyWindowMaximize(); + return; + } +#endif + if (IsVisible()) { widget()->Maximize(); } else { @@ -652,44 +666,46 @@ void NativeWindowViews::Maximize() { NotifyWindowShow(); } } -#endif void NativeWindowViews::Unmaximize() { - if (IsMaximized()) { + if (!IsMaximized()) + return; + #if BUILDFLAG(IS_WIN) + if (IsTranslucent()) { + SetBounds(restore_bounds_, false); + NotifyWindowUnmaximize(); if (transparent()) { - SetBounds(restore_bounds_, false); - NotifyWindowUnmaximize(); UpdateThickFrame(); - return; + } else { + SetRoundedCorners(true); } + return; + } #endif - widget()->Restore(); + widget()->Restore(); #if BUILDFLAG(IS_WIN) - UpdateThickFrame(); + UpdateThickFrame(); #endif - } } bool NativeWindowViews::IsMaximized() const { - if (widget()->IsMaximized()) { + if (widget()->IsMaximized()) return true; - } else { + #if BUILDFLAG(IS_WIN) - if (transparent() && !IsMinimized()) { - // Compare the size of the window with the size of the display - auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( - GetNativeWindow()); - // Maximized if the window is the same dimensions and placement as the - // display - return GetBounds() == display.work_area(); - } + if (IsTranslucent() && !IsMinimized()) { + // If the window is the same dimensions and placement as the + // display, we consider it maximized. + auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( + GetNativeWindow()); + return GetBounds() == display.work_area(); + } #endif - return false; - } + return false; } void NativeWindowViews::Minimize() { @@ -702,10 +718,14 @@ void NativeWindowViews::Minimize() { void NativeWindowViews::Restore() { #if BUILDFLAG(IS_WIN) - if (IsMaximized() && transparent()) { + if (IsMaximized() && IsTranslucent()) { SetBounds(restore_bounds_, false); NotifyWindowRestore(); - UpdateThickFrame(); + if (transparent()) { + UpdateThickFrame(); + } else { + SetRoundedCorners(true); + } return; } #endif @@ -845,7 +865,7 @@ gfx::Size NativeWindowViews::GetContentSize() const { gfx::Rect NativeWindowViews::GetNormalBounds() const { #if BUILDFLAG(IS_WIN) - if (IsMaximized() && transparent()) + if (IsMaximized() && IsTranslucent()) return restore_bounds_; #endif return widget()->GetRestoredBounds(); @@ -860,8 +880,8 @@ void NativeWindowViews::SetContentSizeConstraints( if (!thick_frame_) return; #endif - // widget_delegate() is only available after Init() is called, we make use of - // this to determine whether native widget has initialized. + // widget_delegate() is only available after Init() is called, we make use + // of this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) @@ -1639,9 +1659,9 @@ void NativeWindowViews::UpdateThickFrame() { return; if (IsMaximized() && !transparent()) { - // For maximized window add thick frame always, otherwise it will be removed - // in HWNDMessageHandler::SizeConstraintsChanged() which will result in - // maximized window bounds change. + // For maximized window add thick frame always, otherwise it will be + // removed in HWNDMessageHandler::SizeConstraintsChanged() which will + // result in maximized window bounds change. FlipWindowStyle(GetAcceleratedWidget(), true, WS_THICKFRAME); } else if (has_frame()) { FlipWindowStyle(GetAcceleratedWidget(), resizable_, WS_THICKFRAME); @@ -1679,10 +1699,10 @@ void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, // WidgetObserver::OnWidgetBoundsChanged is being called from // Widget::OnNativeWidgetMove() and not Widget::OnNativeWidgetSizeChanged. // |GetWindowBoundsInScreen| has a ~1 pixel margin - // of error because it converts from floats to integers between calculations, - // so if we check existing bounds directly against the new bounds without - // accounting for that we'll have constant false positives when the window is - // moving but the user hasn't changed its size at all. + // of error because it converts from floats to integers between + // calculations, so if we check existing bounds directly against the new + // bounds without accounting for that we'll have constant false positives + // when the window is moving but the user hasn't changed its size at all. auto isWithinOnePixel = [](gfx::Size old_size, gfx::Size new_size) -> bool { return base::IsApproximatelyEqual(old_size.width(), new_size.width(), 1) && base::IsApproximatelyEqual(old_size.height(), new_size.height(), 1); @@ -1807,8 +1827,8 @@ void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { ui::mojom::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) - // Only restore Maximized state when window is NOT transparent style - if (!transparent()) { + // Restore maximized state for windows that are not translucent. + if (!IsTranslucent()) { return ui::mojom::WindowShowState::kMaximized; } #else diff --git a/shell/browser/native_window_views.h b/shell/browser/native_window_views.h index 05c7bbc866..fe2c3a197b 100644 --- a/shell/browser/native_window_views.h +++ b/shell/browser/native_window_views.h @@ -202,11 +202,9 @@ class NativeWindowViews : public NativeWindow, void OnWidgetMove() override; #if BUILDFLAG(IS_WIN) bool ExecuteWindowsCommand(int command_id) override; -#endif - -#if BUILDFLAG(IS_WIN) void HandleSizeEvent(WPARAM w_param, LPARAM l_param); void ResetWindowControls(); + void SetRoundedCorners(bool rounded); void SetForwardMouseMessages(bool forward); static LRESULT CALLBACK SubclassProc(HWND hwnd, UINT msg, diff --git a/shell/browser/native_window_views_win.cc b/shell/browser/native_window_views_win.cc index 9857d93b22..91bd2413ce 100644 --- a/shell/browser/native_window_views_win.cc +++ b/shell/browser/native_window_views_win.cc @@ -8,6 +8,7 @@ #include "base/win/atl.h" // Must be before UIAutomationCore.h #include "base/win/scoped_handle.h" +#include "base/win/windows_version.h" #include "content/public/browser/browser_accessibility_state.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_views.h" @@ -225,25 +226,6 @@ bool IsScreenReaderActive() { std::set<NativeWindowViews*> NativeWindowViews::forwarding_windows_; HHOOK NativeWindowViews::mouse_hook_ = nullptr; -void NativeWindowViews::Maximize() { - // Only use Maximize() when window is NOT transparent style - if (!transparent()) { - if (IsVisible()) { - widget()->Maximize(); - } else { - widget()->native_widget_private()->Show( - ui::mojom::WindowShowState::kMaximized, gfx::Rect()); - NotifyWindowShow(); - } - } else { - restore_bounds_ = GetBounds(); - auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( - GetNativeWindow()); - SetBounds(display.work_area(), false); - NotifyWindowMaximize(); - } -} - bool NativeWindowViews::ExecuteWindowsCommand(int command_id) { const auto command_name = AppCommandToString(command_id); NotifyWindowExecuteAppCommand(command_name); @@ -535,6 +517,24 @@ void NativeWindowViews::ResetWindowControls() { } } +// Windows with |backgroundMaterial| expand to the same dimensions and +// placement as the display to approximate maximization - unless we remove +// rounded corners there will be a gap between the window and the display +// at the corners noticable to users. +void NativeWindowViews::SetRoundedCorners(bool rounded) { + // DWMWA_WINDOW_CORNER_PREFERENCE is supported after Windows 11 Build 22000. + if (base::win::GetVersion() < base::win::Version::WIN11) + return; + + DWM_WINDOW_CORNER_PREFERENCE round_pref = + rounded ? DWMWCP_ROUND : DWMWCP_DONOTROUND; + HRESULT result = DwmSetWindowAttribute(GetAcceleratedWidget(), + DWMWA_WINDOW_CORNER_PREFERENCE, + &round_pref, sizeof(round_pref)); + if (FAILED(result)) + LOG(WARNING) << "Failed to set rounded corners to " << rounded; +} + void NativeWindowViews::SetForwardMouseMessages(bool forward) { if (forward && !forwarding_mouse_messages_) { forwarding_mouse_messages_ = true;
fix
f20d0b4ecbe9c1cc86c29c8fc84517961151fa69
David Sanders
2023-01-23 00:57:00
chore: clean up .keep files (#36980)
diff --git a/docs/fiddles/media/screenshot/.keep b/docs/fiddles/media/screenshot/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/docs/fiddles/menus/customize-menus/.keep b/docs/fiddles/menus/customize-menus/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/docs/fiddles/menus/shortcuts/.keep b/docs/fiddles/menus/shortcuts/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/docs/fiddles/native-ui/dialogs/.keep b/docs/fiddles/native-ui/dialogs/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/docs/fiddles/native-ui/drag-and-drop/.keep b/docs/fiddles/native-ui/drag-and-drop/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/docs/fiddles/native-ui/external-links-file-manager/.keep b/docs/fiddles/native-ui/external-links-file-manager/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/docs/fiddles/native-ui/notifications/.keep b/docs/fiddles/native-ui/notifications/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/docs/fiddles/native-ui/tray/.keep b/docs/fiddles/native-ui/tray/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/docs/fiddles/system/protocol-handler/.keep b/docs/fiddles/system/protocol-handler/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/docs/fiddles/system/system-app-user-information/.keep b/docs/fiddles/system/system-app-user-information/.keep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/docs/fiddles/windows/manage-windows/.keep b/docs/fiddles/windows/manage-windows/.keep deleted file mode 100644 index e69de29bb2..0000000000
chore
d2948719805f9d2f49956ee93c16cdff06dd8d4d
Shelley Vohr
2024-08-12 10:32:35
chore: deprecate `textured` BrowserWindow `type` option on macOS (#43133)
diff --git a/docs/api/structures/base-window-options.md b/docs/api/structures/base-window-options.md index 57ca4ed705..d211ab7cda 100644 --- a/docs/api/structures/base-window-options.md +++ b/docs/api/structures/base-window-options.md @@ -139,8 +139,7 @@ Possible values are: -webkit-app-region: drag. This type is commonly used for splash screens. * The `notification` type creates a window that behaves like a system notification. * On macOS, possible types are `desktop`, `textured`, `panel`. - * The `textured` type adds metal gradient appearance - (`NSWindowStyleMaskTexturedBackground`). + * The `textured` type adds metal gradient appearance. This option is **deprecated**. * The `desktop` type places the window at the desktop background window level (`kCGDesktopWindowLevel - 1`). Note that desktop window will not receive focus, keyboard or mouse events, but you can use `globalShortcut` to receive diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md index e5bfab625d..7a6e0df45f 100644 --- a/docs/breaking-changes.md +++ b/docs/breaking-changes.md @@ -14,6 +14,10 @@ This document uses the following convention to categorize breaking changes: ## Planned Breaking API Changes (33.0) +### Deprecated: `textured` option in `BrowserWindowConstructorOption.type` + +The `textured` option of `type` in `BrowserWindowConstructorOptions` has been deprecated with no replacement. This option relied on the [`NSWindowStyleMaskTexturedBackground`](https://developer.apple.com/documentation/appkit/nswindowstylemask/nswindowstylemasktexturedbackground) style mask on macOS, which has been deprecated with no alternative. + ### Removed: macOS 10.15 support macOS 10.15 (Catalina) is no longer supported by [Chromium](https://chromium-review.googlesource.com/c/chromium/src/+/5734361). diff --git a/shell/browser/native_window_mac.mm b/shell/browser/native_window_mac.mm index 1975fa9c67..625ffcf612 100644 --- a/shell/browser/native_window_mac.mm +++ b/shell/browser/native_window_mac.mm @@ -38,6 +38,7 @@ #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" +#include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" @@ -154,14 +155,6 @@ NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); - bool useStandardWindow = true; - // eventually deprecate separate "standardWindow" option in favor of - // standard / textured window types - options.Get(options::kStandardWindow, &useStandardWindow); - if (windowType == "textured") { - useStandardWindow = false; - } - // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); @@ -186,8 +179,18 @@ NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; - if (!useStandardWindow || transparent() || !has_frame()) + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + if (windowType == "textured" || transparent() || !has_frame()) { + node::Environment* env = + node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()); + EmitWarning(env, + "The 'textured' window type is deprecated and will be removed", + "DeprecationWarning"); styleMask |= NSWindowStyleMaskTexturedBackground; + } +#pragma clang diagnostic pop // -Wdeprecated-declarations #pragma clang diagnostic pop diff --git a/shell/common/options_switches.cc b/shell/common/options_switches.cc index aea8e847a8..a0ecacd7d7 100644 --- a/shell/common/options_switches.cc +++ b/shell/common/options_switches.cc @@ -86,9 +86,6 @@ const char kType[] = "type"; // Disable auto-hiding cursor. const char kDisableAutoHideCursor[] = "disableAutoHideCursor"; -// Use the macOS' standard window instead of the textured window. -const char kStandardWindow[] = "standardWindow"; - // Default browser window background color. const char kBackgroundColor[] = "backgroundColor"; diff --git a/shell/common/options_switches.h b/shell/common/options_switches.h index 2d89d4e43c..5903291a4c 100644 --- a/shell/common/options_switches.h +++ b/shell/common/options_switches.h @@ -47,7 +47,6 @@ extern const char kDarkTheme[]; extern const char kTransparent[]; extern const char kType[]; extern const char kDisableAutoHideCursor[]; -extern const char kStandardWindow[]; extern const char kBackgroundColor[]; extern const char kHasShadow[]; extern const char kOpacity[];
chore
37f58818827b5c8dc2f5f25a5a1b5f6392a16bbe
Shelley Vohr
2023-01-23 17:21:28
test: add a `<datalist>` spec for time type (#36953) spec: add a datalist spec for time type
diff --git a/spec/autofill-spec.ts b/spec/autofill-spec.ts index 4ae39e29f5..4917780965 100644 --- a/spec/autofill-spec.ts +++ b/spec/autofill-spec.ts @@ -9,10 +9,11 @@ const fixturesPath = path.resolve(__dirname, 'fixtures'); describe('autofill', () => { afterEach(closeAllWindows); - it('can be selected via keyboard', async () => { + it('can be selected via keyboard for a <datalist> with text type', async () => { const w = new BrowserWindow({ show: true }); - await w.loadFile(path.join(fixturesPath, 'pages', 'datalist.html')); + await w.loadFile(path.join(fixturesPath, 'pages', 'datalist-text.html')); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab' }); + const inputText = 'clap'; for (const keyCode of inputText) { w.webContents.sendInputEvent({ type: 'char', keyCode }); @@ -25,4 +26,22 @@ describe('autofill', () => { const value = await w.webContents.executeJavaScript("document.querySelector('input').value"); expect(value).to.equal('Eric Clapton'); }); + + it('can be selected via keyboard for a <datalist> with time type', async () => { + const w = new BrowserWindow({ show: true }); + await w.loadFile(path.join(fixturesPath, 'pages', 'datalist-time.html')); + + const inputText = '11P'; // 1:01 PM + for (const keyCode of inputText) { + w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab' }); + w.webContents.sendInputEvent({ type: 'keyDown', keyCode }); + w.webContents.sendInputEvent({ type: 'char', keyCode }); + await delay(100); + } + + w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab' }); + + const value = await w.webContents.executeJavaScript("document.querySelector('input').value"); + expect(value).to.equal('13:01'); + }); }); diff --git a/spec/fixtures/pages/datalist-text.html b/spec/fixtures/pages/datalist-text.html new file mode 100644 index 0000000000..fc1d2c2801 --- /dev/null +++ b/spec/fixtures/pages/datalist-text.html @@ -0,0 +1,15 @@ +<!DOCTYPE html> +<html> + +<body> + <input type="text" list="guitarists" /> + <datalist id="guitarists"> + <select> + <option value="John Mayer"></option> + <option value="Eric Clapton"></option> + <option value="Django Reinhardt"></option> + </select> + </datalist> +</body> + +</html> \ No newline at end of file diff --git a/spec/fixtures/pages/datalist-time.html b/spec/fixtures/pages/datalist-time.html new file mode 100644 index 0000000000..f38766eb83 --- /dev/null +++ b/spec/fixtures/pages/datalist-time.html @@ -0,0 +1,13 @@ +<!DOCTYPE html> +<html> + +<body> + <input type="time" list="hours" /> + <datalist id="popularHours"> + <option value="12:00"></option> + <option value="13:00"></option> + <option value="14:00"></option> + </datalist> +</body> + +</html> \ No newline at end of file diff --git a/spec/fixtures/pages/datalist.html b/spec/fixtures/pages/datalist.html deleted file mode 100644 index 8fc56ecbf1..0000000000 --- a/spec/fixtures/pages/datalist.html +++ /dev/null @@ -1,13 +0,0 @@ -<!DOCTYPE html> -<html> - <body> - <input type="text" list="guitarists" /> - <datalist id="guitarists"> - <select> - <option value="John Mayer"></option> - <option value="Eric Clapton"></option> - <option value="Django Reinhardt"></option> - </select> - </datalist> - </body> -</html>
test
889859df5bb74e6c18b1c2f21c28ade80a366611
Shelley Vohr
2023-02-14 10:44:34
feat: include all standard paper sizes for webContents.print() (#37159)
diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 2f8b6cb671..ee47301e12 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -1409,8 +1409,8 @@ Returns `Promise<PrinterInfo[]>` - Resolves with a [`PrinterInfo[]`](structures/ * `vertical` number (optional) - The vertical dpi. * `header` string (optional) - string to be printed as page header. * `footer` string (optional) - string to be printed as page footer. - * `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A3`, - `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` and `width`. + * `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A0`, `A1`, `A2`, `A3`, + `A4`, `A5`, `A6`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` and `width`. * `callback` Function (optional) * `success` boolean - Indicates success of the print call. * `failureReason` string - Error description called back if the print fails. diff --git a/lib/browser/api/web-contents.ts b/lib/browser/api/web-contents.ts index 15039d57be..7f1fe3c9cb 100644 --- a/lib/browser/api/web-contents.ts +++ b/lib/browser/api/web-contents.ts @@ -28,24 +28,11 @@ type PostData = LoadURLOptions['postData'] // Stock page sizes const PDFPageSizes: Record<string, ElectronInternal.MediaSize> = { - A5: { - custom_display_name: 'A5', - height_microns: 210000, - name: 'ISO_A5', - width_microns: 148000 - }, - A4: { - custom_display_name: 'A4', - height_microns: 297000, - name: 'ISO_A4', - is_default: 'true', - width_microns: 210000 - }, - A3: { - custom_display_name: 'A3', - height_microns: 420000, - name: 'ISO_A3', - width_microns: 297000 + Letter: { + custom_display_name: 'Letter', + height_microns: 279400, + name: 'NA_LETTER', + width_microns: 215900 }, Legal: { custom_display_name: 'Legal', @@ -53,17 +40,54 @@ const PDFPageSizes: Record<string, ElectronInternal.MediaSize> = { name: 'NA_LEGAL', width_microns: 215900 }, - Letter: { - custom_display_name: 'Letter', - height_microns: 279400, - name: 'NA_LETTER', - width_microns: 215900 - }, Tabloid: { height_microns: 431800, name: 'NA_LEDGER', width_microns: 279400, custom_display_name: 'Tabloid' + }, + A0: { + custom_display_name: 'A0', + height_microns: 1189000, + name: 'ISO_A0', + width_microns: 841000 + }, + A1: { + custom_display_name: 'A1', + height_microns: 841000, + name: 'ISO_A1', + width_microns: 594000 + }, + A2: { + custom_display_name: 'A2', + height_microns: 594000, + name: 'ISO_A2', + width_microns: 420000 + }, + A3: { + custom_display_name: 'A3', + height_microns: 420000, + name: 'ISO_A3', + width_microns: 297000 + }, + A4: { + custom_display_name: 'A4', + height_microns: 297000, + name: 'ISO_A4', + is_default: 'true', + width_microns: 210000 + }, + A5: { + custom_display_name: 'A5', + height_microns: 210000, + name: 'ISO_A5', + width_microns: 148000 + }, + A6: { + custom_display_name: 'A6', + height_microns: 148000, + name: 'ISO_A6', + width_microns: 105000 } } as const;
feat
cdace753894b693ea9b0d6c5570d585fc118c24b
Calvin
2023-04-13 05:27:45
chore: disable flaky node test (#37900)
diff --git a/script/node-disabled-tests.json b/script/node-disabled-tests.json index 3e14d994ab..a5d98ecd77 100644 --- a/script/node-disabled-tests.json +++ b/script/node-disabled-tests.json @@ -24,6 +24,7 @@ "parallel/test-crypto-secure-heap", "parallel/test-fetch", "parallel/test-fs-utimes-y2K38", + "parallel/test-heapsnapshot-near-heap-limit-by-api-in-worker", "parallel/test-heapsnapshot-near-heap-limit-worker", "parallel/test-http2-clean-output", "parallel/test-https-agent-session-reuse",
chore
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
John Kleinschmidt
2023-03-27 09:31:15
fix: allow cancelling of bluetooth requests (#37601) * fix: allow cancelling of bluetooth requests allows cancelling of bluetooth requests when no devices present * docs: update docs to reflect how bluetooth works.
diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index c8b0ef8c01..47f6e8a41c 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -777,20 +777,24 @@ Returns: * `callback` Function * `deviceId` string -Emitted when bluetooth device needs to be selected on call to -`navigator.bluetooth.requestDevice`. To use `navigator.bluetooth` api -`webBluetooth` should be enabled. If `event.preventDefault` is not called, -first available device will be selected. `callback` should be called with -`deviceId` to be selected, passing empty string to `callback` will -cancel the request. +Emitted when a bluetooth device needs to be selected when a call to +`navigator.bluetooth.requestDevice` is made. `callback` should be called with +the `deviceId` of the device to be selected. Passing an empty string to +`callback` will cancel the request. -If no event listener is added for this event, all bluetooth requests will be cancelled. +If an event listener is not added for this event, or if `event.preventDefault` +is not called when handling this event, the first available device will be +automatically selected. + +Due to the nature of bluetooth, scanning for devices when +`navigator.bluetooth.requestDevice` is called may take time and will cause +`select-bluetooth-device` to fire multiple times until `callback` is called +with either a device id or an empty string to cancel the request. ```javascript title='main.js' const { app, BrowserWindow } = require('electron') let win = null -app.commandLine.appendSwitch('enable-experimental-web-platform-features') app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) @@ -800,6 +804,9 @@ app.whenReady().then(() => { return device.deviceName === 'test' }) if (!result) { + // The device wasn't found so we need to either wait longer (eg until the + // device is turned on) or cancel the request by calling the callback + // with an empty string. callback('') } else { callback(result.deviceId) diff --git a/docs/fiddles/features/web-bluetooth/index.html b/docs/fiddles/features/web-bluetooth/index.html index b2be53d400..5b0158fa36 100644 --- a/docs/fiddles/features/web-bluetooth/index.html +++ b/docs/fiddles/features/web-bluetooth/index.html @@ -9,6 +9,7 @@ <h1>Web Bluetooth API</h1> <button id="clickme">Test Bluetooth</button> + <button id="cancel">Cancel Bluetooth Request</button> <p>Currently selected bluetooth device: <strong id="device-name""></strong></p> diff --git a/docs/fiddles/features/web-bluetooth/main.js b/docs/fiddles/features/web-bluetooth/main.js index be44dc0507..4d6e6d38e2 100644 --- a/docs/fiddles/features/web-bluetooth/main.js +++ b/docs/fiddles/features/web-bluetooth/main.js @@ -1,6 +1,9 @@ const {app, BrowserWindow, ipcMain} = require('electron') const path = require('path') +let bluetoothPinCallback +let selectBluetoothCallback + function createWindow () { const mainWindow = new BrowserWindow({ width: 800, @@ -12,10 +15,22 @@ function createWindow () { mainWindow.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault() - if (deviceList && deviceList.length > 0) { - callback(deviceList[0].deviceId) - } + selectBluetoothCallback = callback + const result = deviceList.find((device) => { + return device.deviceName === 'test' + }) + if (result) { + callback(result.deviceId) + } else { + // The device wasn't found so we need to either wait longer (eg until the + // device is turned on) or until the user cancels the request + } + }) + + ipcMain.on('cancel-bluetooth-request', (event) => { + selectBluetoothCallback('') }) + // Listen for a message from the renderer to get the response for the Bluetooth pairing. ipcMain.on('bluetooth-pairing-response', (event, response) => { diff --git a/docs/fiddles/features/web-bluetooth/preload.js b/docs/fiddles/features/web-bluetooth/preload.js index 0c21fcce93..a8d3056036 100644 --- a/docs/fiddles/features/web-bluetooth/preload.js +++ b/docs/fiddles/features/web-bluetooth/preload.js @@ -1,6 +1,7 @@ const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('electronAPI', { + cancelBluetoothRequest: (callback) => ipcRenderer.send('cancel-bluetooth-request', callback), bluetoothPairingRequest: (callback) => ipcRenderer.on('bluetooth-pairing-request', callback), bluetoothPairingResponse: (response) => ipcRenderer.send('bluetooth-pairing-response', response) }) \ No newline at end of file diff --git a/docs/fiddles/features/web-bluetooth/renderer.js b/docs/fiddles/features/web-bluetooth/renderer.js index c51a06ca91..241c253de0 100644 --- a/docs/fiddles/features/web-bluetooth/renderer.js +++ b/docs/fiddles/features/web-bluetooth/renderer.js @@ -7,6 +7,12 @@ async function testIt() { document.getElementById('clickme').addEventListener('click',testIt) +function cancelRequest() { + window.electronAPI.cancelBluetoothRequest() +} + +document.getElementById('cancel').addEventListener('click', cancelRequest) + window.electronAPI.bluetoothPairingRequest((event, details) => { const response = {} diff --git a/shell/browser/lib/bluetooth_chooser.cc b/shell/browser/lib/bluetooth_chooser.cc index 7c9942d7ba..7d84cff45e 100644 --- a/shell/browser/lib/bluetooth_chooser.cc +++ b/shell/browser/lib/bluetooth_chooser.cc @@ -27,8 +27,6 @@ namespace electron { namespace { -const int kMaxScanRetries = 5; - void OnDeviceChosen(const content::BluetoothChooser::EventHandler& handler, const std::string& device_id) { if (device_id.empty()) { @@ -66,29 +64,15 @@ void BluetoothChooser::SetAdapterPresence(AdapterPresence presence) { } void BluetoothChooser::ShowDiscoveryState(DiscoveryState state) { + bool idle_state = false; switch (state) { case DiscoveryState::FAILED_TO_START: refreshing_ = false; event_handler_.Run(content::BluetoothChooserEvent::CANCELLED, ""); - break; + return; case DiscoveryState::IDLE: refreshing_ = false; - if (device_map_.empty()) { - auto event = ++num_retries_ > kMaxScanRetries - ? content::BluetoothChooserEvent::CANCELLED - : content::BluetoothChooserEvent::RESCAN; - event_handler_.Run(event, ""); - } else { - bool prevent_default = api_web_contents_->Emit( - "select-bluetooth-device", GetDeviceList(), - base::BindOnce(&OnDeviceChosen, event_handler_)); - if (!prevent_default) { - auto it = device_map_.begin(); - auto device_id = it->first; - event_handler_.Run(content::BluetoothChooserEvent::SELECTED, - device_id); - } - } + idle_state = true; break; case DiscoveryState::DISCOVERING: // The first time this state fires is due to a rescan triggering so set a @@ -101,6 +85,18 @@ void BluetoothChooser::ShowDiscoveryState(DiscoveryState state) { } break; } + bool prevent_default = + api_web_contents_->Emit("select-bluetooth-device", GetDeviceList(), + base::BindOnce(&OnDeviceChosen, event_handler_)); + if (!prevent_default && idle_state) { + if (device_map_.empty()) { + event_handler_.Run(content::BluetoothChooserEvent::CANCELLED, ""); + } else { + auto it = device_map_.begin(); + auto device_id = it->first; + event_handler_.Run(content::BluetoothChooserEvent::SELECTED, device_id); + } + } } void BluetoothChooser::AddOrUpdateDevice(const std::string& device_id, diff --git a/shell/browser/lib/bluetooth_chooser.h b/shell/browser/lib/bluetooth_chooser.h index 8143e4ce5c..aed252c556 100644 --- a/shell/browser/lib/bluetooth_chooser.h +++ b/shell/browser/lib/bluetooth_chooser.h @@ -44,7 +44,6 @@ class BluetoothChooser : public content::BluetoothChooser { std::map<std::string, std::u16string> device_map_; api::WebContents* api_web_contents_; EventHandler event_handler_; - int num_retries_ = 0; bool refreshing_ = false; bool rescan_ = false; };
fix
f4ffd018e63b4c0aef030c531295df1a437fcd54
Samuel Attard
2024-10-01 13:51:40
build: cleanup release scripts, separate cli entrypoints from logic (#44058) * build: cleanup release scripts, separate cli entrypoints from logic * build: use repo/org constants
diff --git a/script/release/bin/README.md b/script/release/bin/README.md new file mode 100644 index 0000000000..9386a9c7c1 --- /dev/null +++ b/script/release/bin/README.md @@ -0,0 +1,61 @@ +# Release Scripts + +> These ancient artifacts date back to the early days of Electron, they have been modified +> over the years but in reality still very much look how they did at the beginning. You +> have been warned. + +None of these scripts are called manually, they are each called by Sudowoodo at various points +in the Electron release process. What each script does though is loosely documented below, +however this documentation is a best effort so please be careful when modifying the scripts +as there still may be unknown or undocumented effects / intentions. + +## What scripts do we have? + +### `cleanup-release` + +This script completely reverts a failed or otherwise unreleasable version. It does this by: + +* Deleting the draft release if it exists +* Deleting the git tag if it exists + +> [!NOTE] +> This is the only script / case where an existing tag will be deleted. Tags are only considered immutable after the release is published. + +### `print-next-version` + +This script just outputs the theoretical "next" version that a release would use. + +### `prepare-for-release` + +This script creates all the requisite tags and CI builds that will populate required release assets. + +* Creates the git tag +* Kicks off all release builds on AppVeyor and GitHub Actions + +### `run-release-build` + +This script is used to re-kick specific release builds after they fail. Sudowoodo is responsible for prompting the release team as to whether or not to run this script. It's currently only used for AppVeyor builds. + +> [!IMPORTANT] +> This script should be removed and the "rerun" logic for AppVeyor be implemented in Sudowoodo specifically in the same way that GitHub Actions' rerun logic is. + +### `validate-before-publish` + +This script ensures that a release is in a valid state before publishing it anywhere. Specifically it checks: + +* All assets exist +* All checksums match uploaded assets +* Headers have been uploaded to the header CDN +* Symbols have been uploaded to the symbol CDN + +### `publish-to-github` + +This script finalizes the GitHub release, in the process it: + +* Uploads the header SHASUMs to the CDN +* Updates the `index.json` file on the assets CDN with the new version via metadumper +* Publishes the actual GitHub release + +### `publish-to-npm` + +This script finishes the release process by publishing a new `npm` package. diff --git a/script/release/bin/cleanup-release.ts b/script/release/bin/cleanup-release.ts new file mode 100644 index 0000000000..8f1420d2e3 --- /dev/null +++ b/script/release/bin/cleanup-release.ts @@ -0,0 +1,30 @@ +import { parseArgs } from 'node:util'; +import { cleanReleaseArtifacts } from '../release-artifact-cleanup'; + +const { values: { tag: _tag, releaseID } } = parseArgs({ + options: { + tag: { + type: 'string' + }, + releaseID: { + type: 'string', + default: '' + } + } +}); + +if (!_tag) { + console.error('Missing --tag argument'); + process.exit(1); +} + +const tag = _tag; + +cleanReleaseArtifacts({ + releaseID, + tag +}) + .catch((err) => { + console.error(err); + process.exit(1); + }); diff --git a/script/release/bin/prepare-for-release.ts b/script/release/bin/prepare-for-release.ts new file mode 100644 index 0000000000..8e5b0f26b5 --- /dev/null +++ b/script/release/bin/prepare-for-release.ts @@ -0,0 +1,32 @@ +import { parseArgs } from 'node:util'; + +import { prepareRelease } from '../prepare-release'; +import { ELECTRON_REPO, isVersionBumpType, NIGHTLY_REPO } from '../types'; + +const { values: { branch }, positionals } = parseArgs({ + options: { + branch: { + type: 'string' + } + }, + allowPositionals: true +}); + +const bumpType = positionals[0]; + +if (!bumpType || !isVersionBumpType(bumpType)) { + console.log('Usage: prepare-for-release [stable | minor | beta | alpha | nightly]' + + ' (--branch=branch)'); + process.exit(1); +} + +prepareRelease({ + isPreRelease: bumpType !== 'stable' && bumpType !== 'minor', + targetRepo: bumpType === 'nightly' ? NIGHTLY_REPO : ELECTRON_REPO, + targetBranch: branch, + bumpType +}) + .catch((err) => { + console.error(err); + process.exit(1); + }); diff --git a/script/release/bin/print-next-version.ts b/script/release/bin/print-next-version.ts new file mode 100644 index 0000000000..a2223311fd --- /dev/null +++ b/script/release/bin/print-next-version.ts @@ -0,0 +1,32 @@ +import { parseArgs } from 'node:util'; + +import { printNextVersion } from '../prepare-release'; +import { ELECTRON_REPO, isVersionBumpType, NIGHTLY_REPO } from '../types'; + +const { values: { branch }, positionals } = parseArgs({ + options: { + branch: { + type: 'string' + } + }, + allowPositionals: true +}); + +const bumpType = positionals[0]; + +if (!bumpType || !isVersionBumpType(bumpType)) { + console.log('Usage: print-next-version [stable | minor | beta | alpha | nightly]' + + ' (--branch=branch)'); + process.exit(1); +} + +printNextVersion({ + isPreRelease: bumpType !== 'stable' && bumpType !== 'minor', + targetRepo: bumpType === 'nightly' ? NIGHTLY_REPO : ELECTRON_REPO, + targetBranch: branch, + bumpType +}) + .catch((err) => { + console.error(err); + process.exit(1); + }); diff --git a/script/release/bin/publish-to-github.ts b/script/release/bin/publish-to-github.ts new file mode 100644 index 0000000000..a426aa7167 --- /dev/null +++ b/script/release/bin/publish-to-github.ts @@ -0,0 +1,6 @@ +import { makeRelease } from '../release'; + +makeRelease().catch((err) => { + console.error('Error occurred while making release:', err); + process.exit(1); +}); diff --git a/script/release/publish-to-npm.ts b/script/release/bin/publish-to-npm.ts similarity index 96% rename from script/release/publish-to-npm.ts rename to script/release/bin/publish-to-npm.ts index 599f1fe99a..85a293a444 100644 --- a/script/release/publish-to-npm.ts +++ b/script/release/bin/publish-to-npm.ts @@ -5,12 +5,12 @@ import * as path from 'node:path'; import * as semver from 'semver'; import * as temp from 'temp'; -import { getCurrentBranch, ELECTRON_DIR } from '../lib/utils'; -import { getElectronVersion } from '../lib/get-version'; +import { getCurrentBranch, ELECTRON_DIR } from '../../lib/utils'; +import { getElectronVersion } from '../../lib/get-version'; -import { getAssetContents } from './get-asset'; -import { createGitHubTokenStrategy } from './github-token'; -import { ELECTRON_ORG, ELECTRON_REPO, ElectronReleaseRepo, NIGHTLY_REPO } from './types'; +import { getAssetContents } from '../get-asset'; +import { createGitHubTokenStrategy } from '../github-token'; +import { ELECTRON_ORG, ELECTRON_REPO, ElectronReleaseRepo, NIGHTLY_REPO } from '../types'; const rootPackageJson = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf-8')); diff --git a/script/release/bin/run-release-builds.ts b/script/release/bin/run-release-builds.ts new file mode 100644 index 0000000000..4947413a35 --- /dev/null +++ b/script/release/bin/run-release-builds.ts @@ -0,0 +1,53 @@ +import { parseArgs } from 'node:util'; + +import { runReleaseCIJobs } from '../run-release-ci-jobs'; + +const { values: { ghRelease, job, arch, ci, commit, newVersion }, positionals } = parseArgs({ + options: { + ghRelease: { + type: 'boolean' + }, + job: { + type: 'string' + }, + arch: { + type: 'string' + }, + ci: { + type: 'string' + }, + commit: { + type: 'string' + }, + newVersion: { + type: 'string' + } + }, + allowPositionals: true +}); + +const targetBranch = positionals[0]; + +if (positionals.length < 1) { + console.log(`Trigger CI to build release builds of electron. + Usage: ci-release-build.js [--job=CI_JOB_NAME] [--arch=INDIVIDUAL_ARCH] [--ci=AppVeyor|GitHubActions] + [--ghRelease] [--commit=sha] [--newVersion=version_tag] TARGET_BRANCH + `); + process.exit(0); +} + +if (ci === 'GitHubActions' || !ci) { + if (!newVersion) { + console.error('--newVersion is required for GitHubActions'); + process.exit(1); + } +} + +runReleaseCIJobs(targetBranch, { + ci: ci as 'GitHubActions' | 'AppVeyor', + ghRelease, + job: job as any, + arch, + newVersion: newVersion!, + commit +}); diff --git a/script/release/bin/validate-before-publish.ts b/script/release/bin/validate-before-publish.ts new file mode 100644 index 0000000000..301948cb86 --- /dev/null +++ b/script/release/bin/validate-before-publish.ts @@ -0,0 +1,6 @@ +import { validateRelease } from '../release'; + +validateRelease().catch((err) => { + console.error('Error occurred while validating release:', err); + process.exit(1); +}); diff --git a/script/release/get-asset.ts b/script/release/get-asset.ts index 70ae0e2be6..0a129f84c3 100644 --- a/script/release/get-asset.ts +++ b/script/release/get-asset.ts @@ -1,7 +1,7 @@ import { Octokit } from '@octokit/rest'; import got from 'got'; import { createGitHubTokenStrategy } from './github-token'; -import { ElectronReleaseRepo } from './types'; +import { ELECTRON_ORG, ElectronReleaseRepo } from './types'; export async function getAssetContents (repo: ElectronReleaseRepo, assetId: number) { const octokit = new Octokit({ @@ -10,7 +10,7 @@ export async function getAssetContents (repo: ElectronReleaseRepo, assetId: numb }); const requestOptions = octokit.repos.getReleaseAsset.endpoint({ - owner: 'electron', + owner: ELECTRON_ORG, repo, asset_id: assetId, headers: { diff --git a/script/release/notes/index.ts b/script/release/notes/index.ts index 8340cb5d2d..d993d1ba1d 100755 --- a/script/release/notes/index.ts +++ b/script/release/notes/index.ts @@ -10,8 +10,10 @@ import { get, render } from './notes'; import { Octokit } from '@octokit/rest'; import { createGitHubTokenStrategy } from '../github-token'; import { parseArgs } from 'node:util'; +import { ELECTRON_ORG, ELECTRON_REPO } from '../types'; + const octokit = new Octokit({ - authStrategy: createGitHubTokenStrategy('electron') + authStrategy: createGitHubTokenStrategy(ELECTRON_REPO) }); const semverify = (version: string) => version.replace(/^origin\//, '').replace(/[xy]/g, '0').replace(/-/g, '.'); @@ -45,8 +47,8 @@ const getTagsOf = async (point: string) => { const getTagsOnBranch = async (point: string) => { const { data: { default_branch: defaultBranch } } = await octokit.repos.get({ - owner: 'electron', - repo: 'electron' + owner: ELECTRON_ORG, + repo: ELECTRON_REPO }); const mainTags = await getTagsOf(defaultBranch); if (point === defaultBranch) { diff --git a/script/release/notes/notes.ts b/script/release/notes/notes.ts index d4e9b5a6c0..7e73d5203c 100644 --- a/script/release/notes/notes.ts +++ b/script/release/notes/notes.ts @@ -8,9 +8,10 @@ import { GitProcess } from 'dugite'; import { ELECTRON_DIR } from '../../lib/utils'; import { createGitHubTokenStrategy } from '../github-token'; +import { ELECTRON_ORG, ELECTRON_REPO } from '../types'; const octokit = new Octokit({ - authStrategy: createGitHubTokenStrategy('electron') + authStrategy: createGitHubTokenStrategy(ELECTRON_REPO) }); const MAX_FAIL_COUNT = 3; @@ -520,7 +521,7 @@ const getNotes = async (fromRef: string, toRef: string, newVersion: string) => { ); // get the electron/electron commits - const electron = { owner: 'electron', repo: 'electron', dir: ELECTRON_DIR }; + const electron = { owner: ELECTRON_ORG, repo: ELECTRON_REPO, dir: ELECTRON_DIR }; await addRepoToPool(pool, electron, fromRef, toRef); // remove any old commits diff --git a/script/release/prepare-release.ts b/script/release/prepare-release.ts index 2913a3438e..269e3ea7ed 100755 --- a/script/release/prepare-release.ts +++ b/script/release/prepare-release.ts @@ -1,75 +1,43 @@ -#!/usr/bin/env node - import { Octokit } from '@octokit/rest'; import * as chalk from 'chalk'; import { GitProcess } from 'dugite'; import { execSync } from 'node:child_process'; import { join } from 'node:path'; -import { createInterface } from 'node:readline'; -import { parseArgs } from 'node:util'; -import ciReleaseBuild from './ci-release-build'; +import { runReleaseCIJobs } from './run-release-ci-jobs'; import releaseNotesGenerator from './notes'; import { getCurrentBranch, ELECTRON_DIR } from '../lib/utils.js'; import { createGitHubTokenStrategy } from './github-token'; -import { ELECTRON_REPO, ElectronReleaseRepo, NIGHTLY_REPO } from './types'; - -const { values: { notesOnly, dryRun: dryRunArg, stable: isStableArg, branch: branchArg, automaticRelease }, positionals } = parseArgs({ - options: { - notesOnly: { - type: 'boolean' - }, - dryRun: { - type: 'boolean' - }, - stable: { - type: 'boolean' - }, - branch: { - type: 'string' - }, - automaticRelease: { - type: 'boolean' - } - }, - allowPositionals: true -}); - -const bumpType = positionals[0]; -const targetRepo = getRepo(); - -function getRepo (): ElectronReleaseRepo { - return bumpType === 'nightly' ? NIGHTLY_REPO : ELECTRON_REPO; -} - -const octokit = new Octokit({ - authStrategy: createGitHubTokenStrategy(getRepo()) -}); +import { ELECTRON_ORG, ElectronReleaseRepo, VersionBumpType } from './types'; const pass = chalk.green('✓'); const fail = chalk.red('✗'); -if (!bumpType && !notesOnly) { - console.log('Usage: prepare-release [stable | minor | beta | alpha | nightly]' + - ' (--stable) (--notesOnly) (--automaticRelease) (--branch)'); - process.exit(1); -} - enum DryRunMode { DRY_RUN, REAL_RUN, } -async function getNewVersion (dryRunMode: DryRunMode) { +type PrepareReleaseOptions = { + targetRepo: ElectronReleaseRepo; + targetBranch?: string; + bumpType: VersionBumpType; + isPreRelease: boolean; +}; + +async function getNewVersion ( + options: PrepareReleaseOptions, + dryRunMode: DryRunMode +) { if (dryRunMode === DryRunMode.REAL_RUN) { - console.log(`Bumping for new "${bumpType}" version.`); + console.log(`Bumping for new "${options.bumpType}" version.`); } const bumpScript = join(__dirname, 'version-bumper.ts'); const scriptArgs = [ 'node', 'node_modules/.bin/ts-node', bumpScript, - `--bump=${bumpType}` + `--bump=${options.bumpType}` ]; if (dryRunMode === DryRunMode.DRY_RUN) scriptArgs.push('--dryRun'); try { @@ -86,9 +54,15 @@ async function getNewVersion (dryRunMode: DryRunMode) { } } -async function getReleaseNotes (currentBranch: string, newVersion: string) { - if (bumpType === 'nightly') { - return { text: 'Nightlies do not get release notes, please compare tags for info.' }; +async function getReleaseNotes ( + options: PrepareReleaseOptions, + currentBranch: string, + newVersion: string +) { + if (options.bumpType === 'nightly') { + return { + text: 'Nightlies do not get release notes, please compare tags for info.' + }; } console.log(`Generating release notes for ${currentBranch}.`); const releaseNotes = await releaseNotesGenerator(currentBranch, newVersion); @@ -98,22 +72,36 @@ async function getReleaseNotes (currentBranch: string, newVersion: string) { return releaseNotes; } -async function createRelease (branchToTarget: string, isPreRelease: boolean) { - const newVersion = await getNewVersion(DryRunMode.REAL_RUN); - const releaseNotes = await getReleaseNotes(branchToTarget, newVersion); +async function createRelease ( + options: PrepareReleaseOptions, + branchToTarget: string +) { + const newVersion = await getNewVersion(options, DryRunMode.REAL_RUN); + const releaseNotes = await getReleaseNotes( + options, + branchToTarget, + newVersion + ); await tagRelease(newVersion); - console.log('Checking for existing draft release.'); - const releases = await octokit.repos.listReleases({ - owner: 'electron', - repo: targetRepo - }).catch(err => { - console.log(`${fail} Could not get releases. Error was: `, err); - throw err; + const octokit = new Octokit({ + authStrategy: createGitHubTokenStrategy(options.targetRepo) }); - const drafts = releases.data.filter(release => release.draft && - release.tag_name === newVersion); + console.log('Checking for existing draft release.'); + const releases = await octokit.repos + .listReleases({ + owner: ELECTRON_ORG, + repo: options.targetRepo + }) + .catch((err) => { + console.log(`${fail} Could not get releases. Error was: `, err); + throw err; + }); + + const drafts = releases.data.filter( + (release) => release.draft && release.tag_name === newVersion + ); if (drafts.length > 0) { console.log(`${fail} Aborting because draft release for ${drafts[0].tag_name} already exists.`); @@ -123,51 +111,69 @@ async function createRelease (branchToTarget: string, isPreRelease: boolean) { let releaseBody; let releaseIsPrelease = false; - if (isPreRelease) { + if (options.isPreRelease) { if (newVersion.indexOf('nightly') > 0) { - releaseBody = 'Note: This is a nightly release. Please file new issues ' + + releaseBody = + 'Note: This is a nightly release. Please file new issues ' + 'for any bugs you find in it.\n \n This release is published to npm ' + 'under the electron-nightly package and can be installed via `npm install electron-nightly`, ' + - `or \`npm install electron-nightly@${newVersion.substr(1)}\`.\n \n ${releaseNotes.text}`; + `or \`npm install electron-nightly@${newVersion.substr(1)}\`.\n \n ${ + releaseNotes.text + }`; } else if (newVersion.indexOf('alpha') > 0) { - releaseBody = 'Note: This is an alpha release. Please file new issues ' + + releaseBody = + 'Note: This is an alpha release. Please file new issues ' + 'for any bugs you find in it.\n \n This release is published to npm ' + 'under the alpha tag and can be installed via `npm install electron@alpha`, ' + - `or \`npm install electron@${newVersion.substr(1)}\`.\n \n ${releaseNotes.text}`; + `or \`npm install electron@${newVersion.substr(1)}\`.\n \n ${ + releaseNotes.text + }`; } else { - releaseBody = 'Note: This is a beta release. Please file new issues ' + + releaseBody = + 'Note: This is a beta release. Please file new issues ' + 'for any bugs you find in it.\n \n This release is published to npm ' + 'under the beta tag and can be installed via `npm install electron@beta`, ' + - `or \`npm install electron@${newVersion.substr(1)}\`.\n \n ${releaseNotes.text}`; + `or \`npm install electron@${newVersion.substr(1)}\`.\n \n ${ + releaseNotes.text + }`; } releaseIsPrelease = true; } else { releaseBody = releaseNotes.text; } - const release = await octokit.repos.createRelease({ - owner: 'electron', - repo: targetRepo, - tag_name: newVersion, - draft: true, - name: `electron ${newVersion}`, - body: releaseBody, - prerelease: releaseIsPrelease, - target_commitish: newVersion.includes('nightly') ? 'main' : branchToTarget - }).catch(err => { - console.log(`${fail} Error creating new release: `, err); - process.exit(1); - }); + const release = await octokit.repos + .createRelease({ + owner: ELECTRON_ORG, + repo: options.targetRepo, + tag_name: newVersion, + draft: true, + name: `electron ${newVersion}`, + body: releaseBody, + prerelease: releaseIsPrelease, + target_commitish: newVersion.includes('nightly') + ? 'main' + : branchToTarget + }) + .catch((err) => { + console.log(`${fail} Error creating new release: `, err); + process.exit(1); + }); console.log(`Release has been created with id: ${release.data.id}.`); console.log(`${pass} Draft release for ${newVersion} successful.`); } async function pushRelease (branch: string) { - const pushDetails = await GitProcess.exec(['push', 'origin', `HEAD:${branch}`, '--follow-tags'], ELECTRON_DIR); + const pushDetails = await GitProcess.exec( + ['push', 'origin', `HEAD:${branch}`, '--follow-tags'], + ELECTRON_DIR + ); if (pushDetails.exitCode === 0) { - console.log(`${pass} Successfully pushed the release. Wait for ` + - 'release builds to finish before running "npm run release".'); + console.log( + `${pass} Successfully pushed the release. Wait for ` + + 'release builds to finish before running "npm run release".' + ); } else { console.log(`${fail} Error pushing the release: ${pushDetails.stderr}`); process.exit(1); @@ -175,7 +181,7 @@ async function pushRelease (branch: string) { } async function runReleaseBuilds (branch: string, newVersion: string) { - await ciReleaseBuild(branch, { + await runReleaseCIJobs(branch, { ci: undefined, ghRelease: true, newVersion @@ -184,81 +190,51 @@ async function runReleaseBuilds (branch: string, newVersion: string) { async function tagRelease (version: string) { console.log(`Tagging release ${version}.`); - const checkoutDetails = await GitProcess.exec(['tag', '-a', '-m', version, version], ELECTRON_DIR); + const checkoutDetails = await GitProcess.exec( + ['tag', '-a', '-m', version, version], + ELECTRON_DIR + ); if (checkoutDetails.exitCode === 0) { console.log(`${pass} Successfully tagged ${version}.`); } else { - console.log(`${fail} Error tagging ${version}: ` + - `${checkoutDetails.stderr}`); + console.log( + `${fail} Error tagging ${version}: ` + `${checkoutDetails.stderr}` + ); process.exit(1); } } -async function verifyNewVersion () { - const newVersion = await getNewVersion(DryRunMode.DRY_RUN); - let response; - if (automaticRelease) { - response = 'y'; - } else { - response = await promptForVersion(newVersion); - } - if (response.match(/^y/i)) { - console.log(`${pass} Starting release of ${newVersion}`); - } else { - console.log(`${fail} Aborting release of ${newVersion}`); - process.exit(); - } - - return newVersion; -} - -async function promptForVersion (version: string) { - return new Promise<string>(resolve => { - const rl = createInterface({ - input: process.stdin, - output: process.stdout - }); - rl.question(`Do you want to create the release ${chalk.green(version)} (y/N)? `, (answer) => { - rl.close(); - resolve(answer); - }); - }); -} - // function to determine if there have been commits to main since the last release async function changesToRelease () { - const lastCommitWasRelease = /^Bump v[0-9]+.[0-9]+.[0-9]+(-beta.[0-9]+)?(-alpha.[0-9]+)?(-nightly.[0-9]+)?$/g; - const lastCommit = await GitProcess.exec(['log', '-n', '1', '--pretty=format:\'%s\''], ELECTRON_DIR); + const lastCommitWasRelease = + /^Bump v[0-9]+.[0-9]+.[0-9]+(-beta.[0-9]+)?(-alpha.[0-9]+)?(-nightly.[0-9]+)?$/g; + const lastCommit = await GitProcess.exec( + ['log', '-n', '1', "--pretty=format:'%s'"], + ELECTRON_DIR + ); return !lastCommitWasRelease.test(lastCommit.stdout); } -async function prepareRelease (isPreRelease: boolean, dryRunMode: DryRunMode) { - if (dryRunMode === DryRunMode.DRY_RUN) { - const newVersion = await getNewVersion(DryRunMode.DRY_RUN); - console.log(newVersion); - } else { - const currentBranch = branchArg || await getCurrentBranch(ELECTRON_DIR); - if (notesOnly) { - const newVersion = await getNewVersion(DryRunMode.DRY_RUN); - const releaseNotes = await getReleaseNotes(currentBranch, newVersion); - console.log(`Draft release notes are: \n${releaseNotes.text}`); - } else { - const changes = await changesToRelease(); - if (changes) { - const newVersion = await verifyNewVersion(); - await createRelease(currentBranch, isPreRelease); - await pushRelease(currentBranch); - await runReleaseBuilds(currentBranch, newVersion); - } else { - console.log('There are no new changes to this branch since the last release, aborting release.'); - process.exit(1); - } - } - } +export async function printNextVersion (options: PrepareReleaseOptions) { + const newVersion = await getNewVersion(options, DryRunMode.DRY_RUN); + console.log(newVersion); } -prepareRelease(!isStableArg, dryRunArg ? DryRunMode.DRY_RUN : DryRunMode.REAL_RUN) - .catch((err) => { - console.error(err); +export async function prepareRelease (options: PrepareReleaseOptions) { + const currentBranch = + options.targetBranch || (await getCurrentBranch(ELECTRON_DIR)); + + const changes = await changesToRelease(); + if (changes) { + const newVersion = await getNewVersion(options, DryRunMode.DRY_RUN); + console.log(`${pass} Starting release of ${newVersion}`); + await createRelease(options, currentBranch); + await pushRelease(currentBranch); + await runReleaseBuilds(currentBranch, newVersion); + } else { + console.log( + 'There are no new changes to this branch since the last release, aborting release.' + ); process.exit(1); - }); + } +} diff --git a/script/release/release-artifact-cleanup.ts b/script/release/release-artifact-cleanup.ts index fffbac7d61..a071a935fd 100755 --- a/script/release/release-artifact-cleanup.ts +++ b/script/release/release-artifact-cleanup.ts @@ -2,30 +2,10 @@ import { Octokit } from '@octokit/rest'; import * as chalk from 'chalk'; -import { parseArgs } from 'node:util'; import { createGitHubTokenStrategy } from './github-token'; import { ELECTRON_ORG, ELECTRON_REPO, ElectronReleaseRepo, NIGHTLY_REPO } from './types'; -const { values: { tag: _tag, releaseID } } = parseArgs({ - options: { - tag: { - type: 'string' - }, - releaseID: { - type: 'string', - default: '' - } - } -}); - -if (!_tag) { - console.error('Missing --tag argument'); - process.exit(1); -} - -const tag = _tag; - const pass = chalk.green('✓'); const fail = chalk.red('✗'); @@ -75,7 +55,12 @@ async function deleteTag (tag: string, targetRepo: ElectronReleaseRepo) { } } -async function cleanReleaseArtifacts () { +type CleanOptions = { + releaseID?: string; + tag: string; +} + +export async function cleanReleaseArtifacts ({ releaseID, tag }: CleanOptions) { const releaseId = releaseID && releaseID.length > 0 ? releaseID : null; const isNightly = tag.includes('nightly'); @@ -102,9 +87,3 @@ async function cleanReleaseArtifacts () { console.log(`${pass} failed release artifact cleanup complete`); } - -cleanReleaseArtifacts() - .catch((err) => { - console.error(err); - process.exit(1); - }); diff --git a/script/release/release.ts b/script/release/release.ts index 44c3f3931b..4fc9d1396c 100755 --- a/script/release/release.ts +++ b/script/release/release.ts @@ -14,8 +14,7 @@ import { ELECTRON_DIR } from '../lib/utils'; import { getElectronVersion } from '../lib/get-version'; import { getUrlHash } from './get-url-hash'; import { createGitHubTokenStrategy } from './github-token'; -import { ELECTRON_REPO, ElectronReleaseRepo, NIGHTLY_REPO } from './types'; -import { parseArgs } from 'node:util'; +import { ELECTRON_ORG, ELECTRON_REPO, ElectronReleaseRepo, NIGHTLY_REPO } from './types'; const temp = trackTemp(); @@ -40,7 +39,7 @@ async function getDraftRelease ( skipValidation: boolean = false ) { const releaseInfo = await octokit.repos.listReleases({ - owner: 'electron', + owner: ELECTRON_ORG, repo: targetRepo }); @@ -316,7 +315,7 @@ async function createReleaseShasums (release: MinimalRelease) { ); await octokit.repos .deleteReleaseAsset({ - owner: 'electron', + owner: ELECTRON_ORG, repo: targetRepo, asset_id: existingAssets[0].id }) @@ -383,7 +382,7 @@ async function publishRelease (release: MinimalRelease) { let makeLatest = false; if (!release.prerelease) { const currentLatest = await octokit.repos.getLatestRelease({ - owner: 'electron', + owner: ELECTRON_ORG, repo: targetRepo }); @@ -392,7 +391,7 @@ async function publishRelease (release: MinimalRelease) { return octokit.repos .updateRelease({ - owner: 'electron', + owner: ELECTRON_ORG, repo: targetRepo, release_id: release.id, tag_name: release.tag_name, @@ -405,36 +404,31 @@ async function publishRelease (release: MinimalRelease) { }); } -async function makeRelease (releaseToValidate: string | boolean) { - if (releaseToValidate) { - if (releaseToValidate === true) { - releaseToValidate = pkgVersion; - } else { - console.log('Release to validate !=== true'); - } - console.log(`Validating release ${releaseToValidate}`); - const release = await getDraftRelease(releaseToValidate); - await validateReleaseAssets(release, true); - } else { - let draftRelease = await getDraftRelease(); - uploadNodeShasums(); - await createReleaseShasums(draftRelease); - - // Fetch latest version of release before verifying - draftRelease = await getDraftRelease(pkgVersion, true); - await validateReleaseAssets(draftRelease); - // index.json goes live once uploaded so do these uploads as - // late as possible to reduce the chances it contains a release - // which fails to publish. It has to be done before the final - // publish to ensure there aren't published releases not contained - // in index.json, which causes other problems in downstream projects - uploadIndexJson(); - await publishRelease(draftRelease); - console.log( - `${pass} SUCCESS!!! Release has been published. Please run ` + - '"npm run publish-to-npm" to publish release to npm.' - ); - } +export async function validateRelease () { + console.log(`Validating release ${pkgVersion}`); + const release = await getDraftRelease(pkgVersion); + await validateReleaseAssets(release, true); +} + +export async function makeRelease () { + let draftRelease = await getDraftRelease(); + uploadNodeShasums(); + await createReleaseShasums(draftRelease); + + // Fetch latest version of release before verifying + draftRelease = await getDraftRelease(pkgVersion, true); + await validateReleaseAssets(draftRelease); + // index.json goes live once uploaded so do these uploads as + // late as possible to reduce the chances it contains a release + // which fails to publish. It has to be done before the final + // publish to ensure there aren't published releases not contained + // in index.json, which causes other problems in downstream projects + uploadIndexJson(); + await publishRelease(draftRelease); + console.log( + `${pass} SUCCESS!!! Release has been published. Please run ` + + '"npm run publish-to-npm" to publish release to npm.' + ); } const SHASUM_256_FILENAME = 'SHASUMS256.txt'; @@ -446,7 +440,7 @@ async function verifyDraftGitHubReleaseAssets (release: MinimalRelease) { const remoteFilesToHash = await Promise.all( release.assets.map(async (asset) => { const requestOptions = octokit.repos.getReleaseAsset.endpoint({ - owner: 'electron', + owner: ELECTRON_ORG, repo: targetRepo, asset_id: asset.id, headers: { @@ -591,18 +585,3 @@ async function verifyShasumsForRemoteFiles ( ); } } - -const { - values: { validateRelease } -} = parseArgs({ - options: { - validateRelease: { - type: 'boolean' - } - } -}); - -makeRelease(!!validateRelease).catch((err) => { - console.error('Error occurred while making release:', err); - process.exit(1); -}); diff --git a/script/release/ci-release-build.ts b/script/release/run-release-ci-jobs.ts similarity index 86% rename from script/release/ci-release-build.ts rename to script/release/run-release-ci-jobs.ts index e6772b718f..6799314f24 100644 --- a/script/release/ci-release-build.ts +++ b/script/release/run-release-ci-jobs.ts @@ -4,10 +4,9 @@ import * as assert from 'node:assert'; import { createGitHubTokenStrategy } from './github-token'; import { ELECTRON_ORG, ELECTRON_REPO } from './types'; -import { parseArgs } from 'node:util'; const octokit = new Octokit({ - authStrategy: createGitHubTokenStrategy('electron') + authStrategy: createGitHubTokenStrategy(ELECTRON_REPO) }); const BUILD_APPVEYOR_URL = 'https://ci.appveyor.com/api/builds'; @@ -83,8 +82,8 @@ async function githubActionsCall (targetBranch: string, workflowName: string, op jobRequestedCount++; try { const commits = await octokit.repos.listCommits({ - owner: 'electron', - repo: 'electron', + owner: ELECTRON_ORG, + repo: ELECTRON_REPO, sha: targetBranch, per_page: 5 }); @@ -268,7 +267,7 @@ type RunReleaseOptions = ({ ci: undefined, } & BuildAppVeyorOptions & BuildGHActionsOptions); -async function runRelease (targetBranch: string, options: RunReleaseOptions) { +export async function runReleaseCIJobs (targetBranch: string, options: RunReleaseOptions) { if (options.ci) { switch (options.ci) { case 'GitHubActions': { @@ -292,54 +291,3 @@ async function runRelease (targetBranch: string, options: RunReleaseOptions) { } console.log(`${jobRequestedCount} jobs were requested.`); } - -export default runRelease; - -if (require.main === module) { - const { values: { ghRelease, job, arch, ci, commit, newVersion }, positionals } = parseArgs({ - options: { - ghRelease: { - type: 'boolean' - }, - job: { - type: 'string' - }, - arch: { - type: 'string' - }, - ci: { - type: 'string' - }, - commit: { - type: 'string' - }, - newVersion: { - type: 'string' - } - }, - allowPositionals: true - }); - const targetBranch = positionals[0]; - if (positionals.length < 1) { - console.log(`Trigger CI to build release builds of electron. - Usage: ci-release-build.js [--job=CI_JOB_NAME] [--arch=INDIVIDUAL_ARCH] [--ci=AppVeyor|GitHubActions] - [--ghRelease] [--commit=sha] [--newVersion=version_tag] TARGET_BRANCH - `); - process.exit(0); - } - if (ci === 'GitHubActions' || !ci) { - if (!newVersion) { - console.error('--newVersion is required for GitHubActions'); - process.exit(1); - } - } - - runRelease(targetBranch, { - ci: ci as 'GitHubActions' | 'AppVeyor', - ghRelease, - job: job as any, - arch, - newVersion: newVersion!, - commit - }); -} diff --git a/script/release/types.ts b/script/release/types.ts index 01566d4aaf..ec4792a32b 100644 --- a/script/release/types.ts +++ b/script/release/types.ts @@ -5,3 +5,7 @@ export const NIGHTLY_REPO = 'nightlies'; export type ElectronReleaseRepo = 'electron' | 'nightlies'; export type VersionBumpType = 'nightly' | 'alpha' | 'beta' | 'minor' | 'stable'; + +export const isVersionBumpType = (s: string): s is VersionBumpType => { + return ['nightly', 'alpha', 'beta', 'minor', 'stable'].includes(s); +}; diff --git a/script/release/uploaders/upload-to-github.ts b/script/release/uploaders/upload-to-github.ts index 1ed0c0ffc7..43a1dcbf24 100644 --- a/script/release/uploaders/upload-to-github.ts +++ b/script/release/uploaders/upload-to-github.ts @@ -1,6 +1,7 @@ import { Octokit } from '@octokit/rest'; import * as fs from 'node:fs'; import { createGitHubTokenStrategy } from '../github-token'; +import { ELECTRON_ORG, ELECTRON_REPO, ElectronReleaseRepo, NIGHTLY_REPO } from '../types'; if (process.argv.length < 6) { console.log('Usage: upload-to-github filePath fileName releaseId'); @@ -37,8 +38,8 @@ const getHeaders = (filePath: string, fileName: string) => { }; }; -function getRepo () { - return releaseVersion.indexOf('nightly') > 0 ? 'nightlies' : 'electron'; +function getRepo (): ElectronReleaseRepo { + return releaseVersion.indexOf('nightly') > 0 ? NIGHTLY_REPO : ELECTRON_REPO; } const targetRepo = getRepo(); @@ -59,7 +60,7 @@ function uploadToGitHub () { headers: getHeaders(filePath, fileName), data: fileData as any, name: fileName, - owner: 'electron', + owner: ELECTRON_ORG, repo: targetRepo, release_id: releaseId }).then(() => { @@ -71,7 +72,7 @@ function uploadToGitHub () { retry++; octokit.repos.listReleaseAssets({ - owner: 'electron', + owner: ELECTRON_ORG, repo: targetRepo, release_id: releaseId, per_page: 100 @@ -83,7 +84,7 @@ function uploadToGitHub () { if (existingAssets.length > 0) { console.log(`${fileName} already exists; will delete before retrying upload.`); octokit.repos.deleteReleaseAsset({ - owner: 'electron', + owner: ELECTRON_ORG, repo: targetRepo, asset_id: existingAssets[0].id }).catch((deleteErr) => {
build
928c0301e752f53722c5f32aa3b1225c7e96eac8
electron-appveyor-updater[bot]
2024-11-11 13:56:59
build: update appveyor image to latest version (#44606) Co-authored-by: electron-appveyor-updater[bot] <161660339+electron-appveyor-updater[bot]@users.noreply.github.com>
diff --git a/appveyor-woa.yml b/appveyor-woa.yml index 77ddb432f1..d58ba4edf5 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-132.0.6807.0 +image: e-132.0.6824.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default diff --git a/appveyor.yml b/appveyor.yml index 79e273713f..131095213b 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-132.0.6807.0 +image: e-132.0.6824.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default
build
ff6d0df2d534efe1aa8d466e1ea75333290cb0dc
github-actions[bot]
2023-06-26 15:57:10
build: update appveyor image to latest version e-116.0.5845.0 (#38913) build: update appveyor image to latest version Co-authored-by: jkleinsc <[email protected]>
diff --git a/appveyor-woa.yml b/appveyor-woa.yml index cad8ec6335..b949b6fbe4 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-116.0.5833.0 +image: e-116.0.5845.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default diff --git a/appveyor.yml b/appveyor.yml index e180d250f2..33e459ad06 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-116.0.5833.0 +image: e-116.0.5845.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default
build
86f99e9cf00d4c1ab44c71cd1ac16d800b394a64
Shelley Vohr
2023-01-25 14:57:30
chore: cleanup `ElectronContentClient::AddPlugins` (#37005) chore: cleanup ElectronContentClient::AddPlugins
diff --git a/shell/app/electron_content_client.cc b/shell/app/electron_content_client.cc index c855cba599..9d9646fba9 100644 --- a/shell/app/electron_content_client.cc +++ b/shell/app/electron_content_client.cc @@ -104,26 +104,6 @@ bool IsWidevineAvailable( } #endif // BUILDFLAG(ENABLE_WIDEVINE) -#if BUILDFLAG(ENABLE_PLUGINS) -void ComputeBuiltInPlugins(std::vector<content::ContentPluginInfo>* plugins) { -#if BUILDFLAG(ENABLE_PDF_VIEWER) - // TODO(upstream/thestig): Figure out how to make the PDF Viewer work without - // this PPAPI plugin registration. - content::ContentPluginInfo pdf_info; - pdf_info.is_internal = true; - pdf_info.is_out_of_process = true; - pdf_info.name = kPDFInternalPluginName; - pdf_info.description = "Portable Document Format"; - // This isn't a real file path; it's just used as a unique identifier. - pdf_info.path = base::FilePath(kPdfPluginPath); - content::WebPluginMimeType pdf_mime_type(pdf::kInternalPluginMimeType, "pdf", - "Portable Document Format"); - pdf_info.mime_types.push_back(pdf_mime_type); - plugins->push_back(pdf_info); -#endif // BUILDFLAG(ENABLE_PDF_VIEWER) -} -#endif // BUILDFLAG(ENABLE_PLUGINS) - void AppendDelimitedSwitchToVector(const base::StringPiece cmd_switch, std::vector<std::string>* append_me) { auto* command_line = base::CommandLine::ForCurrentProcess(); @@ -204,9 +184,22 @@ void ElectronContentClient::AddAdditionalSchemes(Schemes* schemes) { void ElectronContentClient::AddPlugins( std::vector<content::ContentPluginInfo>* plugins) { -#if BUILDFLAG(ENABLE_PLUGINS) - ComputeBuiltInPlugins(plugins); -#endif // BUILDFLAG(ENABLE_PLUGINS) +#if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_PDF_VIEWER) + static constexpr char kPDFPluginExtension[] = "pdf"; + static constexpr char kPDFPluginDescription[] = "Portable Document Format"; + + content::ContentPluginInfo pdf_info; + pdf_info.is_internal = true; + pdf_info.is_out_of_process = true; + pdf_info.name = kPDFInternalPluginName; + pdf_info.description = kPDFPluginDescription; + // This isn't a real file path; it's just used as a unique identifier. + pdf_info.path = base::FilePath(kPdfPluginPath); + content::WebPluginMimeType pdf_mime_type( + pdf::kInternalPluginMimeType, kPDFPluginExtension, kPDFPluginDescription); + pdf_info.mime_types.push_back(pdf_mime_type); + plugins->push_back(pdf_info); +#endif // BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_PDF_VIEWER) } void ElectronContentClient::AddContentDecryptionModules(
chore
4ca6fb3c4e2e0f66eea67eee4745f0afa14c135e
Erick Zhao
2023-03-31 02:36:59
docs: update references to @electron/rebuild (#37757)
diff --git a/docs/tutorial/using-native-node-modules.md b/docs/tutorial/using-native-node-modules.md index c9c0652c38..d58f43d634 100644 --- a/docs/tutorial/using-native-node-modules.md +++ b/docs/tutorial/using-native-node-modules.md @@ -21,17 +21,17 @@ There are several different ways to install native modules: ### Installing modules and rebuilding for Electron You can install modules like other Node projects, and then rebuild the modules -for Electron with the [`electron-rebuild`][electron-rebuild] package. This +for Electron with the [`@electron/rebuild`][@electron/rebuild] package. This module can automatically determine the version of Electron and handle the manual steps of downloading headers and rebuilding native modules for your app. If you are using [Electron Forge][electron-forge], this tool is used automatically in both development mode and when making distributables. -For example, to install the standalone `electron-rebuild` tool and then rebuild +For example, to install the standalone `@electron/rebuild` tool and then rebuild modules with it via the command line: ```sh -npm install --save-dev electron-rebuild +npm install --save-dev @electron/rebuild # Every time you run "npm install", run this: ./node_modules/.bin/electron-rebuild @@ -53,8 +53,7 @@ For example, to install all dependencies for Electron: ```sh # Electron's version. export npm_config_target=1.2.3 -# The architecture of Electron, see https://electronjs.org/docs/tutorial/support#supported-platforms -# for supported architectures. +# The architecture of your machine export npm_config_arch=x64 export npm_config_target_arch=x64 # Download headers for Electron. @@ -98,7 +97,7 @@ npm rebuild --nodedir=/path/to/src/out/Default/gen/node_headers If you installed a native module and found it was not working, you need to check the following things: -* When in doubt, run `electron-rebuild` first. +* When in doubt, run `@electron/rebuild` first. * Make sure the native module is compatible with the target platform and architecture for your Electron app. * Make sure `win_delay_load_hook` is not set to `false` in the module's `binding.gyp`. @@ -161,14 +160,14 @@ modules with prebuilt binaries, and many popular modules are using it. Sometimes those modules work fine under Electron, but when there are no Electron-specific binaries available, you'll need to build from source. -Because of this, it is recommended to use `electron-rebuild` for these modules. +Because of this, it is recommended to use `@electron/rebuild` for these modules. If you are following the `npm` way of installing modules, you'll need to pass `--build-from-source` to `npm`, or set the `npm_config_build_from_source` environment variable. [abi]: https://en.wikipedia.org/wiki/Application_binary_interface -[electron-rebuild]: https://github.com/electron/electron-rebuild +[@electron/rebuild]: https://github.com/electron/rebuild [electron-forge]: https://electronforge.io/ [electron-packager]: https://github.com/electron/electron-packager [node-pre-gyp]: https://github.com/mapbox/node-pre-gyp
docs
b42c0ae00dd4c67c8a454e89662266a466d6b46e
Charles Kerr
2024-09-03 20:51:39
fix: -Wunsafe-buffer-usage warnings in IsUrlArg() (#43477) * fix: -Wunsafe-buffer-usage warnings in IsUrlArg() * chore: improve code comments for CheckCommandLineArguments() * chore: reduce diffs from main * refactor: CheckCommandLineArguments takes a StringVector arg Fixes another buffer warning!
diff --git a/shell/app/command_line_args.cc b/shell/app/command_line_args.cc index b39e242c01..dd8ab0b0be 100644 --- a/shell/app/command_line_args.cc +++ b/shell/app/command_line_args.cc @@ -4,6 +4,7 @@ #include "shell/app/command_line_args.h" +#include <algorithm> #include <locale> #include "sandbox/policy/switches.h" @@ -11,46 +12,44 @@ namespace { -bool IsUrlArg(const base::CommandLine::CharType* arg) { - // the first character must be a letter for this to be a URL - auto c = *arg; - if (std::isalpha(c, std::locale::classic())) { - for (auto* p = arg + 1; *p; ++p) { - c = *p; - - // colon indicates that the argument starts with a URI scheme - if (c == ':') { - // it could also be a Windows filesystem path - if (p == arg + 1) - break; - - return true; - } - - // white-space before a colon means it's not a URL - if (std::isspace(c, std::locale::classic())) - break; - } - } - - return false; +#if BUILDFLAG(IS_WIN) +constexpr auto DashDash = base::CommandLine::StringViewType{L"--"}; +#else +constexpr auto DashDash = base::CommandLine::StringViewType{"--"}; +#endif + +// we say it's a URL arg if it starts with a URI scheme that: +// 1. starts with an alpha, and +// 2. contains no spaces, and +// 3. is longer than one char (to ensure it's not a Windows drive path) +bool IsUrlArg(const base::CommandLine::StringViewType arg) { + const auto scheme_end = arg.find(':'); + if (scheme_end == base::CommandLine::StringViewType::npos) + return false; + + const auto& c_locale = std::locale::classic(); + const auto isspace = [&](auto ch) { return std::isspace(ch, c_locale); }; + const auto scheme = arg.substr(0U, scheme_end); + return std::size(scheme) > 1U && std::isalpha(scheme.front(), c_locale) && + std::ranges::none_of(scheme, isspace); } - } // namespace namespace electron { -bool CheckCommandLineArguments(int argc, base::CommandLine::CharType** argv) { - const base::CommandLine::StringType dashdash(2, '-'); +// Check for CVE-2018-1000006 issues. Return true iff argv looks safe. +// Sample exploit: 'exodus://aaaaaaaaa" --gpu-launcher="cmd" --aaaaa=' +// Prevent it by returning false if any arg except '--' follows a URL arg. +// More info at https://www.electronjs.org/blog/protocol-handler-fix +bool CheckCommandLineArguments(const base::CommandLine::StringVector& argv) { bool block_args = false; - for (int i = 0; i < argc; ++i) { - if (argv[i] == dashdash) + for (const auto& arg : argv) { + if (arg == DashDash) break; - if (block_args) { + if (block_args) return false; - } else if (IsUrlArg(argv[i])) { + if (IsUrlArg(arg)) block_args = true; - } } return true; } diff --git a/shell/app/command_line_args.h b/shell/app/command_line_args.h index 70e1e6b057..6a8c78b4a9 100644 --- a/shell/app/command_line_args.h +++ b/shell/app/command_line_args.h @@ -9,7 +9,7 @@ namespace electron { -bool CheckCommandLineArguments(int argc, base::CommandLine::CharType** argv); +bool CheckCommandLineArguments(const base::CommandLine::StringVector& argv); bool IsSandboxEnabled(base::CommandLine* command_line); } // namespace electron diff --git a/shell/app/electron_main_win.cc b/shell/app/electron_main_win.cc index d6e035775d..6187f98765 100644 --- a/shell/app/electron_main_win.cc +++ b/shell/app/electron_main_win.cc @@ -224,7 +224,7 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) { CHECK_EQ(fiber_status, FiberStatus::kSuccess); #endif // defined(ARCH_CPU_32_BITS) - if (!electron::CheckCommandLineArguments(arguments.argc, arguments.argv)) + if (!electron::CheckCommandLineArguments(command_line->argv())) return -1; sandbox::SandboxInterfaceInfo sandbox_info = {nullptr};
fix
8210d0f90e1ea057f87c9dd1fedaaa8954942a17
Shelley Vohr
2023-10-31 09:27:31
build: don't rename files in `electron_node/deps/base64` (#40368) build: don't rename files in electron_node/deps/base64 Refs https://github.com/electron/electron/pull/35999/files#r1018305596. Finally addresses an old TODO to use a separate build target for conflicting filenames instead of renaming files in the source tree.
diff --git a/patches/node/build_add_gn_build_files.patch b/patches/node/build_add_gn_build_files.patch index 96734be769..3bb39667d6 100644 --- a/patches/node/build_add_gn_build_files.patch +++ b/patches/node/build_add_gn_build_files.patch @@ -405,10 +405,10 @@ index 0000000000000000000000000000000000000000..a564653c3f05608d59fed5aa071d63b8 +} diff --git a/deps/base64/BUILD.gn b/deps/base64/BUILD.gn new file mode 100644 -index 0000000000000000000000000000000000000000..694e1991bb11c9ea85fcc69a0e06265d4b0c5aab +index 0000000000000000000000000000000000000000..9b97aabe865e4cf12f6c3ccda196b372769a823b --- /dev/null +++ b/deps/base64/BUILD.gn -@@ -0,0 +1,152 @@ +@@ -0,0 +1,135 @@ +config("base64_config") { + include_dirs = [ + "base64/include", @@ -420,7 +420,15 @@ index 0000000000000000000000000000000000000000..694e1991bb11c9ea85fcc69a0e06265d + +static_library("base64") { + defines = [] -+ deps = [] ++ deps = [ ++ ":base64_neon32", ++ ":base64_neon64", ++ ":base64_avx", ++ ":base64_avx2", ++ ":base64_sse41", ++ ":base64_sse42", ++ ":base64_ssse3", ++ ] + + public_configs = [ ":base64_config" ] + @@ -438,157 +446,104 @@ index 0000000000000000000000000000000000000000..694e1991bb11c9ea85fcc69a0e06265d + "base64/lib/lib.c", + "base64/lib/tables/tables.c", + ] -+ -+ if (target_cpu == "arm") { -+ defines += [ "HAVE_NEON32=1" ] -+ deps += [ ":base64_neon32" ] -+ } else { -+ sources += [ "base64/lib/arch/neon32/neon32_codec.c" ] -+ } -+ -+ if (target_cpu == "arm64") { -+ defines += [ "HAVE_NEON64=1" ] -+ deps += [ ":base64_neon64" ] -+ } else { -+ sources += [ "base64/lib/arch/neon64/neon64_codec.c" ] -+ } -+ -+ if (target_cpu == "ia32" || target_cpu == "x64" || target_cpu == "x32") { -+ defines += [ -+ "HAVE_SSSE3=1", -+ "HAVE_SSE41=1", -+ "HAVE_SSE42=1", -+ "HAVE_AVX=1", -+ "HAVE_AVX2=1", -+ ] -+ -+ deps += [ -+ ":base64_avx", -+ ":base64_avx2", -+ ":base64_sse41", -+ ":base64_sse42", -+ ":base64_ssse3", -+ ] -+ } else { -+ sources += [ -+ "base64/lib/arch/avx/avx_codec.c", -+ "base64/lib/arch/avx2/avx2_codec.c", -+ "base64/lib/arch/sse41/sse41_codec.c", -+ "base64/lib/arch/sse42/sse42_codec.c", -+ "base64/lib/arch/ssse3/ssse3_codec.c", -+ ] -+ } +} + +source_set("base64_ssse3") { + public_configs = [ ":base64_config" ] + -+ defines = [ "HAVE_SSSE3=1" ] ++ if (target_cpu == "ia32" || target_cpu == "x64" || target_cpu == "x32") { ++ defines = [ "HAVE_SSSE3=1" ] + -+ cflags = [ "-mssse3" ] -+ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ cflags = [ "-mssse3" ] ++ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ } + -+ sources = [ "base64/lib/arch/ssse3/ssse3_codec.c" ] ++ sources = [ "base64/lib/arch/ssse3/codec.c" ] +} + +source_set("base64_sse41") { + public_configs = [ ":base64_config" ] + -+ defines = [ "HAVE_SSE41=1" ] ++ if (target_cpu == "ia32" || target_cpu == "x64" || target_cpu == "x32") { ++ defines = [ "HAVE_SSE41=1" ] + -+ cflags = [ "-msse4.1" ] -+ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ cflags = [ "-msse4.1" ] ++ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ } + -+ sources = [ "base64/lib/arch/sse41/sse41_codec.c" ] ++ sources = [ "base64/lib/arch/sse41/codec.c" ] +} + ++ +source_set("base64_sse42") { + public_configs = [ ":base64_config" ] + -+ defines = [ -+ "BASE64_STATIC_DEFINE", -+ "HAVE_SSE42=1", -+ ] ++ if (target_cpu == "ia32" || target_cpu == "x64" || target_cpu == "x32") { ++ defines = [ ++ "BASE64_STATIC_DEFINE", ++ "HAVE_SSE42=1", ++ ] + -+ cflags = [ "-msse4.2" ] -+ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ cflags = [ "-msse4.2" ] ++ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ } + -+ sources = [ "base64/lib/arch/sse42/sse42_codec.c" ] ++ sources = [ "base64/lib/arch/sse42/codec.c" ] +} + +source_set("base64_avx") { + public_configs = [ ":base64_config" ] + -+ defines = [ "HAVE_AVX=1" ] ++ if (target_cpu == "ia32" || target_cpu == "x64" || target_cpu == "x32") { ++ defines = [ "HAVE_AVX=1" ] + -+ cflags = [ "-mavx" ] -+ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ cflags = [ "-mavx" ] ++ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ } + -+ sources = [ "base64/lib/arch/avx/avx_codec.c" ] ++ sources = [ "base64/lib/arch/avx/codec.c" ] +} + +source_set("base64_avx2") { + public_configs = [ ":base64_config" ] + -+ defines = [ "HAVE_AVX2=1" ] ++ if (target_cpu == "ia32" || target_cpu == "x64" || target_cpu == "x32") { ++ defines = [ "HAVE_AVX2=1" ] + -+ cflags = [ "-mavx2" ] -+ cflags_c = [ -+ "-Wno-implicit-fallthrough", -+ "-Wno-implicit-function-declaration", -+ ] ++ cflags = [ "-mavx2" ] ++ cflags_c = [ ++ "-Wno-implicit-fallthrough", ++ "-Wno-implicit-function-declaration", ++ ] ++ } + -+ sources = [ "base64/lib/arch/avx2/avx2_codec.c" ] ++ sources = [ "base64/lib/arch/avx2/codec.c" ] +} + +source_set("base64_neon32") { + public_configs = [ ":base64_config" ] + -+ defines = [ "HAVE_NEON32=1" ] ++ if (target_cpu == "arm") { ++ defines = [ "HAVE_NEON32=1" ] + -+ cflags = [ "-mfpu=neon" ] -+ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ cflags = [ "-mfpu=neon" ] ++ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ } + -+ sources = [ "base64/lib/arch/neon32/neon32_codec.c" ] ++ sources = [ "base64/lib/arch/neon32/codec.c" ] +} + +source_set("base64_neon64") { + public_configs = [ ":base64_config" ] + -+ defines = [ "HAVE_NEON64=1" ] ++ if (target_cpu == "arm64") { ++ defines = [ "HAVE_NEON64=1" ] + -+ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ } + -+ sources = [ "base64/lib/arch/neon64/neon64_codec.c" ] ++ sources = [ "base64/lib/arch/neon64/codec.c" ] +} -diff --git a/deps/base64/base64/lib/arch/avx/codec.c b/deps/base64/base64/lib/arch/avx/avx_codec.c -similarity index 100% -rename from deps/base64/base64/lib/arch/avx/codec.c -rename to deps/base64/base64/lib/arch/avx/avx_codec.c -diff --git a/deps/base64/base64/lib/arch/avx2/codec.c b/deps/base64/base64/lib/arch/avx2/avx2_codec.c -similarity index 100% -rename from deps/base64/base64/lib/arch/avx2/codec.c -rename to deps/base64/base64/lib/arch/avx2/avx2_codec.c -diff --git a/deps/base64/base64/lib/arch/neon32/codec.c b/deps/base64/base64/lib/arch/neon32/neon32_codec.c -similarity index 100% -rename from deps/base64/base64/lib/arch/neon32/codec.c -rename to deps/base64/base64/lib/arch/neon32/neon32_codec.c -diff --git a/deps/base64/base64/lib/arch/neon64/codec.c b/deps/base64/base64/lib/arch/neon64/neon64_codec.c -similarity index 100% -rename from deps/base64/base64/lib/arch/neon64/codec.c -rename to deps/base64/base64/lib/arch/neon64/neon64_codec.c -diff --git a/deps/base64/base64/lib/arch/sse41/codec.c b/deps/base64/base64/lib/arch/sse41/sse41_codec.c -similarity index 100% -rename from deps/base64/base64/lib/arch/sse41/codec.c -rename to deps/base64/base64/lib/arch/sse41/sse41_codec.c -diff --git a/deps/base64/base64/lib/arch/sse42/codec.c b/deps/base64/base64/lib/arch/sse42/sse42_codec.c -similarity index 100% -rename from deps/base64/base64/lib/arch/sse42/codec.c -rename to deps/base64/base64/lib/arch/sse42/sse42_codec.c -diff --git a/deps/base64/base64/lib/arch/ssse3/codec.c b/deps/base64/base64/lib/arch/ssse3/ssse3_codec.c -similarity index 100% -rename from deps/base64/base64/lib/arch/ssse3/codec.c -rename to deps/base64/base64/lib/arch/ssse3/ssse3_codec.c diff --git a/deps/cares/BUILD.gn b/deps/cares/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2a902c68ca445b8451e442c314c60ee5a30719e4
build
6dc46e5bcf4a4d7885b09078eca9d89b5f0c9d6a
Milan Burda
2023-03-15 14:07:51
refactor: replace deprecated base::Value::Set<Type>Key usage (#37570) Co-authored-by: Milan Burda <[email protected]>
diff --git a/shell/browser/hid/hid_chooser_context.cc b/shell/browser/hid/hid_chooser_context.cc index 1c008abe0b..1a01be443b 100644 --- a/shell/browser/hid/hid_chooser_context.cc +++ b/shell/browser/hid/hid_chooser_context.cc @@ -70,23 +70,23 @@ bool HidChooserContext::CanStorePersistentEntry( // static base::Value HidChooserContext::DeviceInfoToValue( const device::mojom::HidDeviceInfo& device) { - base::Value value(base::Value::Type::DICT); - value.SetStringKey( + base::Value::Dict value; + value.Set( kHidDeviceNameKey, base::UTF16ToUTF8(HidChooserContext::DisplayNameFromDeviceInfo(device))); - value.SetIntKey(kDeviceVendorIdKey, device.vendor_id); - value.SetIntKey(kDeviceProductIdKey, device.product_id); + value.Set(kDeviceVendorIdKey, device.vendor_id); + value.Set(kDeviceProductIdKey, device.product_id); if (HidChooserContext::CanStorePersistentEntry(device)) { // Use the USB serial number as a persistent identifier. If it is // unavailable, only ephemeral permissions may be granted. - value.SetStringKey(kDeviceSerialNumberKey, device.serial_number); + value.Set(kDeviceSerialNumberKey, device.serial_number); } else { // The GUID is a temporary ID created on connection that remains valid until // the device is disconnected. Ephemeral permissions are keyed by this ID // and must be granted again each time the device is connected. - value.SetStringKey(kHidGuidKey, device.guid); + value.Set(kHidGuidKey, device.guid); } - return value; + return base::Value(std::move(value)); } void HidChooserContext::GrantDevicePermission( diff --git a/shell/browser/ui/inspectable_web_contents.cc b/shell/browser/ui/inspectable_web_contents.cc index 1f7931d55f..6a0afd12e9 100644 --- a/shell/browser/ui/inspectable_web_contents.cc +++ b/shell/browser/ui/inspectable_web_contents.cc @@ -97,12 +97,12 @@ const size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4; InspectableWebContents::List g_web_contents_instances_; base::Value RectToDictionary(const gfx::Rect& bounds) { - base::Value dict(base::Value::Type::DICT); - dict.SetKey("x", base::Value(bounds.x())); - dict.SetKey("y", base::Value(bounds.y())); - dict.SetKey("width", base::Value(bounds.width())); - dict.SetKey("height", base::Value(bounds.height())); - return dict; + base::Value::Dict dict; + dict.Set("x", bounds.x()); + dict.Set("y", bounds.y()); + dict.Set("width", bounds.width()); + dict.Set("height", bounds.height()); + return base::Value(std::move(dict)); } gfx::Rect DictionaryToRect(const base::Value::Dict& dict) { @@ -895,7 +895,7 @@ void InspectableWebContents::ClearPreferences() { void InspectableWebContents::GetSyncInformation(DispatchCallback callback) { base::Value result(base::Value::Type::DICT); - result.SetBoolKey("isSyncActive", false); + result.GetDict().Set("isSyncActive", false); std::move(callback).Run(&result); } diff --git a/shell/browser/usb/usb_chooser_context.cc b/shell/browser/usb/usb_chooser_context.cc index 567fbd30c4..c8acfd961b 100644 --- a/shell/browser/usb/usb_chooser_context.cc +++ b/shell/browser/usb/usb_chooser_context.cc @@ -82,40 +82,35 @@ UsbChooserContext::UsbChooserContext(ElectronBrowserContext* context) // static base::Value UsbChooserContext::DeviceInfoToValue( const device::mojom::UsbDeviceInfo& device_info) { - base::Value device_value(base::Value::Type::DICT); - device_value.SetStringKey(kDeviceNameKey, device_info.product_name - ? *device_info.product_name - : base::StringPiece16()); - device_value.SetIntKey(kDeviceVendorIdKey, device_info.vendor_id); - device_value.SetIntKey(kDeviceProductIdKey, device_info.product_id); + base::Value::Dict device_value; + device_value.Set(kDeviceNameKey, device_info.product_name + ? *device_info.product_name + : base::StringPiece16()); + device_value.Set(kDeviceVendorIdKey, device_info.vendor_id); + device_value.Set(kDeviceProductIdKey, device_info.product_id); if (device_info.manufacturer_name) { - device_value.SetStringKey("manufacturerName", - *device_info.manufacturer_name); + device_value.Set("manufacturerName", *device_info.manufacturer_name); } // CanStorePersistentEntry checks if |device_info.serial_number| is not empty. if (CanStorePersistentEntry(device_info)) { - device_value.SetStringKey(kDeviceSerialNumberKey, - *device_info.serial_number); + device_value.Set(kDeviceSerialNumberKey, *device_info.serial_number); } - device_value.SetStringKey(kDeviceIdKey, device_info.guid); - - device_value.SetIntKey("usbVersionMajor", device_info.usb_version_major); - device_value.SetIntKey("usbVersionMinor", device_info.usb_version_minor); - device_value.SetIntKey("usbVersionSubminor", - device_info.usb_version_subminor); - device_value.SetIntKey("deviceClass", device_info.class_code); - device_value.SetIntKey("deviceSubclass", device_info.subclass_code); - device_value.SetIntKey("deviceProtocol", device_info.protocol_code); - device_value.SetIntKey("deviceVersionMajor", - device_info.device_version_major); - device_value.SetIntKey("deviceVersionMinor", - device_info.device_version_minor); - device_value.SetIntKey("deviceVersionSubminor", - device_info.device_version_subminor); - return device_value; + device_value.Set(kDeviceIdKey, device_info.guid); + + device_value.Set("usbVersionMajor", device_info.usb_version_major); + device_value.Set("usbVersionMinor", device_info.usb_version_minor); + device_value.Set("usbVersionSubminor", device_info.usb_version_subminor); + device_value.Set("deviceClass", device_info.class_code); + device_value.Set("deviceSubclass", device_info.subclass_code); + device_value.Set("deviceProtocol", device_info.protocol_code); + device_value.Set("deviceVersionMajor", device_info.device_version_major); + device_value.Set("deviceVersionMinor", device_info.device_version_minor); + device_value.Set("deviceVersionSubminor", + device_info.device_version_subminor); + return base::Value(std::move(device_value)); } void UsbChooserContext::InitDeviceList( diff --git a/shell/browser/web_contents_preferences.cc b/shell/browser/web_contents_preferences.cc index 8a6fd0d8e5..4371fb0e70 100644 --- a/shell/browser/web_contents_preferences.cc +++ b/shell/browser/web_contents_preferences.cc @@ -389,28 +389,23 @@ void WebContentsPreferences::AppendCommandLineSwitches( } void WebContentsPreferences::SaveLastPreferences() { - last_web_preferences_ = base::Value(base::Value::Type::DICT); - last_web_preferences_.SetKey(options::kNodeIntegration, - base::Value(node_integration_)); - last_web_preferences_.SetKey(options::kNodeIntegrationInSubFrames, - base::Value(node_integration_in_sub_frames_)); - last_web_preferences_.SetKey(options::kSandbox, base::Value(IsSandboxed())); - last_web_preferences_.SetKey(options::kContextIsolation, - base::Value(context_isolation_)); - last_web_preferences_.SetKey(options::kJavaScript, base::Value(javascript_)); - last_web_preferences_.SetKey(options::kEnableWebSQL, - base::Value(enable_websql_)); - last_web_preferences_.SetKey(options::kWebviewTag, base::Value(webview_tag_)); - last_web_preferences_.SetKey("disablePopups", base::Value(disable_popups_)); - last_web_preferences_.SetKey(options::kWebSecurity, - base::Value(web_security_)); - last_web_preferences_.SetKey(options::kAllowRunningInsecureContent, - base::Value(allow_running_insecure_content_)); - last_web_preferences_.SetKey(options::kExperimentalFeatures, - base::Value(experimental_features_)); - last_web_preferences_.SetKey( - options::kEnableBlinkFeatures, - base::Value(enable_blink_features_.value_or(""))); + base::Value::Dict dict; + dict.Set(options::kNodeIntegration, node_integration_); + dict.Set(options::kNodeIntegrationInSubFrames, + node_integration_in_sub_frames_); + dict.Set(options::kSandbox, IsSandboxed()); + dict.Set(options::kContextIsolation, context_isolation_); + dict.Set(options::kJavaScript, javascript_); + dict.Set(options::kEnableWebSQL, enable_websql_); + dict.Set(options::kWebviewTag, webview_tag_); + dict.Set("disablePopups", disable_popups_); + dict.Set(options::kWebSecurity, web_security_); + dict.Set(options::kAllowRunningInsecureContent, + allow_running_insecure_content_); + dict.Set(options::kExperimentalFeatures, experimental_features_); + dict.Set(options::kEnableBlinkFeatures, enable_blink_features_.value_or("")); + + last_web_preferences_ = base::Value(std::move(dict)); } void WebContentsPreferences::OverrideWebkitPrefs( diff --git a/shell/common/gin_converters/hid_device_info_converter.h b/shell/common/gin_converters/hid_device_info_converter.h index 6175b77ab0..09c597466f 100644 --- a/shell/common/gin_converters/hid_device_info_converter.h +++ b/shell/common/gin_converters/hid_device_info_converter.h @@ -18,7 +18,7 @@ struct Converter<device::mojom::HidDeviceInfoPtr> { v8::Isolate* isolate, const device::mojom::HidDeviceInfoPtr& device) { base::Value value = electron::HidChooserContext::DeviceInfoToValue(*device); - value.SetStringKey( + value.GetDict().Set( "deviceId", electron::HidChooserController::PhysicalDeviceIdFromDeviceInfo( *device));
refactor
58beec1da2cacd59a91a556b86f47ec0147b9c36
Samuel Attard
2023-01-25 13:03:47
fix: do not error on null exports in ESM loader (#37009)
diff --git a/patches/node/fix_expose_the_built-in_electron_module_via_the_esm_loader.patch b/patches/node/fix_expose_the_built-in_electron_module_via_the_esm_loader.patch index 4d18cbb616..5fb1654831 100644 --- a/patches/node/fix_expose_the_built-in_electron_module_via_the_esm_loader.patch +++ b/patches/node/fix_expose_the_built-in_electron_module_via_the_esm_loader.patch @@ -51,7 +51,7 @@ index 7cec4e9a3e3675ba75d66a44ed4e142d13ca1821..0c7aad193442a7e5cab62638441969a7 } } diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js -index 6f25b2e67ab77613c6ed63c227bb875d5461f45f..d1527b859bbea15fdf30622fc8f2700bde5b4591 100644 +index 6f25b2e67ab77613c6ed63c227bb875d5461f45f..010fa8f78a21a8146879849e2e887332e2694e51 100644 --- a/lib/internal/modules/esm/translators.js +++ b/lib/internal/modules/esm/translators.js @@ -154,7 +154,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source, @@ -63,15 +63,19 @@ index 6f25b2e67ab77613c6ed63c227bb875d5461f45f..d1527b859bbea15fdf30622fc8f2700b [...exportNames] : ['default', ...exportNames]; return new ModuleWrap(url, undefined, namesWithDefault, function() { -@@ -173,7 +173,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source, +@@ -173,9 +173,9 @@ translators.set('commonjs', async function commonjsStrategy(url, source, } } - for (const exportName of exportNames) { +- if (!ObjectPrototypeHasOwnProperty(exports, exportName) || +- exportName === 'default') + for (const exportName of namesWithDefault) { - if (!ObjectPrototypeHasOwnProperty(exports, exportName) || - exportName === 'default') ++ if (exportName === 'default' || ++ !ObjectPrototypeHasOwnProperty(exports, exportName)) continue; + // We might trigger a getter -> dont fail. + let value; diff --git a/lib/internal/url.js b/lib/internal/url.js index 40b25f6890b5db721923ba2e9cc351e514ca22bc..288f3253b4c686d1b061dfcdf18dc95794943d87 100644 --- a/lib/internal/url.js
fix
07530f8e37060fc58991224e7d027614bffb4721
Jeremy Rose
2022-10-27 06:29:19
test: fix flake in will-navigate test (#36153)
diff --git a/spec/api-browser-window-spec.ts b/spec/api-browser-window-spec.ts index 1edc690465..85fc5f229a 100644 --- a/spec/api-browser-window-spec.ts +++ b/spec/api-browser-window-spec.ts @@ -567,6 +567,10 @@ describe('BrowserWindow module', () => { targetId: iframeTarget.targetId, flatten: true }); + let willNavigateEmitted = false; + w.webContents.on('will-navigate', () => { + willNavigateEmitted = true; + }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, @@ -581,10 +585,6 @@ describe('BrowserWindow module', () => { clickCount: 1, button: 'left' }, sessionId); - let willNavigateEmitted = false; - w.webContents.on('will-navigate', () => { - willNavigateEmitted = true; - }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); });
test
f7c6545eab87e55b5ddc27b00d3d1337997542eb
github-actions[bot]
2023-04-02 21:08:27
build: update appveyor image to latest version (#37773) Co-authored-by: jkleinsc <[email protected]>
diff --git a/appveyor-woa.yml b/appveyor-woa.yml index 1b26dbf668..a8219f6e6f 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-113.0.5636.0 +image: e-114.0.5684.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default diff --git a/appveyor.yml b/appveyor.yml index da25117c18..7730cacf49 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-113.0.5636.0 +image: e-114.0.5684.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default
build
e9db02948e8c3b7f08dcfe4c6984009a2436cd9a
Charles Kerr
2024-07-08 10:04:35
fix: multiple move() calls on the same unique_ptr (#42788)
diff --git a/shell/browser/extensions/electron_extensions_browser_client.cc b/shell/browser/extensions/electron_extensions_browser_client.cc index 1af0a6e815..e972603b20 100644 --- a/shell/browser/extensions/electron_extensions_browser_client.cc +++ b/shell/browser/extensions/electron_extensions_browser_client.cc @@ -343,13 +343,12 @@ void ElectronExtensionsBrowserClient::BroadcastEventToRenderers( return; } - auto event = std::make_unique<extensions::Event>(histogram_value, event_name, - args.Clone()); for (auto const& [key, browser_context] : ElectronBrowserContext::browser_context_map()) { if (browser_context) { extensions::EventRouter::Get(browser_context.get()) - ->BroadcastEvent(std::move(event)); + ->BroadcastEvent(std::make_unique<extensions::Event>( + histogram_value, event_name, args.Clone())); } } }
fix
2e4857fbcbaebd62b7326fe4850add8e8ed4e9d6
David Sanders
2024-06-18 12:30:08
ci: auto close non-maintainer PRs that touch lockfiles (#42534)
diff --git a/.github/workflows/auto-close-pull-request.yml b/.github/workflows/auto-close-pull-request.yml new file mode 100644 index 0000000000..85b3bd3aab --- /dev/null +++ b/.github/workflows/auto-close-pull-request.yml @@ -0,0 +1,24 @@ +name: Auto Close Pull Request + +on: + pull_request_target: + paths: + - 'yarn.lock' + - 'spec/yarn.lock' + +permissions: {} + +jobs: + auto-close-dependency-pull-request: + name: Auto close non-maintainer dependency pull request + if: ${{ !contains(fromJSON('["MEMBER", "OWNER"]'), github.event.pull_request.author_association) && github.event.pull_request.user.type != 'Bot' && !github.event.pull_request.draft }} + permissions: + pull-requests: write + runs-on: ubuntu-latest + steps: + - name: Close pull request + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_URL: ${{ github.event.pull_request.html_url }} + run: | + gh pr close $PR_URL --comment 'Hello @${{ github.event.pull_request.user.login }}! It looks like this pull request touches one of our dependency files, and per [our contribution policy](https://github.com/electron/electron/blob/main/CONTRIBUTING.md#dependencies-upgrades-policy) we do not accept these types of PRs, so this PR will be closed.'
ci
a30a9c7c4faa5aca476dd593dd02bbfac43432df
Robo
2023-01-26 09:01:34
chore: remove crashpad related sandbox policy (#37013)
diff --git a/shell/browser/electron_browser_client.cc b/shell/browser/electron_browser_client.cc index 45dc1f66dd..7165ff4d32 100644 --- a/shell/browser/electron_browser_client.cc +++ b/shell/browser/electron_browser_client.cc @@ -120,10 +120,6 @@ #include "ui/native_theme/native_theme.h" #include "v8/include/v8.h" -#if BUILDFLAG(IS_WIN) -#include "sandbox/win/src/sandbox_policy.h" -#endif - #if BUILDFLAG(USE_NSS_CERTS) #include "net/ssl/client_cert_store_nss.h" #elif BUILDFLAG(IS_WIN) @@ -1435,19 +1431,6 @@ void ElectronBrowserClient::OverrideURLLoaderFactoryParams( browser_context, origin, is_for_isolated_world, factory_params); } -#if BUILDFLAG(IS_WIN) -bool ElectronBrowserClient::PreSpawnChild(sandbox::TargetPolicy* policy, - sandbox::mojom::Sandbox sandbox_type, - ChildSpawnFlags flags) { - sandbox::ResultCode result = policy->GetConfig()->AddRule( - sandbox::SubSystem::kFiles, sandbox::Semantics::kFilesAllowAny, - L"\\??\\pipe\\crashpad_*"); - if (result != sandbox::SBOX_ALL_OK) - return false; - return true; -} -#endif // BUILDFLAG(IS_WIN) - void ElectronBrowserClient:: RegisterAssociatedInterfaceBindersForRenderFrameHost( content::RenderFrameHost& diff --git a/shell/browser/electron_browser_client.h b/shell/browser/electron_browser_client.h index a410ef9781..cac12e8582 100644 --- a/shell/browser/electron_browser_client.h +++ b/shell/browser/electron_browser_client.h @@ -242,11 +242,6 @@ class ElectronBrowserClient : public content::ContentBrowserClient, const url::Origin& origin, bool is_for_isolated_world, network::mojom::URLLoaderFactoryParams* factory_params) override; -#if BUILDFLAG(IS_WIN) - bool PreSpawnChild(sandbox::TargetPolicy* policy, - sandbox::mojom::Sandbox sandbox_type, - ChildSpawnFlags flags) override; -#endif void RegisterAssociatedInterfaceBindersForRenderFrameHost( content::RenderFrameHost& render_frame_host, blink::AssociatedInterfaceRegistry& associated_registry) override;
chore
5931f69f183bfcd57c9dc7dffe8560ac9163bb45
Charles Kerr
2023-06-07 02:28:50
fix: sync api::Screen wrapper method sigs to upstream (#38597) refactor: sync api::Screen getter sigs to upstream ui::Display GetAllDisplays(), GetPrimaryDisplay(), GetDisplayMatching(), and GetDisplayNearestPoint() methods are all const, so make our wrappers const too. ui::Display GetAllDisplays() returns a const reference, so make our wrapper return a const reference too. This avoids creating a new std::vector<display::Display> each time it's called.
diff --git a/shell/browser/api/electron_api_screen.cc b/shell/browser/api/electron_api_screen.cc index ca5c65401c..73e5c93597 100644 --- a/shell/browser/api/electron_api_screen.cc +++ b/shell/browser/api/electron_api_screen.cc @@ -87,22 +87,6 @@ gfx::Point Screen::GetCursorScreenPoint(v8::Isolate* isolate) { return screen_->GetCursorScreenPoint(); } -display::Display Screen::GetPrimaryDisplay() { - return screen_->GetPrimaryDisplay(); -} - -std::vector<display::Display> Screen::GetAllDisplays() { - return screen_->GetAllDisplays(); -} - -display::Display Screen::GetDisplayNearestPoint(const gfx::Point& point) { - return screen_->GetDisplayNearestPoint(point); -} - -display::Display Screen::GetDisplayMatching(const gfx::Rect& match_rect) { - return screen_->GetDisplayMatching(match_rect); -} - #if BUILDFLAG(IS_WIN) static gfx::Rect ScreenToDIPRect(electron::NativeWindow* window, diff --git a/shell/browser/api/electron_api_screen.h b/shell/browser/api/electron_api_screen.h index 20bbff0497..ca29a79f5d 100644 --- a/shell/browser/api/electron_api_screen.h +++ b/shell/browser/api/electron_api_screen.h @@ -42,10 +42,18 @@ class Screen : public gin::Wrappable<Screen>, ~Screen() override; gfx::Point GetCursorScreenPoint(v8::Isolate* isolate); - display::Display GetPrimaryDisplay(); - std::vector<display::Display> GetAllDisplays(); - display::Display GetDisplayNearestPoint(const gfx::Point& point); - display::Display GetDisplayMatching(const gfx::Rect& match_rect); + display::Display GetPrimaryDisplay() const { + return screen_->GetPrimaryDisplay(); + } + const std::vector<display::Display>& GetAllDisplays() const { + return screen_->GetAllDisplays(); + } + display::Display GetDisplayNearestPoint(const gfx::Point& point) const { + return screen_->GetDisplayNearestPoint(point); + } + display::Display GetDisplayMatching(const gfx::Rect& match_rect) const { + return screen_->GetDisplayMatching(match_rect); + } // display::DisplayObserver: void OnDisplayAdded(const display::Display& new_display) override;
fix
e6931a788fad3d3315d3911c1997f3cd98fa34d0
David Sanders
2023-08-03 05:40:29
docs: clean up removed systemPreferences methods (#39334)
diff --git a/docs/api/system-preferences.md b/docs/api/system-preferences.md index 105e11da14..e66e5d0d4e 100644 --- a/docs/api/system-preferences.md +++ b/docs/api/system-preferences.md @@ -6,7 +6,7 @@ Process: [Main](../glossary.md#main-process) ```javascript const { systemPreferences } = require('electron') -console.log(systemPreferences.isDarkMode()) +console.log(systemPreferences.isAeroGlassEnabled()) ``` ## Events @@ -47,12 +47,6 @@ Returns: ## Methods -### `systemPreferences.isDarkMode()` _macOS_ _Windows_ _Deprecated_ - -Returns `boolean` - Whether the system is in Dark Mode. - -**Deprecated:** Should use the new [`nativeTheme.shouldUseDarkColors`](native-theme.md#nativethemeshouldusedarkcolors-readonly) API. - ### `systemPreferences.isSwipeTrackingFromScrollEventsEnabled()` _macOS_ Returns `boolean` - Whether the Swipe between pages setting is on. @@ -356,18 +350,6 @@ Returns `string` - The standard system color formatted as `#RRGGBBAA`. Returns one of several standard system colors that automatically adapt to vibrancy and changes in accessibility settings like 'Increase contrast' and 'Reduce transparency'. See [Apple Documentation](https://developer.apple.com/design/human-interface-guidelines/macos/visual-design/color#system-colors) for more details. -### `systemPreferences.isInvertedColorScheme()` _Windows_ _Deprecated_ - -Returns `boolean` - `true` if an inverted color scheme (a high contrast color scheme with light text and dark backgrounds) is active, `false` otherwise. - -**Deprecated:** Should use the new [`nativeTheme.shouldUseInvertedColorScheme`](native-theme.md#nativethemeshoulduseinvertedcolorscheme-macos-windows-readonly) API. - -### `systemPreferences.isHighContrastColorScheme()` _macOS_ _Windows_ _Deprecated_ - -Returns `boolean` - `true` if a high contrast theme is active, `false` otherwise. - -**Deprecated:** Should use the new [`nativeTheme.shouldUseHighContrastColors`](native-theme.md#nativethemeshouldusehighcontrastcolors-macos-windows-readonly) API. - ### `systemPreferences.getEffectiveAppearance()` _macOS_ Returns `string` - Can be `dark`, `light` or `unknown`.
docs
0026fdb78a68c6a4067191826bd1bfc1d9700998
Shelley Vohr
2023-01-26 14:04:19
fix: resizing borders in nondraggable regions (#37016) * fix: resizing borders in nondraggable regions * chore: remove frame handling from ShouldDescendIntoChildForEventHandling
diff --git a/shell/browser/native_window.cc b/shell/browser/native_window.cc index a566ee8cfb..3a6654e00d 100644 --- a/shell/browser/native_window.cc +++ b/shell/browser/native_window.cc @@ -24,6 +24,10 @@ #include "ui/base/hit_test.h" #include "ui/views/widget/widget.h" +#if !BUILDFLAG(IS_MAC) +#include "shell/browser/ui/views/frameless_view.h" +#endif + #if BUILDFLAG(IS_WIN) #include "ui/base/win/shell.h" #include "ui/display/win/screen_win.h" @@ -693,6 +697,17 @@ void NativeWindow::NotifyWindowMessage(UINT message, #endif int NativeWindow::NonClientHitTest(const gfx::Point& point) { +#if !BUILDFLAG(IS_MAC) + // We need to ensure we account for resizing borders on Windows and Linux. + if ((!has_frame() || has_client_frame()) && IsResizable()) { + auto* frame = + static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); + int border_hit = frame->ResizingBorderHitTest(point); + if (border_hit != HTNOWHERE) + return border_hit; + } +#endif + for (auto* provider : draggable_region_providers_) { int hit = provider->NonClientHitTest(point); if (hit != HTNOWHERE) diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc index 436f9d9d13..19b3b76b22 100644 --- a/shell/browser/native_window_views.cc +++ b/shell/browser/native_window_views.cc @@ -1592,19 +1592,7 @@ views::View* NativeWindowViews::GetContentsView() { bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { - // App window should claim mouse events that fall within any BrowserViews' - // draggable region. - if (NonClientHitTest(location) != HTNOWHERE) - return false; - - // And the events on border for dragging resizable frameless window. - if ((!has_frame() || has_client_frame()) && resizable_) { - auto* frame = - static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); - return frame->ResizingBorderHitTest(location) == HTNOWHERE; - } - - return true; + return NonClientHitTest(location) == HTNOWHERE; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) {
fix
fa81f77f408d78ea0aa1506dbc2587d7ba03b05c
Calvin
2023-05-16 06:30:25
test: re-enable tests that aren't broken & remove old test (#38251)
diff --git a/spec/api-protocol-spec.ts b/spec/api-protocol-spec.ts index 05d9794264..9fab1598a3 100644 --- a/spec/api-protocol-spec.ts +++ b/spec/api-protocol-spec.ts @@ -282,18 +282,6 @@ describe('protocol module', () => { ipcMain.once('loaded-iframe-custom-protocol', () => done()); }); - // DISABLED-FIXME - it('throws an error when custom headers are invalid', (done) => { - registerFileProtocol(protocolName, (request, callback) => { - expect(() => callback({ - path: filePath, - headers: { 'X-Great-Header': (42 as any) } - })).to.throw(Error, 'Value of \'X-Great-Header\' header has to be a string'); - done(); - }); - ajax(protocolName + '://fake-host').catch(() => {}); - }); - it('sends object as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath })); const r = await ajax(protocolName + '://fake-host'); @@ -880,7 +868,6 @@ describe('protocol module', () => { await requestReceived; }); - // DISABLED-FIXME it('can access files through the FileSystem API', (done) => { const filePath = path.join(fixturesPath, 'pages', 'filesystem.html'); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); diff --git a/spec/disabled-tests.json b/spec/disabled-tests.json index 8765f602a8..6391393933 100644 --- a/spec/disabled-tests.json +++ b/spec/disabled-tests.json @@ -4,13 +4,9 @@ "BrowserWindow module document.visibilityState/hidden visibilityState remains visible if backgroundThrottling is disabled", "Menu module Menu.setApplicationMenu unsets a menu with null", "process module main process process.takeHeapSnapshot() returns true on success", - "protocol module protocol.registerFileProtocol throws an error when custom headers are invalid", - "protocol module protocol.registerProtocol throws an error when custom headers are invalid", - "protocol module protocol.registerSchemesAsPrivileged standard can access files through the FileSystem API", "protocol module protocol.registerSchemesAsPrivileged cors-fetch disallows CORS and fetch requests when only supportFetchAPI is specified", "session module ses.cookies should set cookie for standard scheme", "webFrameMain module WebFrame.visibilityState should match window state", "reporting api sends a report for a deprecation", - "chromium features SpeechSynthesis should emit lifecycle events", - "version-bumper nextVersion bump versions bumps to beta from nightly" + "chromium features SpeechSynthesis should emit lifecycle events" ] \ No newline at end of file diff --git a/spec/version-bump-spec.ts b/spec/version-bump-spec.ts index 4a2593da28..3541e3fe28 100644 --- a/spec/version-bump-spec.ts +++ b/spec/version-bump-spec.ts @@ -132,7 +132,6 @@ describe('version-bumper', () => { ).to.be.rejectedWith('Cannot bump to beta from stable.'); }); - // DISABLED-FIXME(ELECTRON 15): Re-enable after Electron 15 alpha has released it('bumps to beta from nightly', async () => { const version = 'v2.0.0-nightly.19950901'; const next = await nextVersion('beta', version);
test
43a646ed8592f31e0c8fa08b684dac329b7bf976
John Kleinschmidt
2023-09-28 11:15:52
build: log uploads to GitHub (#40034)
diff --git a/script/release/uploaders/upload-to-github.ts b/script/release/uploaders/upload-to-github.ts index 42dd9103c4..fa515441f8 100644 --- a/script/release/uploaders/upload-to-github.ts +++ b/script/release/uploaders/upload-to-github.ts @@ -2,7 +2,8 @@ import { Octokit } from '@octokit/rest'; import * as fs from 'node:fs'; const octokit = new Octokit({ - auth: process.env.ELECTRON_GITHUB_TOKEN + auth: process.env.ELECTRON_GITHUB_TOKEN, + log: console }); if (!process.env.CI) require('dotenv-safe').load();
build
1548a2f9fb6d9bf9e0c4f6ace595189cf84b38e9
github-actions[bot]
2023-08-07 13:08:53
build: update appveyor image to e-117.0.5921.0 (#39390) build: update appveyor image to latest version Co-authored-by: jkleinsc <[email protected]>
diff --git a/appveyor-woa.yml b/appveyor-woa.yml index 2c1bdc28cd..6bf813b9e5 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-117.0.5911.0 +image: e-117.0.5921.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default diff --git a/appveyor.yml b/appveyor.yml index 02b669b89d..89d45b84c8 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-117.0.5911.0 +image: e-117.0.5921.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default
build
7686d1c379b59f8672b54b38c055ded43aa4880e
Shelley Vohr
2023-08-02 11:39:40
docs: correct `powerSaveBlocker.stop(id)` return type (#39320) doc: correct powerSaveBlocker.stop return type
diff --git a/docs/api/power-save-blocker.md b/docs/api/power-save-blocker.md index 257fc76f3d..1ba95f0aab 100644 --- a/docs/api/power-save-blocker.md +++ b/docs/api/power-save-blocker.md @@ -49,6 +49,8 @@ is used. Stops the specified power save blocker. +Returns `boolean` - Whether the specified `powerSaveBlocker` has been stopped. + ### `powerSaveBlocker.isStarted(id)` * `id` Integer - The power save blocker id returned by `powerSaveBlocker.start`. diff --git a/spec/ts-smoke/electron/main.ts b/spec/ts-smoke/electron/main.ts index 27ea0da6c3..a81377cbe1 100644 --- a/spec/ts-smoke/electron/main.ts +++ b/spec/ts-smoke/electron/main.ts @@ -904,7 +904,8 @@ app.whenReady().then(() => { const id = powerSaveBlocker.start('prevent-display-sleep'); console.log(powerSaveBlocker.isStarted(id)); -powerSaveBlocker.stop(id); +const stopped = powerSaveBlocker.stop(id); +console.log(`The powerSaveBlocker is ${stopped ? 'stopped' : 'not stopped'}`); // protocol // https://github.com/electron/electron/blob/main/docs/api/protocol.md
docs
e1762e6e44e898783065765048711b4f1f16743b
Charles Kerr
2025-01-21 11:59:38
fix: consume the file permission callback when used (#45267) fixes 0e5fe3f regression
diff --git a/shell/browser/file_system_access/file_system_access_permission_context.cc b/shell/browser/file_system_access/file_system_access_permission_context.cc index d4f6fe482d..9f4b436453 100644 --- a/shell/browser/file_system_access/file_system_access_permission_context.cc +++ b/shell/browser/file_system_access/file_system_access_permission_context.cc @@ -594,7 +594,7 @@ void FileSystemAccessPermissionContext::ConfirmSensitiveEntryAccess( content::GlobalRenderFrameHostId frame_id, base::OnceCallback<void(SensitiveEntryResult)> callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - callback_map_[path_info.path] = std::move(callback); + callback_map_.try_emplace(path_info.path, std::move(callback)); auto after_blocklist_check_callback = base::BindOnce( &FileSystemAccessPermissionContext::DidCheckPathAgainstBlocklist, @@ -640,8 +640,8 @@ void FileSystemAccessPermissionContext::PerformAfterWriteChecks( void FileSystemAccessPermissionContext::RunRestrictedPathCallback( const base::FilePath& file_path, SensitiveEntryResult result) { - if (base::Contains(callback_map_, file_path)) - std::move(callback_map_[file_path]).Run(result); + if (auto val = callback_map_.extract(file_path)) + std::move(val.mapped()).Run(result); } void FileSystemAccessPermissionContext::OnRestrictedPathResult(
fix
f42331f277dd671a31d7a645866c7a4a1af829c3
Piotr Płaczek
2024-08-06 17:07:36
docs: add missing deprecations to `breaking-changes.md` (#43217) * docs: deprecate `BrowserView` Reference: https://github.com/electron/electron/pull/35658 * docs: deprecate `webContents.goToIndex(index)` Reference: https://github.com/electron/electron/pull/41752/files#diff-18ed6a5b5a9084c976509502962b7f05989a8bd13a2ba3dc02868056938c03b6R1165-R1167 * docs: deprecate some protocol methods Reference: https://github.com/electron/electron/pull/36674/files#diff-74861ecada868821b139e79f244ea32b840a93f60de572d585117a0ff8d165c8R380
diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md index 454f8243fd..e5bfab625d 100644 --- a/docs/breaking-changes.md +++ b/docs/breaking-changes.md @@ -65,7 +65,7 @@ contextBridge.exposeInMainWorld('electron', { }) ``` -### Deprecated: `clearHistory`, `canGoBack`, `goBack`, `canGoForward`, `goForward`, `canGoToOffset`, `goToOffset` on `WebContents` +### Deprecated: `clearHistory`, `canGoBack`, `goBack`, `canGoForward`, `goForward`, `goToIndex`, `canGoToOffset`, `goToOffset` on `WebContents` The navigation-related APIs are now deprecated. @@ -78,6 +78,7 @@ win.webContents.canGoBack() win.webContents.goBack() win.webContents.canGoForward() win.webContents.goForward() +win.webContents.goToIndex(index) win.webContents.canGoToOffset() win.webContents.goToOffset(index) @@ -136,6 +137,24 @@ The autoresizing behavior is now standardized across all platforms. If your app uses `BrowserView.setAutoResize` to do anything more complex than making a BrowserView fill the entire window, it's likely you already had custom logic in place to handle this difference in behavior on macOS. If so, that logic will no longer be needed in Electron 30 as autoresizing behavior is consistent. +### Deprecated: `BrowserView` + +The [`BrowserView`](./api/browser-view.md) class has been deprecated and +replaced by the new [`WebContentsView`](./api/web-contents-view.md) class. + +`BrowserView` related methods in [`BrowserWindow`](./api/browser-window.md) have +also been deprecated: + +```js +BrowserWindow.fromBrowserView(browserView) +win.setBrowserView(browserView) +win.getBrowserView() +win.addBrowserView(browserView) +win.removeBrowserView(browserView) +win.setTopBrowserView(browserView) +win.getBrowserViews() +``` + ### Removed: `params.inputFormType` property on `context-menu` on `WebContents` The `inputFormType` property of the params object in the `context-menu` @@ -463,7 +482,7 @@ systemPreferences.getColor('selected-content-background') ## Planned Breaking API Changes (25.0) -### Deprecated: `protocol.{register,intercept}{Buffer,String,Stream,File,Http}Protocol` +### Deprecated: `protocol.{un,}{register,intercept}{Buffer,String,Stream,File,Http}Protocol` and `protocol.isProtocol{Registered,Intercepted}` The `protocol.register*Protocol` and `protocol.intercept*Protocol` methods have been replaced with [`protocol.handle`](api/protocol.md#protocolhandlescheme-handler).
docs
12b85a77a8e008f96dce09ef4fcdb8d796154751
Samuel Attard
2023-06-09 02:30:26
build: upload node checksums before validating them (#38710)
diff --git a/script/release/release.js b/script/release/release.js index efa9b0a073..b12da0f029 100755 --- a/script/release/release.js +++ b/script/release/release.js @@ -354,6 +354,7 @@ async function makeRelease (releaseToValidate) { await validateReleaseAssets(release, true); } else { let draftRelease = await getDraftRelease(); + uploadNodeShasums(); await createReleaseShasums(draftRelease); // Fetch latest version of release before verifying @@ -364,7 +365,6 @@ async function makeRelease (releaseToValidate) { // which fails to publish. It has to be done before the final // publish to ensure there aren't published releases not contained // in index.json, which causes other problems in downstream projects - uploadNodeShasums(); uploadIndexJson(); await publishRelease(draftRelease); console.log(`${pass} SUCCESS!!! Release has been published. Please run ` +
build
9fc94a162bed056daea0324ca878f33061484cb0
Shelley Vohr
2024-10-29 16:35:57
build: fix python util verbose mode logic (#44431) build: fix verbose mode logic
diff --git a/.github/actions/build-electron/action.yml b/.github/actions/build-electron/action.yml index 170dac8f97..3f384f6f3b 100644 --- a/.github/actions/build-electron/action.yml +++ b/.github/actions/build-electron/action.yml @@ -63,7 +63,7 @@ runs: run: | cd src electron/script/copy-debug-symbols.py --target-cpu="${{ inputs.target-arch }}" --out-dir=out/Default/debug --compress - electron/script/strip-binaries.py --target-cpu="${{ inputs.target-arch }}" + electron/script/strip-binaries.py --target-cpu="${{ inputs.target-arch }}" --verbose electron/script/add-debug-link.py --target-cpu="${{ inputs.target-arch }}" --debug-dir=out/Default/debug - name: Build Electron dist.zip ${{ inputs.step-suffix }} shell: bash diff --git a/script/lib/config.py b/script/lib/config.py index 131cd9b24c..bca8b616fe 100644 --- a/script/lib/config.py +++ b/script/lib/config.py @@ -28,16 +28,17 @@ def get_target_arch(): return 'x64' return arch - -def enable_verbose_mode(): +def set_verbose_mode(mode): print('Running in verbose mode') global verbose_mode - verbose_mode = True - + verbose_mode = mode def is_verbose_mode(): return verbose_mode +def verbose_mode_print(output): + if verbose_mode: + print(output) def get_zip_name(name, version, suffix=''): arch = get_target_arch() diff --git a/script/lib/util.py b/script/lib/util.py index eb03a856fd..bc70cb2ed1 100644 --- a/script/lib/util.py +++ b/script/lib/util.py @@ -11,9 +11,7 @@ import sys from urllib.request import urlopen import zipfile -# from lib.config import is_verbose_mode -def is_verbose_mode(): - return False +from lib.config import verbose_mode_print ELECTRON_DIR = os.path.abspath( os.path.dirname(os.path.dirname(os.path.dirname(__file__))) @@ -112,13 +110,11 @@ def safe_mkdir(path): def execute(argv, env=None, cwd=None): if env is None: env = os.environ - if is_verbose_mode(): - print(' '.join(argv)) + verbose_mode_print(' '.join(argv)) try: output = subprocess.check_output(argv, stderr=subprocess.STDOUT, env=env, cwd=cwd) - if is_verbose_mode(): - print(output) + verbose_mode_print(output.decode('utf-8').strip()) return output except subprocess.CalledProcessError as e: print(e.output) diff --git a/script/release/uploaders/upload.py b/script/release/uploaders/upload.py index c65d01ff0b..c5fa934b01 100755 --- a/script/release/uploaders/upload.py +++ b/script/release/uploaders/upload.py @@ -16,8 +16,9 @@ sys.path.append( from zipfile import ZipFile from lib.config import PLATFORM, get_target_arch, \ - get_zip_name, enable_verbose_mode, \ - is_verbose_mode, get_platform_key + get_zip_name, set_verbose_mode, \ + is_verbose_mode, get_platform_key, \ + verbose_mode_print from lib.util import get_electron_branding, execute, get_electron_version, \ store_artifact, get_electron_exec, get_out_dir, \ SRC_DIR, ELECTRON_DIR, TS_NODE @@ -45,8 +46,7 @@ CXX_OBJECTS_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, def main(): args = parse_args() - if args.verbose: - enable_verbose_mode() + set_verbose_mode(args.verbose) if args.upload_to_storage: utcnow = datetime.datetime.utcnow() args.upload_timestamp = utcnow.strftime('%Y%m%d') @@ -391,9 +391,8 @@ def get_release(version): release_env = os.environ.copy() release_env['NODE_NO_WARNINGS'] = '1' release_info = execute([TS_NODE, script_path, version], release_env) - if is_verbose_mode(): - print(f'Release info for version: {version}:\n') - print(release_info) + verbose_mode_print(f'Release info for version: {version}:\n') + verbose_mode_print(release_info) release = json.loads(release_info) return release diff --git a/script/strip-binaries.py b/script/strip-binaries.py index e21fdeb6a6..61fd543862 100755 --- a/script/strip-binaries.py +++ b/script/strip-binaries.py @@ -4,11 +4,26 @@ import argparse import os import sys -from lib.config import enable_verbose_mode +from lib.config import set_verbose_mode, is_verbose_mode, verbose_mode_print from lib.util import execute, get_linux_binaries, get_out_dir +def get_size(path): + size = os.path.getsize(path) + units = ["bytes", "KB", "MB", "GB"] + for unit in units: + if size < 1024: + return f"{size:.2f} {unit}" + size /= 1024 + raise ValueError("File size is too large to be processed") + def strip_binaries(directory, target_cpu): + if not os.path.isdir(directory): + verbose_mode_print('Directory ' + directory + ' does not exist.') + return + + verbose_mode_print('Stripping binaries in ' + directory) for binary in get_linux_binaries(): + verbose_mode_print('\nStripping ' + binary) binary_path = os.path.join(directory, binary) if os.path.isfile(binary_path): strip_binary(binary_path, target_cpu) @@ -20,14 +35,23 @@ def strip_binary(binary_path, target_cpu): strip = 'aarch64-linux-gnu-strip' else: strip = 'strip' - execute([ - strip, '--discard-all', '--strip-debug', '--preserve-dates', - binary_path]) + + strip_args = [strip, + '--discard-all', + '--strip-debug', + '--preserve-dates', + binary_path] + if (is_verbose_mode()): + strip_args.insert(1, '--verbose') + verbose_mode_print('Binary size before stripping: ' + + str(get_size(binary_path))) + execute(strip_args) + verbose_mode_print('Binary size after stripping: ' + + str(get_size(binary_path))) def main(): args = parse_args() - if args.verbose: - enable_verbose_mode() + set_verbose_mode(args.verbose) if args.file: strip_binary(args.file, args.target_cpu) else: @@ -43,6 +67,7 @@ def parse_args(): help='Path to a specific file to strip.', required=False) parser.add_argument('-v', '--verbose', + default=False, action='store_true', help='Prints the output of the subprocesses') parser.add_argument('--target-cpu',
build
f07b040cb998a6126979cec9d562acbac5a23c4c
David Sanders
2023-05-24 01:19:47
build: update yarn.lock (#38422)
diff --git a/yarn.lock b/yarn.lock index eaa3c26fa1..3703a66584 100644 --- a/yarn.lock +++ b/yarn.lock @@ -613,10 +613,10 @@ deprecation "^2.0.0" once "^1.4.0" -"@octokit/[email protected]", "@octokit/request@^5.4.14", "@octokit/request@^5.6.0", "@octokit/request@^5.6.3", "@octokit/request@^6.0.0": - version "6.2.3" - resolved "https://registry.yarnpkg.com/@octokit/request/-/request-6.2.3.tgz#76d5d6d44da5c8d406620a4c285d280ae310bdb4" - integrity sha512-TNAodj5yNzrrZ/VxP+H5HiYaZep0H3GU0O7PaF+fhDrt8FPrnkei9Aal/txsN/1P7V3CPiThG0tIvpPDYUsyAA== +"@octokit/[email protected]", "@octokit/request@^5.4.14", "@octokit/request@^5.6.0", "@octokit/request@^5.6.3", "@octokit/request@^6.0.0": + version "6.2.4" + resolved "https://registry.yarnpkg.com/@octokit/request/-/request-6.2.4.tgz#b00a7185865c72bdd432e63168b1e900953ded0c" + integrity sha512-at92SYQstwh7HH6+Kf3bFMnHrle7aIrC0r5rTP+Bb30118B6j1vI2/M4walh6qcQgfuLIKs8NUO5CytHTnUI3A== dependencies: "@octokit/endpoint" "^7.0.0" "@octokit/request-error" "^3.0.0" @@ -1363,11 +1363,6 @@ resolved "https://registry.yarnpkg.com/@xtuc/long/-/long-4.2.2.tgz#d291c6a4e97989b5c61d9acf396ae4fe133a718d" integrity sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ== -"@yarnpkg/lockfile@^1.1.0": - version "1.1.0" - resolved "https://registry.yarnpkg.com/@yarnpkg/lockfile/-/lockfile-1.1.0.tgz#e77a97fbd345b76d83245edcd17d393b1b41fb31" - integrity sha512-GpSwvyXOcOOlV70vbnzjj4fW5xW/FdUF6nQEt1ENy7m4ZCczi1+/buVUPAqmGfqznsORNFzUMjctTIp8a9tuCQ== - accepts@~1.3.8: version "1.3.8" resolved "https://registry.yarnpkg.com/accepts/-/accepts-1.3.8.tgz#0bf0be125b67014adcb0b0921e62db7bffe16b2e" @@ -1836,14 +1831,6 @@ chalk@^4.0.0: ansi-styles "^4.1.0" supports-color "^7.1.0" -chalk@^4.1.2: - version "4.1.2" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01" - integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA== - dependencies: - ansi-styles "^4.1.0" - supports-color "^7.1.0" - character-entities-legacy@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/character-entities-legacy/-/character-entities-legacy-2.0.0.tgz#57f4d00974c696e8f74e9f493e7fcb75b44d7ee7" @@ -1906,11 +1893,6 @@ chromium-pickle-js@^0.2.0: resolved "https://registry.yarnpkg.com/chromium-pickle-js/-/chromium-pickle-js-0.2.0.tgz#04a106672c18b085ab774d983dfa3ea138f22205" integrity sha1-BKEGZywYsIWrd02YPfo+oTjyIgU= -ci-info@^3.7.0: - version "3.8.0" - resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-3.8.0.tgz#81408265a5380c929f0bc665d62256628ce9ef91" - integrity sha512-eXTggHWSooYhq49F2opQhuHWgzucfF2YgODK4e1566GQs5BIfP30B0oenwBJHfWxAs2fyPB1s7Mg949zLf61Yw== - clean-stack@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/clean-stack/-/clean-stack-2.2.0.tgz#ee8472dbb129e727b31e8a10a427dee9dfe4008b" @@ -3132,13 +3114,6 @@ find-up@^5.0.0: locate-path "^6.0.0" path-exists "^4.0.0" -find-yarn-workspace-root@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/find-yarn-workspace-root/-/find-yarn-workspace-root-2.0.0.tgz#f47fb8d239c900eb78179aa81b66673eac88f7bd" - integrity sha512-1IMnbjt4KzsQfnhnzNd8wUEgXZ44IzZaZmnLYx7D5FZlaHt2gW20Cri8Q+E/t5tIj4+epTBub+2Zxu/vNILzqQ== - dependencies: - micromatch "^4.0.2" - flat-cache@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-2.0.1.tgz#5d296d6f04bda44a4630a301413bdbc2ec085ec0" @@ -3242,16 +3217,6 @@ fs-extra@^8.1.0: jsonfile "^4.0.0" universalify "^0.1.0" -fs-extra@^9.0.0: - version "9.1.0" - resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-9.1.0.tgz#5954460c764a8da2094ba3554bf839e6b9a7c86d" - integrity sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ== - dependencies: - at-least-node "^1.0.0" - graceful-fs "^4.2.0" - jsonfile "^6.0.1" - universalify "^2.0.0" - fs-extra@^9.0.1: version "9.0.1" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-9.0.1.tgz#910da0062437ba4c39fedd863f1675ccfefcb9fc" @@ -3477,11 +3442,6 @@ got@^11.8.5: p-cancelable "^2.0.0" responselike "^2.0.0" -graceful-fs@^4.1.11: - version "4.2.11" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.11.tgz#4183e4e8bf08bb6e05bbb2f7d2e0c8f712ca40e3" - integrity sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ== - graceful-fs@^4.1.15, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.1.9, graceful-fs@^4.2.0, graceful-fs@^4.2.4, graceful-fs@^4.2.9: version "4.2.10" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.10.tgz#147d3a006da4ca3ce14728c7aefc287c367d7a6c" @@ -3820,11 +3780,6 @@ is-decimal@^2.0.0: resolved "https://registry.yarnpkg.com/is-decimal/-/is-decimal-2.0.0.tgz#db1140337809fd043a056ae40a9bd1cdc563034c" integrity sha512-QfrfjQV0LjoWQ1K1XSoEZkTAzSa14RKVMa5zg3SdAfzEmQzRM4+tbSFWb78creCeA9rNBzaZal92opi1TwPWZw== -is-docker@^2.0.0: - version "2.2.1" - resolved "https://registry.yarnpkg.com/is-docker/-/is-docker-2.2.1.tgz#33eeabe23cfe86f14bde4408a02c0cfb853acdaa" - integrity sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ== - is-empty@^1.0.0: version "1.2.0" resolved "https://registry.yarnpkg.com/is-empty/-/is-empty-1.2.0.tgz#de9bb5b278738a05a0b09a57e1fb4d4a341a9f6b" @@ -4001,13 +3956,6 @@ is-weakref@^1.0.2: dependencies: call-bind "^1.0.2" -is-wsl@^2.1.1: - version "2.2.0" - resolved "https://registry.yarnpkg.com/is-wsl/-/is-wsl-2.2.0.tgz#74a4c76e77ca9fd3f932f290c17ea326cd157271" - integrity sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww== - dependencies: - is-docker "^2.0.0" - isarray@^1.0.0, isarray@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" @@ -4168,13 +4116,6 @@ kind-of@^6.0.2: resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== -klaw-sync@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/klaw-sync/-/klaw-sync-6.0.0.tgz#1fd2cfd56ebb6250181114f0a581167099c2b28c" - integrity sha512-nIeuVSzdCCs6TDPTqI8w1Yre34sSq7AkZ4B3sfOBbI2CgVSB4Du4aLQijFU2+lhAFCwt9+42Hel6lQNIv6AntQ== - dependencies: - graceful-fs "^4.1.11" - klaw@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/klaw/-/klaw-3.0.0.tgz#b11bec9cf2492f06756d6e809ab73a2910259146" @@ -5110,14 +5051,6 @@ onetime@^5.1.0: dependencies: mimic-fn "^2.1.0" -open@^7.4.2: - version "7.4.2" - resolved "https://registry.yarnpkg.com/open/-/open-7.4.2.tgz#b8147e26dcf3e426316c730089fd71edd29c2321" - integrity sha512-MVHddDVweXZF3awtlAS+6pgKLlm/JgxZ90+/NBurBoQctVOOB/zDdVjcyPzQ+0laDGbsWgrRkflI65sQeOgT9Q== - dependencies: - is-docker "^2.0.0" - is-wsl "^2.1.1" - optionator@^0.9.1: version "0.9.1" resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.9.1.tgz#4f236a6373dae0566a6d43e1326674f50c291499" @@ -5156,7 +5089,7 @@ ora@^4.0.3: strip-ansi "^6.0.0" wcwidth "^1.0.1" -os-tmpdir@^1.0.0, os-tmpdir@~1.0.2: +os-tmpdir@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" integrity sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ= @@ -5301,26 +5234,6 @@ parseurl@~1.3.3: resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4" integrity sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ== -patch-package@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/patch-package/-/patch-package-7.0.0.tgz#5c646b6b4b4bf37e5184a6950777b21dea6bb66e" - integrity sha512-eYunHbnnB2ghjTNc5iL1Uo7TsGMuXk0vibX3RFcE/CdVdXzmdbMsG/4K4IgoSuIkLTI5oHrMQk4+NkFqSed0BQ== - dependencies: - "@yarnpkg/lockfile" "^1.1.0" - chalk "^4.1.2" - ci-info "^3.7.0" - cross-spawn "^7.0.3" - find-yarn-workspace-root "^2.0.0" - fs-extra "^9.0.0" - klaw-sync "^6.0.0" - minimist "^1.2.6" - open "^7.4.2" - rimraf "^2.6.3" - semver "^5.6.0" - slash "^2.0.0" - tmp "^0.0.33" - yaml "^2.2.2" - path-exists@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-3.0.0.tgz#ce0ebeaa5f78cb18925ea7d810d7b59b010fd515" @@ -6296,13 +6209,6 @@ [email protected]: dependencies: glob "^7.1.3" -rimraf@^2.6.3: - version "2.7.1" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec" - integrity sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w== - dependencies: - glob "^7.1.3" - rimraf@^3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-3.0.2.tgz#f1a5402ba6220ad52cc1282bac1ae3aa49fd061a" @@ -6555,11 +6461,6 @@ simple-git@^3.5.0: "@kwsites/promise-deferred" "^1.1.1" debug "^4.3.4" -slash@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/slash/-/slash-2.0.0.tgz#de552851a1759df3a8f206535442f5ec4ddeab44" - integrity sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A== - slash@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" @@ -7004,13 +6905,6 @@ [email protected]: dependencies: process "~0.11.0" -tmp@^0.0.33: - version "0.0.33" - resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9" - integrity sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw== - dependencies: - os-tmpdir "~1.0.2" - to-regex-range@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" @@ -7750,11 +7644,6 @@ yaml@^1.7.2: resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.10.0.tgz#3b593add944876077d4d683fee01081bd9fff31e" integrity sha512-yr2icI4glYaNG+KWONODapy2/jDdMSDnrONSjblABjD9B4Z5LgiircSt8m8sRZFNi08kG9Sm0uSHtEmP3zaEGg== -yaml@^2.2.2: - version "2.2.2" - resolved "https://registry.yarnpkg.com/yaml/-/yaml-2.2.2.tgz#ec551ef37326e6d42872dad1970300f8eb83a073" - integrity sha512-CBKFWExMn46Foo4cldiChEzn7S7SRV+wqiluAb6xmueD/fGyRHIhX8m14vVGgeFWjN540nKCNVj6P21eQjgTuA== - yauzl@^2.10.0: version "2.10.0" resolved "https://registry.yarnpkg.com/yauzl/-/yauzl-2.10.0.tgz#c7eb17c93e112cb1086fa6d8e51fb0667b79a5f9"
build
7d05fb2a1b236e8ed67ee0b47a852b447ddcee1b
Shelley Vohr
2025-01-20 10:23:44
fix: broken OOP `window.print()` on macOS/Linux (#45214) fix: broken OOP printing on macOS/Linux
diff --git a/shell/utility/electron_content_utility_client.cc b/shell/utility/electron_content_utility_client.cc index 5c5226cfea..45baca4f0b 100644 --- a/shell/utility/electron_content_utility_client.cc +++ b/shell/utility/electron_content_utility_client.cc @@ -31,6 +31,11 @@ #include "components/services/print_compositor/public/mojom/print_compositor.mojom.h" // nogncheck #endif // BUILDFLAG(ENABLE_PRINTING) +#if BUILDFLAG(ENABLE_OOP_PRINTING) +#include "chrome/services/printing/print_backend_service_impl.h" +#include "chrome/services/printing/public/mojom/print_backend_service.mojom.h" +#endif // BUILDFLAG(ENABLE_OOP_PRINTING) + #if BUILDFLAG(ENABLE_PRINTING) && BUILDFLAG(IS_WIN) #include "chrome/services/printing/pdf_to_emf_converter_factory.h" #endif @@ -72,6 +77,21 @@ auto RunPrintCompositor( } #endif +#if BUILDFLAG(ENABLE_OOP_PRINTING) +auto RunPrintingSandboxedPrintBackendHost( + mojo::PendingReceiver<printing::mojom::SandboxedPrintBackendHost> + receiver) { + return std::make_unique<printing::SandboxedPrintBackendHostImpl>( + std::move(receiver)); +} +auto RunPrintingUnsandboxedPrintBackendHost( + mojo::PendingReceiver<printing::mojom::UnsandboxedPrintBackendHost> + receiver) { + return std::make_unique<printing::UnsandboxedPrintBackendHostImpl>( + std::move(receiver)); +} +#endif // BUILDFLAG(ENABLE_OOP_PRINTING) + auto RunProxyResolver( mojo::PendingReceiver<proxy_resolver::mojom::ProxyResolverFactory> receiver) { @@ -122,6 +142,11 @@ void ElectronContentUtilityClient::RegisterMainThreadServices( services.Add(RunPrintCompositor); #endif +#if BUILDFLAG(ENABLE_OOP_PRINTING) + services.Add(RunPrintingSandboxedPrintBackendHost); + services.Add(RunPrintingUnsandboxedPrintBackendHost); +#endif + #if BUILDFLAG(ENABLE_PRINT_PREVIEW) || \ (BUILDFLAG(ENABLE_PRINTING) && BUILDFLAG(IS_WIN)) services.Add(RunPrintingService);
fix
2b259bd69e97f87b83a47b606896a24cb80776d4
Samuel Attard
2024-06-17 02:26:18
build: de-dupe load build tools into composite action (#42518)
diff --git a/.github/actions/install-build-tools/action.yml b/.github/actions/install-build-tools/action.yml new file mode 100644 index 0000000000..bc7a6630b2 --- /dev/null +++ b/.github/actions/install-build-tools/action.yml @@ -0,0 +1,11 @@ +name: 'Install Build Tools' +description: 'Installs an exact SHA of build tools' +runs: + using: "composite" + steps: + - name: Install Build Tools + shell: bash + run: | + export BUILD_TOOLS_SHA=ff3e40a9a2ebb735c18b6450ecd5ddaa8bb364a9 + npm i -g @electron/build-tools + e auto-update disable diff --git a/.github/workflows/pipeline-segment-electron-build.yml b/.github/workflows/pipeline-segment-electron-build.yml index 0eccd0bb64..c8ab252849 100644 --- a/.github/workflows/pipeline-segment-electron-build.yml +++ b/.github/workflows/pipeline-segment-electron-build.yml @@ -140,11 +140,10 @@ jobs: with: path: src/electron fetch-depth: 0 - - name: Load Build Tools + - name: Install Build Tools + uses: ./src/electron/.github/actions/install-build-tools + - name: Init Build Tools run: | - export BUILD_TOOLS_SHA=ff3e40a9a2ebb735c18b6450ecd5ddaa8bb364a9 - npm i -g @electron/build-tools - e auto-update disable e init -f --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} --import ${{ inputs.gn-build-type }} --target-cpu ${{ inputs.target-arch }} --only-sdk - name: Run Electron Only Hooks run: | diff --git a/.github/workflows/pipeline-segment-electron-gn-check.yml b/.github/workflows/pipeline-segment-electron-gn-check.yml index 66ba1af47d..1264a31f53 100644 --- a/.github/workflows/pipeline-segment-electron-gn-check.yml +++ b/.github/workflows/pipeline-segment-electron-gn-check.yml @@ -50,17 +50,16 @@ jobs: BUILD_TYPE: ${{ matrix.build-type }} TARGET_ARCH: ${{ inputs.target-arch }} steps: - - name: Load Build Tools - run: | - export BUILD_TOOLS_SHA=ff3e40a9a2ebb735c18b6450ecd5ddaa8bb364a9 - npm i -g @electron/build-tools - e auto-update disable - e init -f --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} --import ${{ inputs.gn-build-type }} --target-cpu ${{ inputs.target-arch }} --only-sdk - name: Checkout Electron uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 with: path: src/electron fetch-depth: 0 + - name: Install Build Tools + uses: ./src/electron/.github/actions/install-build-tools + - name: Init Build Tools + run: | + e init -f --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} --import ${{ inputs.gn-build-type }} --target-cpu ${{ inputs.target-arch }} --only-sdk - name: Get Depot Tools timeout-minutes: 5 run: | diff --git a/.github/workflows/pipeline-segment-node-nan-test.yml b/.github/workflows/pipeline-segment-node-nan-test.yml index 8caa15842f..5f0bb5a474 100644 --- a/.github/workflows/pipeline-segment-node-nan-test.yml +++ b/.github/workflows/pipeline-segment-node-nan-test.yml @@ -44,17 +44,16 @@ jobs: BUILD_TYPE: linux container: ${{ fromJSON(inputs.test-container) }} steps: - - name: Load Build Tools - run: | - export BUILD_TOOLS_SHA=ff3e40a9a2ebb735c18b6450ecd5ddaa8bb364a9 - npm i -g @electron/build-tools - e auto-update disable - e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} --import ${{ inputs.gn-build-type }} --target-cpu ${{ inputs.target-arch }} - name: Checkout Electron uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 with: path: src/electron fetch-depth: 0 + - name: Install Build Tools + uses: ./src/electron/.github/actions/install-build-tools + - name: Init Build Tools + run: | + e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} --import ${{ inputs.gn-build-type }} --target-cpu ${{ inputs.target-arch }} - name: Install Dependencies run: | cd src/electron @@ -109,17 +108,16 @@ jobs: BUILD_TYPE: linux container: ${{ fromJSON(inputs.test-container) }} steps: - - name: Load Build Tools - run: | - export BUILD_TOOLS_SHA=ff3e40a9a2ebb735c18b6450ecd5ddaa8bb364a9 - npm i -g @electron/build-tools - e auto-update disable - e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} - name: Checkout Electron uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 with: path: src/electron fetch-depth: 0 + - name: Install Build Tools + uses: ./src/electron/.github/actions/install-build-tools + - name: Init Build Tools + run: | + e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} - name: Install Dependencies run: | cd src/electron
build
660872c048b6c040cb740560125eebc71114e31a
Charles Kerr
2024-07-25 13:18:13
refactor: move safe_storage functions into anonymous namespace (#43032)
diff --git a/filenames.gni b/filenames.gni index 5c7ca21fa0..97b348cd7b 100644 --- a/filenames.gni +++ b/filenames.gni @@ -290,7 +290,6 @@ filenames = { "shell/browser/api/electron_api_push_notifications.cc", "shell/browser/api/electron_api_push_notifications.h", "shell/browser/api/electron_api_safe_storage.cc", - "shell/browser/api/electron_api_safe_storage.h", "shell/browser/api/electron_api_screen.cc", "shell/browser/api/electron_api_screen.h", "shell/browser/api/electron_api_service_worker_context.cc", diff --git a/shell/browser/api/electron_api_safe_storage.cc b/shell/browser/api/electron_api_safe_storage.cc index b1704754d1..a8c63ec718 100644 --- a/shell/browser/api/electron_api_safe_storage.cc +++ b/shell/browser/api/electron_api_safe_storage.cc @@ -2,8 +2,6 @@ // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. -#include "shell/browser/api/electron_api_safe_storage.h" - #include <string> #include "components/os_crypt/sync/os_crypt.h" @@ -14,18 +12,18 @@ #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" -namespace electron::safestorage { +namespace { -static const char* kEncryptionVersionPrefixV10 = "v10"; -static const char* kEncryptionVersionPrefixV11 = "v11"; -static bool use_password_v10 = false; +const char* kEncryptionVersionPrefixV10 = "v10"; +const char* kEncryptionVersionPrefixV11 = "v11"; +bool use_password_v10 = false; bool IsEncryptionAvailable() { #if BUILDFLAG(IS_LINUX) // Calling IsEncryptionAvailable() before the app is ready results in a crash // on Linux. // Refs: https://github.com/electron/electron/issues/32206. - if (!Browser::Get()->is_ready()) + if (!electron::Browser::Get()->is_ready()) return false; return OSCrypt::IsEncryptionAvailable() || (use_password_v10 && @@ -42,7 +40,7 @@ void SetUsePasswordV10(bool use) { #if BUILDFLAG(IS_LINUX) std::string GetSelectedLinuxBackend() { - if (!Browser::Get()->is_ready()) + if (!electron::Browser::Get()->is_ready()) return "unknown"; return static_cast<BrowserProcessImpl*>(g_browser_process) ->linux_storage_backend(); @@ -52,7 +50,7 @@ std::string GetSelectedLinuxBackend() { v8::Local<v8::Value> EncryptString(v8::Isolate* isolate, const std::string& plaintext) { if (!IsEncryptionAvailable()) { - if (!Browser::Get()->is_ready()) { + if (!electron::Browser::Get()->is_ready()) { gin_helper::ErrorThrower(isolate).ThrowError( "safeStorage cannot be used before app is ready"); return v8::Local<v8::Value>(); @@ -80,7 +78,7 @@ v8::Local<v8::Value> EncryptString(v8::Isolate* isolate, std::string DecryptString(v8::Isolate* isolate, v8::Local<v8::Value> buffer) { if (!IsEncryptionAvailable()) { - if (!Browser::Get()->is_ready()) { + if (!electron::Browser::Get()->is_ready()) { gin_helper::ErrorThrower(isolate).ThrowError( "safeStorage cannot be used before app is ready"); return ""; @@ -127,7 +125,7 @@ std::string DecryptString(v8::Isolate* isolate, v8::Local<v8::Value> buffer) { return plaintext; } -} // namespace electron::safestorage +} // namespace void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, @@ -135,16 +133,13 @@ void Initialize(v8::Local<v8::Object> exports, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); - dict.SetMethod("isEncryptionAvailable", - &electron::safestorage::IsEncryptionAvailable); - dict.SetMethod("encryptString", &electron::safestorage::EncryptString); - dict.SetMethod("decryptString", &electron::safestorage::DecryptString); - dict.SetMethod("setUsePlainTextEncryption", - &electron::safestorage::SetUsePasswordV10); + dict.SetMethod("decryptString", &DecryptString); + dict.SetMethod("encryptString", &EncryptString); #if BUILDFLAG(IS_LINUX) - dict.SetMethod("getSelectedStorageBackend", - &electron::safestorage::GetSelectedLinuxBackend); + dict.SetMethod("getSelectedStorageBackend", &GetSelectedLinuxBackend); #endif + dict.SetMethod("isEncryptionAvailable", &IsEncryptionAvailable); + dict.SetMethod("setUsePlainTextEncryption", &SetUsePasswordV10); } NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_safe_storage, Initialize) diff --git a/shell/browser/api/electron_api_safe_storage.h b/shell/browser/api/electron_api_safe_storage.h deleted file mode 100644 index 1ecde80f8c..0000000000 --- a/shell/browser/api/electron_api_safe_storage.h +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2021 Slack Technologies, Inc. -// Use of this source code is governed by the MIT license that can be -// found in the LICENSE file. - -#ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SAFE_STORAGE_H_ -#define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SAFE_STORAGE_H_ - -#include "base/dcheck_is_on.h" - -namespace electron::safestorage { - -// Used in a DCHECK to validate that our assumption that the network context -// manager has initialized before app ready holds true. Only used in the -// testing build -#if DCHECK_IS_ON() -void SetElectronCryptoReady(bool ready); -#endif - -} // namespace electron::safestorage - -#endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SAFE_STORAGE_H_
refactor
e64a66bfd31dce94b2754579678a49f97c349129
CezaryKulakowski
2024-09-24 15:28:36
fix: detach native view when its removed from parent on macOS (#43627) Right now DelayedNativeViewHost attaches its underlying native view when it's being attached to a widget but it doesn't detach it when it's being detached. It may lead to use-after-free and crash.
diff --git a/shell/browser/ui/cocoa/delayed_native_view_host.mm b/shell/browser/ui/cocoa/delayed_native_view_host.mm index 6d594e9647..78a5668a4d 100644 --- a/shell/browser/ui/cocoa/delayed_native_view_host.mm +++ b/shell/browser/ui/cocoa/delayed_native_view_host.mm @@ -15,6 +15,8 @@ DelayedNativeViewHost::~DelayedNativeViewHost() = default; void DelayedNativeViewHost::ViewHierarchyChanged( const views::ViewHierarchyChangedDetails& details) { + if (!details.is_add && native_view()) + Detach(); NativeViewHost::ViewHierarchyChanged(details); if (details.is_add && GetWidget() && !native_view()) Attach(native_view_);
fix
00da7279cb4e4bef2ba2d6ba7f0f0afb32ea2650
David Sanders
2024-03-21 06:43:40
ci: set issue status to triaged on status/{confirmed,reviewed} label (#41645)
diff --git a/.github/workflows/issue-labeled.yml b/.github/workflows/issue-labeled.yml index e92b46739c..dd5ad668c2 100644 --- a/.github/workflows/issue-labeled.yml +++ b/.github/workflows/issue-labeled.yml @@ -8,6 +8,24 @@ permissions: # added using https://github.com/step-security/secure-workflows contents: read jobs: + issue-labeled-with-status: + name: status/{confirmed,reviewed} label added + if: github.event.label.name == 'status/confirmed' || github.event.label.name == 'status/reviewed' + runs-on: ubuntu-latest + steps: + - name: Generate GitHub App token + uses: electron/github-app-auth-action@384fd19694fe7b6dcc9a684746c6976ad78228ae # v1.1.1 + id: generate-token + with: + creds: ${{ secrets.ISSUE_TRIAGE_GH_APP_CREDS }} + org: electron + - name: Set status + uses: dsanders11/project-actions/edit-item@82e99438bd44a14ad18d92d036dbc25cbfb9a8c4 # v1.2.0 + with: + token: ${{ steps.generate-token.outputs.token }} + project-number: 90 + field: Status + field-value: ✅ Triaged issue-labeled-blocked: name: blocked/* label added if: startsWith(github.event.label.name, 'blocked/')
ci
ec9c8476fe2c789d8d3bfe94eee6ab88dceeede2
Shelley Vohr
2023-09-12 11:28:45
fix: `keyCode`s being incorrectly converted in `webContents.sendInputEvent()` (#39776) fix: sendInputEvent keyCodes being incorrectly converted
diff --git a/shell/common/gin_converters/blink_converter.cc b/shell/common/gin_converters/blink_converter.cc index 0c42a4ae01..92cd9fa504 100644 --- a/shell/common/gin_converters/blink_converter.cc +++ b/shell/common/gin_converters/blink_converter.cc @@ -10,6 +10,7 @@ #include "base/containers/fixed_flat_map.h" #include "base/strings/string_util.h" +#include "base/strings/utf_string_conversion_utils.h" #include "base/strings/utf_string_conversions.h" #include "gin/converter.h" #include "gin/data_object_builder.h" @@ -275,11 +276,18 @@ bool Converter<blink::WebKeyboardEvent>::FromV8(v8::Isolate* isolate, if ((out->GetType() == blink::WebInputEvent::Type::kChar || out->GetType() == blink::WebInputEvent::Type::kRawKeyDown)) { + // If the keyCode is e.g. Space or Plus we want to use the character + // instead of the keyCode: ' ' instead of 'Space', '+' instead of 'Plus'. + std::string character_str; + if (str.size() > 1 && domKey.IsCharacter()) + base::WriteUnicodeCharacter(domKey.ToCharacter(), &character_str); + // Make sure to not read beyond the buffer in case some bad code doesn't // NULL-terminate it (this is called from plugins). size_t text_length_cap = blink::WebKeyboardEvent::kTextLengthCap; - std::u16string text16 = base::UTF8ToUTF16(str); - + std::u16string text16 = character_str.empty() + ? base::UTF8ToUTF16(str) + : base::UTF8ToUTF16(character_str); std::fill_n(out->text, text_length_cap, 0); std::fill_n(out->unmodified_text, text_length_cap, 0); for (size_t i = 0; i < std::min(text_length_cap - 1, text16.size()); ++i) { diff --git a/spec/api-web-contents-spec.ts b/spec/api-web-contents-spec.ts index 63cdf3729b..8f8fc04397 100644 --- a/spec/api-web-contents-spec.ts +++ b/spec/api-web-contents-spec.ts @@ -839,6 +839,20 @@ describe('webContents module', () => { expect(altKey).to.be.false(); }); + it('can correctly convert accelerators to key codes', async () => { + const keyup = once(ipcMain, 'keyup'); + w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' }); + w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' }); + w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' }); + w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' }); + w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' }); + w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'keyUp' }); + + await keyup; + const inputText = await w.webContents.executeJavaScript('document.getElementById("input").value'); + expect(inputText).to.equal('+ + +'); + }); + it('can send char events with modifiers', async () => { const keypress = once(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' }); diff --git a/spec/fixtures/pages/key-events.html b/spec/fixtures/pages/key-events.html index 7402daf5e9..c16c98bac2 100644 --- a/spec/fixtures/pages/key-events.html +++ b/spec/fixtures/pages/key-events.html @@ -1,11 +1,17 @@ <html> <body> +<input type="text" id="input" autofocus/> <script type="text/javascript" charset="utf-8"> +const { ipcRenderer } = require('electron') + document.onkeydown = function (e) { - require('electron').ipcRenderer.send('keydown', e.key, e.code, e.keyCode, e.shiftKey, e.ctrlKey, e.altKey) + ipcRenderer.send('keydown', e.key, e.code, e.keyCode, e.shiftKey, e.ctrlKey, e.altKey) } document.onkeypress = function (e) { - require('electron').ipcRenderer.send('keypress', e.key, e.code, e.keyCode, e.shiftKey, e.ctrlKey, e.altKey) + ipcRenderer.send('keypress', e.key, e.code, e.keyCode, e.shiftKey, e.ctrlKey, e.altKey) +} +document.onkeyup = function (e) { + ipcRenderer.send('keyup', e.key, e.code, e.keyCode, e.shiftKey, e.ctrlKey, e.altKey) } </script> </body>
fix
5d6023ae0dfa289b8ce1427722b0a8c0ab24e648
David Sanders
2023-10-13 03:00:44
docs: fix some string union typings (#40180)
diff --git a/docs/api/app.md b/docs/api/app.md index 05bb19fef2..40f2422a92 100755 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -1134,11 +1134,11 @@ indicates success while any other value indicates failure according to Chromium resolver will attempt to use the system's DNS settings to do DNS lookups itself. Enabled by default on macOS, disabled by default on Windows and Linux. - * `secureDnsMode` string (optional) - Can be "off", "automatic" or "secure". - Configures the DNS-over-HTTP mode. When "off", no DoH lookups will be - performed. When "automatic", DoH lookups will be performed first if DoH is + * `secureDnsMode` string (optional) - Can be 'off', 'automatic' or 'secure'. + Configures the DNS-over-HTTP mode. When 'off', no DoH lookups will be + performed. When 'automatic', DoH lookups will be performed first if DoH is available, and insecure DNS lookups will be performed as a fallback. When - "secure", only DoH lookups will be performed. Defaults to "automatic". + 'secure', only DoH lookups will be performed. Defaults to 'automatic'. * `secureDnsServers` string[]&#32;(optional) - A list of DNS-over-HTTP server templates. See [RFC8484 § 3][] for details on the template format. Most servers support the POST method; the template for such servers is diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 1fdd7d47e4..d1d419f2ce 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -1211,7 +1211,7 @@ Returns `string` - The user agent for this web page. * `css` string * `options` Object (optional) - * `cssOrigin` string (optional) - Can be either 'user' or 'author'. Sets the [cascade origin](https://www.w3.org/TR/css3-cascade/#cascade-origin) of the inserted stylesheet. Default is 'author'. + * `cssOrigin` string (optional) - Can be 'user' or 'author'. Sets the [cascade origin](https://www.w3.org/TR/css3-cascade/#cascade-origin) of the inserted stylesheet. Default is 'author'. Returns `Promise<string>` - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via `contents.removeInsertedCSS(key)`. diff --git a/docs/api/web-frame.md b/docs/api/web-frame.md index db4ec1c31a..f2ec5aff2d 100644 --- a/docs/api/web-frame.md +++ b/docs/api/web-frame.md @@ -113,7 +113,7 @@ webFrame.setSpellCheckProvider('en-US', { * `css` string * `options` Object (optional) - * `cssOrigin` string (optional) - Can be either 'user' or 'author'. Sets the [cascade origin](https://www.w3.org/TR/css3-cascade/#cascade-origin) of the inserted stylesheet. Default is 'author'. + * `cssOrigin` string (optional) - Can be 'user' or 'author'. Sets the [cascade origin](https://www.w3.org/TR/css3-cascade/#cascade-origin) of the inserted stylesheet. Default is 'author'. Returns `string` - A key for the inserted CSS that can later be used to remove the CSS via `webFrame.removeInsertedCSS(key)`. diff --git a/spec/ts-smoke/electron/main.ts b/spec/ts-smoke/electron/main.ts index 6c770d35cf..319321f215 100644 --- a/spec/ts-smoke/electron/main.ts +++ b/spec/ts-smoke/electron/main.ts @@ -429,6 +429,11 @@ win2.once('ready-to-show', () => { app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) }); app.exit(0); +app.configureHostResolver({ secureDnsMode: 'off' }); + +// @ts-expect-error Invalid type value +app.configureHostResolver({ secureDnsMode: 'foo' }); + // @ts-expect-error Removed API console.log(app.runningUnderRosettaTranslation); @@ -1284,6 +1289,11 @@ win4.webContents.on('devtools-open-url', (event, url) => { console.log(url); }); +win4.webContents.insertCSS('body {}', { cssOrigin: 'user' }); + +// @ts-expect-error Invalid type value +win4.webContents.insertCSS('body {}', { cssOrigin: 'foo' }); + win4.loadURL('http://github.com'); // @ts-expect-error Removed API
docs
168726a0521dd53f160b216f7b84832b1368fff5
David Sanders
2023-01-10 03:16:39
fix: handle null/undefined options for fs.readdir (#34764)
diff --git a/lib/asar/fs-wrapper.ts b/lib/asar/fs-wrapper.ts index 61d55c9f02..2059dc447f 100644 --- a/lib/asar/fs-wrapper.ts +++ b/lib/asar/fs-wrapper.ts @@ -623,11 +623,11 @@ export const wrapFsWithAsar = (fs: Record<string, any>) => { }; const { readdir } = fs; - fs.readdir = function (pathArgument: string, options: { encoding?: string | null; withFileTypes?: boolean } = {}, callback?: Function) { + fs.readdir = function (pathArgument: string, options?: { encoding?: string | null; withFileTypes?: boolean } | null, callback?: Function) { const pathInfo = splitPath(pathArgument); if (typeof options === 'function') { callback = options; - options = {}; + options = undefined; } if (!pathInfo.isAsar) return readdir.apply(this, arguments); const { asarPath, filePath } = pathInfo; @@ -646,7 +646,7 @@ export const wrapFsWithAsar = (fs: Record<string, any>) => { return; } - if (options.withFileTypes) { + if (options?.withFileTypes) { const dirents = []; for (const file of files) { const childPath = path.join(filePath, file); diff --git a/spec/asar-spec.ts b/spec/asar-spec.ts index b96b65a4c0..d835011c69 100644 --- a/spec/asar-spec.ts +++ b/spec/asar-spec.ts @@ -965,6 +965,32 @@ describe('asar package', function () { const err = await new Promise<any>(resolve => fs.readdir(p, resolve)); expect(err.code).to.equal('ENOENT'); }); + + it('handles null for options', function (done) { + const p = path.join(asarDir, 'a.asar', 'dir1'); + fs.readdir(p, null, function (err, dirs) { + try { + expect(err).to.be.null(); + expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']); + done(); + } catch (e) { + done(e); + } + }); + }); + + it('handles undefined for options', function (done) { + const p = path.join(asarDir, 'a.asar', 'dir1'); + fs.readdir(p, undefined, function (err, dirs) { + try { + expect(err).to.be.null(); + expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']); + done(); + } catch (e) { + done(e); + } + }); + }); }); describe('fs.promises.readdir', function () {
fix
fd2861117e04a3c62bfab67a1b50cb9c3a55cd4d
Samuel Attard
2023-10-18 07:21:42
fix: correctly track receiver for methods called via ctx bridge (#39978) * fix: correctly track receiver for methods called via ctx bridge * spec: test for correct contextBridge passage --------- Co-authored-by: Shelley Vohr <[email protected]>
diff --git a/shell/renderer/api/electron_api_context_bridge.cc b/shell/renderer/api/electron_api_context_bridge.cc index 2a5e22728b..cb97fe2cce 100644 --- a/shell/renderer/api/electron_api_context_bridge.cc +++ b/shell/renderer/api/electron_api_context_bridge.cc @@ -44,6 +44,8 @@ namespace api { namespace context_bridge { const char kProxyFunctionPrivateKey[] = "electron_contextBridge_proxy_fn"; +const char kProxyFunctionReceiverPrivateKey[] = + "electron_contextBridge_proxy_fn_receiver"; const char kSupportsDynamicPropertiesPrivateKey[] = "electron_contextBridge_supportsDynamicProperties"; const char kOriginalFunctionPrivateKey[] = "electron_contextBridge_original_fn"; @@ -138,6 +140,7 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext( v8::Local<v8::Context> source_context, v8::Local<v8::Context> destination_context, v8::Local<v8::Value> value, + v8::Local<v8::Value> parent_value, context_bridge::ObjectCache* object_cache, bool support_dynamic_properties, int recursion_depth, @@ -199,6 +202,9 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext( v8::Object::New(destination_context->GetIsolate()); SetPrivate(destination_context, state, context_bridge::kProxyFunctionPrivateKey, func); + SetPrivate(destination_context, state, + context_bridge::kProxyFunctionReceiverPrivateKey, + parent_value); SetPrivate(destination_context, state, context_bridge::kSupportsDynamicPropertiesPrivateKey, gin::ConvertToV8(destination_context->GetIsolate(), @@ -246,10 +252,12 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext( v8::MaybeLocal<v8::Value> val; { v8::TryCatch try_catch(isolate); + v8::Local<v8::Context> source_context = + global_source_context.Get(isolate); val = PassValueToOtherContext( - global_source_context.Get(isolate), - global_destination_context.Get(isolate), result, &object_cache, - false, 0, BridgeErrorTarget::kDestination); + source_context, global_destination_context.Get(isolate), result, + source_context->Global(), &object_cache, false, 0, + BridgeErrorTarget::kDestination); if (try_catch.HasCaught()) { if (try_catch.Message().IsEmpty()) { proxied_promise->RejectWithErrorMessage( @@ -292,10 +300,12 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext( v8::MaybeLocal<v8::Value> val; { v8::TryCatch try_catch(isolate); + v8::Local<v8::Context> source_context = + global_source_context.Get(isolate); val = PassValueToOtherContext( - global_source_context.Get(isolate), - global_destination_context.Get(isolate), result, &object_cache, - false, 0, BridgeErrorTarget::kDestination); + source_context, global_destination_context.Get(isolate), result, + source_context->Global(), &object_cache, false, 0, + BridgeErrorTarget::kDestination); if (try_catch.HasCaught()) { if (try_catch.Message().IsEmpty()) { proxied_promise->RejectWithErrorMessage( @@ -362,7 +372,7 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext( for (size_t i = 0; i < length; i++) { auto value_for_array = PassValueToOtherContext( source_context, destination_context, - arr->Get(source_context, i).ToLocalChecked(), object_cache, + arr->Get(source_context, i).ToLocalChecked(), value, object_cache, support_dynamic_properties, recursion_depth + 1, error_target); if (value_for_array.IsEmpty()) return v8::MaybeLocal<v8::Value>(); @@ -442,8 +452,10 @@ void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info) { context_bridge::kSupportsDynamicPropertiesPrivateKey); v8::MaybeLocal<v8::Value> maybe_func = GetPrivate( calling_context, data, context_bridge::kProxyFunctionPrivateKey); + v8::MaybeLocal<v8::Value> maybe_recv = GetPrivate( + calling_context, data, context_bridge::kProxyFunctionReceiverPrivateKey); v8::Local<v8::Value> func_value; - if (sdp_value.IsEmpty() || maybe_func.IsEmpty() || + if (sdp_value.IsEmpty() || maybe_func.IsEmpty() || maybe_recv.IsEmpty() || !gin::ConvertFromV8(args.isolate(), sdp_value.ToLocalChecked(), &support_dynamic_properties) || !maybe_func.ToLocal(&func_value)) @@ -463,8 +475,9 @@ void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info) { for (auto value : original_args) { auto arg = PassValueToOtherContext( - calling_context, func_owning_context, value, &object_cache, - support_dynamic_properties, 0, BridgeErrorTarget::kSource); + calling_context, func_owning_context, value, + calling_context->Global(), &object_cache, support_dynamic_properties, + 0, BridgeErrorTarget::kSource); if (arg.IsEmpty()) return; proxied_args.push_back(arg.ToLocalChecked()); @@ -475,8 +488,9 @@ void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Value> error_message; { v8::TryCatch try_catch(args.isolate()); - maybe_return_value = func->Call(func_owning_context, func, - proxied_args.size(), proxied_args.data()); + maybe_return_value = + func->Call(func_owning_context, maybe_recv.ToLocalChecked(), + proxied_args.size(), proxied_args.data()); if (try_catch.HasCaught()) { did_error = true; v8::Local<v8::Value> exception = try_catch.Exception(); @@ -531,6 +545,7 @@ void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::TryCatch try_catch(args.isolate()); ret = PassValueToOtherContext(func_owning_context, calling_context, maybe_return_value.ToLocalChecked(), + func_owning_context->Global(), &object_cache, support_dynamic_properties, 0, BridgeErrorTarget::kDestination); if (try_catch.HasCaught()) { @@ -607,18 +622,18 @@ v8::MaybeLocal<v8::Object> CreateProxyForAPI( v8::Local<v8::Value> getter_proxy; v8::Local<v8::Value> setter_proxy; if (!getter.IsEmpty()) { - if (!PassValueToOtherContext(source_context, destination_context, - getter, object_cache, - support_dynamic_properties, 1, - error_target) + if (!PassValueToOtherContext( + source_context, destination_context, getter, + api.GetHandle(), object_cache, + support_dynamic_properties, 1, error_target) .ToLocal(&getter_proxy)) continue; } if (!setter.IsEmpty()) { - if (!PassValueToOtherContext(source_context, destination_context, - setter, object_cache, - support_dynamic_properties, 1, - error_target) + if (!PassValueToOtherContext( + source_context, destination_context, setter, + api.GetHandle(), object_cache, + support_dynamic_properties, 1, error_target) .ToLocal(&setter_proxy)) continue; } @@ -635,8 +650,9 @@ v8::MaybeLocal<v8::Object> CreateProxyForAPI( continue; auto passed_value = PassValueToOtherContext( - source_context, destination_context, value, object_cache, - support_dynamic_properties, recursion_depth + 1, error_target); + source_context, destination_context, value, api.GetHandle(), + object_cache, support_dynamic_properties, recursion_depth + 1, + error_target); if (passed_value.IsEmpty()) return v8::MaybeLocal<v8::Object>(); proxy.Set(key, passed_value.ToLocalChecked()); @@ -683,7 +699,8 @@ void ExposeAPIInWorld(v8::Isolate* isolate, v8::Context::Scope target_context_scope(target_context); v8::MaybeLocal<v8::Value> maybe_proxy = PassValueToOtherContext( - electron_isolated_context, target_context, api, &object_cache, false, 0, + electron_isolated_context, target_context, api, + electron_isolated_context->Global(), &object_cache, false, 0, BridgeErrorTarget::kSource); if (maybe_proxy.IsEmpty()) return; @@ -732,9 +749,11 @@ void OverrideGlobalValueFromIsolatedWorld( { v8::Context::Scope main_context_scope(main_context); context_bridge::ObjectCache object_cache; + v8::Local<v8::Context> source_context = value->GetCreationContextChecked(); v8::MaybeLocal<v8::Value> maybe_proxy = PassValueToOtherContext( - value->GetCreationContextChecked(), main_context, value, &object_cache, - support_dynamic_properties, 1, BridgeErrorTarget::kSource); + source_context, main_context, value, source_context->Global(), + &object_cache, support_dynamic_properties, 1, + BridgeErrorTarget::kSource); DCHECK(!maybe_proxy.IsEmpty()); auto proxy = maybe_proxy.ToLocalChecked(); @@ -768,15 +787,19 @@ bool OverrideGlobalPropertyFromIsolatedWorld( v8::Local<v8::Value> getter_proxy; v8::Local<v8::Value> setter_proxy; if (!getter->IsNullOrUndefined()) { + v8::Local<v8::Context> source_context = + getter->GetCreationContextChecked(); v8::MaybeLocal<v8::Value> maybe_getter_proxy = PassValueToOtherContext( - getter->GetCreationContextChecked(), main_context, getter, + source_context, main_context, getter, source_context->Global(), &object_cache, false, 1, BridgeErrorTarget::kSource); DCHECK(!maybe_getter_proxy.IsEmpty()); getter_proxy = maybe_getter_proxy.ToLocalChecked(); } if (!setter->IsNullOrUndefined() && setter->IsObject()) { + v8::Local<v8::Context> source_context = + getter->GetCreationContextChecked(); v8::MaybeLocal<v8::Value> maybe_setter_proxy = PassValueToOtherContext( - getter->GetCreationContextChecked(), main_context, setter, + source_context, main_context, setter, source_context->Global(), &object_cache, false, 1, BridgeErrorTarget::kSource); DCHECK(!maybe_setter_proxy.IsEmpty()); setter_proxy = maybe_setter_proxy.ToLocalChecked(); diff --git a/shell/renderer/api/electron_api_context_bridge.h b/shell/renderer/api/electron_api_context_bridge.h index dd2af4b713..e0cabdfab2 100644 --- a/shell/renderer/api/electron_api_context_bridge.h +++ b/shell/renderer/api/electron_api_context_bridge.h @@ -36,6 +36,14 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext( v8::Local<v8::Context> source_context, v8::Local<v8::Context> destination_context, v8::Local<v8::Value> value, + /** + * Used to automatically bind a function across + * worlds to its appropriate default "this" value. + * + * If this value is the root of a tree going over + * the bridge set this to the "context" of the value. + */ + v8::Local<v8::Value> parent_value, context_bridge::ObjectCache* object_cache, bool support_dynamic_properties, int recursion_depth, diff --git a/shell/renderer/api/electron_api_web_frame.cc b/shell/renderer/api/electron_api_web_frame.cc index 7ba114f606..9b7f9f9ceb 100644 --- a/shell/renderer/api/electron_api_web_frame.cc +++ b/shell/renderer/api/electron_api_web_frame.cc @@ -140,9 +140,12 @@ class ScriptExecutionCallback { { v8::TryCatch try_catch(isolate); context_bridge::ObjectCache object_cache; - maybe_result = PassValueToOtherContext( - result->GetCreationContextChecked(), promise_.GetContext(), result, - &object_cache, false, 0, BridgeErrorTarget::kSource); + v8::Local<v8::Context> source_context = + result->GetCreationContextChecked(); + maybe_result = + PassValueToOtherContext(source_context, promise_.GetContext(), result, + source_context->Global(), &object_cache, + false, 0, BridgeErrorTarget::kSource); if (maybe_result.IsEmpty() || try_catch.HasCaught()) { success = false; } diff --git a/shell/renderer/renderer_client_base.cc b/shell/renderer/renderer_client_base.cc index d456d414f1..11970869b4 100644 --- a/shell/renderer/renderer_client_base.cc +++ b/shell/renderer/renderer_client_base.cc @@ -608,8 +608,8 @@ void RendererClientBase::SetupMainWorldOverrides( if (global.GetHidden("guestViewInternal", &guest_view_internal)) { api::context_bridge::ObjectCache object_cache; auto result = api::PassValueToOtherContext( - source_context, context, guest_view_internal, &object_cache, false, 0, - api::BridgeErrorTarget::kSource); + source_context, context, guest_view_internal, source_context->Global(), + &object_cache, false, 0, api::BridgeErrorTarget::kSource); if (!result.IsEmpty()) { isolated_api.Set("guestViewInternal", result.ToLocalChecked()); } diff --git a/spec/webview-spec.ts b/spec/webview-spec.ts index 369c5926d9..ea8f787ce7 100644 --- a/spec/webview-spec.ts +++ b/spec/webview-spec.ts @@ -2020,25 +2020,34 @@ describe('<webview> tag', function () { // TODO(miniak): figure out why this is failing on windows ifdescribe(process.platform !== 'win32')('<webview>.capturePage()', () => { - it('returns a Promise with a NativeImage', async () => { + it('returns a Promise with a NativeImage', async function () { + this.retries(5); + const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; await loadWebViewAndWaitForEvent(w, { src }, 'did-stop-loading'); - // Retry a few times due to flake. - for (let i = 0; i < 5; i++) { - try { - const image = await w.executeJavaScript('webview.capturePage()'); - const imgBuffer = image.toPNG(); - - // Check the 25th byte in the PNG. - // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha - expect(imgBuffer[25]).to.equal(6); - return; - } catch { - /* drop the error */ - } - } - expect(false).to.be.true('could not successfully capture the page'); + const image = await w.executeJavaScript('webview.capturePage()'); + expect(image.isEmpty()).to.be.false(); + + // Check the 25th byte in the PNG. + // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha + const imgBuffer = image.toPNG(); + expect(imgBuffer[25]).to.equal(6); + }); + + it('returns a Promise with a NativeImage in the renderer', async function () { + this.retries(5); + + const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; + await loadWebViewAndWaitForEvent(w, { src }, 'did-stop-loading'); + + const byte = await w.executeJavaScript(`new Promise(resolve => { + webview.capturePage().then(image => { + resolve(image.toPNG()[25]) + }); + })`); + + expect(byte).to.equal(6); }); });
fix
96460becf9ab0bf49d7d556a5c567da3c4217701
michal-pichlinski-openfin
2025-02-07 20:31:08
fix: Update widget visibility in `NativeWindowMac::ShowInactive` (#45427) When using `views::WebView` on macOS `NativeWidgetMacNSWindowHost` contains a layer and compositor responsible for drawing web contents. To trigger drawing `NativeWidgetMacNSWindowHost::OnVisibilityChanged` needs to be called and `[NSWindow orderFrontRegardless]` does not trigger `[NSWindow orderWindow:relativeTo:]` which can change `NativeWidgetMacNSWindowHost` visiblity with stack: ``` views::NativeWidgetMacNSWindowHost::OnVisibilityChanged(bool) remote_cocoa::NativeWidgetNSWindowBridge::OnVisibilityChanged() -[ViewsNSWindowDelegate onWindowOrderChanged:] -[NativeWidgetMacNSWindow orderWindow:relativeTo:] ``` `views::Widget` has method for showing inactive window: `views::Widget::ShowInactive` which triggers `NativeWidgetMacNSWindowHost::OnVisibilityChanged` with stack: ``` views::NativeWidgetMacNSWindowHost::OnVisibilityChanged(bool) remote_cocoa::NativeWidgetNSWindowBridge::SetVisibilityState(remote_cocoa::mojom::WindowVisibilityState) views::NativeWidgetMacNSWindowHost::SetVisibilityState(remote_cocoa::mojom::WindowVisibilityState) views::NativeWidgetMac::Show(ui::mojom::WindowShowState, gfx::Rect const&) views::Widget::ShowInactive() + 168 ``` However this call seems to be insufficient to bring window to front, therefore `[NSWindow orderFrontRegardless]` still needs to be called. Calling `views::Widget::ShowInactive` ensures that all logic related to showing Chromium widget will be properly executed, but onfortunately it does not call `[NSWindow orderWindow:relativeTo:]` which is used to disabling headless mode by the `ElectronNSWindow`, therefore we need to trigger it manually through exposed `[ElectronNSWindow disableHeadlessMode]`. Fixes: #45415
diff --git a/shell/browser/native_window_mac.mm b/shell/browser/native_window_mac.mm index 2acea04280..6889eb6f18 100644 --- a/shell/browser/native_window_mac.mm +++ b/shell/browser/native_window_mac.mm @@ -429,7 +429,13 @@ void NativeWindowMac::ShowInactive() { if (parent()) InternalSetParentWindow(parent(), true); + // Triggers `NativeWidgetMacNSWindowHost::OnVisibilityChanged`. + widget()->ShowInactive(); + // `Widget::ShowInactive` is not sufficient to bring window to front. [window_ orderFrontRegardless]; + // Above calls do not trigger `orderWindow: relativeTo:` in which headless + // mode is being disabled. + [window_ disableHeadlessMode]; } void NativeWindowMac::Hide() { diff --git a/shell/browser/ui/cocoa/electron_ns_window.h b/shell/browser/ui/cocoa/electron_ns_window.h index 63ea535546..8c026c0b0b 100644 --- a/shell/browser/ui/cocoa/electron_ns_window.h +++ b/shell/browser/ui/cocoa/electron_ns_window.h @@ -49,6 +49,7 @@ class ElectronNativeWindowObserver; - (NSRect)originalContentRectForFrameRect:(NSRect)frameRect; - (BOOL)toggleFullScreenMode:(id)sender; - (NSImage*)_cornerMask; +- (void)disableHeadlessMode; @end #endif // ELECTRON_SHELL_BROWSER_UI_COCOA_ELECTRON_NS_WINDOW_H_ diff --git a/shell/browser/ui/cocoa/electron_ns_window.mm b/shell/browser/ui/cocoa/electron_ns_window.mm index 30780277d3..6555f47f5b 100644 --- a/shell/browser/ui/cocoa/electron_ns_window.mm +++ b/shell/browser/ui/cocoa/electron_ns_window.mm @@ -259,13 +259,7 @@ void SwizzleSwipeWithEvent(NSView* view, SEL swiz_selector) { } - (void)orderWindow:(NSWindowOrderingMode)place relativeTo:(NSInteger)otherWin { - if (shell_) { - // We initialize the window in headless mode to allow painting before it is - // shown, but we don't want the headless behavior of allowing the window to - // be placed unconstrained. - self.isHeadless = false; - shell_->widget()->DisableHeadlessMode(); - } + [self disableHeadlessMode]; [super orderWindow:place relativeTo:otherWin]; } @@ -328,6 +322,16 @@ void SwizzleSwipeWithEvent(NSView* view, SEL swiz_selector) { } } +- (void)disableHeadlessMode { + if (shell_) { + // We initialize the window in headless mode to allow painting before it is + // shown, but we don't want the headless behavior of allowing the window to + // be placed unconstrained. + self.isHeadless = false; + shell_->widget()->DisableHeadlessMode(); + } +} + // Quicklook methods - (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel*)panel {
fix
4c8583c36525b4fe0778eb6585881b6327737802
David Sanders
2023-04-04 01:27:51
test: remove workaround for fixed Menu.closePopup issue (#37802)
diff --git a/spec/api-menu-spec.ts b/spec/api-menu-spec.ts index adf10663d6..16c2e4b2df 100644 --- a/spec/api-menu-spec.ts +++ b/spec/api-menu-spec.ts @@ -817,10 +817,7 @@ describe('Menu module', function () { it('should emit menu-will-close event', (done) => { menu.on('menu-will-close', () => { done(); }); menu.popup({ window: w }); - // https://github.com/electron/electron/issues/19411 - setTimeout().then(() => { - menu.closePopup(); - }); + menu.closePopup(); }); it('returns immediately', () => { @@ -849,18 +846,12 @@ describe('Menu module', function () { expect(x).to.equal(100); expect(y).to.equal(101); - // https://github.com/electron/electron/issues/19411 - setTimeout().then(() => { - menu.closePopup(); - }); + menu.closePopup(); }); it('works with a given BrowserWindow, no options, and a callback', (done) => { menu.popup({ window: w, callback: () => done() }); - // https://github.com/electron/electron/issues/19411 - setTimeout().then(() => { - menu.closePopup(); - }); + menu.closePopup(); }); it('prevents menu from getting garbage-collected when popuping', async () => {
test
feb804cea817eca9a2b30bdc657905caa9c01367
github-actions[bot]
2023-09-06 14:07:34
build: update appveyor image to latest version (#39716) Co-authored-by: jkleinsc <[email protected]>
diff --git a/appveyor-woa.yml b/appveyor-woa.yml index 0c407e7f80..b93c60cb22 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-118.0.5949.0 +image: e-118.0.5991.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default diff --git a/appveyor.yml b/appveyor.yml index dafbada5b0..883db27610 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-118.0.5949.0 +image: e-118.0.5991.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default
build
996477152d2c11098f6d154e4de9bc51c6088701
Sam Maddock
2025-01-23 21:12:46
feat: contextBridge.executeInMainWorld (#45229)
diff --git a/docs/api/context-bridge.md b/docs/api/context-bridge.md index 59d8a0d363..1776b7c61a 100644 --- a/docs/api/context-bridge.md +++ b/docs/api/context-bridge.md @@ -61,6 +61,20 @@ The `contextBridge` module has the following methods: * `apiKey` string - The key to inject the API onto `window` with. The API will be accessible on `window[apiKey]`. * `api` any - Your API, more information on what this API can be and how it works is available below. +### `contextBridge.executeInMainWorld(executionScript)` _Experimental_ + +<!-- TODO(samuelmaddock): add generics to map the `args` types to the `func` params --> + +* `executionScript` Object + * `func` (...args: any[]) => any - A JavaScript function to execute. This function will be serialized which means + that any bound parameters and execution context will be lost. + * `args` any[] (optional) - An array of arguments to pass to the provided function. These + arguments will be copied between worlds in accordance with + [the table of supported types.](#parameter--error--return-type-support) + +Returns `any` - A copy of the resulting value from executing the function in the main world. +[Refer to the table](#parameter--error--return-type-support) on how values are copied between worlds. + ## Usage ### API diff --git a/lib/renderer/api/context-bridge.ts b/lib/renderer/api/context-bridge.ts index 99b133e6c3..7894ebab7c 100644 --- a/lib/renderer/api/context-bridge.ts +++ b/lib/renderer/api/context-bridge.ts @@ -5,13 +5,17 @@ const checkContextIsolationEnabled = () => { }; const contextBridge: Electron.ContextBridge = { - exposeInMainWorld: (key: string, api: any) => { + exposeInMainWorld: (key, api) => { checkContextIsolationEnabled(); return binding.exposeAPIInWorld(0, key, api); }, - exposeInIsolatedWorld: (worldId: number, key: string, api: any) => { + exposeInIsolatedWorld: (worldId, key, api) => { checkContextIsolationEnabled(); return binding.exposeAPIInWorld(worldId, key, api); + }, + executeInMainWorld: (script) => { + checkContextIsolationEnabled(); + return binding.executeInWorld(0, script); } }; @@ -27,8 +31,7 @@ export const internalContextBridge = { }, overrideGlobalPropertyFromIsolatedWorld: (keys: string[], getter: Function, setter?: Function) => { return binding._overrideGlobalPropertyFromIsolatedWorld(keys, getter, setter || null); - }, - isInMainWorld: () => binding._isCalledFromMainWorld() as boolean + } }; if (binding._isDebug) { diff --git a/shell/renderer/api/electron_api_context_bridge.cc b/shell/renderer/api/electron_api_context_bridge.cc index dd35c5b784..f1dbffa32f 100644 --- a/shell/renderer/api/electron_api_context_bridge.cc +++ b/shell/renderer/api/electron_api_context_bridge.cc @@ -13,11 +13,14 @@ #include "base/containers/contains.h" #include "base/feature_list.h" +#include "base/json/json_writer.h" #include "base/trace_event/trace_event.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_frame_observer.h" +#include "gin/converter.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" +#include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/promise.h" #include "shell/common/node_includes.h" @@ -25,6 +28,7 @@ #include "third_party/blink/public/web/web_blob.h" #include "third_party/blink/public/web/web_element.h" #include "third_party/blink/public/web/web_local_frame.h" +#include "third_party/blink/renderer/core/execution_context/execution_context.h" // nogncheck namespace features { BASE_FEATURE(kContextBridgeMutability, @@ -133,8 +137,21 @@ v8::MaybeLocal<v8::Value> GetPrivate(v8::Local<v8::Context> context, } // namespace -v8::MaybeLocal<v8::Value> PassValueToOtherContext( +// Forward declare methods +void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info); +v8::MaybeLocal<v8::Object> CreateProxyForAPI( + const v8::Local<v8::Object>& api_object, + const v8::Local<v8::Context>& source_context, + const blink::ExecutionContext* source_execution_context, + const v8::Local<v8::Context>& destination_context, + context_bridge::ObjectCache* object_cache, + bool support_dynamic_properties, + int recursion_depth, + BridgeErrorTarget error_target); + +v8::MaybeLocal<v8::Value> PassValueToOtherContextInner( v8::Local<v8::Context> source_context, + const blink::ExecutionContext* source_execution_context, v8::Local<v8::Context> destination_context, v8::Local<v8::Value> value, v8::Local<v8::Value> parent_value, @@ -142,7 +159,7 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext( bool support_dynamic_properties, int recursion_depth, BridgeErrorTarget error_target) { - TRACE_EVENT0("electron", "ContextBridge::PassValueToOtherContext"); + TRACE_EVENT0("electron", "ContextBridge::PassValueToOtherContextInner"); if (recursion_depth >= kMaxRecursion) { v8::Context::Scope error_scope(error_target == BridgeErrorTarget::kSource ? source_context @@ -245,7 +262,6 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext( if (global_source_context.IsEmpty() || global_destination_context.IsEmpty()) return; - context_bridge::ObjectCache object_cache; v8::MaybeLocal<v8::Value> val; { v8::TryCatch try_catch(isolate); @@ -253,7 +269,7 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext( global_source_context.Get(isolate); val = PassValueToOtherContext( source_context, global_destination_context.Get(isolate), result, - source_context->Global(), &object_cache, false, 0, + source_context->Global(), false, BridgeErrorTarget::kDestination); if (try_catch.HasCaught()) { if (try_catch.Message().IsEmpty()) { @@ -293,7 +309,6 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext( if (global_source_context.IsEmpty() || global_destination_context.IsEmpty()) return; - context_bridge::ObjectCache object_cache; v8::MaybeLocal<v8::Value> val; { v8::TryCatch try_catch(isolate); @@ -301,7 +316,7 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext( global_source_context.Get(isolate); val = PassValueToOtherContext( source_context, global_destination_context.Get(isolate), result, - source_context->Global(), &object_cache, false, 0, + source_context->Global(), false, BridgeErrorTarget::kDestination); if (try_catch.HasCaught()) { if (try_catch.Message().IsEmpty()) { @@ -367,8 +382,8 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext( v8::Local<v8::Array> cloned_arr = v8::Array::New(destination_context->GetIsolate(), length); for (size_t i = 0; i < length; i++) { - auto value_for_array = PassValueToOtherContext( - source_context, destination_context, + auto value_for_array = PassValueToOtherContextInner( + source_context, source_execution_context, destination_context, arr->Get(source_context, i).ToLocalChecked(), value, object_cache, support_dynamic_properties, recursion_depth + 1, error_target); if (value_for_array.IsEmpty()) @@ -383,30 +398,34 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext( return v8::MaybeLocal<v8::Value>(cloned_arr); } - // Custom logic to "clone" Element references - blink::WebElement elem = - blink::WebElement::FromV8Value(destination_context->GetIsolate(), value); - if (!elem.IsNull()) { - v8::Context::Scope destination_context_scope(destination_context); - return v8::MaybeLocal<v8::Value>( - elem.ToV8Value(destination_context->GetIsolate())); - } + // Clone certain DOM APIs only within Window contexts. + if (source_execution_context->IsWindow()) { + // Custom logic to "clone" Element references + blink::WebElement elem = blink::WebElement::FromV8Value( + destination_context->GetIsolate(), value); + if (!elem.IsNull()) { + v8::Context::Scope destination_context_scope(destination_context); + return v8::MaybeLocal<v8::Value>( + elem.ToV8Value(destination_context->GetIsolate())); + } - // Custom logic to "clone" Blob references - blink::WebBlob blob = - blink::WebBlob::FromV8Value(destination_context->GetIsolate(), value); - if (!blob.IsNull()) { - v8::Context::Scope destination_context_scope(destination_context); - return v8::MaybeLocal<v8::Value>( - blob.ToV8Value(destination_context->GetIsolate())); + // Custom logic to "clone" Blob references + blink::WebBlob blob = + blink::WebBlob::FromV8Value(destination_context->GetIsolate(), value); + if (!blob.IsNull()) { + v8::Context::Scope destination_context_scope(destination_context); + return v8::MaybeLocal<v8::Value>( + blob.ToV8Value(destination_context->GetIsolate())); + } } // Proxy all objects if (IsPlainObject(value)) { auto object_value = value.As<v8::Object>(); auto passed_value = CreateProxyForAPI( - object_value, source_context, destination_context, object_cache, - support_dynamic_properties, recursion_depth + 1, error_target); + object_value, source_context, source_execution_context, + destination_context, object_cache, support_dynamic_properties, + recursion_depth + 1, error_target); if (passed_value.IsEmpty()) return {}; return v8::MaybeLocal<v8::Value>(passed_value.ToLocalChecked()); @@ -434,6 +453,28 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext( } } +v8::MaybeLocal<v8::Value> PassValueToOtherContext( + v8::Local<v8::Context> source_context, + v8::Local<v8::Context> destination_context, + v8::Local<v8::Value> value, + v8::Local<v8::Value> parent_value, + bool support_dynamic_properties, + BridgeErrorTarget error_target, + context_bridge::ObjectCache* existing_object_cache) { + TRACE_EVENT0("electron", "ContextBridge::PassValueToOtherContext"); + + context_bridge::ObjectCache local_object_cache; + context_bridge::ObjectCache* object_cache = + existing_object_cache ? existing_object_cache : &local_object_cache; + + const blink::ExecutionContext* source_execution_context = + blink::ExecutionContext::From(source_context); + DCHECK(source_execution_context); + return PassValueToOtherContextInner( + source_context, source_execution_context, destination_context, value, + parent_value, object_cache, support_dynamic_properties, 0, error_target); +} + void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT0("electron", "ContextBridge::ProxyFunctionWrapper"); CHECK(info.Data()->IsObject()); @@ -464,6 +505,8 @@ void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info) { { v8::Context::Scope func_owning_context_scope(func_owning_context); + + // Cache duplicate arguments as the same proxied value. context_bridge::ObjectCache object_cache; std::vector<v8::Local<v8::Value>> original_args; @@ -473,8 +516,8 @@ void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info) { for (auto value : original_args) { auto arg = PassValueToOtherContext( calling_context, func_owning_context, value, - calling_context->Global(), &object_cache, support_dynamic_properties, - 0, BridgeErrorTarget::kSource); + calling_context->Global(), support_dynamic_properties, + BridgeErrorTarget::kSource, &object_cache); if (arg.IsEmpty()) return; proxied_args.push_back(arg.ToLocalChecked()); @@ -540,11 +583,10 @@ void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::String> exception; { v8::TryCatch try_catch(args.isolate()); - ret = PassValueToOtherContext(func_owning_context, calling_context, - maybe_return_value.ToLocalChecked(), - func_owning_context->Global(), - &object_cache, support_dynamic_properties, - 0, BridgeErrorTarget::kDestination); + ret = PassValueToOtherContext( + func_owning_context, calling_context, + maybe_return_value.ToLocalChecked(), func_owning_context->Global(), + support_dynamic_properties, BridgeErrorTarget::kDestination); if (try_catch.HasCaught()) { did_error_converting_result = true; if (!try_catch.Message().IsEmpty()) { @@ -576,6 +618,7 @@ void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::MaybeLocal<v8::Object> CreateProxyForAPI( const v8::Local<v8::Object>& api_object, const v8::Local<v8::Context>& source_context, + const blink::ExecutionContext* source_execution_context, const v8::Local<v8::Context>& destination_context, context_bridge::ObjectCache* object_cache, bool support_dynamic_properties, @@ -619,18 +662,20 @@ v8::MaybeLocal<v8::Object> CreateProxyForAPI( v8::Local<v8::Value> getter_proxy; v8::Local<v8::Value> setter_proxy; if (!getter.IsEmpty()) { - if (!PassValueToOtherContext( - source_context, destination_context, getter, - api.GetHandle(), object_cache, - support_dynamic_properties, 1, error_target) + if (!PassValueToOtherContextInner( + source_context, source_execution_context, + destination_context, getter, api.GetHandle(), + object_cache, support_dynamic_properties, 1, + error_target) .ToLocal(&getter_proxy)) continue; } if (!setter.IsEmpty()) { - if (!PassValueToOtherContext( - source_context, destination_context, setter, - api.GetHandle(), object_cache, - support_dynamic_properties, 1, error_target) + if (!PassValueToOtherContextInner( + source_context, source_execution_context, + destination_context, setter, api.GetHandle(), + object_cache, support_dynamic_properties, 1, + error_target) .ToLocal(&setter_proxy)) continue; } @@ -646,10 +691,10 @@ v8::MaybeLocal<v8::Object> CreateProxyForAPI( if (!api.Get(key, &value)) continue; - auto passed_value = PassValueToOtherContext( - source_context, destination_context, value, api.GetHandle(), - object_cache, support_dynamic_properties, recursion_depth + 1, - error_target); + auto passed_value = PassValueToOtherContextInner( + source_context, source_execution_context, destination_context, value, + api.GetHandle(), object_cache, support_dynamic_properties, + recursion_depth + 1, error_target); if (passed_value.IsEmpty()) return {}; proxy.Set(key, passed_value.ToLocalChecked()); @@ -661,24 +706,14 @@ v8::MaybeLocal<v8::Object> CreateProxyForAPI( namespace { -void ExposeAPIInWorld(v8::Isolate* isolate, - const int world_id, - const std::string& key, - v8::Local<v8::Value> api, - gin_helper::Arguments* args) { - TRACE_EVENT2("electron", "ContextBridge::ExposeAPIInWorld", "key", key, - "worldId", world_id); - - auto* render_frame = GetRenderFrame(isolate->GetCurrentContext()->Global()); - CHECK(render_frame); - auto* frame = render_frame->GetWebFrame(); - CHECK(frame); - - v8::Local<v8::Context> target_context = - world_id == WorldIDs::MAIN_WORLD_ID - ? frame->MainWorldScriptContext() - : frame->GetScriptContextFromWorldId(isolate, world_id); - +void ExposeAPI(v8::Isolate* isolate, + v8::Local<v8::Context> source_context, + v8::Local<v8::Context> target_context, + const std::string& key, + v8::Local<v8::Value> api, + gin_helper::Arguments* args) { + DCHECK(!target_context.IsEmpty()); + v8::Context::Scope target_context_scope(target_context); gin_helper::Dictionary global(target_context->GetIsolate(), target_context->Global()); @@ -689,33 +724,70 @@ void ExposeAPIInWorld(v8::Isolate* isolate, return; } - v8::Local<v8::Context> electron_isolated_context = - frame->GetScriptContextFromWorldId(args->isolate(), - WorldIDs::ISOLATED_WORLD_ID); - - { - context_bridge::ObjectCache object_cache; - v8::Context::Scope target_context_scope(target_context); + v8::MaybeLocal<v8::Value> maybe_proxy = PassValueToOtherContext( + source_context, target_context, api, source_context->Global(), false, + BridgeErrorTarget::kSource); + if (maybe_proxy.IsEmpty()) + return; + auto proxy = maybe_proxy.ToLocalChecked(); - v8::MaybeLocal<v8::Value> maybe_proxy = PassValueToOtherContext( - electron_isolated_context, target_context, api, - electron_isolated_context->Global(), &object_cache, false, 0, - BridgeErrorTarget::kSource); - if (maybe_proxy.IsEmpty()) - return; - auto proxy = maybe_proxy.ToLocalChecked(); + if (base::FeatureList::IsEnabled(features::kContextBridgeMutability)) { + global.Set(key, proxy); + return; + } - if (base::FeatureList::IsEnabled(features::kContextBridgeMutability)) { - global.Set(key, proxy); - return; - } + if (proxy->IsObject() && !proxy->IsTypedArray() && + !DeepFreeze(proxy.As<v8::Object>(), target_context)) + return; - if (proxy->IsObject() && !proxy->IsTypedArray() && - !DeepFreeze(proxy.As<v8::Object>(), target_context)) - return; + global.SetReadOnlyNonConfigurable(key, proxy); +} - global.SetReadOnlyNonConfigurable(key, proxy); +// Attempt to get the target context based on the current context. +// +// For render frames, this is either the main world (0) or an arbitrary +// world ID. For service workers, Electron only supports one isolated +// context and the main worker context. Anything else is invalid. +v8::MaybeLocal<v8::Context> GetTargetContext(v8::Isolate* isolate, + const int world_id) { + v8::Local<v8::Context> source_context = isolate->GetCurrentContext(); + v8::MaybeLocal<v8::Context> maybe_target_context; + + blink::ExecutionContext* execution_context = + blink::ExecutionContext::From(source_context); + if (execution_context->IsWindow()) { + auto* render_frame = GetRenderFrame(source_context->Global()); + CHECK(render_frame); + auto* frame = render_frame->GetWebFrame(); + CHECK(frame); + + maybe_target_context = + world_id == WorldIDs::MAIN_WORLD_ID + ? frame->MainWorldScriptContext() + : frame->GetScriptContextFromWorldId(isolate, world_id); + } else { + NOTREACHED(); } + + CHECK(!maybe_target_context.IsEmpty()); + return maybe_target_context; +} + +void ExposeAPIInWorld(v8::Isolate* isolate, + const int world_id, + const std::string& key, + v8::Local<v8::Value> api, + gin_helper::Arguments* args) { + TRACE_EVENT2("electron", "ContextBridge::ExposeAPIInWorld", "key", key, + "worldId", world_id); + v8::Local<v8::Context> source_context = isolate->GetCurrentContext(); + CHECK(!source_context.IsEmpty()); + v8::MaybeLocal<v8::Context> maybe_target_context = + GetTargetContext(isolate, world_id); + if (maybe_target_context.IsEmpty()) + return; + v8::Local<v8::Context> target_context = maybe_target_context.ToLocalChecked(); + ExposeAPI(isolate, source_context, target_context, key, api, args); } gin_helper::Dictionary TraceKeyPath(const gin_helper::Dictionary& start, @@ -747,12 +819,10 @@ void OverrideGlobalValueFromIsolatedWorld( { v8::Context::Scope main_context_scope(main_context); - context_bridge::ObjectCache object_cache; v8::Local<v8::Context> source_context = value->GetCreationContextChecked(); v8::MaybeLocal<v8::Value> maybe_proxy = PassValueToOtherContext( source_context, main_context, value, source_context->Global(), - &object_cache, support_dynamic_properties, 1, - BridgeErrorTarget::kSource); + support_dynamic_properties, BridgeErrorTarget::kSource); DCHECK(!maybe_proxy.IsEmpty()); auto proxy = maybe_proxy.ToLocalChecked(); @@ -789,8 +859,8 @@ bool OverrideGlobalPropertyFromIsolatedWorld( v8::Local<v8::Context> source_context = getter->GetCreationContextChecked(); v8::MaybeLocal<v8::Value> maybe_getter_proxy = PassValueToOtherContext( - source_context, main_context, getter, source_context->Global(), - &object_cache, false, 1, BridgeErrorTarget::kSource); + source_context, main_context, getter, source_context->Global(), false, + BridgeErrorTarget::kSource); DCHECK(!maybe_getter_proxy.IsEmpty()); getter_proxy = maybe_getter_proxy.ToLocalChecked(); } @@ -798,8 +868,8 @@ bool OverrideGlobalPropertyFromIsolatedWorld( v8::Local<v8::Context> source_context = getter->GetCreationContextChecked(); v8::MaybeLocal<v8::Value> maybe_setter_proxy = PassValueToOtherContext( - source_context, main_context, setter, source_context->Global(), - &object_cache, false, 1, BridgeErrorTarget::kSource); + source_context, main_context, setter, source_context->Global(), false, + BridgeErrorTarget::kSource); DCHECK(!maybe_setter_proxy.IsEmpty()); setter_proxy = maybe_setter_proxy.ToLocalChecked(); } @@ -812,13 +882,205 @@ bool OverrideGlobalPropertyFromIsolatedWorld( } } -bool IsCalledFromMainWorld(v8::Isolate* isolate) { - auto* render_frame = GetRenderFrame(isolate->GetCurrentContext()->Global()); - CHECK(render_frame); - auto* frame = render_frame->GetWebFrame(); - CHECK(frame); - v8::Local<v8::Context> main_context = frame->MainWorldScriptContext(); - return isolate->GetCurrentContext() == main_context; +// Serialize script to be executed in the given world. +v8::Local<v8::Value> ExecuteInWorld(v8::Isolate* isolate, + const int world_id, + gin_helper::Arguments* args) { + // Get context of caller + v8::Local<v8::Context> source_context = isolate->GetCurrentContext(); + + // Get execution script argument + gin_helper::Dictionary exec_script; + if (args->Length() >= 1 && !args->GetNext(&exec_script)) { + gin_helper::ErrorThrower(args->isolate()).ThrowError("Invalid script"); + return v8::Undefined(isolate); + } + + // Get "func" from execution script + v8::Local<v8::Function> func; + if (!exec_script.Get("func", &func)) { + gin_helper::ErrorThrower(isolate).ThrowError( + "Function 'func' is required in script"); + return v8::Undefined(isolate); + } + + // Get optional "args" from execution script + v8::Local<v8::Array> args_array; + v8::Local<v8::Value> args_value; + if (exec_script.Get("args", &args_value)) { + if (!args_value->IsArray()) { + gin_helper::ErrorThrower(isolate).ThrowError("'args' must be an array"); + return v8::Undefined(isolate); + } + args_array = args_value.As<v8::Array>(); + } + + // Serialize the function + std::string function_str; + { + v8::Local<v8::String> serialized_function; + if (!func->FunctionProtoToString(isolate->GetCurrentContext()) + .ToLocal(&serialized_function)) { + gin_helper::ErrorThrower(isolate).ThrowError( + "Failed to serialize function"); + return v8::Undefined(isolate); + } + // If ToLocal() succeeds, this should always be a string. + CHECK(gin::Converter<std::string>::FromV8(isolate, serialized_function, + &function_str)); + } + + // Get the target context + v8::MaybeLocal<v8::Context> maybe_target_context = + GetTargetContext(isolate, world_id); + v8::Local<v8::Context> target_context; + if (!maybe_target_context.ToLocal(&target_context)) { + isolate->ThrowException(v8::Exception::Error(gin::StringToV8( + isolate, + base::StringPrintf("Failed to get context for world %d", world_id)))); + return v8::Undefined(isolate); + } + + // Compile the script + v8::Local<v8::Script> compiled_script; + { + v8::Context::Scope target_scope(target_context); + std::string error_message; + v8::MaybeLocal<v8::Script> maybe_compiled_script; + { + v8::TryCatch try_catch(isolate); + std::string return_func_code = + base::StringPrintf("(%s)", function_str.c_str()); + maybe_compiled_script = v8::Script::Compile( + target_context, gin::StringToV8(isolate, return_func_code)); + if (try_catch.HasCaught()) { + // Must throw outside of TryCatch scope + v8::String::Utf8Value error(isolate, try_catch.Exception()); + error_message = + *error ? *error : "Unknown error during script compilation"; + } + } + if (!maybe_compiled_script.ToLocal(&compiled_script)) { + isolate->ThrowException( + v8::Exception::Error(gin::StringToV8(isolate, error_message))); + return v8::Undefined(isolate); + } + } + + // Run the script + v8::Local<v8::Function> copied_func; + { + v8::Context::Scope target_scope(target_context); + std::string error_message; + v8::MaybeLocal<v8::Value> maybe_script_result; + { + v8::TryCatch try_catch(isolate); + maybe_script_result = compiled_script->Run(target_context); + if (try_catch.HasCaught()) { + // Must throw outside of TryCatch scope + v8::String::Utf8Value error(isolate, try_catch.Exception()); + error_message = + *error ? *error : "Unknown error during script execution"; + } + } + v8::Local<v8::Value> script_result; + if (!maybe_script_result.ToLocal(&script_result)) { + isolate->ThrowException( + v8::Exception::Error(gin::StringToV8(isolate, error_message))); + return v8::Undefined(isolate); + } + if (!script_result->IsFunction()) { + isolate->ThrowException(v8::Exception::Error( + gin::StringToV8(isolate, + "Expected script to result in a function but a " + "non-function type was found"))); + return v8::Undefined(isolate); + } + // Get copied function from the script result + copied_func = script_result.As<v8::Function>(); + } + + // Proxy args to be passed into copied function + std::vector<v8::Local<v8::Value>> proxied_args; + { + v8::Context::Scope target_scope(target_context); + bool support_dynamic_properties = false; + uint32_t args_length = args_array.IsEmpty() ? 0 : args_array->Length(); + + // Cache duplicate arguments as the same proxied value. + context_bridge::ObjectCache object_cache; + + for (uint32_t i = 0; i < args_length; ++i) { + v8::Local<v8::Value> arg; + if (!args_array->Get(source_context, i).ToLocal(&arg)) { + gin_helper::ErrorThrower(isolate).ThrowError( + base::StringPrintf("Failed to get argument at index %d", i)); + return v8::Undefined(isolate); + } + + auto proxied_arg = PassValueToOtherContext( + source_context, target_context, arg, source_context->Global(), + support_dynamic_properties, BridgeErrorTarget::kSource, + &object_cache); + if (proxied_arg.IsEmpty()) { + gin_helper::ErrorThrower(isolate).ThrowError( + base::StringPrintf("Failed to proxy argument at index %d", i)); + return v8::Undefined(isolate); + } + proxied_args.push_back(proxied_arg.ToLocalChecked()); + } + } + + // Call the function and get the result + v8::Local<v8::Value> result; + { + v8::Context::Scope target_scope(target_context); + std::string error_message; + v8::MaybeLocal<v8::Value> maybe_result; + { + v8::TryCatch try_catch(isolate); + maybe_result = + copied_func->Call(isolate, target_context, v8::Null(isolate), + proxied_args.size(), proxied_args.data()); + if (try_catch.HasCaught()) { + v8::String::Utf8Value error(isolate, try_catch.Exception()); + error_message = + *error ? *error : "Unknown error during function execution"; + } + } + if (!maybe_result.ToLocal(&result)) { + // Must throw outside of TryCatch scope + isolate->ThrowException( + v8::Exception::Error(gin::StringToV8(isolate, error_message))); + return v8::Undefined(isolate); + } + } + + // Clone the result into the source/caller context + v8::Local<v8::Value> cloned_result; + { + v8::Context::Scope source_scope(source_context); + std::string error_message; + v8::MaybeLocal<v8::Value> maybe_cloned_result; + { + v8::TryCatch try_catch(isolate); + // Pass value from target context back to source context + maybe_cloned_result = PassValueToOtherContext( + target_context, source_context, result, target_context->Global(), + false, BridgeErrorTarget::kSource); + if (try_catch.HasCaught()) { + v8::String::Utf8Value utf8(isolate, try_catch.Exception()); + error_message = *utf8 ? *utf8 : "Unknown error cloning result"; + } + } + if (!maybe_cloned_result.ToLocal(&cloned_result)) { + // Must throw outside of TryCatch scope + isolate->ThrowException( + v8::Exception::Error(gin::StringToV8(isolate, error_message))); + return v8::Undefined(isolate); + } + } + return cloned_result; } } // namespace @@ -835,13 +1097,12 @@ void Initialize(v8::Local<v8::Object> exports, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); + dict.SetMethod("executeInWorld", &electron::api::ExecuteInWorld); dict.SetMethod("exposeAPIInWorld", &electron::api::ExposeAPIInWorld); dict.SetMethod("_overrideGlobalValueFromIsolatedWorld", &electron::api::OverrideGlobalValueFromIsolatedWorld); dict.SetMethod("_overrideGlobalPropertyFromIsolatedWorld", &electron::api::OverrideGlobalPropertyFromIsolatedWorld); - dict.SetMethod("_isCalledFromMainWorld", - &electron::api::IsCalledFromMainWorld); #if DCHECK_IS_ON() dict.Set("_isDebug", true); #endif diff --git a/shell/renderer/api/electron_api_context_bridge.h b/shell/renderer/api/electron_api_context_bridge.h index 4f17f0b06e..f8498ae658 100644 --- a/shell/renderer/api/electron_api_context_bridge.h +++ b/shell/renderer/api/electron_api_context_bridge.h @@ -14,8 +14,6 @@ class Arguments; namespace electron::api { -void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info); - // Where the context bridge should create the exception it is about to throw enum class BridgeErrorTarget { // The source / calling context. This is default and correct 99% of the time, @@ -44,19 +42,9 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext( * the bridge set this to the "context" of the value. */ v8::Local<v8::Value> parent_value, - context_bridge::ObjectCache* object_cache, - bool support_dynamic_properties, - int recursion_depth, - BridgeErrorTarget error_target); - -v8::MaybeLocal<v8::Object> CreateProxyForAPI( - const v8::Local<v8::Object>& api_object, - const v8::Local<v8::Context>& source_context, - const v8::Local<v8::Context>& destination_context, - context_bridge::ObjectCache* object_cache, bool support_dynamic_properties, - int recursion_depth, - BridgeErrorTarget error_target); + BridgeErrorTarget error_target, + context_bridge::ObjectCache* existing_object_cache = nullptr); } // namespace electron::api diff --git a/shell/renderer/api/electron_api_web_frame.cc b/shell/renderer/api/electron_api_web_frame.cc index 2424eeec65..0f5211c5b2 100644 --- a/shell/renderer/api/electron_api_web_frame.cc +++ b/shell/renderer/api/electron_api_web_frame.cc @@ -150,13 +150,11 @@ class ScriptExecutionCallback { "An unknown exception occurred while getting the result of the script"; { v8::TryCatch try_catch(isolate); - context_bridge::ObjectCache object_cache; v8::Local<v8::Context> source_context = result->GetCreationContextChecked(); - maybe_result = - PassValueToOtherContext(source_context, promise_.GetContext(), result, - source_context->Global(), &object_cache, - false, 0, BridgeErrorTarget::kSource); + maybe_result = PassValueToOtherContext( + source_context, promise_.GetContext(), result, + source_context->Global(), false, BridgeErrorTarget::kSource); if (maybe_result.IsEmpty() || try_catch.HasCaught()) { success = false; } diff --git a/shell/renderer/renderer_client_base.cc b/shell/renderer/renderer_client_base.cc index ffac675b0f..1db92a9a95 100644 --- a/shell/renderer/renderer_client_base.cc +++ b/shell/renderer/renderer_client_base.cc @@ -611,10 +611,9 @@ void RendererClientBase::SetupMainWorldOverrides( v8::Local<v8::Value> guest_view_internal; if (global.GetHidden("guestViewInternal", &guest_view_internal)) { - api::context_bridge::ObjectCache object_cache; auto result = api::PassValueToOtherContext( source_context, context, guest_view_internal, source_context->Global(), - &object_cache, false, 0, api::BridgeErrorTarget::kSource); + false, api::BridgeErrorTarget::kSource); if (!result.IsEmpty()) { isolated_api.Set("guestViewInternal", result.ToLocalChecked()); } diff --git a/spec/api-context-bridge-spec.ts b/spec/api-context-bridge-spec.ts index d82470ab8b..b7fa471042 100644 --- a/spec/api-context-bridge-spec.ts +++ b/spec/api-context-bridge-spec.ts @@ -108,7 +108,7 @@ describe('contextBridge', () => { }; const callWithBindings = (fn: Function, worldId: number = 0) => - worldId === 0 ? w.webContents.executeJavaScript(`(${fn.toString()})(window)`) : w.webContents.executeJavaScriptInIsolatedWorld(worldId, [{ code: `(${fn.toString()})(window)` }]); ; + worldId === 0 ? w.webContents.executeJavaScript(`(${fn.toString()})(window)`) : w.webContents.executeJavaScriptInIsolatedWorld(worldId, [{ code: `(${fn.toString()})(window)` }]); const getGCInfo = async (): Promise<{ trackedValues: number; @@ -408,6 +408,17 @@ describe('contextBridge', () => { expect(result).equal(true); }); + it('should proxy function arguments only once', async () => { + await makeBindingWindow(() => { + contextBridge.exposeInMainWorld('example', (a: any, b: any) => a === b); + }); + const result = await callWithBindings(async (root: any) => { + const obj = { foo: 1 }; + return root.example(obj, obj); + }); + expect(result).to.be.true(); + }); + it('should properly handle errors thrown in proxied functions', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', () => { throw new Error('oh no'); }); @@ -1290,6 +1301,131 @@ describe('contextBridge', () => { }); }); }); + + describe('executeInMainWorld', () => { + it('serializes function and proxies args', async () => { + await makeBindingWindow(async () => { + const values = [ + undefined, + null, + 123, + 'string', + true, + [123, 'string', true, ['foo']], + () => 'string', + Symbol('foo') + ]; + function appendArg (arg: any) { + // @ts-ignore + globalThis.args = globalThis.args || []; + // @ts-ignore + globalThis.args.push(arg); + } + for (const value of values) { + try { + await contextBridge.executeInMainWorld({ + func: appendArg, + args: [value] + }); + } catch { + contextBridge.executeInMainWorld({ + func: appendArg, + args: ['FAIL'] + }); + } + } + }); + const result = await callWithBindings(() => { + // @ts-ignore + return globalThis.args.map(arg => { + // Map unserializable IPC types to their type string + if (['function', 'symbol'].includes(typeof arg)) { + return typeof arg; + } else { + return arg; + } + }); + }); + expect(result).to.deep.equal([ + undefined, + null, + 123, + 'string', + true, + [123, 'string', true, ['foo']], + 'function', + 'symbol' + ]); + }); + + it('allows function args to be invoked', async () => { + const donePromise = once(ipcMain, 'done'); + makeBindingWindow(() => { + const uuid = crypto.randomUUID(); + const done = (receivedUuid: string) => { + if (receivedUuid === uuid) { + require('electron').ipcRenderer.send('done'); + } + }; + contextBridge.executeInMainWorld({ + func: (callback, innerUuid) => { + callback(innerUuid); + }, + args: [done, uuid] + }); + }); + await donePromise; + }); + + it('proxies arguments only once', async () => { + await makeBindingWindow(() => { + const obj = {}; + // @ts-ignore + globalThis.result = contextBridge.executeInMainWorld({ + func: (a, b) => a === b, + args: [obj, obj] + }); + }); + const result = await callWithBindings(() => { + // @ts-ignore + return globalThis.result; + }, 999); + expect(result).to.be.true(); + }); + + it('safely clones returned objects', async () => { + await makeBindingWindow(() => { + const obj = contextBridge.executeInMainWorld({ + func: () => ({}) + }); + // @ts-ignore + globalThis.safe = obj.constructor === Object; + }); + const result = await callWithBindings(() => { + // @ts-ignore + return globalThis.safe; + }, 999); + expect(result).to.be.true(); + }); + + it('uses internal Function.prototype.toString', async () => { + await makeBindingWindow(() => { + const funcHack = () => { + // @ts-ignore + globalThis.hacked = 'nope'; + }; + funcHack.toString = () => '() => { globalThis.hacked = \'gotem\'; }'; + contextBridge.executeInMainWorld({ + func: funcHack + }); + }); + const result = await callWithBindings(() => { + // @ts-ignore + return globalThis.hacked; + }); + expect(result).to.equal('nope'); + }); + }); }); }; diff --git a/typings/internal-electron.d.ts b/typings/internal-electron.d.ts index 41da29713f..1ab4507af1 100644 --- a/typings/internal-electron.d.ts +++ b/typings/internal-electron.d.ts @@ -63,7 +63,6 @@ declare namespace Electron { overrideGlobalValueFromIsolatedWorld(keys: string[], value: any): void; overrideGlobalValueWithDynamicPropsFromIsolatedWorld(keys: string[], value: any): void; overrideGlobalPropertyFromIsolatedWorld(keys: string[], getter: Function, setter?: Function): void; - isInMainWorld(): boolean; } }
feat
90a7e5acae5ac8f77443bdc16c678fcee350d22b
Piotr Płaczek
2024-03-22 14:28:44
fix: normalize path before calling `showItemInFolder` and `openPath` (#41642) * fix: normalize path before calling ShowItemInFolder * fix: normalize path before calling OpenPath
diff --git a/shell/common/platform_util_win.cc b/shell/common/platform_util_win.cc index a2deae69bf..43684fc9e0 100644 --- a/shell/common/platform_util_win.cc +++ b/shell/common/platform_util_win.cc @@ -336,7 +336,8 @@ void ShowItemInFolder(const base::FilePath& full_path) { base::ThreadPool::CreateCOMSTATaskRunner( {base::MayBlock(), base::TaskPriority::USER_BLOCKING}) ->PostTask(FROM_HERE, - base::BindOnce(&ShowItemInFolderOnWorkerThread, full_path)); + base::BindOnce(&ShowItemInFolderOnWorkerThread, + full_path.NormalizePathSeparators())); } void OpenPath(const base::FilePath& full_path, OpenCallback callback) { @@ -344,9 +345,11 @@ void OpenPath(const base::FilePath& full_path, OpenCallback callback) { base::ThreadPool::CreateCOMSTATaskRunner( {base::MayBlock(), base::TaskPriority::USER_BLOCKING}) - ->PostTaskAndReplyWithResult(FROM_HERE, - base::BindOnce(&OpenPathOnThread, full_path), - std::move(callback)); + ->PostTaskAndReplyWithResult( + FROM_HERE, + base::BindOnce(&OpenPathOnThread, + full_path.NormalizePathSeparators()), + std::move(callback)); } void OpenExternal(const GURL& url,
fix
a0a1a3645b7353c010311aff17f6a10048e676bd
Francis Chartrand
2023-04-25 05:19:14
docs: fix start highlight tutorial-2-first-app.md (#38069) doc: fix start highlight tutorial-2-first-app.md
diff --git a/docs/tutorial/tutorial-2-first-app.md b/docs/tutorial/tutorial-2-first-app.md index 0194e2b3be..e30d2dc87d 100644 --- a/docs/tutorial/tutorial-2-first-app.md +++ b/docs/tutorial/tutorial-2-first-app.md @@ -134,7 +134,7 @@ add `electron .` to the `start` command in the [`scripts`][package-scripts] field of your package.json. This command will tell the Electron executable to look for the main script in the current directory and run it in dev mode. -```json {8-10} title='package.json' +```json {7} title='package.json' { "name": "my-electron-app", "version": "1.0.0",
docs
4f76fff97879ee8f9b2d0dcfd43e686ff8757c69
taoky
2024-03-27 17:53:23
fix: don't do self-destroy in LibnotifyNotification::Dismiss() (#41691) Callers of Notification::Dismiss() assume that the notification instance is not deleted after the call, but this was not the case for LibnotifyNotification: - Destroy() would get `this` deleted. - notify_notification_close() in portal environment triggers LibnotifyNotification::OnNotificationClosed(), and finally calls Destroy() This patch removes all Destroy() in Dismiss(), and adds a boolean to tell whether notify_notification_close() is running, to avoid crash under portal environment. Fixes #40461.
diff --git a/shell/browser/notifications/linux/libnotify_notification.cc b/shell/browser/notifications/linux/libnotify_notification.cc index e039b382e3..4c8452fad1 100644 --- a/shell/browser/notifications/linux/libnotify_notification.cc +++ b/shell/browser/notifications/linux/libnotify_notification.cc @@ -159,21 +159,21 @@ void LibnotifyNotification::Show(const NotificationOptions& options) { void LibnotifyNotification::Dismiss() { if (!notification_) { - Destroy(); return; } GError* error = nullptr; + on_dismissing_ = true; libnotify_loader_.notify_notification_close(notification_, &error); if (error) { log_and_clear_error(error, "notify_notification_close"); - Destroy(); } + on_dismissing_ = false; } void LibnotifyNotification::OnNotificationClosed( NotifyNotification* notification) { - NotificationDismissed(); + NotificationDismissed(!on_dismissing_); } void LibnotifyNotification::OnNotificationView(NotifyNotification* notification, diff --git a/shell/browser/notifications/linux/libnotify_notification.h b/shell/browser/notifications/linux/libnotify_notification.h index 8aacd09520..315419fc5c 100644 --- a/shell/browser/notifications/linux/libnotify_notification.h +++ b/shell/browser/notifications/linux/libnotify_notification.h @@ -33,6 +33,7 @@ class LibnotifyNotification : public Notification { RAW_PTR_EXCLUSION NotifyNotification* notification_ = nullptr; ScopedGSignal signal_; + bool on_dismissing_ = false; }; } // namespace electron
fix
200153da8e30bad1ffee3fefad03b1fadd6f9a74
Leon Schwanitz
2022-09-13 18:38:06
docs: fix typescript error in code samples (#35641) Fixed typescript error
diff --git a/docs/fiddles/features/web-serial/main.js b/docs/fiddles/features/web-serial/main.js index 37b9f35c27..7150ec6065 100644 --- a/docs/fiddles/features/web-serial/main.js +++ b/docs/fiddles/features/web-serial/main.js @@ -33,12 +33,16 @@ function createWindow () { if (permission === 'serial' && details.securityOrigin === 'file:///') { return true } + + return false }) mainWindow.webContents.session.setDevicePermissionHandler((details) => { if (details.deviceType === 'serial' && details.origin === 'file://') { return true } + + return false }) mainWindow.loadFile('index.html')
docs
6803624576dc0086b83bdf50051a0dfd96f71401
Shelley Vohr
2024-01-16 14:29:00
fix: check for Node.js-created module when `contextIsolation` disabled (#40993)
diff --git a/patches/node/chore_expose_importmoduledynamically_and.patch b/patches/node/chore_expose_importmoduledynamically_and.patch index 5b7bd5bb23..c28e46b210 100644 --- a/patches/node/chore_expose_importmoduledynamically_and.patch +++ b/patches/node/chore_expose_importmoduledynamically_and.patch @@ -87,7 +87,7 @@ index 52c30dcb47d1faba0c2267e4381a624e450baa02..ba4c1a0d5a987e4d410b49f5c4716694 MaybeLocal<Value> ModuleWrap::SyntheticModuleEvaluationStepsCallback( diff --git a/src/module_wrap.h b/src/module_wrap.h -index 1fc801edced9c5e44613846b4dc555804c5bae97..23a0d7aee1dfa0ebe26e0507e31eacb0b4d137ed 100644 +index 1fc801edced9c5e44613846b4dc555804c5bae97..767d183c6b6b6d97726cf5d63c0b202bd9ae10a6 100644 --- a/src/module_wrap.h +++ b/src/module_wrap.h @@ -30,7 +30,14 @@ enum HostDefinedOptions : int { @@ -106,3 +106,20 @@ index 1fc801edced9c5e44613846b4dc555804c5bae97..23a0d7aee1dfa0ebe26e0507e31eacb0 public: enum InternalFields { kModuleSlot = BaseObject::kInternalFieldCount, +@@ -65,6 +72,8 @@ class ModuleWrap : public BaseObject { + return true; + } + ++ static ModuleWrap* GetFromModule(node::Environment*, v8::Local<v8::Module>); ++ + private: + ModuleWrap(Environment* env, + v8::Local<v8::Object> object, +@@ -99,7 +108,6 @@ class ModuleWrap : public BaseObject { + v8::Local<v8::String> specifier, + v8::Local<v8::FixedArray> import_attributes, + v8::Local<v8::Module> referrer); +- static ModuleWrap* GetFromModule(node::Environment*, v8::Local<v8::Module>); + + v8::Global<v8::Module> module_; + std::unordered_map<std::string, v8::Global<v8::Promise>> resolve_cache_; diff --git a/patches/node/fix_missing_include_for_node_extern.patch b/patches/node/fix_missing_include_for_node_extern.patch index 43e7d2628d..aa9271806e 100644 --- a/patches/node/fix_missing_include_for_node_extern.patch +++ b/patches/node/fix_missing_include_for_node_extern.patch @@ -13,7 +13,7 @@ causing the following error: This should be upstreamed. diff --git a/src/module_wrap.h b/src/module_wrap.h -index 23a0d7aee1dfa0ebe26e0507e31eacb0b4d137ed..0733017d8e1ac6e60589082b402bd44a98ddc312 100644 +index 767d183c6b6b6d97726cf5d63c0b202bd9ae10a6..a134b3817c0a10174ead927589626789851760d0 100644 --- a/src/module_wrap.h +++ b/src/module_wrap.h @@ -7,6 +7,7 @@ diff --git a/shell/common/node_bindings.cc b/shell/common/node_bindings.cc index ca02920f84..9fc4166bd0 100644 --- a/shell/common/node_bindings.cc +++ b/shell/common/node_bindings.cc @@ -119,6 +119,8 @@ ELECTRON_TESTING_BINDINGS(V) #endif #undef V +using node::loader::ModuleWrap; + namespace { void stop_and_close_uv_loop(uv_loop_t* loop) { @@ -209,16 +211,24 @@ v8::MaybeLocal<v8::Promise> HostImportModuleDynamically( void HostInitializeImportMetaObject(v8::Local<v8::Context> context, v8::Local<v8::Module> module, v8::Local<v8::Object> meta) { - if (node::Environment::GetCurrent(context) == nullptr) { + node::Environment* env = node::Environment::GetCurrent(context); + if (env == nullptr) { if (electron::IsBrowserProcess() || electron::IsUtilityProcess()) return; return blink::V8Initializer::HostGetImportMetaProperties(context, module, meta); } - // If we're running with contextIsolation enabled in the renderer process, - // fall back to Blink's logic. if (electron::IsRendererProcess()) { + // If the module is created by Node.js, use Node.js' handling. + if (env != nullptr) { + ModuleWrap* wrap = ModuleWrap::GetFromModule(env, module); + if (wrap) + return ModuleWrap::HostInitializeImportMetaObjectCallback(context, + module, meta); + } + + // If contextIsolation is enabled, fall back to Blink's handling. blink::WebLocalFrame* frame = blink::WebLocalFrame::FrameForContext(context); if (!frame || frame->GetScriptContextWorldId(context) != @@ -228,8 +238,8 @@ void HostInitializeImportMetaObject(v8::Local<v8::Context> context, } } - return node::loader::ModuleWrap::HostInitializeImportMetaObjectCallback( - context, module, meta); + return ModuleWrap::HostInitializeImportMetaObjectCallback(context, module, + meta); } v8::ModifyCodeGenerationFromStringsResult ModifyCodeGenerationFromStrings( diff --git a/spec/esm-spec.ts b/spec/esm-spec.ts index 0e2dbc6d30..c967634a04 100644 --- a/spec/esm-spec.ts +++ b/spec/esm-spec.ts @@ -141,7 +141,7 @@ describe('esm', () => { const hostsUrl = pathToFileURL(process.platform === 'win32' ? 'C:\\Windows\\System32\\drivers\\etc\\hosts' : '/etc/hosts'); describe('without context isolation', () => { - it('should use blinks dynamic loader in the main world', async () => { + it('should use Blinks dynamic loader in the main world', async () => { const [webContents] = await loadWindowWithPreload('', { nodeIntegration: true, sandbox: false, @@ -159,6 +159,11 @@ describe('esm', () => { // This is a blink specific error message expect(error?.message).to.include('Failed to fetch dynamically imported module'); }); + + it('should use import.meta callback handling from Node.js for Node.js modules', async () => { + const result = await runFixture(path.resolve(fixturePath, 'import-meta')); + expect(result.code).to.equal(0); + }); }); describe('with context isolation', () => { @@ -173,7 +178,7 @@ describe('esm', () => { await fs.promises.unlink(badFilePath); }); - it('should use nodes esm dynamic loader in the isolated context', async () => { + it('should use Node.js ESM dynamic loader in the isolated context', async () => { const [, preloadError] = await loadWindowWithPreload(`await import(${JSON.stringify((pathToFileURL(badFilePath)))})`, { nodeIntegration: true, sandbox: false, @@ -185,7 +190,7 @@ describe('esm', () => { expect(preloadError!.toString()).to.include('Unknown file extension'); }); - it('should use blinks dynamic loader in the main world', async () => { + it('should use Blinks dynamic loader in the main world', async () => { const [webContents] = await loadWindowWithPreload('', { nodeIntegration: true, sandbox: false, diff --git a/spec/fixtures/esm/import-meta/index.html b/spec/fixtures/esm/import-meta/index.html new file mode 100644 index 0000000000..6899ed0c0b --- /dev/null +++ b/spec/fixtures/esm/import-meta/index.html @@ -0,0 +1,15 @@ + +<!DOCTYPE html> +<html> + <head> + <meta charset="UTF-8"> + <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'"> + <title>Hello World!</title> + </head> + <body> + <h1>Hello World!</h1> + We are using Node.js <span id="node-version"></span>, + Chromium <span id="chrome-version"></span>, + and Electron <span id="electron-version"></span>. + </body> +</html> diff --git a/spec/fixtures/esm/import-meta/main.mjs b/spec/fixtures/esm/import-meta/main.mjs new file mode 100644 index 0000000000..9b350298c3 --- /dev/null +++ b/spec/fixtures/esm/import-meta/main.mjs @@ -0,0 +1,33 @@ +import { app, BrowserWindow } from 'electron' +import { fileURLToPath } from 'node:url' +import { dirname, join } from 'node:path'; + +async function createWindow() { + const mainWindow = new BrowserWindow({ + show: false, + webPreferences: { + preload: fileURLToPath(new URL('preload.mjs', import.meta.url)), + sandbox: false, + contextIsolation: false + } + }) + + await mainWindow.loadFile('index.html') + + const importMetaPreload = await mainWindow.webContents.executeJavaScript('window.importMetaPath'); + const expected = join(dirname(fileURLToPath(import.meta.url)), 'preload.mjs'); + + process.exit(importMetaPreload === expected ? 0 : 1); +} + +app.whenReady().then(() => { + createWindow() + + app.on('activate', function () { + if (BrowserWindow.getAllWindows().length === 0) createWindow() + }) +}) + +app.on('window-all-closed', function () { + if (process.platform !== 'darwin') app.quit() +}) diff --git a/spec/fixtures/esm/import-meta/package.json b/spec/fixtures/esm/import-meta/package.json new file mode 100644 index 0000000000..13ef5537eb --- /dev/null +++ b/spec/fixtures/esm/import-meta/package.json @@ -0,0 +1,4 @@ +{ + "main": "main.mjs", + "type": "module" +} diff --git a/spec/fixtures/esm/import-meta/preload.mjs b/spec/fixtures/esm/import-meta/preload.mjs new file mode 100644 index 0000000000..c2b5856580 --- /dev/null +++ b/spec/fixtures/esm/import-meta/preload.mjs @@ -0,0 +1,3 @@ +import { fileURLToPath } from 'node:url' + +window.importMetaPath = fileURLToPath(import.meta.url)
fix
99f4a42d4135cf2a596abbb31782485e41734230
Milan Burda
2022-09-20 20:25:33
chore: add missing .eslintrc.json files to limit imports properly (#35719)
diff --git a/lib/browser/.eslintrc.json b/lib/browser/.eslintrc.json index 27d223a509..dab1dafc3f 100644 --- a/lib/browser/.eslintrc.json +++ b/lib/browser/.eslintrc.json @@ -18,4 +18,4 @@ } ] } -} \ No newline at end of file +} diff --git a/lib/common/.eslintrc.json b/lib/common/.eslintrc.json new file mode 100644 index 0000000000..42964484b5 --- /dev/null +++ b/lib/common/.eslintrc.json @@ -0,0 +1,23 @@ +{ + "rules": { + "no-restricted-imports": [ + "error", + { + "paths": [ + "electron", + "electron/main", + "electron/renderer" + ], + "patterns": [ + "./*", + "../*", + "@electron/internal/browser/*", + "@electron/internal/isolated_renderer/*", + "@electron/internal/renderer/*", + "@electron/internal/sandboxed_worker/*", + "@electron/internal/worker/*" + ] + } + ] + } +} diff --git a/lib/common/api/clipboard.ts b/lib/common/api/clipboard.ts index dd03b4f279..55f7958bc7 100644 --- a/lib/common/api/clipboard.ts +++ b/lib/common/api/clipboard.ts @@ -1,5 +1,6 @@ import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages'; +// eslint-disable-next-line no-restricted-imports import type * as ipcRendererUtilsModule from '@electron/internal/renderer/ipc-renderer-internal-utils'; const clipboard = process._linkedBinding('electron_common_clipboard'); diff --git a/lib/isolated_renderer/.eslintrc.json b/lib/isolated_renderer/.eslintrc.json new file mode 100644 index 0000000000..cb5f6cadaa --- /dev/null +++ b/lib/isolated_renderer/.eslintrc.json @@ -0,0 +1,18 @@ +{ + "rules": { + "no-restricted-imports": [ + "error", + { + "paths": [ + "electron", + "electron/main" + ], + "patterns": [ + "./*", + "../*", + "@electron/internal/browser/*" + ] + } + ] + } +} diff --git a/lib/renderer/.eslintrc.json b/lib/renderer/.eslintrc.json new file mode 100644 index 0000000000..cb5f6cadaa --- /dev/null +++ b/lib/renderer/.eslintrc.json @@ -0,0 +1,18 @@ +{ + "rules": { + "no-restricted-imports": [ + "error", + { + "paths": [ + "electron", + "electron/main" + ], + "patterns": [ + "./*", + "../*", + "@electron/internal/browser/*" + ] + } + ] + } +} diff --git a/lib/renderer/common-init.ts b/lib/renderer/common-init.ts index 4ceff37416..bfec34419d 100644 --- a/lib/renderer/common-init.ts +++ b/lib/renderer/common-init.ts @@ -1,4 +1,4 @@ -import { ipcRenderer } from 'electron'; +import { ipcRenderer } from 'electron/renderer'; import { ipcRendererInternal } from '@electron/internal/renderer/ipc-renderer-internal'; import type * as webViewInitModule from '@electron/internal/renderer/web-view/web-view-init'; diff --git a/lib/renderer/inspector.ts b/lib/renderer/inspector.ts index 346de2030e..8dd941d306 100644 --- a/lib/renderer/inspector.ts +++ b/lib/renderer/inspector.ts @@ -2,7 +2,7 @@ import { internalContextBridge } from '@electron/internal/renderer/api/context-b import { ipcRendererInternal } from '@electron/internal/renderer/ipc-renderer-internal'; import * as ipcRendererUtils from '@electron/internal/renderer/ipc-renderer-internal-utils'; import { webFrame } from 'electron/renderer'; -import { IPC_MESSAGES } from '../common/ipc-messages'; +import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages'; const { contextIsolationEnabled } = internalContextBridge; diff --git a/lib/renderer/web-frame-init.ts b/lib/renderer/web-frame-init.ts index 37225cfb34..ac4db7f9a7 100644 --- a/lib/renderer/web-frame-init.ts +++ b/lib/renderer/web-frame-init.ts @@ -1,4 +1,4 @@ -import { webFrame, WebFrame } from 'electron'; +import { webFrame, WebFrame } from 'electron/renderer'; import * as ipcRendererUtils from '@electron/internal/renderer/ipc-renderer-internal-utils'; import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages'; diff --git a/lib/sandboxed_renderer/.eslintrc.json b/lib/sandboxed_renderer/.eslintrc.json new file mode 100644 index 0000000000..cb5f6cadaa --- /dev/null +++ b/lib/sandboxed_renderer/.eslintrc.json @@ -0,0 +1,18 @@ +{ + "rules": { + "no-restricted-imports": [ + "error", + { + "paths": [ + "electron", + "electron/main" + ], + "patterns": [ + "./*", + "../*", + "@electron/internal/browser/*" + ] + } + ] + } +} diff --git a/lib/worker/.eslintrc.json b/lib/worker/.eslintrc.json new file mode 100644 index 0000000000..cb5f6cadaa --- /dev/null +++ b/lib/worker/.eslintrc.json @@ -0,0 +1,18 @@ +{ + "rules": { + "no-restricted-imports": [ + "error", + { + "paths": [ + "electron", + "electron/main" + ], + "patterns": [ + "./*", + "../*", + "@electron/internal/browser/*" + ] + } + ] + } +}
chore
e7156071786d98e08dc9c9a61a35c5807746d44b
Keeley Hammond
2025-01-28 11:59:04
build: use Python311 exe (#45360) build: yse Python311 exe
diff --git a/.github/actions/install-build-tools/action.yml b/.github/actions/install-build-tools/action.yml index f84472b4b1..0dca6d0130 100644 --- a/.github/actions/install-build-tools/action.yml +++ b/.github/actions/install-build-tools/action.yml @@ -16,5 +16,5 @@ runs: e auto-update disable if [ "$(expr substr $(uname -s) 1 10)" == "MSYS_NT-10" ]; then e d cipd.bat --version - cp "C:\Python37\python.exe" "C:\Python37\python3.exe" + cp "C:\Python311\python.exe" "C:\Python311\python3.exe" fi
build
fcdd5cba71b82c13c4f64a3e529dea91ed72d23c
Shelley Vohr
2023-10-31 11:59:39
fix: `navigator.keyboard.lock()` fullscreen exit handling (#40365) fix: navigator.keyboard.lock() fullscreen exit handling
diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc index 6e64b7bdac..cb66a8d963 100644 --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -1334,12 +1334,6 @@ bool WebContents::HandleKeyboardEvent( bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { - // Escape exits tabbed fullscreen mode. - if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { - ExitFullscreenModeForTab(source); - return true; - } - // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) diff --git a/shell/browser/api/electron_api_web_contents_mac.mm b/shell/browser/api/electron_api_web_contents_mac.mm index e93597e996..bf1c69dbf5 100644 --- a/shell/browser/api/electron_api_web_contents_mac.mm +++ b/shell/browser/api/electron_api_web_contents_mac.mm @@ -42,12 +42,6 @@ bool WebContents::PlatformHandleKeyboardEvent( event.GetType() == content::NativeWebKeyboardEvent::Type::kChar) return false; - // Escape exits tabbed fullscreen mode. - if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { - ExitFullscreenModeForTab(source); - return true; - } - // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) diff --git a/spec/chromium-spec.ts b/spec/chromium-spec.ts index 98973558e9..6d21d1a0c7 100644 --- a/spec/chromium-spec.ts +++ b/spec/chromium-spec.ts @@ -606,6 +606,63 @@ describe('chromium features', () => { }); }); + describe('navigator.keyboard', () => { + afterEach(closeAllWindows); + + it('getLayoutMap() should return a KeyboardLayoutMap object', async () => { + const w = new BrowserWindow({ show: false }); + await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); + const size = await w.webContents.executeJavaScript(` + navigator.keyboard.getLayoutMap().then(map => map.size) + `); + + expect(size).to.be.a('number'); + }); + + it('should lock the keyboard', async () => { + const w = new BrowserWindow({ show: false }); + await w.loadFile(path.join(fixturesPath, 'pages', 'modal.html')); + + // Test that without lock, with ESC: + // - the window leaves fullscreen + // - the dialog is not closed + const enterFS1 = once(w, 'enter-full-screen'); + await w.webContents.executeJavaScript('document.body.requestFullscreen()', true); + await enterFS1; + + await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').showModal()', true); + const open1 = await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').open'); + expect(open1).to.be.true(); + + w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); + await setTimeout(1000); + const openAfter1 = await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').open'); + expect(openAfter1).to.be.true(); + expect(w.isFullScreen()).to.be.false(); + + // Test that with lock, with ESC: + // - the window does not leave fullscreen + // - the dialog is closed + const enterFS2 = once(w, 'enter-full-screen'); + await w.webContents.executeJavaScript(` + navigator.keyboard.lock(['Escape']); + document.body.requestFullscreen(); + `, true); + + await enterFS2; + + await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').showModal()', true); + const open2 = await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').open'); + expect(open2).to.be.true(); + + w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); + await setTimeout(1000); + const openAfter2 = await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').open'); + expect(openAfter2).to.be.false(); + expect(w.isFullScreen()).to.be.true(); + }); + }); + describe('navigator.languages', () => { it('should return the system locale only', async () => { const appLocale = app.getLocale(); diff --git a/spec/fixtures/pages/modal.html b/spec/fixtures/pages/modal.html new file mode 100644 index 0000000000..28b9e6b2c9 --- /dev/null +++ b/spec/fixtures/pages/modal.html @@ -0,0 +1,26 @@ +<!DOCTYPE html> +<html lang="en"> + +<body> + <dialog id="favDialog"> + <form> + <p> + <label> + Favorite animal: + <select> + <option value="default">Choose…</option> + <option>Brine shrimp</option> + <option>Red panda</option> + <option>Spider monkey</option> + </select> + </label> + </p> + <div> + <button value="cancel" formmethod="dialog">Cancel</button> + <button id="confirmBtn" value="default">Confirm</button> + </div> + </form> + </dialog> +</body> + +</html> \ No newline at end of file diff --git a/spec/webview-spec.ts b/spec/webview-spec.ts index 17b222ef40..7563fef1a5 100644 --- a/spec/webview-spec.ts +++ b/spec/webview-spec.ts @@ -547,17 +547,16 @@ describe('<webview> tag', function () { await close; }); - // Sending ESC via sendInputEvent only works on Windows. - ifit(process.platform === 'win32')('pressing ESC should unfullscreen window', async () => { + it('pressing ESC should unfullscreen window', async () => { const [w, webview] = await loadWebViewWindow(); const enterFullScreen = once(w, 'enter-full-screen'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); - w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); + webview.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); await leaveFullScreen; - await setTimeout(); + await setTimeout(1000); expect(w.isFullScreen()).to.be.false(); const close = once(w, 'closed');
fix
aeb89b143b5c61f52d8852ab247297ea2b2045b5
Shelley Vohr
2023-08-17 16:42:53
chore: cleanup asar initialization logic (#39532)
diff --git a/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch b/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch index 68519aef7e..55d58d9b82 100644 --- a/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch +++ b/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch @@ -26,10 +26,10 @@ index 001343b74ce236f89dca030c0fc9dd0299df0b39..6f277daf4ce846f093f634c473daec07 try { resolvedArgv = Module._resolveFilename(process.argv[1], null, false); diff --git a/lib/internal/process/pre_execution.js b/lib/internal/process/pre_execution.js -index 2e35cbba2ac02494c44821af395fe0195b1ab6b5..f5b6fecf6843a6204ec532a77f39a36d33bf061d 100644 +index 4e7a9e7a7585fea2013ff70161672568477172b1..f96d19969aa59a9964d947a9fd6295cf25ad3b03 100644 --- a/lib/internal/process/pre_execution.js +++ b/lib/internal/process/pre_execution.js -@@ -149,11 +149,13 @@ function patchProcessObject(expandArgv1) { +@@ -151,11 +151,13 @@ function patchProcessObject(expandArgv1) { if (expandArgv1 && process.argv[1] && !StringPrototypeStartsWith(process.argv[1], '-')) { // Expand process.argv[1] into a full path. diff --git a/patches/node/feat_initialize_asar_support.patch b/patches/node/feat_initialize_asar_support.patch index ccdc9a9bd4..6303ab63a4 100644 --- a/patches/node/feat_initialize_asar_support.patch +++ b/patches/node/feat_initialize_asar_support.patch @@ -5,25 +5,20 @@ Subject: feat: initialize asar support This patch initializes asar support in Node.js. -diff --git a/lib/internal/process/policy.js b/lib/internal/process/policy.js -index 8e07cb92118c84b2bc1156532cae8b033b9a48f4..2073a024ad548fe80e84cafee012b003454d6c93 100644 ---- a/lib/internal/process/policy.js -+++ b/lib/internal/process/policy.js -@@ -39,9 +39,6 @@ module.exports = ObjectFreeze({ - process.binding = function binding(_module) { - throw new ERR_ACCESS_DENIED('process.binding'); - }; -- process._linkedBinding = function _linkedBinding(_module) { -- throw new ERR_ACCESS_DENIED('process._linkedBinding'); -- }; - }, - - get manifest() { diff --git a/lib/internal/process/pre_execution.js b/lib/internal/process/pre_execution.js -index 250a43c5455b4f9ff72dd3a34d5b0aa270f43cc6..2e35cbba2ac02494c44821af395fe0195b1ab6b5 100644 +index 250a43c5455b4f9ff72dd3a34d5b0aa270f43cc6..4e7a9e7a7585fea2013ff70161672568477172b1 100644 --- a/lib/internal/process/pre_execution.js +++ b/lib/internal/process/pre_execution.js -@@ -117,12 +117,17 @@ function setupUserModules() { +@@ -49,6 +49,8 @@ function prepareWorkerThreadExecution() { + }); + } + ++ ++let processLinkedBinding = process._linkedBinding; + function prepareExecution(options) { + const { expandArgv1, initializeModules, isMainThread } = options; + +@@ -117,12 +119,17 @@ function setupUserModules() { loadPreloadModules(); // Need to be done after --require setup. initializeFrozenIntrinsics(); @@ -35,20 +30,9 @@ index 250a43c5455b4f9ff72dd3a34d5b0aa270f43cc6..2e35cbba2ac02494c44821af395fe019 } +function setupAsarSupport() { -+ process._linkedBinding('electron_common_asar').initAsarSupport(require); ++ processLinkedBinding('electron_common_asar').initAsarSupport(require); +} + function patchProcessObject(expandArgv1) { const binding = internalBinding('process_methods'); binding.patchProcessObject(process); -diff --git a/test/fixtures/policy/process-binding/app.js b/test/fixtures/policy/process-binding/app.js -index 16e26d12a160286b1b6aaeb64b15668b05b9865b..a287d0a2363acbf24077eec040116f96ef18a7b3 100644 ---- a/test/fixtures/policy/process-binding/app.js -+++ b/test/fixtures/policy/process-binding/app.js -@@ -5,6 +5,3 @@ const assert = require('assert'); - assert.throws(() => { process.binding(); }, { - code: 'ERR_ACCESS_DENIED' - }); --assert.throws(() => { process._linkedBinding(); }, { -- code: 'ERR_ACCESS_DENIED' --});
chore
c2c079dc820d7edbac3f875ab4ef8b3444237253
David Sanders
2024-07-25 02:00:32
build: update docs-parser and typescript-definitions packages (#43038) build: update docs-parser and typescript-definitions pacakges
diff --git a/package.json b/package.json index 42e13783f1..27c18b17ef 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "devDependencies": { "@azure/storage-blob": "^12.9.0", "@electron/asar": "^3.2.1", - "@electron/docs-parser": "^1.2.0", + "@electron/docs-parser": "^1.2.1", "@electron/fiddle-core": "^1.0.4", "@electron/github-app-auth": "^2.0.0", "@electron/lint-roller": "^2.3.0", diff --git a/yarn.lock b/yarn.lock index 3b6a72139e..6693c69956 100644 --- a/yarn.lock +++ b/yarn.lock @@ -146,10 +146,10 @@ optionalDependencies: "@types/glob" "^7.1.1" -"@electron/docs-parser@^1.2.0": - version "1.2.0" - resolved "https://registry.yarnpkg.com/@electron/docs-parser/-/docs-parser-1.2.0.tgz#dc3032012dd270c667777e097e185d92e7ff86ef" - integrity sha512-Rz/lMLRDSvEshYNmSC30v/3rk7Mj6EL/76wraKvfM5XvYPHsmApo9CedvcJNNMm7+Rc29NOohoqA4B2/XtFm1Q== +"@electron/docs-parser@^1.2.1": + version "1.2.1" + resolved "https://registry.yarnpkg.com/@electron/docs-parser/-/docs-parser-1.2.1.tgz#ee0b4e686c1117605aa3c22bd0e1786f2f19d8aa" + integrity sha512-kgYcZS/OkfB+2+v4e72wknJ/Eo0UJIaxMTkCshTFRjuGTLIp/J1ZFNxHOWJHp7InJD6mc/VjjIc6bMCoxtA1Rw== dependencies: "@types/markdown-it" "^12.0.0" chai "^4.2.0" @@ -222,9 +222,9 @@ yaml "^2.4.5" "@electron/typescript-definitions@^8.15.2": - version "8.15.6" - resolved "https://registry.yarnpkg.com/@electron/typescript-definitions/-/typescript-definitions-8.15.6.tgz#a578ee3de6e6dcfdb5765da58f303900a34b2d06" - integrity sha512-9YR2jG7AdRLvZMhQLgTljZzkoaKNP1wbQq+/qjBCCCCCbUpECvMRk1/UeuZErZEmddhSYanQZgXiftF1T072uQ== + version "8.15.7" + resolved "https://registry.yarnpkg.com/@electron/typescript-definitions/-/typescript-definitions-8.15.7.tgz#7a39c611ac6878017be66bafd4103d62fc322d23" + integrity sha512-fJiElhj3yfJ3tilRohEikfGpfJ1cD7RWv3BpgZgsP7dfCVt4Jm2UeEDGGAL9gQIlk7jDetngIW6tcNrL1INWOg== dependencies: "@types/node" "^11.13.7" chalk "^2.4.2"
build
8fdd7de3d27d159479b653c932feb0950b79738a
Milan Burda
2023-06-05 08:57:15
docs: clarify which electron modules are exposed in sandboxed renderers (#38568)
diff --git a/docs/tutorial/sandbox.md b/docs/tutorial/sandbox.md index 472b1900ef..20259c9299 100644 --- a/docs/tutorial/sandbox.md +++ b/docs/tutorial/sandbox.md @@ -46,7 +46,7 @@ scripts attached to sandboxed renderers will still have a polyfilled subset of N APIs available. A `require` function similar to Node's `require` module is exposed, but can only import a subset of Electron and Node's built-in modules: -* `electron` (only renderer process modules) +* `electron` (following renderer process modules: `contextBridge`, `crashReporter`, `ipcRenderer`, `nativeImage`, `webFrame`) * [`events`](https://nodejs.org/api/events.html) * [`timers`](https://nodejs.org/api/timers.html) * [`url`](https://nodejs.org/api/url.html)
docs
5c1321b20ad3b375b9ef5f8f6267d78ee306bdc3
Charles Kerr
2023-06-06 14:03:39
refactor: remove redundant resizing strategy equality check (#38596) * refactor: remove redundant resizing strategy equality check Upstream already checks this.
diff --git a/shell/browser/ui/inspectable_web_contents.cc b/shell/browser/ui/inspectable_web_contents.cc index 643d229be6..f67043d8c5 100644 --- a/shell/browser/ui/inspectable_web_contents.cc +++ b/shell/browser/ui/inspectable_web_contents.cc @@ -21,6 +21,7 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" +#include "chrome/browser/devtools/devtools_contents_resizing_strategy.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" @@ -624,13 +625,8 @@ void InspectableWebContents::AddDevToolsExtensionsToClient() { #endif void InspectableWebContents::SetInspectedPageBounds(const gfx::Rect& rect) { - DevToolsContentsResizingStrategy strategy(rect); - if (contents_resizing_strategy_.Equals(strategy)) - return; - - contents_resizing_strategy_.CopyFrom(strategy); if (managed_devtools_web_contents_) - view_->SetContentsResizingStrategy(contents_resizing_strategy_); + view_->SetContentsResizingStrategy(DevToolsContentsResizingStrategy{rect}); } void InspectableWebContents::InspectElementCompleted() {} diff --git a/shell/browser/ui/inspectable_web_contents.h b/shell/browser/ui/inspectable_web_contents.h index 6c514a63be..1a3ea3855a 100644 --- a/shell/browser/ui/inspectable_web_contents.h +++ b/shell/browser/ui/inspectable_web_contents.h @@ -10,15 +10,12 @@ #include <memory> #include <set> #include <string> -#include <vector> #include "base/containers/span.h" #include "base/containers/unique_ptr_adapters.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" -#include "chrome/browser/devtools/devtools_contents_resizing_strategy.h" #include "chrome/browser/devtools/devtools_embedder_message_dispatcher.h" -#include "chrome/browser/devtools/devtools_settings.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/devtools_frontend_host.h" #include "content/public/browser/web_contents_delegate.h" @@ -202,7 +199,6 @@ class InspectableWebContents void AddDevToolsExtensionsToClient(); #endif - DevToolsContentsResizingStrategy contents_resizing_strategy_; gfx::Rect devtools_bounds_; bool can_dock_ = true; std::string dock_state_;
refactor
00746e662bf2cc128cbcade58b525fffe717d2e2
Shelley Vohr
2023-08-17 14:17:55
feat: allow headers to be sent with `webContents.downloadURL()` (#39455) feat: allow headers to be sent with webContents.downloadURL()
diff --git a/docs/api/session.md b/docs/api/session.md index d157e3464a..d13ccf009c 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -1311,7 +1311,7 @@ The API will generate a [DownloadItem](download-item.md) that can be accessed with the [will-download](#event-will-download) event. **Note:** This does not perform any security checks that relate to a page's origin, -unlike [`webContents.downloadURL`](web-contents.md#contentsdownloadurlurl). +unlike [`webContents.downloadURL`](web-contents.md#contentsdownloadurlurl-options). #### `ses.createInterruptedDownload(options)` diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index de9c66ed5e..715885369a 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -1046,9 +1046,11 @@ const win = new BrowserWindow() win.loadFile('src/index.html') ``` -#### `contents.downloadURL(url)` +#### `contents.downloadURL(url[, options])` * `url` string +* `options` Object (optional) + * `headers` Record<string, string> (optional) - HTTP request headers. Initiates a download of the resource at `url` without navigating. The `will-download` event of `session` will be triggered. diff --git a/docs/api/webview-tag.md b/docs/api/webview-tag.md index 340365b78c..825921b9be 100644 --- a/docs/api/webview-tag.md +++ b/docs/api/webview-tag.md @@ -280,9 +280,11 @@ if the page fails to load (see Loads the `url` in the webview, the `url` must contain the protocol prefix, e.g. the `http://` or `file://`. -### `<webview>.downloadURL(url)` +### `<webview>.downloadURL(url[, options])` * `url` string +* `options` Object (optional) + * `headers` Record<string, string> (optional) - HTTP request headers. Initiates a download of the resource at `url` without navigating. diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc index 993861fe58..069b777856 100644 --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -2444,12 +2444,25 @@ void WebContents::ReloadIgnoringCache() { /* check_for_repost */ true); } -void WebContents::DownloadURL(const GURL& url) { - auto* browser_context = web_contents()->GetBrowserContext(); - auto* download_manager = browser_context->GetDownloadManager(); +void WebContents::DownloadURL(const GURL& url, gin::Arguments* args) { + std::map<std::string, std::string> headers; + gin_helper::Dictionary options; + if (args->GetNext(&options)) { + if (options.Has("headers") && !options.Get("headers", &headers)) { + args->ThrowTypeError("Invalid value for headers - must be an object"); + return; + } + } + std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); + for (const auto& [name, value] : headers) { + download_params->add_request_header(name, value); + } + + auto* download_manager = + web_contents()->GetBrowserContext()->GetDownloadManager(); download_manager->DownloadUrl(std::move(download_params)); } diff --git a/shell/browser/api/electron_api_web_contents.h b/shell/browser/api/electron_api_web_contents.h index ae3d9ecd19..d0c65fd4b4 100644 --- a/shell/browser/api/electron_api_web_contents.h +++ b/shell/browser/api/electron_api_web_contents.h @@ -169,7 +169,7 @@ class WebContents : public ExclusiveAccessContext, void LoadURL(const GURL& url, const gin_helper::Dictionary& options); void Reload(); void ReloadIgnoringCache(); - void DownloadURL(const GURL& url); + void DownloadURL(const GURL& url, gin::Arguments* args); GURL GetURL() const; std::u16string GetTitle() const; bool IsLoading() const; diff --git a/spec/api-session-spec.ts b/spec/api-session-spec.ts index 592d43eb69..614ec6cba6 100644 --- a/spec/api-session-spec.ts +++ b/spec/api-session-spec.ts @@ -827,277 +827,383 @@ describe('session module', () => { fs.unlinkSync(downloadFilePath); }; - it('can download using session.downloadURL', (done) => { - session.defaultSession.once('will-download', function (e, item) { - item.savePath = downloadFilePath; - item.on('done', function (e, state) { - try { - assertDownload(state, item); - done(); - } catch (e) { - done(e); - } + describe('session.downloadURL', () => { + it('can perform a download', (done) => { + session.defaultSession.once('will-download', function (e, item) { + item.savePath = downloadFilePath; + item.on('done', function (e, state) { + try { + assertDownload(state, item); + done(); + } catch (e) { + done(e); + } + }); }); + session.defaultSession.downloadURL(`${url}:${port}`); }); - session.defaultSession.downloadURL(`${url}:${port}`); - }); - it('can download using session.downloadURL with a valid auth header', async () => { - const server = http.createServer((req, res) => { - const { authorization } = req.headers; - if (!authorization || authorization !== 'Basic i-am-an-auth-header') { - res.statusCode = 401; - res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"'); - res.end(); - } else { - res.writeHead(200, { - 'Content-Length': mockPDF.length, - 'Content-Type': 'application/pdf', - 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition - }); - res.end(mockPDF); - } - }); + it('can perform a download with a valid auth header', async () => { + const server = http.createServer((req, res) => { + const { authorization } = req.headers; + if (!authorization || authorization !== 'Basic i-am-an-auth-header') { + res.statusCode = 401; + res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"'); + res.end(); + } else { + res.writeHead(200, { + 'Content-Length': mockPDF.length, + 'Content-Type': 'application/pdf', + 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition + }); + res.end(mockPDF); + } + }); - const { port } = await listen(server); + const { port } = await listen(server); - const downloadDone: Promise<Electron.DownloadItem> = new Promise((resolve) => { - session.defaultSession.once('will-download', (e, item) => { - item.savePath = downloadFilePath; - item.on('done', () => { - try { - resolve(item); - } catch {} + const downloadDone: Promise<Electron.DownloadItem> = new Promise((resolve) => { + session.defaultSession.once('will-download', (e, item) => { + item.savePath = downloadFilePath; + item.on('done', () => { + try { + resolve(item); + } catch { } + }); }); }); + + session.defaultSession.downloadURL(`${url}:${port}`, { + headers: { + Authorization: 'Basic i-am-an-auth-header' + } + }); + + const item = await downloadDone; + expect(item.getState()).to.equal('completed'); + expect(item.getFilename()).to.equal('mock.pdf'); + expect(item.getMimeType()).to.equal('application/pdf'); + expect(item.getReceivedBytes()).to.equal(mockPDF.length); + expect(item.getTotalBytes()).to.equal(mockPDF.length); + expect(item.getContentDisposition()).to.equal(contentDisposition); }); - session.defaultSession.downloadURL(`${url}:${port}`, { - headers: { - Authorization: 'Basic i-am-an-auth-header' - } + it('throws when called with invalid headers', () => { + expect(() => { + session.defaultSession.downloadURL(`${url}:${port}`, { + // @ts-ignore this line is intentionally incorrect + headers: 'i-am-a-bad-header' + }); + }).to.throw(/Invalid value for headers - must be an object/); }); - const item = await downloadDone; - expect(item.getState()).to.equal('completed'); - expect(item.getFilename()).to.equal('mock.pdf'); - expect(item.getMimeType()).to.equal('application/pdf'); - expect(item.getReceivedBytes()).to.equal(mockPDF.length); - expect(item.getTotalBytes()).to.equal(mockPDF.length); - expect(item.getContentDisposition()).to.equal(contentDisposition); - }); + it('correctly handles a download with an invalid auth header', async () => { + const server = http.createServer((req, res) => { + const { authorization } = req.headers; + if (!authorization || authorization !== 'Basic i-am-an-auth-header') { + res.statusCode = 401; + res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"'); + res.end(); + } else { + res.writeHead(200, { + 'Content-Length': mockPDF.length, + 'Content-Type': 'application/pdf', + 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition + }); + res.end(mockPDF); + } + }); + + const { port } = await listen(server); + + const downloadFailed: Promise<Electron.DownloadItem> = new Promise((resolve) => { + session.defaultSession.once('will-download', (_, item) => { + item.savePath = downloadFilePath; + item.on('done', (e, state) => { + console.log(state); + try { + resolve(item); + } catch { } + }); + }); + }); - it('throws when session.downloadURL is called with invalid headers', () => { - expect(() => { session.defaultSession.downloadURL(`${url}:${port}`, { - // @ts-ignore this line is intentionally incorrect - headers: 'i-am-a-bad-header' + headers: { + Authorization: 'wtf-is-this' + } }); - }).to.throw(/Invalid value for headers - must be an object/); - }); - it('can download using session.downloadURL with an invalid auth header', async () => { - const server = http.createServer((req, res) => { - const { authorization } = req.headers; - if (!authorization || authorization !== 'Basic i-am-an-auth-header') { - res.statusCode = 401; - res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"'); - res.end(); - } else { - res.writeHead(200, { - 'Content-Length': mockPDF.length, - 'Content-Type': 'application/pdf', - 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition - }); - res.end(mockPDF); - } + const item = await downloadFailed; + expect(item.getState()).to.equal('interrupted'); + expect(item.getReceivedBytes()).to.equal(0); + expect(item.getTotalBytes()).to.equal(0); }); + }); - const { port } = await listen(server); - - const downloadFailed: Promise<Electron.DownloadItem> = new Promise((resolve) => { - session.defaultSession.once('will-download', (_, item) => { + describe('webContents.downloadURL', () => { + it('can perform a download', (done) => { + const w = new BrowserWindow({ show: false }); + w.webContents.session.once('will-download', function (e, item) { item.savePath = downloadFilePath; - item.on('done', (e, state) => { - console.log(state); + item.on('done', function (e, state) { try { - resolve(item); - } catch {} + assertDownload(state, item); + done(); + } catch (e) { + done(e); + } }); }); + w.webContents.downloadURL(`${url}:${port}`); }); - session.defaultSession.downloadURL(`${url}:${port}`, { - headers: { - Authorization: 'wtf-is-this' - } - }); + it('can perform a download with a valid auth header', async () => { + const server = http.createServer((req, res) => { + const { authorization } = req.headers; + if (!authorization || authorization !== 'Basic i-am-an-auth-header') { + res.statusCode = 401; + res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"'); + res.end(); + } else { + res.writeHead(200, { + 'Content-Length': mockPDF.length, + 'Content-Type': 'application/pdf', + 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition + }); + res.end(mockPDF); + } + }); - const item = await downloadFailed; - expect(item.getState()).to.equal('interrupted'); - expect(item.getReceivedBytes()).to.equal(0); - expect(item.getTotalBytes()).to.equal(0); - }); + const { port } = await listen(server); - it('can download using WebContents.downloadURL', (done) => { - const w = new BrowserWindow({ show: false }); - w.webContents.session.once('will-download', function (e, item) { - item.savePath = downloadFilePath; - item.on('done', function (e, state) { - try { - assertDownload(state, item); - done(); - } catch (e) { - done(e); + const w = new BrowserWindow({ show: false }); + const downloadDone: Promise<Electron.DownloadItem> = new Promise((resolve) => { + w.webContents.session.once('will-download', (e, item) => { + item.savePath = downloadFilePath; + item.on('done', () => { + try { + resolve(item); + } catch { } + }); + }); + }); + + w.webContents.downloadURL(`${url}:${port}`, { + headers: { + Authorization: 'Basic i-am-an-auth-header' } }); + + const item = await downloadDone; + expect(item.getState()).to.equal('completed'); + expect(item.getFilename()).to.equal('mock.pdf'); + expect(item.getMimeType()).to.equal('application/pdf'); + expect(item.getReceivedBytes()).to.equal(mockPDF.length); + expect(item.getTotalBytes()).to.equal(mockPDF.length); + expect(item.getContentDisposition()).to.equal(contentDisposition); }); - w.webContents.downloadURL(`${url}:${port}`); - }); - it('can download from custom protocols using WebContents.downloadURL', (done) => { - const protocol = session.defaultSession.protocol; - const handler = (ignoredError: any, callback: Function) => { - callback({ url: `${url}:${port}` }); - }; - protocol.registerHttpProtocol(protocolName, handler); - const w = new BrowserWindow({ show: false }); - w.webContents.session.once('will-download', function (e, item) { - item.savePath = downloadFilePath; - item.on('done', function (e, state) { - try { - assertDownload(state, item, true); - done(); - } catch (e) { - done(e); + it('throws when called with invalid headers', () => { + const w = new BrowserWindow({ show: false }); + expect(() => { + w.webContents.downloadURL(`${url}:${port}`, { + // @ts-ignore this line is intentionally incorrect + headers: 'i-am-a-bad-header' + }); + }).to.throw(/Invalid value for headers - must be an object/); + }); + + it('correctly handles a download and an invalid auth header', async () => { + const server = http.createServer((req, res) => { + const { authorization } = req.headers; + if (!authorization || authorization !== 'Basic i-am-an-auth-header') { + res.statusCode = 401; + res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"'); + res.end(); + } else { + res.writeHead(200, { + 'Content-Length': mockPDF.length, + 'Content-Type': 'application/pdf', + 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition + }); + res.end(mockPDF); } }); - }); - w.webContents.downloadURL(`${protocolName}://item`); - }); - it('can download using WebView.downloadURL', async () => { - const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); - await w.loadURL('about:blank'); - function webviewDownload ({ fixtures, url, port }: {fixtures: string, url: string, port: string}) { - const webview = new (window as any).WebView(); - webview.addEventListener('did-finish-load', () => { - webview.downloadURL(`${url}:${port}/`); + const { port } = await listen(server); + + const w = new BrowserWindow({ show: false }); + const downloadFailed: Promise<Electron.DownloadItem> = new Promise((resolve) => { + w.webContents.session.once('will-download', (_, item) => { + item.savePath = downloadFilePath; + item.on('done', (e, state) => { + console.log(state); + try { + resolve(item); + } catch { } + }); + }); + }); + + w.webContents.downloadURL(`${url}:${port}`, { + headers: { + Authorization: 'wtf-is-this' + } }); - webview.src = `file://${fixtures}/api/blank.html`; - document.body.appendChild(webview); - } - const done: Promise<[string, Electron.DownloadItem]> = new Promise(resolve => { + + const item = await downloadFailed; + expect(item.getState()).to.equal('interrupted'); + expect(item.getReceivedBytes()).to.equal(0); + expect(item.getTotalBytes()).to.equal(0); + }); + + it('can download from custom protocols', (done) => { + const protocol = session.defaultSession.protocol; + const handler = (ignoredError: any, callback: Function) => { + callback({ url: `${url}:${port}` }); + }; + protocol.registerHttpProtocol(protocolName, handler); + const w = new BrowserWindow({ show: false }); w.webContents.session.once('will-download', function (e, item) { item.savePath = downloadFilePath; item.on('done', function (e, state) { - resolve([state, item]); + try { + assertDownload(state, item, true); + done(); + } catch (e) { + done(e); + } }); }); + w.webContents.downloadURL(`${protocolName}://item`); }); - await w.webContents.executeJavaScript(`(${webviewDownload})(${JSON.stringify({ fixtures, url, port })})`); - const [state, item] = await done; - assertDownload(state, item); - }); - it('can cancel download', (done) => { - const w = new BrowserWindow({ show: false }); - w.webContents.session.once('will-download', function (e, item) { - item.savePath = downloadFilePath; - item.on('done', function (e, state) { - try { - expect(state).to.equal('cancelled'); - expect(item.getFilename()).to.equal('mock.pdf'); - expect(item.getMimeType()).to.equal('application/pdf'); - expect(item.getReceivedBytes()).to.equal(0); - expect(item.getTotalBytes()).to.equal(mockPDF.length); - expect(item.getContentDisposition()).to.equal(contentDisposition); - done(); - } catch (e) { - done(e); - } + it('can cancel download', (done) => { + const w = new BrowserWindow({ show: false }); + w.webContents.session.once('will-download', function (e, item) { + item.savePath = downloadFilePath; + item.on('done', function (e, state) { + try { + expect(state).to.equal('cancelled'); + expect(item.getFilename()).to.equal('mock.pdf'); + expect(item.getMimeType()).to.equal('application/pdf'); + expect(item.getReceivedBytes()).to.equal(0); + expect(item.getTotalBytes()).to.equal(mockPDF.length); + expect(item.getContentDisposition()).to.equal(contentDisposition); + done(); + } catch (e) { + done(e); + } + }); + item.cancel(); }); - item.cancel(); + w.webContents.downloadURL(`${url}:${port}/`); }); - w.webContents.downloadURL(`${url}:${port}/`); - }); - it('can generate a default filename', function (done) { - if (process.env.APPVEYOR === 'True') { - // FIXME(alexeykuzmin): Skip the test. - // this.skip() - return done(); - } + it('can generate a default filename', function (done) { + if (process.env.APPVEYOR === 'True') { + // FIXME(alexeykuzmin): Skip the test. + // this.skip() + return done(); + } - const w = new BrowserWindow({ show: false }); - w.webContents.session.once('will-download', function (e, item) { - item.savePath = downloadFilePath; - item.on('done', function () { - try { - expect(item.getFilename()).to.equal('download.pdf'); - done(); - } catch (e) { - done(e); - } + const w = new BrowserWindow({ show: false }); + w.webContents.session.once('will-download', function (e, item) { + item.savePath = downloadFilePath; + item.on('done', function () { + try { + expect(item.getFilename()).to.equal('download.pdf'); + done(); + } catch (e) { + done(e); + } + }); + item.cancel(); }); - item.cancel(); + w.webContents.downloadURL(`${url}:${port}/?testFilename`); }); - w.webContents.downloadURL(`${url}:${port}/?testFilename`); - }); - - it('can set options for the save dialog', (done) => { - const filePath = path.join(__dirname, 'fixtures', 'mock.pdf'); - const options = { - window: null, - title: 'title', - message: 'message', - buttonLabel: 'buttonLabel', - nameFieldLabel: 'nameFieldLabel', - defaultPath: '/', - filters: [{ - name: '1', extensions: ['.1', '.2'] - }, { - name: '2', extensions: ['.3', '.4', '.5'] - }], - showsTagField: true, - securityScopedBookmarks: true - }; - const w = new BrowserWindow({ show: false }); - w.webContents.session.once('will-download', function (e, item) { - item.setSavePath(filePath); - item.setSaveDialogOptions(options); - item.on('done', function () { - try { - expect(item.getSaveDialogOptions()).to.deep.equal(options); - done(); - } catch (e) { - done(e); - } - }); - item.cancel(); - }); - w.webContents.downloadURL(`${url}:${port}`); - }); + it('can set options for the save dialog', (done) => { + const filePath = path.join(__dirname, 'fixtures', 'mock.pdf'); + const options = { + window: null, + title: 'title', + message: 'message', + buttonLabel: 'buttonLabel', + nameFieldLabel: 'nameFieldLabel', + defaultPath: '/', + filters: [{ + name: '1', extensions: ['.1', '.2'] + }, { + name: '2', extensions: ['.3', '.4', '.5'] + }], + showsTagField: true, + securityScopedBookmarks: true + }; - describe('when a save path is specified and the URL is unavailable', () => { - it('does not display a save dialog and reports the done state as interrupted', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.session.once('will-download', function (e, item) { - item.savePath = downloadFilePath; - if (item.getState() === 'interrupted') { - item.resume(); - } - item.on('done', function (e, state) { + item.setSavePath(filePath); + item.setSaveDialogOptions(options); + item.on('done', function () { try { - expect(state).to.equal('interrupted'); + expect(item.getSaveDialogOptions()).to.deep.equal(options); done(); } catch (e) { done(e); } }); + item.cancel(); + }); + w.webContents.downloadURL(`${url}:${port}`); + }); + + describe('when a save path is specified and the URL is unavailable', () => { + it('does not display a save dialog and reports the done state as interrupted', (done) => { + const w = new BrowserWindow({ show: false }); + w.webContents.session.once('will-download', function (e, item) { + item.savePath = downloadFilePath; + if (item.getState() === 'interrupted') { + item.resume(); + } + item.on('done', function (e, state) { + try { + expect(state).to.equal('interrupted'); + done(); + } catch (e) { + done(e); + } + }); + }); + w.webContents.downloadURL(`file://${path.join(__dirname, 'does-not-exist.txt')}`); + }); + }); + }); + + describe('WebView.downloadURL', () => { + it('can perform a download', async () => { + const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); + await w.loadURL('about:blank'); + function webviewDownload ({ fixtures, url, port }: { fixtures: string, url: string, port: string }) { + const webview = new (window as any).WebView(); + webview.addEventListener('did-finish-load', () => { + webview.downloadURL(`${url}:${port}/`); + }); + webview.src = `file://${fixtures}/api/blank.html`; + document.body.appendChild(webview); + } + const done: Promise<[string, Electron.DownloadItem]> = new Promise(resolve => { + w.webContents.session.once('will-download', function (e, item) { + item.savePath = downloadFilePath; + item.on('done', function (e, state) { + resolve([state, item]); + }); + }); }); - w.webContents.downloadURL(`file://${path.join(__dirname, 'does-not-exist.txt')}`); + await w.webContents.executeJavaScript(`(${webviewDownload})(${JSON.stringify({ fixtures, url, port })})`); + const [state, item] = await done; + assertDownload(state, item); }); }); });
feat
9f862af7433b06626f3aaafab699985de3a52d46
Samuel Attard
2024-06-13 22:14:49
build: add lint GHA job (#42494)
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c6d8cb876f..9863393f4a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -12,6 +12,13 @@ on: # pull_request: jobs: + # Lint Jobs + lint: + uses: ./.github/workflows/pipeline-electron-lint.yml + with: + container: '{"image":"ghcr.io/electron/build:${{ inputs.build-image-sha }}","options":"--user root"}' + secrets: inherit + # Checkout Jobs checkout-macos: runs-on: aks-linux-large @@ -52,6 +59,7 @@ jobs: - name: Checkout & Sync & Save uses: ./src/electron/.github/actions/checkout + # Build Jobs - These cascade into testing jobs macos-x64: uses: ./.github/workflows/pipeline-electron-build-and-test.yml needs: checkout-macos diff --git a/.github/workflows/pipeline-electron-lint.yml b/.github/workflows/pipeline-electron-lint.yml new file mode 100644 index 0000000000..ff906e5e9a --- /dev/null +++ b/.github/workflows/pipeline-electron-lint.yml @@ -0,0 +1,77 @@ +name: Electron Lint + +on: + workflow_call: + inputs: + container: + required: true + description: 'Container to run lint in' + type: string + +concurrency: + group: electron-lint-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + name: Lint + runs-on: aks-linux-medium + timeout-minutes: 20 + container: ${{ fromJSON(inputs.container) }} + steps: + - name: Checkout Electron + uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 + with: + path: src/electron + fetch-depth: 0 + - name: Install Dependencies + run: | + cd src/electron + node script/yarn install + - name: Setup third_party Depot Tools + shell: bash + run: | + # "depot_tools" has to be checkout into "//third_party/depot_tools" so pylint.py can a "pylintrc" file. + git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git src/third_party/depot_tools + echo "$(pwd)/src/third_party/depot_tools" >> $GITHUB_PATH + - name: Download GN Binary + shell: bash + run: | + chromium_revision="$(grep -A1 chromium_version src/electron/DEPS | tr -d '\n' | cut -d\' -f4)" + gn_version="$(curl -sL "https://chromium.googlesource.com/chromium/src/+/${chromium_revision}/DEPS?format=TEXT" | base64 -d | grep gn_version | head -n1 | cut -d\' -f4)" + + cipd ensure -ensure-file - -root . <<-CIPD + \$ServiceURL https://chrome-infra-packages.appspot.com/ + @Subdir src/buildtools/linux64 + gn/gn/linux-amd64 $gn_version + CIPD + + buildtools_path="$(pwd)/src/buildtools" + echo "CHROMIUM_BUILDTOOLS_PATH=$buildtools_path" >> $GITHUB_ENV + - name: Download clang-format Binary + shell: bash + run: | + chromium_revision="$(grep -A1 chromium_version src/electron/DEPS | tr -d '\n' | cut -d\' -f4)" + + mkdir -p src/buildtools + curl -sL "https://chromium.googlesource.com/chromium/src/+/${chromium_revision}/buildtools/DEPS?format=TEXT" | base64 -d > src/buildtools/DEPS + + gclient runhooks --spec="solutions=[{'name':'src/buildtools','url':None,'deps_file':'DEPS','custom_vars':{'process_deps':True},'managed':False}]" + - name: Run Lint + shell: bash + run: | + # gn.py tries to find a gclient root folder starting from the current dir. + # When it fails and returns "None" path, the whole script fails. Let's "fix" it. + touch .gclient + # Another option would be to checkout "buildtools" inside the Electron checkout, + # but then we would lint its contents (at least gn format), and it doesn't pass it. + + cd src/electron + node script/yarn install --frozen-lockfile + node script/yarn lint + - name: Run Script Typechecker + shell: bash + run: | + cd src/electron + node script/yarn tsc -p tsconfig.script.json + \ No newline at end of file
build
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
Milan Burda
2023-05-31 16:47:08
docs: add `<webview>` `new-window` event removal to breaking-changes.md (#36985) Co-authored-by: Milan Burda <[email protected]>
diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md index 68cf3d4e04..ab473fc43e 100644 --- a/docs/breaking-changes.md +++ b/docs/breaking-changes.md @@ -278,6 +278,39 @@ webContents.setWindowOpenHandler((details) => { }) ``` +### Removed: `<webview>` `new-window` event + +The `new-window` event of `<webview>` has been removed. There is no direct replacement. + +```js +// Removed in Electron 22 +webview.addEventListener('new-window', (event) => {}) +``` + +```javascript fiddle='docs/fiddles/ipc/webview-new-window' +// Replace with + +// main.js +mainWindow.webContents.on('did-attach-webview', (event, wc) => { + wc.setWindowOpenHandler((details) => { + mainWindow.webContents.send('webview-new-window', wc.id, details) + return { action: 'deny' } + }) +}) + +// preload.js +const { ipcRenderer } = require('electron') +ipcRenderer.on('webview-new-window', (e, webContentsId, details) => { + console.log('webview-new-window', webContentsId, details) + document.getElementById('webview').dispatchEvent(new Event('new-window')) +}) + +// renderer.js +document.getElementById('webview').addEventListener('new-window', () => { + console.log('got new-window event') +}) +``` + ### Deprecated: BrowserWindow `scroll-touch-*` events The `scroll-touch-begin`, `scroll-touch-end` and `scroll-touch-edge` events on diff --git a/docs/fiddles/ipc/webview-new-window/child.html b/docs/fiddles/ipc/webview-new-window/child.html new file mode 100644 index 0000000000..90c94376c2 --- /dev/null +++ b/docs/fiddles/ipc/webview-new-window/child.html @@ -0,0 +1,3 @@ +<body> + <a href="child.html" target="_blank">new window</a> +</body> diff --git a/docs/fiddles/ipc/webview-new-window/index.html b/docs/fiddles/ipc/webview-new-window/index.html new file mode 100644 index 0000000000..8b461bd15f --- /dev/null +++ b/docs/fiddles/ipc/webview-new-window/index.html @@ -0,0 +1,4 @@ +<body> + <webview id=webview src="child.html" allowpopups></webview> + <script src="renderer.js"></script> +</body> diff --git a/docs/fiddles/ipc/webview-new-window/main.js b/docs/fiddles/ipc/webview-new-window/main.js new file mode 100644 index 0000000000..cab3b1ec1b --- /dev/null +++ b/docs/fiddles/ipc/webview-new-window/main.js @@ -0,0 +1,51 @@ +// Modules to control application life and create native browser window +const { app, BrowserWindow } = require('electron') +const path = require('path') + +function createWindow () { + // Create the browser window. + const mainWindow = new BrowserWindow({ + width: 800, + height: 600, + webPreferences: { + preload: path.join(__dirname, 'preload.js'), + webviewTag: true + } + }) + + mainWindow.webContents.on('did-attach-webview', (event, wc) => { + wc.setWindowOpenHandler((details) => { + mainWindow.webContents.send('webview-new-window', wc.id, details) + return { action: 'deny' } + }) + }) + + // and load the index.html of the app. + mainWindow.loadFile('index.html') + + // Open the DevTools. + // mainWindow.webContents.openDevTools() +} + +// This method will be called when Electron has finished +// initialization and is ready to create browser windows. +// Some APIs can only be used after this event occurs. +app.whenReady().then(() => { + createWindow() + + app.on('activate', function () { + // On macOS it's common to re-create a window in the app when the + // dock icon is clicked and there are no other windows open. + if (BrowserWindow.getAllWindows().length === 0) createWindow() + }) +}) + +// Quit when all windows are closed, except on macOS. There, it's common +// for applications and their menu bar to stay active until the user quits +// explicitly with Cmd + Q. +app.on('window-all-closed', function () { + if (process.platform !== 'darwin') app.quit() +}) + +// In this file you can include the rest of your app's specific main process +// code. You can also put them in separate files and require them here. diff --git a/docs/fiddles/ipc/webview-new-window/preload.js b/docs/fiddles/ipc/webview-new-window/preload.js new file mode 100644 index 0000000000..5b5b6e70a6 --- /dev/null +++ b/docs/fiddles/ipc/webview-new-window/preload.js @@ -0,0 +1,6 @@ +const { ipcRenderer } = require('electron') +const webview = document.getElementById('webview') +ipcRenderer.on('webview-new-window', (e, webContentsId, details) => { + console.log('webview-new-window', webContentsId, details) + webview.dispatchEvent(new Event('new-window')) +}) diff --git a/docs/fiddles/ipc/webview-new-window/renderer.js b/docs/fiddles/ipc/webview-new-window/renderer.js new file mode 100644 index 0000000000..e62d0b4d17 --- /dev/null +++ b/docs/fiddles/ipc/webview-new-window/renderer.js @@ -0,0 +1,4 @@ +const webview = document.getElementById('webview') +webview.addEventListener('new-window', () => { + console.log('got new-window event') +})
docs
0218af9af0e4a8896e01b4272013b46d43fb4d6c
Shelley Vohr
2024-02-14 04:08:03
fix: work around `unarchivedObjectOfClass` requiring `secureCoding` (#41319)
diff --git a/patches/squirrel.mac/refactor_use_non-deprecated_nskeyedarchiver_apis.patch b/patches/squirrel.mac/refactor_use_non-deprecated_nskeyedarchiver_apis.patch index c18ba2b778..6d8b7b8b16 100644 --- a/patches/squirrel.mac/refactor_use_non-deprecated_nskeyedarchiver_apis.patch +++ b/patches/squirrel.mac/refactor_use_non-deprecated_nskeyedarchiver_apis.patch @@ -11,23 +11,33 @@ Several NSKeyedArchiver methods have been deprecated and replaced as of macOS 10 - archivedDataWithRootObject -> archivedDataWithRootObject:requiringSecureCoding:error: diff --git a/Squirrel/SQRLInstaller.m b/Squirrel/SQRLInstaller.m -index f502df2f88424ea902a061adfeb30358daf212e4..8db6406ec7f0cb51140ea2ee39c04f91626f6e18 100644 +index f502df2f88424ea902a061adfeb30358daf212e4..40f55812bf5795dc60bb8a4cd19c62cb37f40359 100644 --- a/Squirrel/SQRLInstaller.m +++ b/Squirrel/SQRLInstaller.m -@@ -182,14 +182,30 @@ - (SQRLInstallerOwnedBundle *)ownedBundle { +@@ -182,14 +182,40 @@ - (SQRLInstallerOwnedBundle *)ownedBundle { id archiveData = CFBridgingRelease(CFPreferencesCopyValue((__bridge CFStringRef)SQRLInstallerOwnedBundleKey, (__bridge CFStringRef)self.applicationIdentifier, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost)); if (![archiveData isKindOfClass:NSData.class]) return nil; - SQRLInstallerOwnedBundle *ownedBundle = [NSKeyedUnarchiver unarchiveObjectWithData:archiveData]; - if (![ownedBundle isKindOfClass:SQRLInstallerOwnedBundle.class]) return nil; ++ // unarchivedObjectOfClass:fromData:error: sets secureCoding to true and we don't ++ // archive data with secureCoding enabled - use our own unarchiver to work around that. + NSError *error; -+ SQRLInstallerOwnedBundle *ownedBundle = [NSKeyedUnarchiver unarchivedObjectOfClass:[SQRLInstallerOwnedBundle class] -+ fromData:archiveData -+ error:&error]; ++ NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingFromData:archiveData ++ error:&error]; ++ unarchiver.requiresSecureCoding = NO; ++ SQRLInstallerOwnedBundle *ownedBundle = [unarchiver decodeObjectForKey:NSKeyedArchiveRootObjectKey]; ++ [unarchiver finishDecoding]; ++ + if (error) { -+ NSLog(@"Couldn't unarchive ownedBundle - %@", error.localizedDescription); ++ NSLog(@"Error while unarchiving ownedBundle - %@", error.localizedDescription); + return nil; + } ++ ++ if (!ownedBundle || ![ownedBundle isKindOfClass:SQRLInstallerOwnedBundle.class]) { ++ NSLog(@"Unknown error while unarchiving ownedBundle - did not conform to SQRLInstallerOwnedBundle"); ++ return nil; ++ } return ownedBundle; }
fix
13f9e2db40df5537c13ee72a92fad13a0c09b730
github-actions[bot]
2023-05-30 21:13:33
build: update appveyor image to latest version (#38449) Co-authored-by: jkleinsc <[email protected]>
diff --git a/appveyor-woa.yml b/appveyor-woa.yml index 574dc8120e..84c1877bc7 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-115.0.5786.0 +image: e-116.0.5791.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default diff --git a/appveyor.yml b/appveyor.yml index 2be04d1bf5..b241bccbb9 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-115.0.5786.0 +image: e-116.0.5791.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default
build
cbc12d6675da24b00e1ca1682e8c4926d7a51801
David Sanders
2024-10-17 07:35:50
ci: use Node.js 20 in Bake AppVeyor Image workflow (#44290) * ci: use Node.js 20 in Bake AppVeyor Image workflow * chore: add bake workflow to CODEOWNERS
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 8d5b9aa4e1..c1f5a5362b 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -8,6 +8,7 @@ DEPS @electron/wg-upgrades # Releases WG +/.github/workflows/update_appveyor_image.yml @electron/wg-releases /docs/breaking-changes.md @electron/wg-releases /npm/ @electron/wg-releases /script/release @electron/wg-releases diff --git a/.github/workflows/update_appveyor_image.yml b/.github/workflows/update_appveyor_image.yml index f8beab2ef0..e6f3bf8381 100644 --- a/.github/workflows/update_appveyor_image.yml +++ b/.github/workflows/update_appveyor_image.yml @@ -23,6 +23,10 @@ jobs: with: fetch-depth: 0 token: ${{ steps.generate-token.outputs.token }} + - name: Setup Node.js + uses: actions/setup-node@0a44ba7841725637a19e28fa30b79a866c81b0a6 # v4.0.4 + with: + node-version: 20.11.x - name: Yarn install run: | node script/yarn.js install --frozen-lockfile
ci
a072f06168711bd0abc289ca3df0bd139c4f7fed
David Sanders
2022-10-10 03:01:11
docs: remove pywin32 mention in Windows build instructions (#35940)
diff --git a/docs/development/build-instructions-windows.md b/docs/development/build-instructions-windows.md index 171679ddab..20db54fabc 100644 --- a/docs/development/build-instructions-windows.md +++ b/docs/development/build-instructions-windows.md @@ -116,10 +116,6 @@ $ git config --system core.longpaths true This can happen during build, when Debugging Tools for Windows has been installed with Windows Driver Kit. Uninstall Windows Driver Kit and install Debugging Tools with steps described above. -### ImportError: No module named win32file - -Make sure you have installed `pywin32` with `pip install pywin32`. - ### Build Scripts Hang Until Keypress This bug is a "feature" of Windows' command prompt. It happens when clicking inside the prompt window with
docs
cc16de7032228933f6a0f09cbd72178d8ffd84d0
Shelley Vohr
2024-08-19 20:25:14
fix: printing occasionally showing failed when cancelled (#43337) Closes https://github.com/electron/electron/issues/36084
diff --git a/patches/chromium/printing.patch b/patches/chromium/printing.patch index 0204294003..73cc706270 100644 --- a/patches/chromium/printing.patch +++ b/patches/chromium/printing.patch @@ -91,7 +91,7 @@ index 163eacc8bb6654880d37111923a87ea5a6134485..565258e9bd4cc52e347e1f4a72ee29ec : PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3; } diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc -index 5c2be309159b3f7c67601a08366b5221c198a1fb..10ceb545e5ff98b36c57d23584e701ba0e2c752e 100644 +index 5c2be309159b3f7c67601a08366b5221c198a1fb..0ae0552e3683d226df39d292f45d7002a3bfe286 100644 --- a/chrome/browser/printing/print_view_manager_base.cc +++ b/chrome/browser/printing/print_view_manager_base.cc @@ -87,6 +87,20 @@ namespace printing { @@ -374,7 +374,14 @@ index 5c2be309159b3f7c67601a08366b5221c198a1fb..10ceb545e5ff98b36c57d23584e701ba } void PrintViewManagerBase::RenderFrameDeleted( -@@ -941,7 +985,7 @@ void PrintViewManagerBase::SystemDialogCancelled() { +@@ -935,13 +979,14 @@ void PrintViewManagerBase::SystemDialogCancelled() { + // System dialog was cancelled. Clean up the print job and notify the + // BackgroundPrintingManager. + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); ++ printing_status_ = PrintStatus::kCanceled; + ReleasePrinterQuery(); + TerminatePrintJob(true); + } #endif bool PrintViewManagerBase::GetPrintingEnabledBooleanPref() const { @@ -383,7 +390,7 @@ index 5c2be309159b3f7c67601a08366b5221c198a1fb..10ceb545e5ff98b36c57d23584e701ba } void PrintViewManagerBase::OnDocDone(int job_id, PrintedDocument* document) { -@@ -958,7 +1002,12 @@ void PrintViewManagerBase::OnJobDone() { +@@ -958,18 +1003,26 @@ void PrintViewManagerBase::OnJobDone() { // Printing is done, we don't need it anymore. // print_job_->is_job_pending() may still be true, depending on the order // of object registration. @@ -397,11 +404,14 @@ index 5c2be309159b3f7c67601a08366b5221c198a1fb..10ceb545e5ff98b36c57d23584e701ba ReleasePrintJob(); } -@@ -967,9 +1016,9 @@ void PrintViewManagerBase::OnCanceling() { + void PrintViewManagerBase::OnCanceling() { ++ printing_status_ = PrintStatus::kCanceled; + canceling_job_ = true; } void PrintViewManagerBase::OnFailed() { -- if (!canceling_job_) + if (!canceling_job_) ++ printing_status_ = PrintStatus::kFailed; +#if 0 // Electron does not use Chromium error dialogs ShowPrintErrorDialogForGenericError(); - @@ -409,7 +419,7 @@ index 5c2be309159b3f7c67601a08366b5221c198a1fb..10ceb545e5ff98b36c57d23584e701ba TerminatePrintJob(true); } -@@ -979,7 +1028,7 @@ bool PrintViewManagerBase::RenderAllMissingPagesNow() { +@@ -979,7 +1032,7 @@ bool PrintViewManagerBase::RenderAllMissingPagesNow() { // Is the document already complete? if (print_job_->document() && print_job_->document()->IsComplete()) { @@ -418,7 +428,7 @@ index 5c2be309159b3f7c67601a08366b5221c198a1fb..10ceb545e5ff98b36c57d23584e701ba return true; } -@@ -1032,7 +1081,10 @@ bool PrintViewManagerBase::SetupNewPrintJob( +@@ -1032,7 +1085,10 @@ bool PrintViewManagerBase::SetupNewPrintJob( // Disconnect the current `print_job_`. auto weak_this = weak_ptr_factory_.GetWeakPtr(); @@ -430,16 +440,16 @@ index 5c2be309159b3f7c67601a08366b5221c198a1fb..10ceb545e5ff98b36c57d23584e701ba if (!weak_this) return false; -@@ -1052,7 +1104,7 @@ bool PrintViewManagerBase::SetupNewPrintJob( +@@ -1052,7 +1108,7 @@ bool PrintViewManagerBase::SetupNewPrintJob( #endif print_job_->AddObserver(*this); - printing_succeeded_ = false; -+ printing_status_ = PrintStatus::kFailed; ++ printing_status_ = PrintStatus::kUnknown; return true; } -@@ -1110,7 +1162,7 @@ void PrintViewManagerBase::ReleasePrintJob() { +@@ -1110,7 +1166,7 @@ void PrintViewManagerBase::ReleasePrintJob() { // Ensure that any residual registration of printing client is released. // This might be necessary in some abnormal cases, such as the associated // render process having terminated. @@ -448,7 +458,7 @@ index 5c2be309159b3f7c67601a08366b5221c198a1fb..10ceb545e5ff98b36c57d23584e701ba if (!analyzing_content_) { UnregisterSystemPrintClient(); } -@@ -1120,6 +1172,11 @@ void PrintViewManagerBase::ReleasePrintJob() { +@@ -1120,6 +1176,11 @@ void PrintViewManagerBase::ReleasePrintJob() { } #endif @@ -460,7 +470,7 @@ index 5c2be309159b3f7c67601a08366b5221c198a1fb..10ceb545e5ff98b36c57d23584e701ba if (!print_job_) return; -@@ -1127,7 +1184,7 @@ void PrintViewManagerBase::ReleasePrintJob() { +@@ -1127,7 +1188,7 @@ void PrintViewManagerBase::ReleasePrintJob() { // printing_rfh_ should only ever point to a RenderFrameHost with a live // RenderFrame. DCHECK(rfh->IsRenderFrameLive()); @@ -469,7 +479,7 @@ index 5c2be309159b3f7c67601a08366b5221c198a1fb..10ceb545e5ff98b36c57d23584e701ba } print_job_->RemoveObserver(*this); -@@ -1169,7 +1226,7 @@ bool PrintViewManagerBase::RunInnerMessageLoop() { +@@ -1169,7 +1230,7 @@ bool PrintViewManagerBase::RunInnerMessageLoop() { } bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) { @@ -478,7 +488,7 @@ index 5c2be309159b3f7c67601a08366b5221c198a1fb..10ceb545e5ff98b36c57d23584e701ba return true; if (!cookie) { -@@ -1192,7 +1249,7 @@ bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) { +@@ -1192,7 +1253,7 @@ bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) { return false; } @@ -487,7 +497,7 @@ index 5c2be309159b3f7c67601a08366b5221c198a1fb..10ceb545e5ff98b36c57d23584e701ba // Don't start printing if enterprise checks are being performed to check if // printing is allowed, or if content analysis is going to take place right // before starting `print_job_`. -@@ -1323,6 +1380,8 @@ void PrintViewManagerBase::CompleteScriptedPrint( +@@ -1323,6 +1384,8 @@ void PrintViewManagerBase::CompleteScriptedPrint( auto callback_wrapper = base::BindOnce( &PrintViewManagerBase::ScriptedPrintReply, weak_ptr_factory_.GetWeakPtr(), std::move(callback), render_process_host->GetID()); @@ -496,7 +506,7 @@ index 5c2be309159b3f7c67601a08366b5221c198a1fb..10ceb545e5ff98b36c57d23584e701ba #if BUILDFLAG(IS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) DisableThirdPartyBlocking(); #endif -@@ -1337,10 +1396,10 @@ void PrintViewManagerBase::CompleteScriptedPrint( +@@ -1337,10 +1400,10 @@ void PrintViewManagerBase::CompleteScriptedPrint( params->expected_pages_count, params->has_selection, params->margin_type, params->is_scripted, !render_process_host->IsPdf(), base::BindOnce(&OnDidScriptedPrint, queue_, std::move(printer_query),
fix
90ba2df4fa43a3e6108b84b0e5e745a73acf3855
John Kleinschmidt
2024-09-03 21:32:05
build: free up macos disk space as soon as possible (#43533) * chore: free up macos disk space as soon as possible * build: free up disk space on gn check too
diff --git a/.github/workflows/pipeline-segment-electron-build.yml b/.github/workflows/pipeline-segment-electron-build.yml index 27f4ca0a24..f123bfe9ac 100644 --- a/.github/workflows/pipeline-segment-electron-build.yml +++ b/.github/workflows/pipeline-segment-electron-build.yml @@ -82,6 +82,12 @@ jobs: with: path: src/electron fetch-depth: 0 + - name: Free up space (macOS) + if: ${{ inputs.target-platform == 'macos' }} + uses: ./src/electron/.github/actions/free-space-macos + - name: Check disk space after freeing up space + if: ${{ inputs.target-platform == 'macos' }} + run: df -h - name: Setup Node.js/npm if: ${{ inputs.target-platform == 'macos' }} uses: actions/setup-node@1e60f620b9541d16bece96c5465dc8ee9832be0b diff --git a/.github/workflows/pipeline-segment-electron-gn-check.yml b/.github/workflows/pipeline-segment-electron-gn-check.yml index 997ed1d9c0..094404c533 100644 --- a/.github/workflows/pipeline-segment-electron-gn-check.yml +++ b/.github/workflows/pipeline-segment-electron-gn-check.yml @@ -54,6 +54,23 @@ jobs: with: path: src/electron fetch-depth: 0 + - name: Cleanup disk space on macOS + if: ${{ inputs.target-platform == 'macos' }} + shell: bash + run: | + sudo mkdir -p $TMPDIR/del-target + + tmpify() { + if [ -d "$1" ]; then + sudo mv "$1" $TMPDIR/del-target/$(echo $1|shasum -a 256|head -n1|cut -d " " -f1) + fi + } + tmpify /Library/Developer/CoreSimulator + tmpify ~/Library/Developer/CoreSimulator + sudo rm -rf $TMPDIR/del-target + - name: Check disk space after freeing up space + if: ${{ inputs.target-platform == 'macos' }} + run: df -h - name: Install Build Tools uses: ./src/electron/.github/actions/install-build-tools - name: Init Build Tools
build
976f5d1b7558d596c0e28e614a02bf6acfc7e6f8
Shelley Vohr
2024-07-25 15:53:30
fix: File System API permissions should reset on WebContents destruction (#43009) fix: active File System API permissions should reset on WebContents destruction
diff --git a/filenames.gni b/filenames.gni index 37c92a9b09..5c7ca21fa0 100644 --- a/filenames.gni +++ b/filenames.gni @@ -390,6 +390,8 @@ filenames = { "shell/browser/file_system_access/file_system_access_permission_context.h", "shell/browser/file_system_access/file_system_access_permission_context_factory.cc", "shell/browser/file_system_access/file_system_access_permission_context_factory.h", + "shell/browser/file_system_access/file_system_access_web_contents_helper.cc", + "shell/browser/file_system_access/file_system_access_web_contents_helper.h", "shell/browser/font_defaults.cc", "shell/browser/font_defaults.h", "shell/browser/hid/electron_hid_delegate.cc", diff --git a/shell/browser/file_system_access/file_system_access_permission_context.cc b/shell/browser/file_system_access/file_system_access_permission_context.cc index 5413b6bd3e..98ea6d0cd0 100644 --- a/shell/browser/file_system_access/file_system_access_permission_context.cc +++ b/shell/browser/file_system_access/file_system_access_permission_context.cc @@ -14,6 +14,7 @@ #include "base/task/bind_post_task.h" #include "base/task/thread_pool.h" #include "base/time/time.h" +#include "base/timer/timer.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/file_system_access/chrome_file_system_access_permission_context.h" // nogncheck @@ -92,6 +93,8 @@ const char kPathKey[] = "path"; const char kPathTypeKey[] = "path-type"; const char kTimestampKey[] = "timestamp"; +constexpr base::TimeDelta kPermissionRevocationTimeout = base::Seconds(5); + #if BUILDFLAG(IS_WIN) [[nodiscard]] constexpr bool ContainsInvalidDNSCharacter( base::FilePath::StringType hostname) { @@ -418,6 +421,7 @@ class FileSystemAccessPermissionContext::PermissionGrantImpl }; struct FileSystemAccessPermissionContext::OriginState { + std::unique_ptr<base::RetainingOneShotTimer> cleanup_timer; // Raw pointers, owned collectively by all the handles that reference this // grant. When last reference goes away this state is cleared as well by // PermissionGrantDestroyed(). @@ -831,7 +835,7 @@ void FileSystemAccessPermissionContext::CheckPathsAgainstEnterprisePolicy( std::move(callback).Run(std::move(entries)); } -void FileSystemAccessPermissionContext::RevokeGrant( +void FileSystemAccessPermissionContext::RevokeActiveGrants( const url::Origin& origin, const base::FilePath& file_path) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -881,10 +885,30 @@ bool FileSystemAccessPermissionContext::OriginHasWriteAccess( return false; } +void FileSystemAccessPermissionContext::NavigatedAwayFromOrigin( + const url::Origin& origin) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + auto it = active_permissions_map_.find(origin); + // If we have no permissions for the origin, there is nothing to do. + if (it == active_permissions_map_.end()) { + return; + } + + // Start a timer to possibly clean up permissions for this origin. + if (!it->second.cleanup_timer) { + it->second.cleanup_timer = std::make_unique<base::RetainingOneShotTimer>( + FROM_HERE, kPermissionRevocationTimeout, + base::BindRepeating( + &FileSystemAccessPermissionContext::CleanupPermissions, + base::Unretained(this), origin)); + } + it->second.cleanup_timer->Reset(); +} + void FileSystemAccessPermissionContext::CleanupPermissions( const url::Origin& origin) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - RevokeGrant(origin); + RevokeActiveGrants(origin); } bool FileSystemAccessPermissionContext::AncestorHasActivePermission( diff --git a/shell/browser/file_system_access/file_system_access_permission_context.h b/shell/browser/file_system_access/file_system_access_permission_context.h index 851d1958bd..4011fceedd 100644 --- a/shell/browser/file_system_access/file_system_access_permission_context.h +++ b/shell/browser/file_system_access/file_system_access_permission_context.h @@ -112,12 +112,16 @@ class FileSystemAccessPermissionContext enum class RequestType { kNewPermission, kRestorePermissions }; - void RevokeGrant(const url::Origin& origin, - const base::FilePath& file_path = base::FilePath()); + void RevokeActiveGrants(const url::Origin& origin, + const base::FilePath& file_path = base::FilePath()); bool OriginHasReadAccess(const url::Origin& origin); bool OriginHasWriteAccess(const url::Origin& origin); + // Called by FileSystemAccessWebContentsHelper when a top-level frame was + // navigated away from `origin` to some other origin. + void NavigatedAwayFromOrigin(const url::Origin& origin); + content::BrowserContext* browser_context() const { return browser_context_; } protected: diff --git a/shell/browser/file_system_access/file_system_access_web_contents_helper.cc b/shell/browser/file_system_access/file_system_access_web_contents_helper.cc new file mode 100644 index 0000000000..183ca23603 --- /dev/null +++ b/shell/browser/file_system_access/file_system_access_web_contents_helper.cc @@ -0,0 +1,56 @@ +// Copyright (c) 2024 Microsoft, GmbH +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "shell/browser/file_system_access/file_system_access_web_contents_helper.h" + +#include "content/public/browser/browser_context.h" +#include "content/public/browser/navigation_handle.h" +#include "shell/browser/file_system_access/file_system_access_permission_context.h" +#include "shell/browser/file_system_access/file_system_access_permission_context_factory.h" + +FileSystemAccessWebContentsHelper::~FileSystemAccessWebContentsHelper() = + default; + +void FileSystemAccessWebContentsHelper::DidFinishNavigation( + content::NavigationHandle* navigation) { + // We only care about top-level navigations that actually committed. + if (!navigation->IsInPrimaryMainFrame() || !navigation->HasCommitted()) + return; + + auto src_origin = + url::Origin::Create(navigation->GetPreviousPrimaryMainFrameURL()); + auto dest_origin = url::Origin::Create(navigation->GetURL()); + + if (src_origin == dest_origin) + return; + + // Navigated away from |src_origin|, tell permission context to check if + // permissions need to be revoked. + auto* context = + electron::FileSystemAccessPermissionContextFactory::GetForBrowserContext( + web_contents()->GetBrowserContext()); + if (context) + context->NavigatedAwayFromOrigin(src_origin); +} + +void FileSystemAccessWebContentsHelper::WebContentsDestroyed() { + auto src_origin = + web_contents()->GetPrimaryMainFrame()->GetLastCommittedOrigin(); + + // Navigated away from |src_origin|, tell permission context to check if + // permissions need to be revoked. + auto* context = + electron::FileSystemAccessPermissionContextFactory::GetForBrowserContext( + web_contents()->GetBrowserContext()); + if (context) + context->NavigatedAwayFromOrigin(src_origin); +} + +FileSystemAccessWebContentsHelper::FileSystemAccessWebContentsHelper( + content::WebContents* web_contents) + : content::WebContentsObserver(web_contents), + content::WebContentsUserData<FileSystemAccessWebContentsHelper>( + *web_contents) {} + +WEB_CONTENTS_USER_DATA_KEY_IMPL(FileSystemAccessWebContentsHelper); diff --git a/shell/browser/file_system_access/file_system_access_web_contents_helper.h b/shell/browser/file_system_access/file_system_access_web_contents_helper.h new file mode 100644 index 0000000000..22733c6ba7 --- /dev/null +++ b/shell/browser/file_system_access/file_system_access_web_contents_helper.h @@ -0,0 +1,34 @@ +// Copyright (c) 2024 Microsoft, GmbH +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#ifndef ELECTRON_SHELL_BROWSER_FILE_SYSTEM_ACCESS_FILE_SYSTEM_ACCESS_WEB_CONTENTS_HELPER_H_ +#define ELECTRON_SHELL_BROWSER_FILE_SYSTEM_ACCESS_FILE_SYSTEM_ACCESS_WEB_CONTENTS_HELPER_H_ + +#include "content/public/browser/web_contents_observer.h" +#include "content/public/browser/web_contents_user_data.h" + +class FileSystemAccessWebContentsHelper + : public content::WebContentsObserver, + public content::WebContentsUserData<FileSystemAccessWebContentsHelper> { + public: + FileSystemAccessWebContentsHelper(const FileSystemAccessWebContentsHelper&) = + delete; + FileSystemAccessWebContentsHelper& operator=( + const FileSystemAccessWebContentsHelper&) = delete; + ~FileSystemAccessWebContentsHelper() override; + + // content::WebContentsObserver + void DidFinishNavigation( + content::NavigationHandle* navigation_handle) override; + void WebContentsDestroyed() override; + + private: + explicit FileSystemAccessWebContentsHelper( + content::WebContents* web_contents); + friend class content::WebContentsUserData<FileSystemAccessWebContentsHelper>; + + WEB_CONTENTS_USER_DATA_KEY_DECL(); +}; + +#endif // ELECTRON_SHELL_BROWSER_FILE_SYSTEM_ACCESS_FILE_SYSTEM_ACCESS_WEB_CONTENTS_HELPER_H_
fix
4ff0642af745e57df6736b9d68fe0228b8e28968
Jeremy Rose
2022-11-30 17:02:22
fix: treat maxWidth/Height<=0 as unlimited (#36487)
diff --git a/shell/browser/native_window.cc b/shell/browser/native_window.cc index fd1be39c6c..47429f0864 100644 --- a/shell/browser/native_window.cc +++ b/shell/browser/native_window.cc @@ -175,7 +175,11 @@ void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) { int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX; int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX; bool have_max_width = options.Get(options::kMaxWidth, &max_width); + if (have_max_width && max_width <= 0) + max_width = INT_MAX; bool have_max_height = options.Get(options::kMaxHeight, &max_height); + if (have_max_height && max_height <= 0) + max_height = INT_MAX; // By default the window has a default maximum size that prevents it // from being resized larger than the screen, so we should only set this
fix
9d525f98610fb65fa304cee33e8b6161f32a00b5
Shelley Vohr
2023-04-26 10:11:14
test: formally mark some Node.js tests as flaky (#38117)
diff --git a/patches/node/.patches b/patches/node/.patches index 03190292c5..175faea888 100644 --- a/patches/node/.patches +++ b/patches/node/.patches @@ -29,7 +29,7 @@ api_pass_oomdetails_to_oomerrorcallback.patch fix_expose_lookupandcompile_with_parameters.patch fix_prevent_changing_functiontemplateinfo_after_publish.patch enable_crashpad_linux_node_processes.patch -test_mark_cpu_prof_tests_as_flaky_in_electron.patch +test_formally_mark_some_tests_as_flaky.patch fix_adapt_debugger_tests_for_upstream_v8_changes.patch fix_libc_buffer_overflow_in_string_view_ctor.patch fix_preventing_potential_oob_in_ada_no_scheme_parsing.patch diff --git a/patches/node/test_mark_cpu_prof_tests_as_flaky_in_electron.patch b/patches/node/test_formally_mark_some_tests_as_flaky.patch similarity index 50% rename from patches/node/test_mark_cpu_prof_tests_as_flaky_in_electron.patch rename to patches/node/test_formally_mark_some_tests_as_flaky.patch index 8b40ddffd2..5feaad2b9f 100644 --- a/patches/node/test_mark_cpu_prof_tests_as_flaky_in_electron.patch +++ b/patches/node/test_formally_mark_some_tests_as_flaky.patch @@ -1,26 +1,46 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Samuel Attard <[email protected]> Date: Wed, 8 Feb 2023 02:54:05 -0800 -Subject: test: mark cpu prof tests as flaky in electron +Subject: test: formally mark some tests as flaky Instead of disabling the tests, flag them as flaky so they still run but don't cause CI failures on flakes. +diff --git a/test/parallel/parallel.status b/test/parallel/parallel.status +index 1cbcefb9712fae45b9a0ec7ed361bfe4ec7790be..6a6b52e9ae4150e7215e3587d8ddb41ce4374780 100644 +--- a/test/parallel/parallel.status ++++ b/test/parallel/parallel.status +@@ -5,6 +5,12 @@ prefix parallel + # sample-test : PASS,FLAKY + + [true] # This section applies to all platforms ++test-inspector-multisession-ws: PASS, FLAKY ++test-heapsnapshot-near-heap-limit-by-api-in-worker: PASS, FLAKY ++test-heapsnapshot-near-heap-limit-worker: PASS, FLAKY ++test-fetch: PASS, FLAKY ++test-cluster-bind-privileged-port: PASS, FLAKY ++test-cluster-shared-handle-bind-privileged-port: PASS, FLAKY + + [$system==win32] + # https://github.com/nodejs/node/issues/24497 diff --git a/test/sequential/sequential.status b/test/sequential/sequential.status -index 5d88747b7066ce795b091eaaec2a5653f42b2c26..e3c7b531bc519bc97f363a1d4e7df2f059b11614 100644 +index 5d88747b7066ce795b091eaaec2a5653f42b2c26..c40cb8827c3e1b91f46147cead5a91a7520019b9 100644 --- a/test/sequential/sequential.status +++ b/test/sequential/sequential.status -@@ -7,6 +7,15 @@ prefix sequential +@@ -7,6 +7,18 @@ prefix sequential [true] # This section applies to all platforms # https://github.com/nodejs/node/issues/27611#issuecomment-613100468 test-cpu-prof-dir-worker: PASS, FLAKY +test-cpu-prof-dir-and-name: PASS, FLAKY -+test-cpu-prof-worker-argv: PASS, FLAKY ++test-cpu-prof-drained: PASS, FLAKY +test-cpu-prof-default: PASS, FLAKY +test-cpu-prof-dir-absolute: PASS, FLAKY +test-cpu-prof-dir-relative: PASS, FLAKY +test-cpu-prof-exit: PASS, FLAKY ++test-cpu-prof-kill: PASS, FLAKY +test-cpu-prof-name: PASS, FLAKY ++test-cpu-prof-worker-argv: PASS, FLAKY ++test-diagnostic-dir-cpu-prof: PASS, FLAKY +test-worker-prof: PASS, FLAKY +test-inspector-stop-profile-after-done: PASS, FLAKY # https://github.com/nodejs/node/issues/44898 diff --git a/script/node-disabled-tests.json b/script/node-disabled-tests.json index 652eb3d1ca..46a34f20e0 100644 --- a/script/node-disabled-tests.json +++ b/script/node-disabled-tests.json @@ -5,8 +5,6 @@ "parallel/test-bootstrap-modules", "parallel/test-child-process-fork-exec-path", "parallel/test-cli-node-print-help", - "parallel/test-cluster-bind-privileged-port", - "parallel/test-cluster-shared-handle-bind-privileged-port", "parallel/test-code-cache", "parallel/test-crypto-aes-wrap", "parallel/test-crypto-authenticated-stream", @@ -22,16 +20,12 @@ "parallel/test-crypto-key-objects", "parallel/test-crypto-padding-aes256", "parallel/test-crypto-secure-heap", - "parallel/test-fetch", "parallel/test-fs-utimes-y2K38", - "parallel/test-heapsnapshot-near-heap-limit-by-api-in-worker", - "parallel/test-heapsnapshot-near-heap-limit-worker", "parallel/test-http2-clean-output", "parallel/test-https-agent-session-reuse", "parallel/test-https-options-boolean-check", "parallel/test-icu-minimum-version", "parallel/test-icu-env", - "parallel/test-inspector-multisession-ws", "parallel/test-inspector-port-zero-cluster", "parallel/test-inspector-tracing-domain", "parallel/test-module-loading-globalpaths", @@ -151,9 +145,6 @@ "report/test-report-uv-handles", "report/test-report-worker", "report/test-report-writereport", - "sequential/test-cpu-prof-kill", - "sequential/test-diagnostic-dir-cpu-prof", - "sequential/test-cpu-prof-drained", "sequential/test-tls-connect", "wpt/test-webcrypto" ]
test
1432f9bb657489cabc33cd73ad4508e5782dc093
Bruno Pitrus
2022-12-13 19:55:08
chore: reland “fix ambiguous reference gcc compile error” (#36544) This is a reland of #35714. The broken code got reintroduced in #35310 due to a mismerge.
diff --git a/shell/browser/serial/electron_serial_delegate.h b/shell/browser/serial/electron_serial_delegate.h index 5fc7317d48..e66f6a51df 100644 --- a/shell/browser/serial/electron_serial_delegate.h +++ b/shell/browser/serial/electron_serial_delegate.h @@ -45,9 +45,9 @@ class ElectronSerialDelegate : public content::SerialDelegate, device::mojom::SerialPortManager* GetPortManager( content::RenderFrameHost* frame) override; void AddObserver(content::RenderFrameHost* frame, - Observer* observer) override; + content::SerialDelegate::Observer* observer) override; void RemoveObserver(content::RenderFrameHost* frame, - Observer* observer) override; + content::SerialDelegate::Observer* observer) override; void DeleteControllerForFrame(content::RenderFrameHost* render_frame_host);
chore
56138d879e57d5d5fce55ecbe3f8d3a8ed08e7f8
Shelley Vohr
2023-05-29 00:39:13
fix: Windows FrameView always appearing inactive (#38468)
diff --git a/shell/browser/ui/win/electron_desktop_window_tree_host_win.cc b/shell/browser/ui/win/electron_desktop_window_tree_host_win.cc index b49b566cff..90420a95f2 100644 --- a/shell/browser/ui/win/electron_desktop_window_tree_host_win.cc +++ b/shell/browser/ui/win/electron_desktop_window_tree_host_win.cc @@ -37,14 +37,6 @@ bool ElectronDesktopWindowTreeHostWin::PreHandleMSG(UINT message, return native_window_view_->PreHandleMSG(message, w_param, l_param, result); } -bool ElectronDesktopWindowTreeHostWin::ShouldPaintAsActive() const { - // Tell Chromium to use system default behavior when rendering inactive - // titlebar, otherwise it would render inactive titlebar as active under - // some cases. - // See also https://github.com/electron/electron/issues/24647. - return false; -} - bool ElectronDesktopWindowTreeHostWin::GetDwmFrameInsetsInPixels( gfx::Insets* insets) const { // Set DWMFrameInsets to prevent maximized frameless window from bleeding diff --git a/shell/browser/ui/win/electron_desktop_window_tree_host_win.h b/shell/browser/ui/win/electron_desktop_window_tree_host_win.h index 3581da11b8..26ddea5979 100644 --- a/shell/browser/ui/win/electron_desktop_window_tree_host_win.h +++ b/shell/browser/ui/win/electron_desktop_window_tree_host_win.h @@ -31,7 +31,6 @@ class ElectronDesktopWindowTreeHostWin : public views::DesktopWindowTreeHostWin, WPARAM w_param, LPARAM l_param, LRESULT* result) override; - bool ShouldPaintAsActive() const override; bool GetDwmFrameInsetsInPixels(gfx::Insets* insets) const override; bool GetClientAreaInsets(gfx::Insets* insets, HMONITOR monitor) const override;
fix