mirror of
https://github.com/electron/electron.git
synced 2026-04-10 03:01:51 -04:00
Compare commits
75 Commits
v24.1.2
...
v25.0.0-ni
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ee58e18fd | ||
|
|
f33bf2a271 | ||
|
|
77bd80dfb2 | ||
|
|
0d3aee26b9 | ||
|
|
efde7a140b | ||
|
|
4e85bb921b | ||
|
|
512e56baf7 | ||
|
|
c8f715f9a1 | ||
|
|
829fb4f586 | ||
|
|
17ccb3c6ec | ||
|
|
6bd9ee6988 | ||
|
|
76c825d619 | ||
|
|
692876c737 | ||
|
|
c3f06ef037 | ||
|
|
9b20b3a722 | ||
|
|
8f2917db01 | ||
|
|
49df19214e | ||
|
|
5e25d23794 | ||
|
|
8fb0f43030 | ||
|
|
1f390119fe | ||
|
|
87f2a1d572 | ||
|
|
2e03bdb9b6 | ||
|
|
3a5ae28c95 | ||
|
|
ed7b5c44a2 | ||
|
|
edf887bdc5 | ||
|
|
1ff7f098f1 | ||
|
|
fb100e8f49 | ||
|
|
3384908da1 | ||
|
|
73bd9a3155 | ||
|
|
e27905c765 | ||
|
|
a3e3efe4c4 | ||
|
|
46c8b9c728 | ||
|
|
6395898a79 | ||
|
|
32c60b29bb | ||
|
|
868676aa5c | ||
|
|
85cf56d80b | ||
|
|
a92fd2aa05 | ||
|
|
ee966ad6ec | ||
|
|
872d1fe05a | ||
|
|
63f94f2359 | ||
|
|
67a6fbf265 | ||
|
|
f97d68c4bf | ||
|
|
969665eaa2 | ||
|
|
0d8dd61257 | ||
|
|
cf10c19c33 | ||
|
|
fcfbcbc7e1 | ||
|
|
e34cc6f48c | ||
|
|
ee87438d28 | ||
|
|
0de1012280 | ||
|
|
0a5e634736 | ||
|
|
73b7aac6a4 | ||
|
|
ea848bc1c5 | ||
|
|
a44e76fb70 | ||
|
|
3138acc377 | ||
|
|
beed240454 | ||
|
|
fdab0799fe | ||
|
|
17ea7f42fc | ||
|
|
d0cf9c4b08 | ||
|
|
fe7c535a3f | ||
|
|
8eee4f2df1 | ||
|
|
4d6f230d21 | ||
|
|
889859df5b | ||
|
|
cb03c6516b | ||
|
|
2e8114aea3 | ||
|
|
a38b711fb1 | ||
|
|
3972073116 | ||
|
|
8c986ff194 | ||
|
|
71944f2c3b | ||
|
|
8b3e498436 | ||
|
|
cf80994729 | ||
|
|
01f1522cbd | ||
|
|
a37f572388 | ||
|
|
3180312595 | ||
|
|
ff60fe25c1 | ||
|
|
12ed401ca2 |
@@ -1054,6 +1054,8 @@ commands:
|
||||
parameters:
|
||||
artifact-key:
|
||||
type: string
|
||||
build-type:
|
||||
type: string
|
||||
build-nonproprietary-ffmpeg:
|
||||
type: boolean
|
||||
default: true
|
||||
@@ -1061,6 +1063,7 @@ commands:
|
||||
- *step-gn-gen-default
|
||||
- ninja_build_electron:
|
||||
clean-prebuilt-snapshot: false
|
||||
build-type: << parameters.build-type >>
|
||||
- *step-maybe-electron-dist-strip
|
||||
- step-electron-dist-build:
|
||||
additional-targets: shell_browser_ui_unittests third_party/electron_node:headers third_party/electron_node:overlapped-checker electron:hunspell_dictionaries_zip
|
||||
@@ -1222,9 +1225,12 @@ commands:
|
||||
clean-prebuilt-snapshot:
|
||||
type: boolean
|
||||
default: true
|
||||
build-type:
|
||||
type: string
|
||||
|
||||
steps:
|
||||
- run:
|
||||
name: Electron build
|
||||
name: Electron << parameters.build-type >> build
|
||||
no_output_timeout: 60m
|
||||
command: |
|
||||
cd src
|
||||
@@ -1292,6 +1298,8 @@ commands:
|
||||
default: true
|
||||
artifact-key:
|
||||
type: string
|
||||
build-type:
|
||||
type: string
|
||||
after-build-and-save:
|
||||
type: steps
|
||||
default: []
|
||||
@@ -1418,6 +1426,7 @@ commands:
|
||||
steps:
|
||||
- build_and_save_artifacts:
|
||||
artifact-key: << parameters.artifact-key >>
|
||||
build-type: << parameters.build-type >>
|
||||
build-nonproprietary-ffmpeg: << parameters.build-nonproprietary-ffmpeg >>
|
||||
- steps: << parameters.after-build-and-save >>
|
||||
|
||||
@@ -1563,6 +1572,8 @@ commands:
|
||||
checkout:
|
||||
type: boolean
|
||||
default: true
|
||||
build-type:
|
||||
type: string
|
||||
steps:
|
||||
- when:
|
||||
condition: << parameters.attach >>
|
||||
@@ -1594,7 +1605,8 @@ commands:
|
||||
- *step-gn-gen-default
|
||||
|
||||
# Electron app
|
||||
- ninja_build_electron
|
||||
- ninja_build_electron:
|
||||
build-type: << parameters.build-type >>
|
||||
- *step-show-goma-stats
|
||||
- *step-maybe-generate-breakpad-symbols
|
||||
- *step-maybe-electron-dist-strip
|
||||
@@ -1657,6 +1669,7 @@ jobs:
|
||||
save-git-cache: true
|
||||
checkout-to-create-src-cache: true
|
||||
artifact-key: 'nil'
|
||||
build-type: 'nil'
|
||||
|
||||
mac-checkout:
|
||||
executor:
|
||||
@@ -1675,6 +1688,7 @@ jobs:
|
||||
persist-checkout: true
|
||||
restore-src-cache: false
|
||||
artifact-key: 'nil'
|
||||
build-type: 'nil'
|
||||
|
||||
mac-make-src-cache:
|
||||
executor:
|
||||
@@ -1693,6 +1707,7 @@ jobs:
|
||||
save-git-cache: true
|
||||
checkout-to-create-src-cache: true
|
||||
artifact-key: 'nil'
|
||||
build-type: 'nil'
|
||||
|
||||
# Layer 2: Builds.
|
||||
linux-x64-testing:
|
||||
@@ -1710,6 +1725,7 @@ jobs:
|
||||
checkout: false
|
||||
checkout-and-assume-cache: true
|
||||
artifact-key: 'linux-x64'
|
||||
build-type: 'Linux'
|
||||
|
||||
linux-x64-testing-asan:
|
||||
executor:
|
||||
@@ -1728,6 +1744,7 @@ jobs:
|
||||
checkout: true
|
||||
build-nonproprietary-ffmpeg: false
|
||||
artifact-key: 'linux-x64-asan'
|
||||
build-type: 'Linux'
|
||||
|
||||
linux-x64-testing-no-run-as-node:
|
||||
executor:
|
||||
@@ -1744,6 +1761,7 @@ jobs:
|
||||
persist: false
|
||||
checkout: true
|
||||
artifact-key: 'linux-x64-no-run-as-node'
|
||||
build-type: 'Linux'
|
||||
|
||||
linux-x64-testing-gn-check:
|
||||
executor:
|
||||
@@ -1775,6 +1793,7 @@ jobs:
|
||||
- electron-publish:
|
||||
attach: false
|
||||
checkout: true
|
||||
build-type: 'Linux'
|
||||
|
||||
|
||||
linux-arm-testing:
|
||||
@@ -1795,6 +1814,7 @@ jobs:
|
||||
checkout: false
|
||||
checkout-and-assume-cache: true
|
||||
artifact-key: 'linux-arm'
|
||||
build-type: 'Linux ARM'
|
||||
|
||||
linux-arm-publish:
|
||||
executor:
|
||||
@@ -1819,6 +1839,7 @@ jobs:
|
||||
- electron-publish:
|
||||
attach: false
|
||||
checkout: true
|
||||
build-type: 'Linux ARM'
|
||||
|
||||
linux-arm64-testing:
|
||||
executor:
|
||||
@@ -1838,6 +1859,7 @@ jobs:
|
||||
checkout: false
|
||||
checkout-and-assume-cache: true
|
||||
artifact-key: 'linux-arm64'
|
||||
build-type: 'Linux ARM64'
|
||||
|
||||
linux-arm64-testing-gn-check:
|
||||
executor:
|
||||
@@ -1872,6 +1894,7 @@ jobs:
|
||||
- electron-publish:
|
||||
attach: false
|
||||
checkout: true
|
||||
build-type: 'Linux ARM64'
|
||||
|
||||
osx-testing-x64:
|
||||
executor:
|
||||
@@ -1890,6 +1913,7 @@ jobs:
|
||||
checkout-and-assume-cache: true
|
||||
attach: true
|
||||
artifact-key: 'darwin-x64'
|
||||
build-type: 'Darwin'
|
||||
after-build-and-save:
|
||||
- run:
|
||||
name: Configuring MAS build
|
||||
@@ -1900,6 +1924,7 @@ jobs:
|
||||
rm -rf src/out/Default/Electron*.app
|
||||
- build_and_save_artifacts:
|
||||
artifact-key: 'mas-x64'
|
||||
build-type: 'MAS'
|
||||
after-persist:
|
||||
- persist_to_workspace:
|
||||
root: .
|
||||
@@ -1936,6 +1961,7 @@ jobs:
|
||||
- electron-publish:
|
||||
attach: true
|
||||
checkout: false
|
||||
build-type: 'Darwin'
|
||||
|
||||
osx-publish-arm64:
|
||||
executor:
|
||||
@@ -1958,6 +1984,7 @@ jobs:
|
||||
- electron-publish:
|
||||
attach: true
|
||||
checkout: false
|
||||
build-type: 'Darwin ARM64'
|
||||
|
||||
osx-testing-arm64:
|
||||
executor:
|
||||
@@ -1978,6 +2005,7 @@ jobs:
|
||||
checkout-and-assume-cache: true
|
||||
attach: true
|
||||
artifact-key: 'darwin-arm64'
|
||||
build-type: 'Darwin ARM64'
|
||||
after-build-and-save:
|
||||
- run:
|
||||
name: Configuring MAS build
|
||||
@@ -1988,6 +2016,7 @@ jobs:
|
||||
rm -rf src/out/Default/Electron*.app
|
||||
- build_and_save_artifacts:
|
||||
artifact-key: 'mas-arm64'
|
||||
build-type: 'MAS ARM64'
|
||||
after-persist:
|
||||
- persist_to_workspace:
|
||||
root: .
|
||||
@@ -2014,6 +2043,7 @@ jobs:
|
||||
- electron-publish:
|
||||
attach: true
|
||||
checkout: false
|
||||
build-type: 'MAS'
|
||||
|
||||
mas-publish-arm64:
|
||||
executor:
|
||||
@@ -2036,6 +2066,7 @@ jobs:
|
||||
- electron-publish:
|
||||
attach: true
|
||||
checkout: false
|
||||
build-type: 'MAS ARM64'
|
||||
|
||||
# Layer 3: Tests.
|
||||
linux-x64-testing-tests:
|
||||
|
||||
1
.github/CODEOWNERS
vendored
1
.github/CODEOWNERS
vendored
@@ -8,6 +8,7 @@
|
||||
DEPS @electron/wg-upgrades
|
||||
|
||||
# Releases WG
|
||||
/docs/breaking-changes.md @electron/wg-releases
|
||||
/npm/ @electron/wg-releases
|
||||
/script/release @electron/wg-releases
|
||||
|
||||
|
||||
14
.github/config.yml
vendored
14
.github/config.yml
vendored
@@ -25,17 +25,3 @@ newPRWelcomeComment: |
|
||||
# Comment to be posted to on pull requests merged by a first time user
|
||||
firstPRMergeComment: >
|
||||
Congrats on merging your first pull request! 🎉🎉🎉
|
||||
|
||||
# Users authorized to run manual trop backports
|
||||
authorizedUsers:
|
||||
- alexeykuzmin
|
||||
- ckerr
|
||||
- codebytere
|
||||
- deepak1556
|
||||
- jkleinsc
|
||||
- loc
|
||||
- MarshallOfSound
|
||||
- miniak
|
||||
- mlaurencin
|
||||
- nornagon
|
||||
- zcbenz
|
||||
|
||||
2
DEPS
2
DEPS
@@ -4,7 +4,7 @@ vars = {
|
||||
'chromium_version':
|
||||
'111.0.5560.0',
|
||||
'node_version':
|
||||
'v18.14.0',
|
||||
'v18.14.2',
|
||||
'nan_version':
|
||||
'16fa32231e2ccd89d2804b3f765319128b20c4ac',
|
||||
'squirrel.mac_version':
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
version: 1.0.{build}
|
||||
build_cloud: electronhq-16-core
|
||||
image: e-110.0.5451.0
|
||||
image: e-111.0.5560.0-node18
|
||||
environment:
|
||||
GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache
|
||||
ELECTRON_OUT_DIR: Default
|
||||
@@ -16,22 +16,58 @@ environment:
|
||||
GOMA_FALLBACK_ON_AUTH_FAILURE: true
|
||||
DEPOT_TOOLS_WIN_TOOLCHAIN: 0
|
||||
PYTHONIOENCODING: UTF-8
|
||||
# Uncomment these lines and set APPVEYOR_RDP_PASSWORD in project settings to enable RDP before bake begins
|
||||
# install:
|
||||
# - ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))
|
||||
|
||||
# The following lines are needed when baking from a completely new image (eg MicrosoftWindowsServer:WindowsServer:2019-Datacenter:latest via image: base-windows-server2019)
|
||||
# init:
|
||||
# - ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))
|
||||
# - appveyor version
|
||||
# - ps: $ErrorActionPreference = 'Stop'
|
||||
# - ps: 'Write-Host "OS Build: $((Get-CimInstance Win32_OperatingSystem).BuildNumber)"'
|
||||
|
||||
# clone_folder: '%USERPROFILE%\image-bake-scripts'
|
||||
|
||||
# clone_script:
|
||||
# - ps: Invoke-WebRequest "https://github.com/appveyor/build-images/archive/1f90d94e74c8243c909a09b994e527584dfcb838.zip" -OutFile "$env:temp\scripts.zip"
|
||||
# - ps: Expand-Archive -Path "$env:temp\scripts.zip" -DestinationPath "$env:temp\scripts" -Force
|
||||
# - ps: Copy-Item -Path "$env:temp\scripts\build-images-1f90d94e74c8243c909a09b994e527584dfcb838\scripts\Windows\*" -Destination $env:APPVEYOR_BUILD_FOLDER -Recurse
|
||||
|
||||
build_script:
|
||||
# Uncomment/change the following line if the hard drive/partition size needs to change
|
||||
# - ps: Resize-Partition -DriveLetter C -Size (256GB) # ensure initial partition size
|
||||
# The following lines are needed when baking from a completely new image (eg MicrosoftWindowsServer:WindowsServer:2019-Datacenter:latest via image: base-windows-server2019)
|
||||
# - ps: .\init_server.ps1
|
||||
# - ps: .\extend_system_volume.ps1
|
||||
|
||||
# # Restart VM
|
||||
# - ps: Start-Sleep -s 5; Restart-Computer
|
||||
# - ps: Start-Sleep -s 5
|
||||
|
||||
# - appveyor version
|
||||
# - ps: .\install_path_utils.ps1
|
||||
# - ps: .\install_powershell_core.ps1
|
||||
# - ps: .\install_powershell_get.ps1
|
||||
# - ps: .\install_7zip.ps1
|
||||
# - ps: .\install_chocolatey.ps1
|
||||
# - ps: .\install_webpi.ps1
|
||||
# - ps: .\install_nuget.ps1
|
||||
# - ps: .\install_pstools.ps1
|
||||
|
||||
# - ps: .\install_git.ps1
|
||||
# - ps: .\install_git_lfs.ps1
|
||||
|
||||
# # Restart VM
|
||||
# - ps: Start-Sleep -s 5; Restart-Computer
|
||||
# - ps: Start-Sleep -s 5
|
||||
# END LINES FOR COMPLETELY NEW IMAGE
|
||||
|
||||
- git config --global core.longpaths true
|
||||
- cd ..
|
||||
- ps: >-
|
||||
if (-not (Test-Path -Path .\src)) {
|
||||
New-Item -Path .\src -ItemType Directory
|
||||
if (-not (Test-Path -Path C:\projects\src)) {
|
||||
New-Item -Path C:\projects\src -ItemType Directory
|
||||
}
|
||||
- ps: git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git
|
||||
- cd C:\projects\
|
||||
- git clone -q --branch=%APPVEYOR_REPO_BRANCH% https://github.com/electron/electron.git C:\projects\src\electron
|
||||
- git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git
|
||||
- ps: $env:PATH="$pwd\depot_tools;$env:PATH"
|
||||
- update_depot_tools.bat
|
||||
- ps: Move-Item $env:APPVEYOR_BUILD_FOLDER -Destination src\electron
|
||||
# Uncomment the following line if windows deps change
|
||||
# - src\electron\script\setup-win-for-dev.bat
|
||||
- >-
|
||||
@@ -47,20 +83,25 @@ build_script:
|
||||
- ps: cd ..\..
|
||||
- gclient sync --with_branch_heads --with_tags --nohooks
|
||||
- ps: regsvr32 /s "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\DIA SDK\bin\amd64\msdia140.dll"
|
||||
- ps: |
|
||||
$env:appveyor_user = "appveyor"
|
||||
|
||||
$env:appveyor_password = [Guid]::NewGuid().ToString('B')
|
||||
# The following lines are needed when baking from a completely new image (eg MicrosoftWindowsServer:WindowsServer:2019-Datacenter:latest via image: base-windows-server2019)
|
||||
# # Restart VM
|
||||
# - ps: Start-Sleep -s 5; Restart-Computer
|
||||
# - ps: Start-Sleep -s 5
|
||||
|
||||
Set-LocalUser -Name $env:appveyor_user -Password (ConvertTo-SecureString -AsPlainText $env:appveyor_password -Force) -PasswordNeverExpires:$true
|
||||
|
||||
iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/build-images/master/scripts/Windows/enable_autologon.ps1'))
|
||||
# - cd %USERPROFILE%\image-bake-scripts
|
||||
# - appveyor version
|
||||
# - ps: .\optimize_dotnet_runtime.ps1
|
||||
# - ps: .\disable_windows_background_services.ps1
|
||||
# - ps: .\enforce_windows_firewall.ps1
|
||||
# - ps: .\cleanup_windows.ps1
|
||||
# END LINES FOR COMPLETELY NEW IMAGE
|
||||
on_image_bake:
|
||||
- ps: >-
|
||||
echo "Baking image: $env:APPVEYOR_BAKE_IMAGE at dir $PWD"
|
||||
- ps: Remove-Item -Recurse -Force $pwd\depot_tools
|
||||
- ps: Remove-Item -Recurse -Force $pwd\src\electron
|
||||
- ps: Remove-Item -Recurse -Force C:\projects\depot_tools
|
||||
- ps: Remove-Item -Recurse -Force C:\projects\src\electron
|
||||
# Uncomment these lines and set APPVEYOR_RDP_PASSWORD in project settings to enable RDP after bake is done
|
||||
#on_finish:
|
||||
# - ps: >-
|
||||
# $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))
|
||||
# # on_finish:
|
||||
# - ps: >-
|
||||
# $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))
|
||||
@@ -6,7 +6,7 @@
|
||||
# - "GN_CONFIG" Build type. One of {'testing', 'release'}.
|
||||
# - "GN_EXTRA_ARGS" Additional gn arguments for a build config,
|
||||
# e.g. 'target_cpu="x86"' to build for a 32bit platform.
|
||||
# https://gn.googlesource.com/gn/+/master/docs/reference.md#target_cpu
|
||||
# https://gn.googlesource.com/gn/+/main/docs/reference.md#var_target_cpu
|
||||
# Don't forget to set up "NPM_CONFIG_ARCH" and "TARGET_ARCH" accordingly
|
||||
# if you pass a custom value for 'target_cpu'.
|
||||
# - "ELECTRON_RELEASE" Set it to '1' upload binaries on success.
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
version: 1.0.{build}
|
||||
build_cloud: electronhq-16-core
|
||||
image: e-111.0.5518.0
|
||||
image: e-111.0.5560.0-2
|
||||
environment:
|
||||
GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache
|
||||
ELECTRON_OUT_DIR: Default
|
||||
@@ -82,7 +82,7 @@ for:
|
||||
if (Test-Path -Path "$pwd\build-tools") {
|
||||
Remove-Item -Recurse -Force $pwd\build-tools
|
||||
}
|
||||
- ps: git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git
|
||||
- git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git
|
||||
- ps: $env:PATH="$pwd\depot_tools;$env:PATH"
|
||||
- ps: >-
|
||||
if (Test-Path -Path "$pwd\src\electron") {
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
# - "GN_CONFIG" Build type. One of {'testing', 'release'}.
|
||||
# - "GN_EXTRA_ARGS" Additional gn arguments for a build config,
|
||||
# e.g. 'target_cpu="x86"' to build for a 32bit platform.
|
||||
# https://gn.googlesource.com/gn/+/master/docs/reference.md#target_cpu
|
||||
# https://gn.googlesource.com/gn/+/main/docs/reference.md#var_target_cpu
|
||||
# Don't forget to set up "NPM_CONFIG_ARCH" and "TARGET_ARCH" accordingly
|
||||
# if you pass a custom value for 'target_cpu'.
|
||||
# - "ELECTRON_RELEASE" Set it to '1' upload binaries on success.
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
version: 1.0.{build}
|
||||
build_cloud: electronhq-16-core
|
||||
image: e-111.0.5560.0
|
||||
image: e-111.0.5560.0-node18
|
||||
environment:
|
||||
GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache
|
||||
ELECTRON_OUT_DIR: Default
|
||||
@@ -80,7 +80,7 @@ for:
|
||||
if (Test-Path -Path "$pwd\build-tools") {
|
||||
Remove-Item -Recurse -Force $pwd\build-tools
|
||||
}
|
||||
- ps: git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git
|
||||
- git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git
|
||||
- ps: $env:PATH="$pwd\depot_tools;$env:PATH"
|
||||
- ps: >-
|
||||
if (Test-Path -Path "$pwd\src\electron") {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
is_electron_build = true
|
||||
root_extra_deps = [ "//electron" ]
|
||||
|
||||
# Registry of NMVs --> https://github.com/nodejs/node/blob/master/doc/abi_version_registry.json
|
||||
# Registry of NMVs --> https://github.com/nodejs/node/blob/main/doc/abi_version_registry.json
|
||||
node_module_version = 114
|
||||
|
||||
v8_promise_internal_field_count = 1
|
||||
|
||||
@@ -23,8 +23,7 @@ The `app` object emits the following events:
|
||||
Emitted when the application has finished basic startup. On Windows and Linux,
|
||||
the `will-finish-launching` event is the same as the `ready` event; on macOS,
|
||||
this event represents the `applicationWillFinishLaunching` notification of
|
||||
`NSApplication`. You would usually set up listeners for the `open-file` and
|
||||
`open-url` events here, and start the crash reporter and auto updater.
|
||||
`NSApplication`.
|
||||
|
||||
In most cases, you should do everything in the `ready` event handler.
|
||||
|
||||
@@ -1357,7 +1356,7 @@ This API must be called after the `ready` event is emitted.
|
||||
|
||||
### `app.showAboutPanel()`
|
||||
|
||||
Show the app's about panel options. These options can be overridden with `app.setAboutPanelOptions(options)`.
|
||||
Show the app's about panel options. These options can be overridden with `app.setAboutPanelOptions(options)`. This function runs asynchronously.
|
||||
|
||||
### `app.setAboutPanelOptions(options)`
|
||||
|
||||
|
||||
@@ -269,7 +269,7 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
|
||||
zoom to the width of the screen. This will also affect the behavior when
|
||||
calling `maximize()` directly. Default is `false`.
|
||||
* `tabbingIdentifier` string (optional) _macOS_ - Tab group name, allows
|
||||
opening the window as a native tab on macOS 10.12+. Windows with the same
|
||||
opening the window as a native tab. Windows with the same
|
||||
tabbing identifier will be grouped together. This also adds a native new
|
||||
tab button to your window's tab bar and allows your `app` and window to
|
||||
receive the `new-window-for-tab` event.
|
||||
@@ -1776,7 +1776,7 @@ On macOS it does not remove the focus from the window.
|
||||
|
||||
#### `win.isFocusable()` _macOS_ _Windows_
|
||||
|
||||
Returns whether the window can be focused.
|
||||
Returns `boolean` - Whether the window can be focused.
|
||||
|
||||
#### `win.setParentWindow(parent)`
|
||||
|
||||
@@ -1842,16 +1842,36 @@ will remove the vibrancy effect on the window.
|
||||
Note that `appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` have been
|
||||
deprecated and will be removed in an upcoming version of macOS.
|
||||
|
||||
#### `win.setTrafficLightPosition(position)` _macOS_
|
||||
#### `win.setWindowButtonPosition(position)` _macOS_
|
||||
|
||||
* `position` [Point](structures/point.md) | null
|
||||
|
||||
Set a custom position for the traffic light buttons in frameless window.
|
||||
Passing `null` will reset the position to default.
|
||||
|
||||
#### `win.getWindowButtonPosition()` _macOS_
|
||||
|
||||
Returns `Point | null` - The custom position for the traffic light buttons in
|
||||
frameless window, `null` will be returned when there is no custom position.
|
||||
|
||||
#### `win.setTrafficLightPosition(position)` _macOS_ _Deprecated_
|
||||
|
||||
* `position` [Point](structures/point.md)
|
||||
|
||||
Set a custom position for the traffic light buttons in frameless window.
|
||||
Passing `{ x: 0, y: 0 }` will reset the position to default.
|
||||
|
||||
#### `win.getTrafficLightPosition()` _macOS_
|
||||
> **Note**
|
||||
> This function is deprecated. Use [setWindowButtonPosition](#winsetwindowbuttonpositionposition-macos) instead.
|
||||
|
||||
#### `win.getTrafficLightPosition()` _macOS_ _Deprecated_
|
||||
|
||||
Returns `Point` - The custom position for the traffic light buttons in
|
||||
frameless window.
|
||||
frameless window, `{ x: 0, y: 0 }` will be returned when there is no custom
|
||||
position.
|
||||
|
||||
> **Note**
|
||||
> This function is deprecated. Use [getWindowButtonPosition](#wingetwindowbuttonposition-macos) instead.
|
||||
|
||||
#### `win.setTouchBar(touchBar)` _macOS_
|
||||
|
||||
@@ -1859,7 +1879,7 @@ frameless window.
|
||||
|
||||
Sets the touchBar layout for the current window. Specifying `null` or
|
||||
`undefined` clears the touch bar. This method only has an effect if the
|
||||
machine has a touch bar and is running on macOS 10.12.1+.
|
||||
machine has a touch bar.
|
||||
|
||||
**Note:** The TouchBar API is currently experimental and may change or be
|
||||
removed in future Electron releases.
|
||||
@@ -1910,7 +1930,7 @@ removed in future Electron releases.
|
||||
On a Window with Window Controls Overlay already enabled, this method updates
|
||||
the style of the title bar overlay.
|
||||
|
||||
[runtime-enabled-features]: https://cs.chromium.org/chromium/src/third_party/blink/renderer/platform/runtime_enabled_features.json5?l=70
|
||||
[runtime-enabled-features]: https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/runtime_enabled_features.json5
|
||||
[page-visibility-api]: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
|
||||
[quick-look]: https://en.wikipedia.org/wiki/Quick_Look
|
||||
[vibrancy-docs]: https://developer.apple.com/documentation/appkit/nsvisualeffectview?preferredLanguage=objc
|
||||
|
||||
@@ -23,12 +23,14 @@ following properties:
|
||||
with which the request is associated. Defaults to the empty string. The
|
||||
`session` option supersedes `partition`. Thus if a `session` is explicitly
|
||||
specified, `partition` is ignored.
|
||||
* `credentials` string (optional) - Can be `include` or `omit`. Whether to
|
||||
send [credentials](https://fetch.spec.whatwg.org/#credentials) with this
|
||||
* `credentials` string (optional) - Can be `include`, `omit` or
|
||||
`same-origin`. Whether to send
|
||||
[credentials](https://fetch.spec.whatwg.org/#credentials) with this
|
||||
request. If set to `include`, credentials from the session associated with
|
||||
the request will be used. If set to `omit`, credentials will not be sent
|
||||
with the request (and the `'login'` event will not be triggered in the
|
||||
event of a 401). This matches the behavior of the
|
||||
event of a 401). If set to `same-origin`, `origin` must also be specified.
|
||||
This matches the behavior of the
|
||||
[fetch](https://fetch.spec.whatwg.org/#concept-request-credentials-mode)
|
||||
option of the same name. If this option is not specified, authentication
|
||||
data from the session will be sent, and cookies will not be sent (unless
|
||||
@@ -49,6 +51,13 @@ following properties:
|
||||
[`request.followRedirect`](#requestfollowredirect) is invoked synchronously
|
||||
during the [`redirect`](#event-redirect) event. Defaults to `follow`.
|
||||
* `origin` string (optional) - The origin URL of the request.
|
||||
* `referrerPolicy` string (optional) - can be `""`, `no-referrer`,
|
||||
`no-referrer-when-downgrade`, `origin`, `origin-when-cross-origin`,
|
||||
`unsafe-url`, `same-origin`, `strict-origin`, or
|
||||
`strict-origin-when-cross-origin`. Defaults to
|
||||
`strict-origin-when-cross-origin`.
|
||||
* `cache` string (optional) - can be `default`, `no-store`, `reload`,
|
||||
`no-cache`, `force-cache` or `only-if-cached`.
|
||||
|
||||
`options` properties such as `protocol`, `host`, `hostname`, `port` and `path`
|
||||
strictly follow the Node.js model as described in the
|
||||
|
||||
@@ -226,7 +226,7 @@ clipboard.writeBuffer('public/utf8-plain-text', buffer)
|
||||
|
||||
const ret = clipboard.readBuffer('public/utf8-plain-text')
|
||||
|
||||
console.log(buffer.equals(out))
|
||||
console.log(buffer.equals(ret))
|
||||
// true
|
||||
```
|
||||
|
||||
|
||||
@@ -78,6 +78,7 @@ The following methods are available on instances of `Cookies`:
|
||||
* `path` string (optional) - Retrieves cookies whose path matches `path`.
|
||||
* `secure` boolean (optional) - Filters cookies by their Secure property.
|
||||
* `session` boolean (optional) - Filters out session or persistent cookies.
|
||||
* `httpOnly` boolean (optional) - Filters cookies by httpOnly.
|
||||
|
||||
Returns `Promise<Cookie[]>` - A promise which resolves an array of cookie objects.
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ See [`Menu`](menu.md) for examples.
|
||||
the placement of their containing group after the containing group of the item
|
||||
with the specified label.
|
||||
|
||||
**Note:** `acceleratorWorksWhenHidden` is specified as being macOS-only because accelerators always work when items are hidden on Windows and Linux. The option is exposed to users to give them the option to turn it off, as this is possible in native macOS development. This property is only usable on macOS High Sierra 10.13 or newer.
|
||||
**Note:** `acceleratorWorksWhenHidden` is specified as being macOS-only because accelerators always work when items are hidden on Windows and Linux. The option is exposed to users to give them the option to turn it off, as this is possible in native macOS development.
|
||||
|
||||
### Roles
|
||||
|
||||
|
||||
@@ -119,13 +119,15 @@ Returns `NativeImage`
|
||||
|
||||
Creates an empty `NativeImage` instance.
|
||||
|
||||
### `nativeImage.createThumbnailFromPath(path, maxSize)` _macOS_ _Windows_
|
||||
### `nativeImage.createThumbnailFromPath(path, size)` _macOS_ _Windows_
|
||||
|
||||
* `path` string - path to a file that we intend to construct a thumbnail out of.
|
||||
* `maxSize` [Size](structures/size.md) - the maximum width and height (positive numbers) the thumbnail returned can be. The Windows implementation will ignore `maxSize.height` and scale the height according to `maxSize.width`.
|
||||
* `size` [Size](structures/size.md) - the desired width and height (positive numbers) of the thumbnail.
|
||||
|
||||
Returns `Promise<NativeImage>` - fulfilled with the file's thumbnail preview image, which is a [NativeImage](native-image.md).
|
||||
|
||||
Note: The Windows implementation will ignore `size.height` and scale the height according to `size.width`.
|
||||
|
||||
### `nativeImage.createFromPath(path)`
|
||||
|
||||
* `path` string
|
||||
|
||||
@@ -63,6 +63,48 @@ Creates a [`ClientRequest`](./client-request.md) instance using the provided
|
||||
The `net.request` method would be used to issue both secure and insecure HTTP
|
||||
requests according to the specified protocol scheme in the `options` object.
|
||||
|
||||
### `net.fetch(input[, init])`
|
||||
|
||||
* `input` string | [Request](https://nodejs.org/api/globals.html#request)
|
||||
* `init` [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options) (optional)
|
||||
|
||||
Returns `Promise<GlobalResponse>` - see [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response).
|
||||
|
||||
Sends a request, similarly to how `fetch()` works in the renderer, using
|
||||
Chrome's network stack. This differs from Node's `fetch()`, which uses
|
||||
Node.js's HTTP stack.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
async function example () {
|
||||
const response = await net.fetch('https://my.app')
|
||||
if (response.ok) {
|
||||
const body = await response.json()
|
||||
// ... use the result.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This method will issue requests from the [default
|
||||
session](session.md#sessiondefaultsession). To send a `fetch` request from
|
||||
another session, use [ses.fetch()](session.md#sesfetchinput-init).
|
||||
|
||||
See the MDN documentation for
|
||||
[`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) for more
|
||||
details.
|
||||
|
||||
Limitations:
|
||||
|
||||
* `net.fetch()` does not support the `data:` or `blob:` schemes.
|
||||
* The value of the `integrity` option is ignored.
|
||||
* The `.type` and `.url` values of the returned `Response` object are
|
||||
incorrect.
|
||||
|
||||
Requests made with `net.fetch` can be made to [custom protocols](protocol.md)
|
||||
as well as `file:`, and will trigger [webRequest](web-request.md) handlers if
|
||||
present.
|
||||
|
||||
### `net.isOnline()`
|
||||
|
||||
Returns `boolean` - Whether there is currently internet connection.
|
||||
|
||||
@@ -49,8 +49,11 @@ beginning to load the web page or the main script.
|
||||
|
||||
### `process.defaultApp` _Readonly_
|
||||
|
||||
A `boolean`. When app is started by being passed as parameter to the default app, this
|
||||
A `boolean`. When the app is started by being passed as parameter to the default Electron executable, this
|
||||
property is `true` in the main process, otherwise it is `undefined`.
|
||||
For example when running the app with `electron .`, it is `true`,
|
||||
even if the app is packaged ([`isPackaged`](app.md#appispackaged-readonly)) is `true`.
|
||||
This can be useful to determine how many arguments will need to be sliced off from `process.argv`.
|
||||
|
||||
### `process.isMainFrame` _Readonly_
|
||||
|
||||
|
||||
@@ -731,6 +731,47 @@ Returns `Promise<void>` - Resolves when all connections are closed.
|
||||
|
||||
**Note:** It will terminate / fail all requests currently in flight.
|
||||
|
||||
#### `ses.fetch(input[, init])`
|
||||
|
||||
* `input` string | [GlobalRequest](https://nodejs.org/api/globals.html#request)
|
||||
* `init` [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options) (optional)
|
||||
|
||||
Returns `Promise<GlobalResponse>` - see [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response).
|
||||
|
||||
Sends a request, similarly to how `fetch()` works in the renderer, using
|
||||
Chrome's network stack. This differs from Node's `fetch()`, which uses
|
||||
Node.js's HTTP stack.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
async function example () {
|
||||
const response = await net.fetch('https://my.app')
|
||||
if (response.ok) {
|
||||
const body = await response.json()
|
||||
// ... use the result.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See also [`net.fetch()`](net.md#netfetchinput-init), a convenience method which
|
||||
issues requests from the [default session](#sessiondefaultsession).
|
||||
|
||||
See the MDN documentation for
|
||||
[`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) for more
|
||||
details.
|
||||
|
||||
Limitations:
|
||||
|
||||
* `net.fetch()` does not support the `data:` or `blob:` schemes.
|
||||
* The value of the `integrity` option is ignored.
|
||||
* The `.type` and `.url` values of the returned `Response` object are
|
||||
incorrect.
|
||||
|
||||
Requests made with `ses.fetch` can be made to [custom protocols](protocol.md)
|
||||
as well as `file:`, and will trigger [webRequest](web-request.md) handlers if
|
||||
present.
|
||||
|
||||
#### `ses.disableNetworkEmulation()`
|
||||
|
||||
Disables any network emulation already active for the `session`. Resets to
|
||||
@@ -879,6 +920,10 @@ session.fromPartition('some-partition').setPermissionCheckHandler((webContents,
|
||||
Specifying a loopback device will capture system audio, and is
|
||||
currently only supported on Windows. If a WebFrameMain is specified,
|
||||
will capture audio from that frame.
|
||||
* `enableLocalEcho` Boolean (optional) - If `audio` is a [WebFrameMain](web-frame-main.md)
|
||||
and this is set to `true`, then local playback of audio will not be muted (e.g. using `MediaRecorder`
|
||||
to record `WebFrameMain` with this flag set to `true` will allow audio to pass through to the speakers
|
||||
while recording). Default is `false`.
|
||||
|
||||
This handler will be called when web content requests access to display media
|
||||
via the `navigator.mediaDevices.getDisplayMedia` API. Use the
|
||||
|
||||
@@ -40,6 +40,8 @@ Open the given file in the desktop's default manner.
|
||||
* `options` Object (optional)
|
||||
* `activate` boolean (optional) _macOS_ - `true` to bring the opened application to the foreground. The default is `true`.
|
||||
* `workingDirectory` string (optional) _Windows_ - The working directory.
|
||||
* `logUsage` boolean (optional) _Windows_ - Indicates a user initiated launch that enables tracking of frequently used programs and other behaviors.
|
||||
The default is `false`.
|
||||
|
||||
Returns `Promise<void>`
|
||||
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
# Event Object extends `GlobalEvent`
|
||||
|
||||
* `preventDefault` VoidFunction
|
||||
@@ -1,3 +1,4 @@
|
||||
# WebRequestFilter Object
|
||||
|
||||
* `urls` string[] - Array of [URL patterns](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns) that will be used to filter out the requests that do not match the URL patterns.
|
||||
* `types` String[] (optional) - Array of types that will be used to filter out the requests that do not match the types. When not specified, all types will be matched. Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media` or `webSocket`.
|
||||
|
||||
@@ -394,8 +394,6 @@ system default and override the value of `getEffectiveAppearance`.
|
||||
|
||||
Returns `boolean` - whether or not this device has the ability to use Touch ID.
|
||||
|
||||
**NOTE:** This API will return `false` on macOS systems older than Sierra 10.12.2.
|
||||
|
||||
### `systemPreferences.promptTouchID(reason)` _macOS_
|
||||
|
||||
* `reason` string - The reason you are asking for Touch ID authentication
|
||||
@@ -414,8 +412,6 @@ systemPreferences.promptTouchID('To get consent for a Security-Gated Thing').the
|
||||
|
||||
This API itself will not protect your user data; rather, it is a mechanism to allow you to do so. Native apps will need to set [Access Control Constants](https://developer.apple.com/documentation/security/secaccesscontrolcreateflags?language=objc) like [`kSecAccessControlUserPresence`](https://developer.apple.com/documentation/security/secaccesscontrolcreateflags/ksecaccesscontroluserpresence?language=objc) on their keychain entry so that reading it would auto-prompt for Touch ID biometric consent. This could be done with [`node-keytar`](https://github.com/atom/node-keytar), such that one would store an encryption key with `node-keytar` and only fetch it if `promptTouchID()` resolves.
|
||||
|
||||
**NOTE:** This API will return a rejected Promise on macOS systems older than Sierra 10.12.2.
|
||||
|
||||
### `systemPreferences.isTrustedAccessibilityClient(prompt)` _macOS_
|
||||
|
||||
* `prompt` boolean - whether or not the user will be informed via prompt if the current process is untrusted.
|
||||
@@ -428,7 +424,7 @@ Returns `boolean` - `true` if the current process is a trusted accessibility cli
|
||||
|
||||
Returns `string` - Can be `not-determined`, `granted`, `denied`, `restricted` or `unknown`.
|
||||
|
||||
This user consent was not required on macOS 10.13 High Sierra or lower so this method will always return `granted`.
|
||||
This user consent was not required on macOS 10.13 High Sierra so this method will always return `granted`.
|
||||
macOS 10.14 Mojave or higher requires consent for `microphone` and `camera` access.
|
||||
macOS 10.15 Catalina or higher requires consent for `screen` access.
|
||||
|
||||
@@ -443,7 +439,7 @@ Returns `Promise<boolean>` - A promise that resolves with `true` if consent was
|
||||
|
||||
**Important:** In order to properly leverage this API, you [must set](https://developer.apple.com/documentation/avfoundation/cameras_and_media_capture/requesting_authorization_for_media_capture_on_macos?language=objc) the `NSMicrophoneUsageDescription` and `NSCameraUsageDescription` strings in your app's `Info.plist` file. The values for these keys will be used to populate the permission dialogs so that the user will be properly informed as to the purpose of the permission request. See [Electron Application Distribution](../tutorial/application-distribution.md#rebranding-with-downloaded-binaries) for more information about how to set these in the context of Electron.
|
||||
|
||||
This user consent was not required until macOS 10.14 Mojave, so this method will always return `true` if your system is running 10.13 High Sierra or lower.
|
||||
This user consent was not required until macOS 10.14 Mojave, so this method will always return `true` if your system is running 10.13 High Sierra.
|
||||
|
||||
### `systemPreferences.getAnimationSettings()`
|
||||
|
||||
|
||||
@@ -235,7 +235,7 @@ Sets the hover text for this tray icon.
|
||||
|
||||
* `title` string
|
||||
* `options` Object (optional)
|
||||
* `fontType` string (optional) - The font family variant to display, can be `monospaced` or `monospacedDigit`. `monospaced` is available in macOS 10.15+ and `monospacedDigit` is available in macOS 10.11+. When left blank, the title uses the default system font.
|
||||
* `fontType` string (optional) - The font family variant to display, can be `monospaced` or `monospacedDigit`. `monospaced` is available in macOS 10.15+ When left blank, the title uses the default system font.
|
||||
|
||||
Sets the title displayed next to the tray icon in the status bar (Support ANSI colors).
|
||||
|
||||
|
||||
@@ -207,8 +207,23 @@ See [`window.open()`](window-open.md) for more details and how to use this in co
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `url` string
|
||||
* `details` Event<>
|
||||
* `url` string - The URL the frame is navigating to.
|
||||
* `isSameDocument` boolean - Whether the navigation happened without changing
|
||||
document. Examples of same document navigations are reference fragment
|
||||
navigations, pushState/replaceState, and same page history navigation.
|
||||
* `isMainFrame` boolean - True if the navigation is taking place in a main frame.
|
||||
* `frame` WebFrameMain - The frame to be navigated.
|
||||
* `initiator` WebFrameMain (optional) - The frame which initiated the
|
||||
navigation, which can be a parent frame (e.g. via `window.open` with a
|
||||
frame's name), or null if the navigation was not initiated by a frame. This
|
||||
can also be null if the initiating frame was deleted before the event was
|
||||
emitted.
|
||||
* `url` string _Deprecated_
|
||||
* `isInPlace` boolean _Deprecated_
|
||||
* `isMainFrame` boolean _Deprecated_
|
||||
* `frameProcessId` Integer _Deprecated_
|
||||
* `frameRoutingId` Integer _Deprecated_
|
||||
|
||||
Emitted when a user or the page wants to start navigation. It can happen when
|
||||
the `window.location` object is changed or a user clicks a link in the page.
|
||||
@@ -226,26 +241,47 @@ Calling `event.preventDefault()` will prevent the navigation.
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `url` string
|
||||
* `isInPlace` boolean
|
||||
* `isMainFrame` boolean
|
||||
* `frameProcessId` Integer
|
||||
* `frameRoutingId` Integer
|
||||
* `details` Event<>
|
||||
* `url` string - The URL the frame is navigating to.
|
||||
* `isSameDocument` boolean - Whether the navigation happened without changing
|
||||
document. Examples of same document navigations are reference fragment
|
||||
navigations, pushState/replaceState, and same page history navigation.
|
||||
* `isMainFrame` boolean - True if the navigation is taking place in a main frame.
|
||||
* `frame` WebFrameMain - The frame to be navigated.
|
||||
* `initiator` WebFrameMain (optional) - The frame which initiated the
|
||||
navigation, which can be a parent frame (e.g. via `window.open` with a
|
||||
frame's name), or null if the navigation was not initiated by a frame. This
|
||||
can also be null if the initiating frame was deleted before the event was
|
||||
emitted.
|
||||
* `url` string _Deprecated_
|
||||
* `isInPlace` boolean _Deprecated_
|
||||
* `isMainFrame` boolean _Deprecated_
|
||||
* `frameProcessId` Integer _Deprecated_
|
||||
* `frameRoutingId` Integer _Deprecated_
|
||||
|
||||
Emitted when any frame (including main) starts navigating. `isInPlace` will be
|
||||
`true` for in-page navigations.
|
||||
Emitted when any frame (including main) starts navigating.
|
||||
|
||||
#### Event: 'will-redirect'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `url` string
|
||||
* `isInPlace` boolean
|
||||
* `isMainFrame` boolean
|
||||
* `frameProcessId` Integer
|
||||
* `frameRoutingId` Integer
|
||||
* `details` Event<>
|
||||
* `url` string - The URL the frame is navigating to.
|
||||
* `isSameDocument` boolean - Whether the navigation happened without changing
|
||||
document. Examples of same document navigations are reference fragment
|
||||
navigations, pushState/replaceState, and same page history navigation.
|
||||
* `isMainFrame` boolean - True if the navigation is taking place in a main frame.
|
||||
* `frame` WebFrameMain - The frame to be navigated.
|
||||
* `initiator` WebFrameMain (optional) - The frame which initiated the
|
||||
navigation, which can be a parent frame (e.g. via `window.open` with a
|
||||
frame's name), or null if the navigation was not initiated by a frame. This
|
||||
can also be null if the initiating frame was deleted before the event was
|
||||
emitted.
|
||||
* `url` string _Deprecated_
|
||||
* `isInPlace` boolean _Deprecated_
|
||||
* `isMainFrame` boolean _Deprecated_
|
||||
* `frameProcessId` Integer _Deprecated_
|
||||
* `frameRoutingId` Integer _Deprecated_
|
||||
|
||||
Emitted when a server side redirect occurs during navigation. For example a 302
|
||||
redirect.
|
||||
@@ -260,12 +296,23 @@ redirect).
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `url` string
|
||||
* `isInPlace` boolean
|
||||
* `isMainFrame` boolean
|
||||
* `frameProcessId` Integer
|
||||
* `frameRoutingId` Integer
|
||||
* `details` Event<>
|
||||
* `url` string - The URL the frame is navigating to.
|
||||
* `isSameDocument` boolean - Whether the navigation happened without changing
|
||||
document. Examples of same document navigations are reference fragment
|
||||
navigations, pushState/replaceState, and same page history navigation.
|
||||
* `isMainFrame` boolean - True if the navigation is taking place in a main frame.
|
||||
* `frame` WebFrameMain - The frame to be navigated.
|
||||
* `initiator` WebFrameMain (optional) - The frame which initiated the
|
||||
navigation, which can be a parent frame (e.g. via `window.open` with a
|
||||
frame's name), or null if the navigation was not initiated by a frame. This
|
||||
can also be null if the initiating frame was deleted before the event was
|
||||
emitted.
|
||||
* `url` string _Deprecated_
|
||||
* `isInPlace` boolean _Deprecated_
|
||||
* `isMainFrame` boolean _Deprecated_
|
||||
* `frameProcessId` Integer _Deprecated_
|
||||
* `frameRoutingId` Integer _Deprecated_
|
||||
|
||||
Emitted after a server side redirect occurs during navigation. For example a 302
|
||||
redirect.
|
||||
@@ -588,6 +635,15 @@ Emitted when media starts playing.
|
||||
|
||||
Emitted when media is paused or done playing.
|
||||
|
||||
#### Event: 'audio-state-changed'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event<>
|
||||
* `audible` boolean - True if one or more frames or child `webContents` are emitting audio.
|
||||
|
||||
Emitted when media becomes audible or inaudible.
|
||||
|
||||
#### Event: 'did-change-theme-color'
|
||||
|
||||
Returns:
|
||||
@@ -730,7 +786,7 @@ cancel the request.
|
||||
|
||||
If no event listener is added for this event, all bluetooth requests will be cancelled.
|
||||
|
||||
```javascript
|
||||
```javascript title='main.js'
|
||||
const { app, BrowserWindow } = require('electron')
|
||||
|
||||
let win = null
|
||||
@@ -831,7 +887,7 @@ Emitted when the preload script `preloadPath` throws an unhandled exception `err
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `event` [IpcMainEvent](structures/ipc-main-event.md)
|
||||
* `channel` string
|
||||
* `...args` any[]
|
||||
|
||||
@@ -843,7 +899,7 @@ See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `event` [IpcMainEvent](structures/ipc-main-event.md)
|
||||
* `channel` string
|
||||
* `...args` any[]
|
||||
|
||||
@@ -1409,8 +1465,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.
|
||||
@@ -1575,7 +1631,7 @@ ipcMain.on('open-devtools', (event, targetContentsId, devtoolsContentsId) => {
|
||||
|
||||
An example of showing devtools in a `BrowserWindow`:
|
||||
|
||||
```js
|
||||
```js title='main.js'
|
||||
const { app, BrowserWindow } = require('electron')
|
||||
|
||||
let win = null
|
||||
@@ -1658,40 +1714,14 @@ Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be
|
||||
included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will
|
||||
throw an exception.
|
||||
|
||||
> **NOTE**: Sending non-standard JavaScript types such as DOM objects or
|
||||
> special Electron objects will throw an exception.
|
||||
:::warning
|
||||
|
||||
The renderer process can handle the message by listening to `channel` with the
|
||||
[`ipcRenderer`](ipc-renderer.md) module.
|
||||
Sending non-standard JavaScript types such as DOM objects or
|
||||
special Electron objects will throw an exception.
|
||||
|
||||
An example of sending messages from the main process to the renderer process:
|
||||
:::
|
||||
|
||||
```javascript
|
||||
// In the main process.
|
||||
const { app, BrowserWindow } = require('electron')
|
||||
let win = null
|
||||
|
||||
app.whenReady().then(() => {
|
||||
win = new BrowserWindow({ width: 800, height: 600 })
|
||||
win.loadURL(`file://${__dirname}/index.html`)
|
||||
win.webContents.on('did-finish-load', () => {
|
||||
win.webContents.send('ping', 'whoooooooh!')
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- index.html -->
|
||||
<html>
|
||||
<body>
|
||||
<script>
|
||||
require('electron').ipcRenderer.on('ping', (event, message) => {
|
||||
console.log(message) // Prints 'whoooooooh!'
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
For additional reading, refer to [Electron's IPC guide](../tutorial/ipc.md).
|
||||
|
||||
#### `contents.sendToFrame(frameId, channel, ...args)`
|
||||
|
||||
|
||||
@@ -1001,7 +1001,7 @@ Emitted when DevTools is closed.
|
||||
|
||||
Emitted when DevTools is focused / opened.
|
||||
|
||||
[runtime-enabled-features]: https://cs.chromium.org/chromium/src/third_party/blink/renderer/platform/runtime_enabled_features.json5?l=70
|
||||
[runtime-enabled-features]: https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/runtime_enabled_features.json5
|
||||
[chrome-webview]: https://developer.chrome.com/docs/extensions/reference/webviewTag/
|
||||
|
||||
### Event: 'context-menu'
|
||||
|
||||
@@ -12,8 +12,91 @@ This document uses the following convention to categorize breaking changes:
|
||||
* **Deprecated:** An API was marked as deprecated. The API will continue to function, but will emit a deprecation warning, and will be removed in a future release.
|
||||
* **Removed:** An API or feature was removed, and is no longer supported by Electron.
|
||||
|
||||
## Planned Breaking API Changes (24.0)
|
||||
|
||||
### API Changed: `nativeImage.createThumbnailFromPath(path, size)`
|
||||
|
||||
The `maxSize` parameter has been changed to `size` to reflect that the size passed in will be the size the thumbnail created. Previously, Windows would not scale the image up if it were smaller than `maxSize`, and
|
||||
macOS would always set the size to `maxSize`. Behavior is now the same across platforms.
|
||||
|
||||
Updated Behavior:
|
||||
|
||||
```js
|
||||
// a 128x128 image.
|
||||
const imagePath = path.join('path', 'to', 'capybara.png')
|
||||
|
||||
// Scaling up a smaller image.
|
||||
const upSize = { width: 256, height: 256 }
|
||||
nativeImage.createThumbnailFromPath(imagePath, upSize).then(result => {
|
||||
console.log(result.getSize()) // { width: 256, height: 256 }
|
||||
})
|
||||
|
||||
// Scaling down a larger image.
|
||||
const downSize = { width: 64, height: 64 }
|
||||
nativeImage.createThumbnailFromPath(imagePath, downSize).then(result => {
|
||||
console.log(result.getSize()) // { width: 64, height: 64 }
|
||||
})
|
||||
```
|
||||
|
||||
Previous Behavior (on Windows):
|
||||
|
||||
```js
|
||||
// a 128x128 image
|
||||
const imagePath = path.join('path', 'to', 'capybara.png')
|
||||
const size = { width: 256, height: 256 }
|
||||
nativeImage.createThumbnailFromPath(imagePath, size).then(result => {
|
||||
console.log(result.getSize()) // { width: 128, height: 128 }
|
||||
})
|
||||
```
|
||||
|
||||
### Deprecated: `BrowserWindow.setTrafficLightPosition(position)`
|
||||
|
||||
`BrowserWindow.setTrafficLightPosition(position)` has been deprecated, the
|
||||
`BrowserWindow.setWindowButtonPosition(position)` API should be used instead
|
||||
which accepts `null` instead of `{ x: 0, y: 0 }` to reset the position to
|
||||
system default.
|
||||
|
||||
```js
|
||||
// Removed in Electron 24
|
||||
win.setTrafficLightPosition({ x: 10, y: 10 })
|
||||
win.setTrafficLightPosition({ x: 0, y: 0 })
|
||||
|
||||
// Replace with
|
||||
win.setWindowButtonPosition({ x: 10, y: 10 })
|
||||
win.setWindowButtonPosition(null)
|
||||
```
|
||||
|
||||
### Deprecated: `BrowserWindow.getTrafficLightPosition()`
|
||||
|
||||
`BrowserWindow.getTrafficLightPosition()` has been deprecated, the
|
||||
`BrowserWindow.getWindowButtonPosition()` API should be used instead
|
||||
which returns `null` instead of `{ x: 0, y: 0 }` when there is no custom
|
||||
position.
|
||||
|
||||
```js
|
||||
// Removed in Electron 24
|
||||
const pos = win.getTrafficLightPosition()
|
||||
if (pos.x === 0 && pos.y === 0) {
|
||||
// No custom position.
|
||||
}
|
||||
|
||||
// Replace with
|
||||
const ret = win.getWindowButtonPosition()
|
||||
if (ret === null) {
|
||||
// No custom position.
|
||||
}
|
||||
```
|
||||
|
||||
## Planned Breaking API Changes (23.0)
|
||||
|
||||
### Behavior Changed: Draggable Regions on macOS
|
||||
|
||||
The implementation of draggable regions (using the CSS property `-webkit-app-region: drag`) has changed on macOS to bring it in line with Windows and Linux. Previously, when a region with `-webkit-app-region: no-drag` overlapped a region with `-webkit-app-region: drag`, the `no-drag` region would always take precedence on macOS, regardless of CSS layering. That is, if a `drag` region was above a `no-drag` region, it would be ignored. Beginning in Electron 23, a `drag` region on top of a `no-drag` region will correctly cause the region to be draggable.
|
||||
|
||||
Additionally, the `customButtonsOnHover` BrowserWindow property previously created a draggable region which ignored the `-webkit-app-region` CSS property. This has now been fixed (see [#37210](https://github.com/electron/electron/issues/37210#issuecomment-1440509592) for discussion).
|
||||
|
||||
As a result, if your app uses a frameless window with draggable regions on macOS, the regions which are draggable in your app may change in Electron 23.
|
||||
|
||||
### Removed: Windows 7 / 8 / 8.1 support
|
||||
|
||||
[Windows 7, Windows 8, and Windows 8.1 are no longer supported](https://www.electronjs.org/blog/windows-7-to-8-1-deprecation-notice). Electron follows the planned Chromium deprecation policy, which will [deprecate Windows 7 support beginning in Chromium 109](https://support.google.com/chrome/thread/185534985/sunsetting-support-for-windows-7-8-8-1-in-early-2023?hl=en).
|
||||
@@ -236,6 +319,13 @@ webContents.printToPDF({
|
||||
|
||||
## Planned Breaking API Changes (20.0)
|
||||
|
||||
### Removed: macOS 10.11 / 10.12 support
|
||||
|
||||
macOS 10.11 (El Capitan) and macOS 10.12 (Sierra) are no longer supported by [Chromium](https://chromium-review.googlesource.com/c/chromium/src/+/3646050).
|
||||
|
||||
Older versions of Electron will continue to run on these operating systems, but macOS 10.13 (High Sierra)
|
||||
or later will be required to run Electron v20.0.0 and higher.
|
||||
|
||||
### Default Changed: renderers without `nodeIntegration: true` are sandboxed by default
|
||||
|
||||
Previously, renderers that specified a preload script defaulted to being
|
||||
|
||||
@@ -18,8 +18,8 @@ See also [V8 Development](v8-development.md)
|
||||
|
||||
### Code Resources
|
||||
|
||||
- [Code Search](https://cs.chromium.org/) - Indexed and searchable source code for Chromium and associated projects.
|
||||
- [Source Code](https://cs.chromium.org/chromium/src/) - The source code for Chromium itself.
|
||||
- [Code Search](https://source.chromium.org/chromium) - Indexed and searchable source code for Chromium and associated projects.
|
||||
- [Source Code](https://source.chromium.org/chromium/chromium/src) - The source code for Chromium itself.
|
||||
- [Chromium Review](https://chromium-review.googlesource.com) - The searchable code host which facilitates code reviews for Chromium and related projects.
|
||||
|
||||
### Informational Resources
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
const {app, BrowserWindow} = require('electron')
|
||||
const e = require('express')
|
||||
const path = require('path')
|
||||
|
||||
function createWindow () {
|
||||
@@ -44,7 +43,6 @@ function createWindow () {
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
mainWindow.webContents.session.setDevicePermissionHandler((details) => {
|
||||
if (details.deviceType === 'usb' && details.origin === 'file://') {
|
||||
if (!grantedDeviceThroughPermHandler) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
function getDeviceDetails(device) {
|
||||
return grantedDevice.productName || `Unknown device ${grantedDevice.deviceId}`
|
||||
return device.productName || `Unknown device ${device.deviceId}`
|
||||
}
|
||||
|
||||
async function testIt() {
|
||||
|
||||
@@ -79,7 +79,6 @@ auto_filenames = {
|
||||
"docs/api/structures/custom-scheme.md",
|
||||
"docs/api/structures/desktop-capturer-source.md",
|
||||
"docs/api/structures/display.md",
|
||||
"docs/api/structures/event.md",
|
||||
"docs/api/structures/extension-info.md",
|
||||
"docs/api/structures/extension.md",
|
||||
"docs/api/structures/file-filter.md",
|
||||
@@ -209,6 +208,8 @@ auto_filenames = {
|
||||
"lib/browser/api/message-channel.ts",
|
||||
"lib/browser/api/module-list.ts",
|
||||
"lib/browser/api/native-theme.ts",
|
||||
"lib/browser/api/net-client-request.ts",
|
||||
"lib/browser/api/net-fetch.ts",
|
||||
"lib/browser/api/net-log.ts",
|
||||
"lib/browser/api/net.ts",
|
||||
"lib/browser/api/notification.ts",
|
||||
|
||||
@@ -153,7 +153,7 @@ filenames = {
|
||||
"shell/browser/notifications/mac/notification_presenter_mac.mm",
|
||||
"shell/browser/relauncher_mac.cc",
|
||||
"shell/browser/ui/certificate_trust_mac.mm",
|
||||
"shell/browser/ui/cocoa/delayed_native_view_host.cc",
|
||||
"shell/browser/ui/cocoa/delayed_native_view_host.mm",
|
||||
"shell/browser/ui/cocoa/delayed_native_view_host.h",
|
||||
"shell/browser/ui/cocoa/electron_bundle_mover.h",
|
||||
"shell/browser/ui/cocoa/electron_bundle_mover.mm",
|
||||
@@ -175,8 +175,6 @@ filenames = {
|
||||
"shell/browser/ui/cocoa/electron_touch_bar.mm",
|
||||
"shell/browser/ui/cocoa/event_dispatching_window.h",
|
||||
"shell/browser/ui/cocoa/event_dispatching_window.mm",
|
||||
"shell/browser/ui/cocoa/NSColor+Hex.h",
|
||||
"shell/browser/ui/cocoa/NSColor+Hex.mm",
|
||||
"shell/browser/ui/cocoa/NSString+ANSI.h",
|
||||
"shell/browser/ui/cocoa/NSString+ANSI.mm",
|
||||
"shell/browser/ui/cocoa/root_view_mac.h",
|
||||
@@ -267,7 +265,6 @@ filenames = {
|
||||
"shell/browser/api/electron_api_dialog.cc",
|
||||
"shell/browser/api/electron_api_download_item.cc",
|
||||
"shell/browser/api/electron_api_download_item.h",
|
||||
"shell/browser/api/electron_api_event.cc",
|
||||
"shell/browser/api/electron_api_event_emitter.cc",
|
||||
"shell/browser/api/electron_api_event_emitter.h",
|
||||
"shell/browser/api/electron_api_global_shortcut.cc",
|
||||
@@ -320,8 +317,6 @@ filenames = {
|
||||
"shell/browser/api/electron_api_web_request.cc",
|
||||
"shell/browser/api/electron_api_web_request.h",
|
||||
"shell/browser/api/electron_api_web_view_manager.cc",
|
||||
"shell/browser/api/event.cc",
|
||||
"shell/browser/api/event.h",
|
||||
"shell/browser/api/frame_subscriber.cc",
|
||||
"shell/browser/api/frame_subscriber.h",
|
||||
"shell/browser/api/gpu_info_enumerator.cc",
|
||||
@@ -382,7 +377,6 @@ filenames = {
|
||||
"shell/browser/electron_web_contents_utility_handler_impl.h",
|
||||
"shell/browser/electron_web_ui_controller_factory.cc",
|
||||
"shell/browser/electron_web_ui_controller_factory.h",
|
||||
"shell/browser/event_emitter_mixin.cc",
|
||||
"shell/browser/event_emitter_mixin.h",
|
||||
"shell/browser/extended_web_contents_observer.h",
|
||||
"shell/browser/feature_list.cc",
|
||||
@@ -586,6 +580,7 @@ filenames = {
|
||||
"shell/common/gin_converters/native_window_converter.h",
|
||||
"shell/common/gin_converters/net_converter.cc",
|
||||
"shell/common/gin_converters/net_converter.h",
|
||||
"shell/common/gin_converters/optional_converter.h",
|
||||
"shell/common/gin_converters/serial_port_info_converter.h",
|
||||
"shell/common/gin_converters/std_converter.h",
|
||||
"shell/common/gin_converters/time_converter.cc",
|
||||
@@ -606,10 +601,13 @@ filenames = {
|
||||
"shell/common/gin_helper/dictionary.h",
|
||||
"shell/common/gin_helper/error_thrower.cc",
|
||||
"shell/common/gin_helper/error_thrower.h",
|
||||
"shell/common/gin_helper/event_emitter.cc",
|
||||
"shell/common/gin_helper/event.cc",
|
||||
"shell/common/gin_helper/event.h",
|
||||
"shell/common/gin_helper/event_emitter.h",
|
||||
"shell/common/gin_helper/event_emitter_caller.cc",
|
||||
"shell/common/gin_helper/event_emitter_caller.h",
|
||||
"shell/common/gin_helper/event_emitter_template.cc",
|
||||
"shell/common/gin_helper/event_emitter_template.h",
|
||||
"shell/common/gin_helper/function_template.cc",
|
||||
"shell/common/gin_helper/function_template.h",
|
||||
"shell/common/gin_helper/function_template_extensions.h",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import type { BaseWindow as TLWT } from 'electron/main';
|
||||
import * as deprecate from '@electron/internal/common/deprecate';
|
||||
const { BaseWindow } = process._linkedBinding('electron_browser_base_window') as { BaseWindow: typeof TLWT };
|
||||
|
||||
Object.setPrototypeOf(BaseWindow.prototype, EventEmitter.prototype);
|
||||
@@ -15,6 +16,25 @@ BaseWindow.prototype._init = function () {
|
||||
}
|
||||
};
|
||||
|
||||
// Deprecation.
|
||||
const setTrafficLightPositionDeprecated = deprecate.warnOnce('setTrafficLightPosition', 'setWindowButtonPosition');
|
||||
// Converting to any as the methods are defined under BrowserWindow in our docs.
|
||||
(BaseWindow as any).prototype.setTrafficLightPosition = function (pos: Electron.Point) {
|
||||
setTrafficLightPositionDeprecated();
|
||||
if (typeof pos === 'object' && pos.x === 0 && pos.y === 0) {
|
||||
this.setWindowButtonPosition(null);
|
||||
} else {
|
||||
this.setWindowButtonPosition(pos);
|
||||
}
|
||||
};
|
||||
|
||||
const getTrafficLightPositionDeprecated = deprecate.warnOnce('getTrafficLightPosition', 'getWindowButtonPosition');
|
||||
(BaseWindow as any).prototype.getTrafficLightPosition = function () {
|
||||
getTrafficLightPositionDeprecated();
|
||||
const pos = this.getWindowButtonPosition();
|
||||
return pos === null ? { x: 0, y: 0 } : pos;
|
||||
};
|
||||
|
||||
// Properties
|
||||
|
||||
Object.defineProperty(BaseWindow.prototype, 'autoHideMenuBar', {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { BaseWindow, WebContents, Event, BrowserView, TouchBar } from 'electron/main';
|
||||
import { BaseWindow, WebContents, BrowserView, TouchBar } from 'electron/main';
|
||||
import type { BrowserWindow as BWT } from 'electron/main';
|
||||
import * as deprecate from '@electron/internal/common/deprecate';
|
||||
const { BrowserWindow } = process._linkedBinding('electron_browser_window') as { BrowserWindow: typeof BWT };
|
||||
@@ -22,10 +22,10 @@ BrowserWindow.prototype._init = function (this: BWT) {
|
||||
};
|
||||
|
||||
// Redirect focus/blur event to app instance too.
|
||||
this.on('blur', (event: Event) => {
|
||||
this.on('blur', (event: Electron.Event) => {
|
||||
app.emit('browser-window-blur', event, this);
|
||||
});
|
||||
this.on('focus', (event: Event) => {
|
||||
this.on('focus', (event: Electron.Event) => {
|
||||
app.emit('browser-window-focus', event, this);
|
||||
});
|
||||
|
||||
@@ -68,8 +68,7 @@ BrowserWindow.prototype._init = function (this: BWT) {
|
||||
});
|
||||
|
||||
// Notify the creation of the window.
|
||||
const event = process._linkedBinding('electron_browser_event').createEmpty();
|
||||
app.emit('browser-window-created', event, this);
|
||||
app.emit('browser-window-created', { preventDefault () {} }, this);
|
||||
|
||||
Object.defineProperty(this, 'devToolsWebContents', {
|
||||
enumerable: true,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as roles from '@electron/internal/browser/api/menu-item-roles';
|
||||
import { Menu, Event, BrowserWindow, WebContents } from 'electron/main';
|
||||
import { Menu, BrowserWindow, WebContents, KeyboardEvent } from 'electron/main';
|
||||
|
||||
let nextCommandId = 0;
|
||||
|
||||
@@ -53,7 +53,7 @@ const MenuItem = function (this: any, options: any) {
|
||||
});
|
||||
|
||||
const click = options.click;
|
||||
this.click = (event: Event, focusedWindow: BrowserWindow, focusedWebContents: WebContents) => {
|
||||
this.click = (event: KeyboardEvent, focusedWindow: BrowserWindow, focusedWebContents: WebContents) => {
|
||||
// Manually flip the checked flags when clicked.
|
||||
if (!roles.shouldOverrideCheckStatus(this.role) &&
|
||||
(this.type === 'checkbox' || this.type === 'radio')) {
|
||||
|
||||
537
lib/browser/api/net-client-request.ts
Normal file
537
lib/browser/api/net-client-request.ts
Normal file
@@ -0,0 +1,537 @@
|
||||
import * as url from 'url';
|
||||
import { Readable, Writable } from 'stream';
|
||||
import { app } from 'electron/main';
|
||||
import type { ClientRequestConstructorOptions, UploadProgress } from 'electron/main';
|
||||
|
||||
const {
|
||||
isValidHeaderName,
|
||||
isValidHeaderValue,
|
||||
createURLLoader
|
||||
} = process._linkedBinding('electron_browser_net');
|
||||
const { Session } = process._linkedBinding('electron_browser_session');
|
||||
|
||||
const kHttpProtocols = new Set(['http:', 'https:']);
|
||||
|
||||
// set of headers that Node.js discards duplicates for
|
||||
// see https://nodejs.org/api/http.html#http_message_headers
|
||||
const discardableDuplicateHeaders = new Set([
|
||||
'content-type',
|
||||
'content-length',
|
||||
'user-agent',
|
||||
'referer',
|
||||
'host',
|
||||
'authorization',
|
||||
'proxy-authorization',
|
||||
'if-modified-since',
|
||||
'if-unmodified-since',
|
||||
'from',
|
||||
'location',
|
||||
'max-forwards',
|
||||
'retry-after',
|
||||
'etag',
|
||||
'last-modified',
|
||||
'server',
|
||||
'age',
|
||||
'expires'
|
||||
]);
|
||||
|
||||
class IncomingMessage extends Readable {
|
||||
_shouldPush: boolean = false;
|
||||
_data: (Buffer | null)[] = [];
|
||||
_responseHead: NodeJS.ResponseHead;
|
||||
_resume: (() => void) | null = null;
|
||||
|
||||
constructor (responseHead: NodeJS.ResponseHead) {
|
||||
super();
|
||||
this._responseHead = responseHead;
|
||||
}
|
||||
|
||||
get statusCode () {
|
||||
return this._responseHead.statusCode;
|
||||
}
|
||||
|
||||
get statusMessage () {
|
||||
return this._responseHead.statusMessage;
|
||||
}
|
||||
|
||||
get headers () {
|
||||
const filteredHeaders: Record<string, string | string[]> = {};
|
||||
const { headers, rawHeaders } = this._responseHead;
|
||||
for (const [name, values] of Object.entries(headers)) {
|
||||
filteredHeaders[name] = discardableDuplicateHeaders.has(name) ? values[0] : values.join(', ');
|
||||
}
|
||||
const cookies = rawHeaders.filter(({ key }) => key.toLowerCase() === 'set-cookie').map(({ value }) => value);
|
||||
// keep set-cookie as an array per Node.js rules
|
||||
// see https://nodejs.org/api/http.html#http_message_headers
|
||||
if (cookies.length) { filteredHeaders['set-cookie'] = cookies; }
|
||||
return filteredHeaders;
|
||||
}
|
||||
|
||||
get rawHeaders () {
|
||||
const rawHeadersArr: string[] = [];
|
||||
const { rawHeaders } = this._responseHead;
|
||||
rawHeaders.forEach(header => {
|
||||
rawHeadersArr.push(header.key, header.value);
|
||||
});
|
||||
return rawHeadersArr;
|
||||
}
|
||||
|
||||
get httpVersion () {
|
||||
return `${this.httpVersionMajor}.${this.httpVersionMinor}`;
|
||||
}
|
||||
|
||||
get httpVersionMajor () {
|
||||
return this._responseHead.httpVersion.major;
|
||||
}
|
||||
|
||||
get httpVersionMinor () {
|
||||
return this._responseHead.httpVersion.minor;
|
||||
}
|
||||
|
||||
get rawTrailers () {
|
||||
throw new Error('HTTP trailers are not supported');
|
||||
}
|
||||
|
||||
get trailers () {
|
||||
throw new Error('HTTP trailers are not supported');
|
||||
}
|
||||
|
||||
_storeInternalData (chunk: Buffer | null, resume: (() => void) | null) {
|
||||
// save the network callback for use in _pushInternalData
|
||||
this._resume = resume;
|
||||
this._data.push(chunk);
|
||||
this._pushInternalData();
|
||||
}
|
||||
|
||||
_pushInternalData () {
|
||||
while (this._shouldPush && this._data.length > 0) {
|
||||
const chunk = this._data.shift();
|
||||
this._shouldPush = this.push(chunk);
|
||||
}
|
||||
if (this._shouldPush && this._resume) {
|
||||
// Reset the callback, so that a new one is used for each
|
||||
// batch of throttled data. Do this before calling resume to avoid a
|
||||
// potential race-condition
|
||||
const resume = this._resume;
|
||||
this._resume = null;
|
||||
|
||||
resume();
|
||||
}
|
||||
}
|
||||
|
||||
_read () {
|
||||
this._shouldPush = true;
|
||||
this._pushInternalData();
|
||||
}
|
||||
}
|
||||
|
||||
/** Writable stream that buffers up everything written to it. */
|
||||
class SlurpStream extends Writable {
|
||||
_data: Buffer;
|
||||
constructor () {
|
||||
super();
|
||||
this._data = Buffer.alloc(0);
|
||||
}
|
||||
|
||||
_write (chunk: Buffer, encoding: string, callback: () => void) {
|
||||
this._data = Buffer.concat([this._data, chunk]);
|
||||
callback();
|
||||
}
|
||||
|
||||
data () { return this._data; }
|
||||
}
|
||||
|
||||
class ChunkedBodyStream extends Writable {
|
||||
_pendingChunk: Buffer | undefined;
|
||||
_downstream?: NodeJS.DataPipe;
|
||||
_pendingCallback?: (error?: Error) => void;
|
||||
_clientRequest: ClientRequest;
|
||||
|
||||
constructor (clientRequest: ClientRequest) {
|
||||
super();
|
||||
this._clientRequest = clientRequest;
|
||||
}
|
||||
|
||||
_write (chunk: Buffer, encoding: string, callback: () => void) {
|
||||
if (this._downstream) {
|
||||
this._downstream.write(chunk).then(callback, callback);
|
||||
} else {
|
||||
// the contract of _write is that we won't be called again until we call
|
||||
// the callback, so we're good to just save a single chunk.
|
||||
this._pendingChunk = chunk;
|
||||
this._pendingCallback = callback;
|
||||
|
||||
// The first write to a chunked body stream begins the request.
|
||||
this._clientRequest._startRequest();
|
||||
}
|
||||
}
|
||||
|
||||
_final (callback: () => void) {
|
||||
this._downstream!.done();
|
||||
callback();
|
||||
}
|
||||
|
||||
startReading (pipe: NodeJS.DataPipe) {
|
||||
if (this._downstream) {
|
||||
throw new Error('two startReading calls???');
|
||||
}
|
||||
this._downstream = pipe;
|
||||
if (this._pendingChunk) {
|
||||
const doneWriting = (maybeError: Error | void) => {
|
||||
// If the underlying request has been aborted, we honestly don't care about the error
|
||||
// all work should cease as soon as we abort anyway, this error is probably a
|
||||
// "mojo pipe disconnected" error (code=9)
|
||||
if (this._clientRequest._aborted) return;
|
||||
|
||||
const cb = this._pendingCallback!;
|
||||
delete this._pendingCallback;
|
||||
delete this._pendingChunk;
|
||||
cb(maybeError || undefined);
|
||||
};
|
||||
this._downstream.write(this._pendingChunk).then(doneWriting, doneWriting);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type RedirectPolicy = 'manual' | 'follow' | 'error';
|
||||
|
||||
const kAllowNonHttpProtocols = Symbol('kAllowNonHttpProtocols');
|
||||
export function allowAnyProtocol (opts: ClientRequestConstructorOptions): ClientRequestConstructorOptions {
|
||||
return {
|
||||
...opts,
|
||||
[kAllowNonHttpProtocols]: true
|
||||
} as any;
|
||||
}
|
||||
|
||||
type ExtraURLLoaderOptions = {
|
||||
redirectPolicy: RedirectPolicy;
|
||||
headers: Record<string, { name: string, value: string | string[] }>;
|
||||
allowNonHttpProtocols: boolean;
|
||||
}
|
||||
function parseOptions (optionsIn: ClientRequestConstructorOptions | string): NodeJS.CreateURLLoaderOptions & ExtraURLLoaderOptions {
|
||||
const options: any = typeof optionsIn === 'string' ? url.parse(optionsIn) : { ...optionsIn };
|
||||
|
||||
let urlStr: string = options.url;
|
||||
|
||||
if (!urlStr) {
|
||||
const urlObj: url.UrlObject = {};
|
||||
const protocol = options.protocol || 'http:';
|
||||
urlObj.protocol = protocol;
|
||||
|
||||
if (options.host) {
|
||||
urlObj.host = options.host;
|
||||
} else {
|
||||
if (options.hostname) {
|
||||
urlObj.hostname = options.hostname;
|
||||
} else {
|
||||
urlObj.hostname = 'localhost';
|
||||
}
|
||||
|
||||
if (options.port) {
|
||||
urlObj.port = options.port;
|
||||
}
|
||||
}
|
||||
|
||||
if (options.path && / /.test(options.path)) {
|
||||
// The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/
|
||||
// with an additional rule for ignoring percentage-escaped characters
|
||||
// but that's a) hard to capture in a regular expression that performs
|
||||
// well, and b) possibly too restrictive for real-world usage. That's
|
||||
// why it only scans for spaces because those are guaranteed to create
|
||||
// an invalid request.
|
||||
throw new TypeError('Request path contains unescaped characters');
|
||||
}
|
||||
const pathObj = url.parse(options.path || '/');
|
||||
urlObj.pathname = pathObj.pathname;
|
||||
urlObj.search = pathObj.search;
|
||||
urlObj.hash = pathObj.hash;
|
||||
urlStr = url.format(urlObj);
|
||||
}
|
||||
|
||||
const redirectPolicy = options.redirect || 'follow';
|
||||
if (!['follow', 'error', 'manual'].includes(redirectPolicy)) {
|
||||
throw new Error('redirect mode should be one of follow, error or manual');
|
||||
}
|
||||
|
||||
if (options.headers != null && typeof options.headers !== 'object') {
|
||||
throw new TypeError('headers must be an object');
|
||||
}
|
||||
|
||||
const urlLoaderOptions: NodeJS.CreateURLLoaderOptions & { redirectPolicy: RedirectPolicy, headers: Record<string, { name: string, value: string | string[] }>, allowNonHttpProtocols: boolean } = {
|
||||
method: (options.method || 'GET').toUpperCase(),
|
||||
url: urlStr,
|
||||
redirectPolicy,
|
||||
headers: {},
|
||||
body: null as any,
|
||||
useSessionCookies: options.useSessionCookies,
|
||||
credentials: options.credentials,
|
||||
origin: options.origin,
|
||||
referrerPolicy: options.referrerPolicy,
|
||||
cache: options.cache,
|
||||
allowNonHttpProtocols: Object.prototype.hasOwnProperty.call(options, kAllowNonHttpProtocols)
|
||||
};
|
||||
const headers: Record<string, string | string[]> = options.headers || {};
|
||||
for (const [name, value] of Object.entries(headers)) {
|
||||
if (!isValidHeaderName(name)) {
|
||||
throw new Error(`Invalid header name: '${name}'`);
|
||||
}
|
||||
if (!isValidHeaderValue(value.toString())) {
|
||||
throw new Error(`Invalid value for header '${name}': '${value}'`);
|
||||
}
|
||||
const key = name.toLowerCase();
|
||||
urlLoaderOptions.headers[key] = { name, value };
|
||||
}
|
||||
if (options.session) {
|
||||
if (!(options.session instanceof Session)) { throw new TypeError('`session` should be an instance of the Session class'); }
|
||||
urlLoaderOptions.session = options.session;
|
||||
} else if (options.partition) {
|
||||
if (typeof options.partition === 'string') {
|
||||
urlLoaderOptions.partition = options.partition;
|
||||
} else {
|
||||
throw new TypeError('`partition` should be a string');
|
||||
}
|
||||
}
|
||||
return urlLoaderOptions;
|
||||
}
|
||||
|
||||
export class ClientRequest extends Writable implements Electron.ClientRequest {
|
||||
_started: boolean = false;
|
||||
_firstWrite: boolean = false;
|
||||
_aborted: boolean = false;
|
||||
_chunkedEncoding: boolean | undefined;
|
||||
_body: Writable | undefined;
|
||||
_urlLoaderOptions: NodeJS.CreateURLLoaderOptions & { headers: Record<string, { name: string, value: string | string[] }> };
|
||||
_redirectPolicy: RedirectPolicy;
|
||||
_followRedirectCb?: () => void;
|
||||
_uploadProgress?: { active: boolean, started: boolean, current: number, total: number };
|
||||
_urlLoader?: NodeJS.URLLoader;
|
||||
_response?: IncomingMessage;
|
||||
|
||||
constructor (options: ClientRequestConstructorOptions | string, callback?: (message: IncomingMessage) => void) {
|
||||
super({ autoDestroy: true });
|
||||
|
||||
if (!app.isReady()) {
|
||||
throw new Error('net module can only be used after app is ready');
|
||||
}
|
||||
|
||||
if (callback) {
|
||||
this.once('response', callback);
|
||||
}
|
||||
|
||||
const { redirectPolicy, ...urlLoaderOptions } = parseOptions(options);
|
||||
const urlObj = new URL(urlLoaderOptions.url);
|
||||
if (!urlLoaderOptions.allowNonHttpProtocols && !kHttpProtocols.has(urlObj.protocol)) {
|
||||
throw new Error('ClientRequest only supports http: and https: protocols');
|
||||
}
|
||||
if (urlLoaderOptions.credentials === 'same-origin' && !urlLoaderOptions.origin) { throw new Error('credentials: same-origin requires origin to be set'); }
|
||||
this._urlLoaderOptions = urlLoaderOptions;
|
||||
this._redirectPolicy = redirectPolicy;
|
||||
}
|
||||
|
||||
get chunkedEncoding () {
|
||||
return this._chunkedEncoding || false;
|
||||
}
|
||||
|
||||
set chunkedEncoding (value: boolean) {
|
||||
if (this._started) {
|
||||
throw new Error('chunkedEncoding can only be set before the request is started');
|
||||
}
|
||||
if (typeof this._chunkedEncoding !== 'undefined') {
|
||||
throw new Error('chunkedEncoding can only be set once');
|
||||
}
|
||||
this._chunkedEncoding = !!value;
|
||||
if (this._chunkedEncoding) {
|
||||
this._body = new ChunkedBodyStream(this);
|
||||
this._urlLoaderOptions.body = (pipe: NodeJS.DataPipe) => {
|
||||
(this._body! as ChunkedBodyStream).startReading(pipe);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
setHeader (name: string, value: string) {
|
||||
if (typeof name !== 'string') {
|
||||
throw new TypeError('`name` should be a string in setHeader(name, value)');
|
||||
}
|
||||
if (value == null) {
|
||||
throw new Error('`value` required in setHeader("' + name + '", value)');
|
||||
}
|
||||
if (this._started || this._firstWrite) {
|
||||
throw new Error('Can\'t set headers after they are sent');
|
||||
}
|
||||
if (!isValidHeaderName(name)) {
|
||||
throw new Error(`Invalid header name: '${name}'`);
|
||||
}
|
||||
if (!isValidHeaderValue(value.toString())) {
|
||||
throw new Error(`Invalid value for header '${name}': '${value}'`);
|
||||
}
|
||||
|
||||
const key = name.toLowerCase();
|
||||
this._urlLoaderOptions.headers[key] = { name, value };
|
||||
}
|
||||
|
||||
getHeader (name: string) {
|
||||
if (name == null) {
|
||||
throw new Error('`name` is required for getHeader(name)');
|
||||
}
|
||||
|
||||
const key = name.toLowerCase();
|
||||
const header = this._urlLoaderOptions.headers[key];
|
||||
return header && header.value as any;
|
||||
}
|
||||
|
||||
removeHeader (name: string) {
|
||||
if (name == null) {
|
||||
throw new Error('`name` is required for removeHeader(name)');
|
||||
}
|
||||
|
||||
if (this._started || this._firstWrite) {
|
||||
throw new Error('Can\'t remove headers after they are sent');
|
||||
}
|
||||
|
||||
const key = name.toLowerCase();
|
||||
delete this._urlLoaderOptions.headers[key];
|
||||
}
|
||||
|
||||
_write (chunk: Buffer, encoding: BufferEncoding, callback: () => void) {
|
||||
this._firstWrite = true;
|
||||
if (!this._body) {
|
||||
this._body = new SlurpStream();
|
||||
this._body.on('finish', () => {
|
||||
this._urlLoaderOptions.body = (this._body as SlurpStream).data();
|
||||
this._startRequest();
|
||||
});
|
||||
}
|
||||
// TODO: is this the right way to forward to another stream?
|
||||
this._body.write(chunk, encoding, callback);
|
||||
}
|
||||
|
||||
_final (callback: () => void) {
|
||||
if (this._body) {
|
||||
// TODO: is this the right way to forward to another stream?
|
||||
this._body.end(callback);
|
||||
} else {
|
||||
// end() called without a body, go ahead and start the request
|
||||
this._startRequest();
|
||||
callback();
|
||||
}
|
||||
}
|
||||
|
||||
_startRequest () {
|
||||
this._started = true;
|
||||
const stringifyValues = (obj: Record<string, { name: string, value: string | string[] }>) => {
|
||||
const ret: Record<string, string> = {};
|
||||
for (const k of Object.keys(obj)) {
|
||||
const kv = obj[k];
|
||||
ret[kv.name] = kv.value.toString();
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
this._urlLoaderOptions.referrer = this.getHeader('referer') || '';
|
||||
this._urlLoaderOptions.origin = this._urlLoaderOptions.origin || this.getHeader('origin') || '';
|
||||
this._urlLoaderOptions.hasUserActivation = this.getHeader('sec-fetch-user') === '?1';
|
||||
this._urlLoaderOptions.mode = this.getHeader('sec-fetch-mode') || '';
|
||||
this._urlLoaderOptions.destination = this.getHeader('sec-fetch-dest') || '';
|
||||
const opts = { ...this._urlLoaderOptions, extraHeaders: stringifyValues(this._urlLoaderOptions.headers) };
|
||||
this._urlLoader = createURLLoader(opts);
|
||||
this._urlLoader.on('response-started', (event, finalUrl, responseHead) => {
|
||||
const response = this._response = new IncomingMessage(responseHead);
|
||||
this.emit('response', response);
|
||||
});
|
||||
this._urlLoader.on('data', (event, data, resume) => {
|
||||
this._response!._storeInternalData(Buffer.from(data), resume);
|
||||
});
|
||||
this._urlLoader.on('complete', () => {
|
||||
if (this._response) { this._response._storeInternalData(null, null); }
|
||||
});
|
||||
this._urlLoader.on('error', (event, netErrorString) => {
|
||||
const error = new Error(netErrorString);
|
||||
if (this._response) this._response.destroy(error);
|
||||
this._die(error);
|
||||
});
|
||||
|
||||
this._urlLoader.on('login', (event, authInfo, callback) => {
|
||||
const handled = this.emit('login', authInfo, callback);
|
||||
if (!handled) {
|
||||
// If there were no listeners, cancel the authentication request.
|
||||
callback();
|
||||
}
|
||||
});
|
||||
|
||||
this._urlLoader.on('redirect', (event, redirectInfo, headers) => {
|
||||
const { statusCode, newMethod, newUrl } = redirectInfo;
|
||||
if (this._redirectPolicy === 'error') {
|
||||
this._die(new Error('Attempted to redirect, but redirect policy was \'error\''));
|
||||
} else if (this._redirectPolicy === 'manual') {
|
||||
let _followRedirect = false;
|
||||
this._followRedirectCb = () => { _followRedirect = true; };
|
||||
try {
|
||||
this.emit('redirect', statusCode, newMethod, newUrl, headers);
|
||||
} finally {
|
||||
this._followRedirectCb = undefined;
|
||||
if (!_followRedirect && !this._aborted) {
|
||||
this._die(new Error('Redirect was cancelled'));
|
||||
}
|
||||
}
|
||||
} else if (this._redirectPolicy === 'follow') {
|
||||
// Calling followRedirect() when the redirect policy is 'follow' is
|
||||
// allowed but does nothing. (Perhaps it should throw an error
|
||||
// though...? Since the redirect will happen regardless.)
|
||||
try {
|
||||
this._followRedirectCb = () => {};
|
||||
this.emit('redirect', statusCode, newMethod, newUrl, headers);
|
||||
} finally {
|
||||
this._followRedirectCb = undefined;
|
||||
}
|
||||
} else {
|
||||
this._die(new Error(`Unexpected redirect policy '${this._redirectPolicy}'`));
|
||||
}
|
||||
});
|
||||
|
||||
this._urlLoader.on('upload-progress', (event, position, total) => {
|
||||
this._uploadProgress = { active: true, started: true, current: position, total };
|
||||
this.emit('upload-progress', position, total); // Undocumented, for now
|
||||
});
|
||||
|
||||
this._urlLoader.on('download-progress', (event, current) => {
|
||||
if (this._response) {
|
||||
this._response.emit('download-progress', current); // Undocumented, for now
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
followRedirect () {
|
||||
if (this._followRedirectCb) {
|
||||
this._followRedirectCb();
|
||||
} else {
|
||||
throw new Error('followRedirect() called, but was not waiting for a redirect');
|
||||
}
|
||||
}
|
||||
|
||||
abort () {
|
||||
if (!this._aborted) {
|
||||
process.nextTick(() => { this.emit('abort'); });
|
||||
}
|
||||
this._aborted = true;
|
||||
this._die();
|
||||
}
|
||||
|
||||
_die (err?: Error) {
|
||||
// Node.js assumes that any stream which is ended is no longer capable of emitted events
|
||||
// which is a faulty assumption for the case of an object that is acting like a stream
|
||||
// (our urlRequest). If we don't emit here, this causes errors since we *do* expect
|
||||
// that error events can be emitted after urlRequest.end().
|
||||
if ((this as any)._writableState.destroyed && err) {
|
||||
this.emit('error', err);
|
||||
}
|
||||
|
||||
this.destroy(err);
|
||||
if (this._urlLoader) {
|
||||
this._urlLoader.cancel();
|
||||
if (this._response) this._response.destroy(err);
|
||||
}
|
||||
}
|
||||
|
||||
getUploadProgress (): UploadProgress {
|
||||
return this._uploadProgress ? { ...this._uploadProgress } : { active: false, started: false, current: 0, total: 0 };
|
||||
}
|
||||
}
|
||||
117
lib/browser/api/net-fetch.ts
Normal file
117
lib/browser/api/net-fetch.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import { net, IncomingMessage, Session as SessionT } from 'electron/main';
|
||||
import { Readable, Writable, isReadable } from 'stream';
|
||||
import { allowAnyProtocol } from '@electron/internal/browser/api/net-client-request';
|
||||
|
||||
function createDeferredPromise<T, E extends Error = Error> (): { promise: Promise<T>; resolve: (x: T) => void; reject: (e: E) => void; } {
|
||||
let res: (x: T) => void;
|
||||
let rej: (e: E) => void;
|
||||
const promise = new Promise<T>((resolve, reject) => {
|
||||
res = resolve;
|
||||
rej = reject;
|
||||
});
|
||||
|
||||
return { promise, resolve: res!, reject: rej! };
|
||||
}
|
||||
|
||||
export function fetchWithSession (input: RequestInfo, init: RequestInit | undefined, session: SessionT): Promise<Response> {
|
||||
const p = createDeferredPromise<Response>();
|
||||
let req: Request;
|
||||
try {
|
||||
req = new Request(input, init);
|
||||
} catch (e: any) {
|
||||
p.reject(e);
|
||||
return p.promise;
|
||||
}
|
||||
|
||||
if (req.signal.aborted) {
|
||||
// 1. Abort the fetch() call with p, request, null, and
|
||||
// requestObject’s signal’s abort reason.
|
||||
const error = (req.signal as any).reason ?? new DOMException('The operation was aborted.', 'AbortError');
|
||||
p.reject(error);
|
||||
|
||||
if (req.body != null && isReadable(req.body as unknown as NodeJS.ReadableStream)) {
|
||||
req.body.cancel(error).catch((err) => {
|
||||
if (err.code === 'ERR_INVALID_STATE') {
|
||||
// Node bug?
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Return p.
|
||||
return p.promise;
|
||||
}
|
||||
|
||||
let locallyAborted = false;
|
||||
req.signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
// 1. Set locallyAborted to true.
|
||||
locallyAborted = true;
|
||||
|
||||
// 2. Abort the fetch() call with p, request, responseObject,
|
||||
// and requestObject’s signal’s abort reason.
|
||||
const error = (req.signal as any).reason ?? new DOMException('The operation was aborted.', 'AbortError');
|
||||
p.reject(error);
|
||||
if (req.body != null && isReadable(req.body as unknown as NodeJS.ReadableStream)) {
|
||||
req.body.cancel(error).catch((err) => {
|
||||
if (err.code === 'ERR_INVALID_STATE') {
|
||||
// Node bug?
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
r.abort();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
|
||||
const origin = req.headers.get('origin') ?? undefined;
|
||||
// We can't set credentials to same-origin unless there's an origin set.
|
||||
const credentials = req.credentials === 'same-origin' && !origin ? 'include' : req.credentials;
|
||||
|
||||
const r = net.request(allowAnyProtocol({
|
||||
session,
|
||||
method: req.method,
|
||||
url: req.url,
|
||||
origin,
|
||||
credentials,
|
||||
cache: req.cache,
|
||||
referrerPolicy: req.referrerPolicy,
|
||||
redirect: req.redirect
|
||||
}));
|
||||
|
||||
// cors is the default mode, but we can't set mode=cors without an origin.
|
||||
if (req.mode && (req.mode !== 'cors' || origin)) {
|
||||
r.setHeader('Sec-Fetch-Mode', req.mode);
|
||||
}
|
||||
|
||||
for (const [k, v] of req.headers) {
|
||||
r.setHeader(k, v);
|
||||
}
|
||||
|
||||
r.on('response', (resp: IncomingMessage) => {
|
||||
if (locallyAborted) return;
|
||||
const headers = new Headers();
|
||||
for (const [k, v] of Object.entries(resp.headers)) { headers.set(k, Array.isArray(v) ? v.join(', ') : v); }
|
||||
const nullBodyStatus = [101, 204, 205, 304];
|
||||
const body = nullBodyStatus.includes(resp.statusCode) || req.method === 'HEAD' ? null : Readable.toWeb(resp as unknown as Readable) as ReadableStream;
|
||||
const rResp = new Response(body, {
|
||||
headers,
|
||||
status: resp.statusCode,
|
||||
statusText: resp.statusMessage
|
||||
});
|
||||
p.resolve(rResp);
|
||||
});
|
||||
|
||||
r.on('error', (err) => {
|
||||
p.reject(err);
|
||||
});
|
||||
|
||||
if (!req.body?.pipeTo(Writable.toWeb(r as unknown as Writable)).then(() => r.end())) { r.end(); }
|
||||
|
||||
return p.promise;
|
||||
}
|
||||
@@ -1,531 +1,17 @@
|
||||
import * as url from 'url';
|
||||
import { Readable, Writable } from 'stream';
|
||||
import { app } from 'electron/main';
|
||||
import type { ClientRequestConstructorOptions, UploadProgress } from 'electron/main';
|
||||
import { IncomingMessage, session } from 'electron/main';
|
||||
import type { ClientRequestConstructorOptions } from 'electron/main';
|
||||
import { ClientRequest } from '@electron/internal/browser/api/net-client-request';
|
||||
|
||||
const {
|
||||
isOnline,
|
||||
isValidHeaderName,
|
||||
isValidHeaderValue,
|
||||
createURLLoader
|
||||
} = process._linkedBinding('electron_browser_net');
|
||||
|
||||
const kSupportedProtocols = new Set(['http:', 'https:']);
|
||||
|
||||
// set of headers that Node.js discards duplicates for
|
||||
// see https://nodejs.org/api/http.html#http_message_headers
|
||||
const discardableDuplicateHeaders = new Set([
|
||||
'content-type',
|
||||
'content-length',
|
||||
'user-agent',
|
||||
'referer',
|
||||
'host',
|
||||
'authorization',
|
||||
'proxy-authorization',
|
||||
'if-modified-since',
|
||||
'if-unmodified-since',
|
||||
'from',
|
||||
'location',
|
||||
'max-forwards',
|
||||
'retry-after',
|
||||
'etag',
|
||||
'last-modified',
|
||||
'server',
|
||||
'age',
|
||||
'expires'
|
||||
]);
|
||||
|
||||
class IncomingMessage extends Readable {
|
||||
_shouldPush: boolean = false;
|
||||
_data: (Buffer | null)[] = [];
|
||||
_responseHead: NodeJS.ResponseHead;
|
||||
_resume: (() => void) | null = null;
|
||||
|
||||
constructor (responseHead: NodeJS.ResponseHead) {
|
||||
super();
|
||||
this._responseHead = responseHead;
|
||||
}
|
||||
|
||||
get statusCode () {
|
||||
return this._responseHead.statusCode;
|
||||
}
|
||||
|
||||
get statusMessage () {
|
||||
return this._responseHead.statusMessage;
|
||||
}
|
||||
|
||||
get headers () {
|
||||
const filteredHeaders: Record<string, string | string[]> = {};
|
||||
const { headers, rawHeaders } = this._responseHead;
|
||||
for (const [name, values] of Object.entries(headers)) {
|
||||
filteredHeaders[name] = discardableDuplicateHeaders.has(name) ? values[0] : values.join(', ');
|
||||
}
|
||||
const cookies = rawHeaders.filter(({ key }) => key.toLowerCase() === 'set-cookie').map(({ value }) => value);
|
||||
// keep set-cookie as an array per Node.js rules
|
||||
// see https://nodejs.org/api/http.html#http_message_headers
|
||||
if (cookies.length) { filteredHeaders['set-cookie'] = cookies; }
|
||||
return filteredHeaders;
|
||||
}
|
||||
|
||||
get rawHeaders () {
|
||||
const rawHeadersArr: string[] = [];
|
||||
const { rawHeaders } = this._responseHead;
|
||||
rawHeaders.forEach(header => {
|
||||
rawHeadersArr.push(header.key, header.value);
|
||||
});
|
||||
return rawHeadersArr;
|
||||
}
|
||||
|
||||
get httpVersion () {
|
||||
return `${this.httpVersionMajor}.${this.httpVersionMinor}`;
|
||||
}
|
||||
|
||||
get httpVersionMajor () {
|
||||
return this._responseHead.httpVersion.major;
|
||||
}
|
||||
|
||||
get httpVersionMinor () {
|
||||
return this._responseHead.httpVersion.minor;
|
||||
}
|
||||
|
||||
get rawTrailers () {
|
||||
throw new Error('HTTP trailers are not supported');
|
||||
}
|
||||
|
||||
get trailers () {
|
||||
throw new Error('HTTP trailers are not supported');
|
||||
}
|
||||
|
||||
_storeInternalData (chunk: Buffer | null, resume: (() => void) | null) {
|
||||
// save the network callback for use in _pushInternalData
|
||||
this._resume = resume;
|
||||
this._data.push(chunk);
|
||||
this._pushInternalData();
|
||||
}
|
||||
|
||||
_pushInternalData () {
|
||||
while (this._shouldPush && this._data.length > 0) {
|
||||
const chunk = this._data.shift();
|
||||
this._shouldPush = this.push(chunk);
|
||||
}
|
||||
if (this._shouldPush && this._resume) {
|
||||
// Reset the callback, so that a new one is used for each
|
||||
// batch of throttled data. Do this before calling resume to avoid a
|
||||
// potential race-condition
|
||||
const resume = this._resume;
|
||||
this._resume = null;
|
||||
|
||||
resume();
|
||||
}
|
||||
}
|
||||
|
||||
_read () {
|
||||
this._shouldPush = true;
|
||||
this._pushInternalData();
|
||||
}
|
||||
}
|
||||
|
||||
/** Writable stream that buffers up everything written to it. */
|
||||
class SlurpStream extends Writable {
|
||||
_data: Buffer;
|
||||
constructor () {
|
||||
super();
|
||||
this._data = Buffer.alloc(0);
|
||||
}
|
||||
|
||||
_write (chunk: Buffer, encoding: string, callback: () => void) {
|
||||
this._data = Buffer.concat([this._data, chunk]);
|
||||
callback();
|
||||
}
|
||||
|
||||
data () { return this._data; }
|
||||
}
|
||||
|
||||
class ChunkedBodyStream extends Writable {
|
||||
_pendingChunk: Buffer | undefined;
|
||||
_downstream?: NodeJS.DataPipe;
|
||||
_pendingCallback?: (error?: Error) => void;
|
||||
_clientRequest: ClientRequest;
|
||||
|
||||
constructor (clientRequest: ClientRequest) {
|
||||
super();
|
||||
this._clientRequest = clientRequest;
|
||||
}
|
||||
|
||||
_write (chunk: Buffer, encoding: string, callback: () => void) {
|
||||
if (this._downstream) {
|
||||
this._downstream.write(chunk).then(callback, callback);
|
||||
} else {
|
||||
// the contract of _write is that we won't be called again until we call
|
||||
// the callback, so we're good to just save a single chunk.
|
||||
this._pendingChunk = chunk;
|
||||
this._pendingCallback = callback;
|
||||
|
||||
// The first write to a chunked body stream begins the request.
|
||||
this._clientRequest._startRequest();
|
||||
}
|
||||
}
|
||||
|
||||
_final (callback: () => void) {
|
||||
this._downstream!.done();
|
||||
callback();
|
||||
}
|
||||
|
||||
startReading (pipe: NodeJS.DataPipe) {
|
||||
if (this._downstream) {
|
||||
throw new Error('two startReading calls???');
|
||||
}
|
||||
this._downstream = pipe;
|
||||
if (this._pendingChunk) {
|
||||
const doneWriting = (maybeError: Error | void) => {
|
||||
// If the underlying request has been aborted, we honestly don't care about the error
|
||||
// all work should cease as soon as we abort anyway, this error is probably a
|
||||
// "mojo pipe disconnected" error (code=9)
|
||||
if (this._clientRequest._aborted) return;
|
||||
|
||||
const cb = this._pendingCallback!;
|
||||
delete this._pendingCallback;
|
||||
delete this._pendingChunk;
|
||||
cb(maybeError || undefined);
|
||||
};
|
||||
this._downstream.write(this._pendingChunk).then(doneWriting, doneWriting);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type RedirectPolicy = 'manual' | 'follow' | 'error';
|
||||
|
||||
function parseOptions (optionsIn: ClientRequestConstructorOptions | string): NodeJS.CreateURLLoaderOptions & { redirectPolicy: RedirectPolicy, headers: Record<string, { name: string, value: string | string[] }> } {
|
||||
const options: any = typeof optionsIn === 'string' ? url.parse(optionsIn) : { ...optionsIn };
|
||||
|
||||
let urlStr: string = options.url;
|
||||
|
||||
if (!urlStr) {
|
||||
const urlObj: url.UrlObject = {};
|
||||
const protocol = options.protocol || 'http:';
|
||||
if (!kSupportedProtocols.has(protocol)) {
|
||||
throw new Error('Protocol "' + protocol + '" not supported');
|
||||
}
|
||||
urlObj.protocol = protocol;
|
||||
|
||||
if (options.host) {
|
||||
urlObj.host = options.host;
|
||||
} else {
|
||||
if (options.hostname) {
|
||||
urlObj.hostname = options.hostname;
|
||||
} else {
|
||||
urlObj.hostname = 'localhost';
|
||||
}
|
||||
|
||||
if (options.port) {
|
||||
urlObj.port = options.port;
|
||||
}
|
||||
}
|
||||
|
||||
if (options.path && / /.test(options.path)) {
|
||||
// The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/
|
||||
// with an additional rule for ignoring percentage-escaped characters
|
||||
// but that's a) hard to capture in a regular expression that performs
|
||||
// well, and b) possibly too restrictive for real-world usage. That's
|
||||
// why it only scans for spaces because those are guaranteed to create
|
||||
// an invalid request.
|
||||
throw new TypeError('Request path contains unescaped characters');
|
||||
}
|
||||
const pathObj = url.parse(options.path || '/');
|
||||
urlObj.pathname = pathObj.pathname;
|
||||
urlObj.search = pathObj.search;
|
||||
urlObj.hash = pathObj.hash;
|
||||
urlStr = url.format(urlObj);
|
||||
}
|
||||
|
||||
const redirectPolicy = options.redirect || 'follow';
|
||||
if (!['follow', 'error', 'manual'].includes(redirectPolicy)) {
|
||||
throw new Error('redirect mode should be one of follow, error or manual');
|
||||
}
|
||||
|
||||
if (options.headers != null && typeof options.headers !== 'object') {
|
||||
throw new TypeError('headers must be an object');
|
||||
}
|
||||
|
||||
const urlLoaderOptions: NodeJS.CreateURLLoaderOptions & { redirectPolicy: RedirectPolicy, headers: Record<string, { name: string, value: string | string[] }> } = {
|
||||
method: (options.method || 'GET').toUpperCase(),
|
||||
url: urlStr,
|
||||
redirectPolicy,
|
||||
headers: {},
|
||||
body: null as any,
|
||||
useSessionCookies: options.useSessionCookies,
|
||||
credentials: options.credentials,
|
||||
origin: options.origin
|
||||
};
|
||||
const headers: Record<string, string | string[]> = options.headers || {};
|
||||
for (const [name, value] of Object.entries(headers)) {
|
||||
if (!isValidHeaderName(name)) {
|
||||
throw new Error(`Invalid header name: '${name}'`);
|
||||
}
|
||||
if (!isValidHeaderValue(value.toString())) {
|
||||
throw new Error(`Invalid value for header '${name}': '${value}'`);
|
||||
}
|
||||
const key = name.toLowerCase();
|
||||
urlLoaderOptions.headers[key] = { name, value };
|
||||
}
|
||||
if (options.session) {
|
||||
// Weak check, but it should be enough to catch 99% of accidental misuses.
|
||||
if (options.session.constructor && options.session.constructor.name === 'Session') {
|
||||
urlLoaderOptions.session = options.session;
|
||||
} else {
|
||||
throw new TypeError('`session` should be an instance of the Session class');
|
||||
}
|
||||
} else if (options.partition) {
|
||||
if (typeof options.partition === 'string') {
|
||||
urlLoaderOptions.partition = options.partition;
|
||||
} else {
|
||||
throw new TypeError('`partition` should be a string');
|
||||
}
|
||||
}
|
||||
return urlLoaderOptions;
|
||||
}
|
||||
|
||||
export class ClientRequest extends Writable implements Electron.ClientRequest {
|
||||
_started: boolean = false;
|
||||
_firstWrite: boolean = false;
|
||||
_aborted: boolean = false;
|
||||
_chunkedEncoding: boolean | undefined;
|
||||
_body: Writable | undefined;
|
||||
_urlLoaderOptions: NodeJS.CreateURLLoaderOptions & { headers: Record<string, { name: string, value: string | string[] }> };
|
||||
_redirectPolicy: RedirectPolicy;
|
||||
_followRedirectCb?: () => void;
|
||||
_uploadProgress?: { active: boolean, started: boolean, current: number, total: number };
|
||||
_urlLoader?: NodeJS.URLLoader;
|
||||
_response?: IncomingMessage;
|
||||
|
||||
constructor (options: ClientRequestConstructorOptions | string, callback?: (message: IncomingMessage) => void) {
|
||||
super({ autoDestroy: true });
|
||||
|
||||
if (!app.isReady()) {
|
||||
throw new Error('net module can only be used after app is ready');
|
||||
}
|
||||
|
||||
if (callback) {
|
||||
this.once('response', callback);
|
||||
}
|
||||
|
||||
const { redirectPolicy, ...urlLoaderOptions } = parseOptions(options);
|
||||
this._urlLoaderOptions = urlLoaderOptions;
|
||||
this._redirectPolicy = redirectPolicy;
|
||||
}
|
||||
|
||||
get chunkedEncoding () {
|
||||
return this._chunkedEncoding || false;
|
||||
}
|
||||
|
||||
set chunkedEncoding (value: boolean) {
|
||||
if (this._started) {
|
||||
throw new Error('chunkedEncoding can only be set before the request is started');
|
||||
}
|
||||
if (typeof this._chunkedEncoding !== 'undefined') {
|
||||
throw new Error('chunkedEncoding can only be set once');
|
||||
}
|
||||
this._chunkedEncoding = !!value;
|
||||
if (this._chunkedEncoding) {
|
||||
this._body = new ChunkedBodyStream(this);
|
||||
this._urlLoaderOptions.body = (pipe: NodeJS.DataPipe) => {
|
||||
(this._body! as ChunkedBodyStream).startReading(pipe);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
setHeader (name: string, value: string) {
|
||||
if (typeof name !== 'string') {
|
||||
throw new TypeError('`name` should be a string in setHeader(name, value)');
|
||||
}
|
||||
if (value == null) {
|
||||
throw new Error('`value` required in setHeader("' + name + '", value)');
|
||||
}
|
||||
if (this._started || this._firstWrite) {
|
||||
throw new Error('Can\'t set headers after they are sent');
|
||||
}
|
||||
if (!isValidHeaderName(name)) {
|
||||
throw new Error(`Invalid header name: '${name}'`);
|
||||
}
|
||||
if (!isValidHeaderValue(value.toString())) {
|
||||
throw new Error(`Invalid value for header '${name}': '${value}'`);
|
||||
}
|
||||
|
||||
const key = name.toLowerCase();
|
||||
this._urlLoaderOptions.headers[key] = { name, value };
|
||||
}
|
||||
|
||||
getHeader (name: string) {
|
||||
if (name == null) {
|
||||
throw new Error('`name` is required for getHeader(name)');
|
||||
}
|
||||
|
||||
const key = name.toLowerCase();
|
||||
const header = this._urlLoaderOptions.headers[key];
|
||||
return header && header.value as any;
|
||||
}
|
||||
|
||||
removeHeader (name: string) {
|
||||
if (name == null) {
|
||||
throw new Error('`name` is required for removeHeader(name)');
|
||||
}
|
||||
|
||||
if (this._started || this._firstWrite) {
|
||||
throw new Error('Can\'t remove headers after they are sent');
|
||||
}
|
||||
|
||||
const key = name.toLowerCase();
|
||||
delete this._urlLoaderOptions.headers[key];
|
||||
}
|
||||
|
||||
_write (chunk: Buffer, encoding: BufferEncoding, callback: () => void) {
|
||||
this._firstWrite = true;
|
||||
if (!this._body) {
|
||||
this._body = new SlurpStream();
|
||||
this._body.on('finish', () => {
|
||||
this._urlLoaderOptions.body = (this._body as SlurpStream).data();
|
||||
this._startRequest();
|
||||
});
|
||||
}
|
||||
// TODO: is this the right way to forward to another stream?
|
||||
this._body.write(chunk, encoding, callback);
|
||||
}
|
||||
|
||||
_final (callback: () => void) {
|
||||
if (this._body) {
|
||||
// TODO: is this the right way to forward to another stream?
|
||||
this._body.end(callback);
|
||||
} else {
|
||||
// end() called without a body, go ahead and start the request
|
||||
this._startRequest();
|
||||
callback();
|
||||
}
|
||||
}
|
||||
|
||||
_startRequest () {
|
||||
this._started = true;
|
||||
const stringifyValues = (obj: Record<string, { name: string, value: string | string[] }>) => {
|
||||
const ret: Record<string, string> = {};
|
||||
for (const k of Object.keys(obj)) {
|
||||
const kv = obj[k];
|
||||
ret[kv.name] = kv.value.toString();
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
this._urlLoaderOptions.referrer = this.getHeader('referer') || '';
|
||||
this._urlLoaderOptions.origin = this._urlLoaderOptions.origin || this.getHeader('origin') || '';
|
||||
this._urlLoaderOptions.hasUserActivation = this.getHeader('sec-fetch-user') === '?1';
|
||||
this._urlLoaderOptions.mode = this.getHeader('sec-fetch-mode') || '';
|
||||
this._urlLoaderOptions.destination = this.getHeader('sec-fetch-dest') || '';
|
||||
const opts = { ...this._urlLoaderOptions, extraHeaders: stringifyValues(this._urlLoaderOptions.headers) };
|
||||
this._urlLoader = createURLLoader(opts);
|
||||
this._urlLoader.on('response-started', (event, finalUrl, responseHead) => {
|
||||
const response = this._response = new IncomingMessage(responseHead);
|
||||
this.emit('response', response);
|
||||
});
|
||||
this._urlLoader.on('data', (event, data, resume) => {
|
||||
this._response!._storeInternalData(Buffer.from(data), resume);
|
||||
});
|
||||
this._urlLoader.on('complete', () => {
|
||||
if (this._response) { this._response._storeInternalData(null, null); }
|
||||
});
|
||||
this._urlLoader.on('error', (event, netErrorString) => {
|
||||
const error = new Error(netErrorString);
|
||||
if (this._response) this._response.destroy(error);
|
||||
this._die(error);
|
||||
});
|
||||
|
||||
this._urlLoader.on('login', (event, authInfo, callback) => {
|
||||
const handled = this.emit('login', authInfo, callback);
|
||||
if (!handled) {
|
||||
// If there were no listeners, cancel the authentication request.
|
||||
callback();
|
||||
}
|
||||
});
|
||||
|
||||
this._urlLoader.on('redirect', (event, redirectInfo, headers) => {
|
||||
const { statusCode, newMethod, newUrl } = redirectInfo;
|
||||
if (this._redirectPolicy === 'error') {
|
||||
this._die(new Error('Attempted to redirect, but redirect policy was \'error\''));
|
||||
} else if (this._redirectPolicy === 'manual') {
|
||||
let _followRedirect = false;
|
||||
this._followRedirectCb = () => { _followRedirect = true; };
|
||||
try {
|
||||
this.emit('redirect', statusCode, newMethod, newUrl, headers);
|
||||
} finally {
|
||||
this._followRedirectCb = undefined;
|
||||
if (!_followRedirect && !this._aborted) {
|
||||
this._die(new Error('Redirect was cancelled'));
|
||||
}
|
||||
}
|
||||
} else if (this._redirectPolicy === 'follow') {
|
||||
// Calling followRedirect() when the redirect policy is 'follow' is
|
||||
// allowed but does nothing. (Perhaps it should throw an error
|
||||
// though...? Since the redirect will happen regardless.)
|
||||
try {
|
||||
this._followRedirectCb = () => {};
|
||||
this.emit('redirect', statusCode, newMethod, newUrl, headers);
|
||||
} finally {
|
||||
this._followRedirectCb = undefined;
|
||||
}
|
||||
} else {
|
||||
this._die(new Error(`Unexpected redirect policy '${this._redirectPolicy}'`));
|
||||
}
|
||||
});
|
||||
|
||||
this._urlLoader.on('upload-progress', (event, position, total) => {
|
||||
this._uploadProgress = { active: true, started: true, current: position, total };
|
||||
this.emit('upload-progress', position, total); // Undocumented, for now
|
||||
});
|
||||
|
||||
this._urlLoader.on('download-progress', (event, current) => {
|
||||
if (this._response) {
|
||||
this._response.emit('download-progress', current); // Undocumented, for now
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
followRedirect () {
|
||||
if (this._followRedirectCb) {
|
||||
this._followRedirectCb();
|
||||
} else {
|
||||
throw new Error('followRedirect() called, but was not waiting for a redirect');
|
||||
}
|
||||
}
|
||||
|
||||
abort () {
|
||||
if (!this._aborted) {
|
||||
process.nextTick(() => { this.emit('abort'); });
|
||||
}
|
||||
this._aborted = true;
|
||||
this._die();
|
||||
}
|
||||
|
||||
_die (err?: Error) {
|
||||
// Node.js assumes that any stream which is ended is no longer capable of emitted events
|
||||
// which is a faulty assumption for the case of an object that is acting like a stream
|
||||
// (our urlRequest). If we don't emit here, this causes errors since we *do* expect
|
||||
// that error events can be emitted after urlRequest.end().
|
||||
if ((this as any)._writableState.destroyed && err) {
|
||||
this.emit('error', err);
|
||||
}
|
||||
|
||||
this.destroy(err);
|
||||
if (this._urlLoader) {
|
||||
this._urlLoader.cancel();
|
||||
if (this._response) this._response.destroy(err);
|
||||
}
|
||||
}
|
||||
|
||||
getUploadProgress (): UploadProgress {
|
||||
return this._uploadProgress ? { ...this._uploadProgress } : { active: false, started: false, current: 0, total: 0 };
|
||||
}
|
||||
}
|
||||
const { isOnline } = process._linkedBinding('electron_browser_net');
|
||||
|
||||
export function request (options: ClientRequestConstructorOptions | string, callback?: (message: IncomingMessage) => void) {
|
||||
return new ClientRequest(options, callback);
|
||||
}
|
||||
|
||||
export function fetch (input: RequestInfo, init?: RequestInit): Promise<Response> {
|
||||
return session.defaultSession.fetch(input, init);
|
||||
}
|
||||
|
||||
exports.isOnline = isOnline;
|
||||
|
||||
Object.defineProperty(exports, 'online', {
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
const { fromPartition } = process._linkedBinding('electron_browser_session');
|
||||
import { fetchWithSession } from '@electron/internal/browser/api/net-fetch';
|
||||
const { fromPartition, Session } = process._linkedBinding('electron_browser_session');
|
||||
|
||||
Session.prototype.fetch = function (input: RequestInfo, init?: RequestInit) {
|
||||
return fetchWithSession(input, init, this);
|
||||
};
|
||||
|
||||
export default {
|
||||
fromPartition,
|
||||
|
||||
@@ -28,11 +28,47 @@ 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
|
||||
Letter: {
|
||||
custom_display_name: 'Letter',
|
||||
height_microns: 279400,
|
||||
name: 'NA_LETTER',
|
||||
width_microns: 215900
|
||||
},
|
||||
Legal: {
|
||||
custom_display_name: 'Legal',
|
||||
height_microns: 355600,
|
||||
name: 'NA_LEGAL',
|
||||
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',
|
||||
@@ -41,29 +77,17 @@ const PDFPageSizes: Record<string, ElectronInternal.MediaSize> = {
|
||||
is_default: 'true',
|
||||
width_microns: 210000
|
||||
},
|
||||
A3: {
|
||||
custom_display_name: 'A3',
|
||||
height_microns: 420000,
|
||||
name: 'ISO_A3',
|
||||
width_microns: 297000
|
||||
A5: {
|
||||
custom_display_name: 'A5',
|
||||
height_microns: 210000,
|
||||
name: 'ISO_A5',
|
||||
width_microns: 148000
|
||||
},
|
||||
Legal: {
|
||||
custom_display_name: 'Legal',
|
||||
height_microns: 355600,
|
||||
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'
|
||||
A6: {
|
||||
custom_display_name: 'A6',
|
||||
height_microns: 148000,
|
||||
name: 'ISO_A6',
|
||||
width_microns: 105000
|
||||
}
|
||||
} as const;
|
||||
|
||||
@@ -394,10 +418,6 @@ WebContents.prototype.loadFile = function (filePath, options = {}) {
|
||||
};
|
||||
|
||||
WebContents.prototype.loadURL = function (url, options) {
|
||||
if (!options) {
|
||||
options = {};
|
||||
}
|
||||
|
||||
const p = new Promise<void>((resolve, reject) => {
|
||||
const resolveAndCleanup = () => {
|
||||
removeListeners();
|
||||
@@ -464,7 +484,7 @@ WebContents.prototype.loadURL = function (url, options) {
|
||||
});
|
||||
// Add a no-op rejection handler to silence the unhandled rejection error.
|
||||
p.catch(() => {});
|
||||
this._loadURL(url, options);
|
||||
this._loadURL(url, options ?? {});
|
||||
return p;
|
||||
};
|
||||
|
||||
@@ -524,7 +544,8 @@ const addReplyToEvent = (event: Electron.IpcMainEvent) => {
|
||||
};
|
||||
};
|
||||
|
||||
const addSenderFrameToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => {
|
||||
const addSenderToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent, sender: Electron.WebContents) => {
|
||||
event.sender = sender;
|
||||
const { processId, frameId } = event;
|
||||
Object.defineProperty(event, 'senderFrame', {
|
||||
get: () => webFrameMain.fromId(processId, frameId)
|
||||
@@ -533,7 +554,7 @@ const addSenderFrameToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainIn
|
||||
|
||||
const addReturnValueToEvent = (event: Electron.IpcMainEvent) => {
|
||||
Object.defineProperty(event, 'returnValue', {
|
||||
set: (value) => event.sendReply(value),
|
||||
set: (value) => event._replyChannel.sendReply(value),
|
||||
get: () => {}
|
||||
});
|
||||
};
|
||||
@@ -574,7 +595,7 @@ WebContents.prototype._init = function () {
|
||||
|
||||
// Dispatch IPC messages to the ipc module.
|
||||
this.on('-ipc-message' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
|
||||
addSenderFrameToEvent(event);
|
||||
addSenderToEvent(event, this);
|
||||
if (internal) {
|
||||
ipcMainInternal.emit(channel, event, ...args);
|
||||
} else {
|
||||
@@ -587,25 +608,30 @@ WebContents.prototype._init = function () {
|
||||
}
|
||||
});
|
||||
|
||||
this.on('-ipc-invoke' as any, function (event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) {
|
||||
addSenderFrameToEvent(event);
|
||||
event._reply = (result: any) => event.sendReply({ result });
|
||||
event._throw = (error: Error) => {
|
||||
this.on('-ipc-invoke' as any, async function (this: Electron.WebContents, event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) {
|
||||
addSenderToEvent(event, this);
|
||||
const replyWithResult = (result: any) => event._replyChannel.sendReply({ result });
|
||||
const replyWithError = (error: Error) => {
|
||||
console.error(`Error occurred in handler for '${channel}':`, error);
|
||||
event.sendReply({ error: error.toString() });
|
||||
event._replyChannel.sendReply({ error: error.toString() });
|
||||
};
|
||||
const maybeWebFrame = getWebFrameForEvent(event);
|
||||
const targets: (ElectronInternal.IpcMainInternal| undefined)[] = internal ? [ipcMainInternal] : [maybeWebFrame?.ipc, ipc, ipcMain];
|
||||
const target = targets.find(target => target && (target as any)._invokeHandlers.has(channel));
|
||||
if (target) {
|
||||
(target as any)._invokeHandlers.get(channel)(event, ...args);
|
||||
const handler = (target as any)._invokeHandlers.get(channel);
|
||||
try {
|
||||
replyWithResult(await Promise.resolve(handler(event, ...args)));
|
||||
} catch (err) {
|
||||
replyWithError(err as Error);
|
||||
}
|
||||
} else {
|
||||
event._throw(`No handler registered for '${channel}'`);
|
||||
replyWithError(new Error(`No handler registered for '${channel}'`));
|
||||
}
|
||||
});
|
||||
|
||||
this.on('-ipc-message-sync' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
|
||||
addSenderFrameToEvent(event);
|
||||
addSenderToEvent(event, this);
|
||||
addReturnValueToEvent(event);
|
||||
if (internal) {
|
||||
ipcMainInternal.emit(channel, event, ...args);
|
||||
@@ -622,8 +648,8 @@ WebContents.prototype._init = function () {
|
||||
}
|
||||
});
|
||||
|
||||
this.on('-ipc-ports' as any, function (event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) {
|
||||
addSenderFrameToEvent(event);
|
||||
this.on('-ipc-ports' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) {
|
||||
addSenderToEvent(event, this);
|
||||
event.ports = ports.map(p => new MessagePortMain(p));
|
||||
const maybeWebFrame = getWebFrameForEvent(event);
|
||||
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, message);
|
||||
@@ -651,7 +677,7 @@ WebContents.prototype._init = function () {
|
||||
|
||||
if (this.getType() !== 'remote') {
|
||||
// Make new windows requested by links behave like "window.open".
|
||||
this.on('-new-window' as any, (event: ElectronInternal.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'],
|
||||
this.on('-new-window' as any, (event: Electron.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'],
|
||||
rawFeatures: string, referrer: Electron.Referrer, postData: PostData) => {
|
||||
const postBody = postData ? {
|
||||
data: postData,
|
||||
@@ -677,7 +703,7 @@ WebContents.prototype._init = function () {
|
||||
const options = result.browserWindowConstructorOptions;
|
||||
if (!event.defaultPrevented) {
|
||||
openGuestWindow({
|
||||
embedder: event.sender,
|
||||
embedder: this,
|
||||
disposition,
|
||||
referrer,
|
||||
postData,
|
||||
@@ -690,7 +716,7 @@ WebContents.prototype._init = function () {
|
||||
|
||||
let windowOpenOverriddenOptions: BrowserWindowConstructorOptions | null = null;
|
||||
let windowOpenOutlivesOpenerOption: boolean = false;
|
||||
this.on('-will-add-new-contents' as any, (event: ElectronInternal.Event, url: string, frameName: string, rawFeatures: string, disposition: Electron.HandlerDetails['disposition'], referrer: Electron.Referrer, postData: PostData) => {
|
||||
this.on('-will-add-new-contents' as any, (event: Electron.Event, url: string, frameName: string, rawFeatures: string, disposition: Electron.HandlerDetails['disposition'], referrer: Electron.Referrer, postData: PostData) => {
|
||||
const postBody = postData ? {
|
||||
data: postData,
|
||||
...parseContentTypeFormat(postData)
|
||||
@@ -725,7 +751,7 @@ WebContents.prototype._init = function () {
|
||||
} : undefined;
|
||||
const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures);
|
||||
const webPreferences = makeWebPreferences({
|
||||
embedder: event.sender,
|
||||
embedder: this,
|
||||
insecureParsedWebPreferences: parsedWebPreferences,
|
||||
secureOverrideWebPreferences
|
||||
});
|
||||
@@ -738,7 +764,7 @@ WebContents.prototype._init = function () {
|
||||
});
|
||||
|
||||
// Create a new browser window for "window.open"
|
||||
this.on('-add-new-contents' as any, (event: ElectronInternal.Event, webContents: Electron.WebContents, disposition: string,
|
||||
this.on('-add-new-contents' as any, (event: Electron.Event, webContents: Electron.WebContents, disposition: string,
|
||||
_userGesture: boolean, _left: number, _top: number, _width: number, _height: number, url: string, frameName: string,
|
||||
referrer: Electron.Referrer, rawFeatures: string, postData: PostData) => {
|
||||
const overriddenOptions = windowOpenOverriddenOptions || undefined;
|
||||
@@ -754,7 +780,7 @@ WebContents.prototype._init = function () {
|
||||
}
|
||||
|
||||
openGuestWindow({
|
||||
embedder: event.sender,
|
||||
embedder: this,
|
||||
guest: webContents,
|
||||
overrideBrowserWindowOptions: overriddenOptions,
|
||||
disposition,
|
||||
@@ -791,8 +817,7 @@ WebContents.prototype._init = function () {
|
||||
}
|
||||
});
|
||||
|
||||
const event = process._linkedBinding('electron_browser_event').createEmpty();
|
||||
app.emit('web-contents-created', event, this);
|
||||
app.emit('web-contents-created', { sender: this, preventDefault () {}, get defaultPrevented () { return false; } }, this);
|
||||
|
||||
// Properties
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ interface GuestInstance {
|
||||
}
|
||||
|
||||
const webViewManager = process._linkedBinding('electron_browser_web_view_manager');
|
||||
const eventBinding = process._linkedBinding('electron_browser_event');
|
||||
const netBinding = process._linkedBinding('electron_browser_net');
|
||||
|
||||
const supportedWebViewEvents = Object.keys(webViewEvents);
|
||||
@@ -82,7 +81,13 @@ function makeLoadURLOptions (params: Record<string, any>) {
|
||||
// Create a new guest instance.
|
||||
const createGuest = function (embedder: Electron.WebContents, embedderFrameId: number, elementInstanceId: number, params: Record<string, any>) {
|
||||
const webPreferences = makeWebPreferences(embedder, params);
|
||||
const event = eventBinding.createWithSender(embedder);
|
||||
const event = {
|
||||
sender: embedder,
|
||||
preventDefault () {
|
||||
this.defaultPrevented = true;
|
||||
},
|
||||
defaultPrevented: false
|
||||
};
|
||||
|
||||
const { instanceId } = params;
|
||||
|
||||
|
||||
@@ -18,13 +18,7 @@ export class IpcMainImpl extends EventEmitter {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`Expected handler to be a function, but found type '${typeof fn}'`);
|
||||
}
|
||||
this._invokeHandlers.set(method, async (e, ...args) => {
|
||||
try {
|
||||
e._reply(await Promise.resolve(fn(e, ...args)));
|
||||
} catch (err) {
|
||||
e._throw(err as Error);
|
||||
}
|
||||
});
|
||||
this._invokeHandlers.set(method, fn);
|
||||
}
|
||||
|
||||
handleOnce: Electron.IpcMain['handleOnce'] = (method, fn) => {
|
||||
|
||||
@@ -7,11 +7,11 @@
|
||||
"@azure/storage-blob": "^12.9.0",
|
||||
"@dsanders11/vscode-markdown-languageservice": "^0.3.0-alpha.4",
|
||||
"@electron/asar": "^3.2.1",
|
||||
"@electron/docs-parser": "^1.0.0",
|
||||
"@electron/docs-parser": "^1.1.0",
|
||||
"@electron/fiddle-core": "^1.0.4",
|
||||
"@electron/github-app-auth": "^1.5.0",
|
||||
"@electron/typescript-definitions": "^8.10.0",
|
||||
"@octokit/rest": "^18.0.3",
|
||||
"@electron/typescript-definitions": "^8.14.0",
|
||||
"@octokit/rest": "^19.0.7",
|
||||
"@primer/octicons": "^10.0.0",
|
||||
"@types/basic-auth": "^1.1.3",
|
||||
"@types/busboy": "^1.5.0",
|
||||
|
||||
@@ -125,3 +125,5 @@ chore_introduce_blocking_api_for_electron.patch
|
||||
chore_patch_out_partition_attribute_dcheck_for_webviews.patch
|
||||
expose_v8initializer_codegenerationcheckcallbackinmainthread.patch
|
||||
chore_patch_out_profile_methods_in_profile_selections_cc.patch
|
||||
fix_x11_window_restore_minimized_maximized_window.patch
|
||||
chore_defer_usb_service_getdevices_request_until_usb_service_is.patch
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
|
||||
From: John Kleinschmidt <jkleinsc@electronjs.org>
|
||||
Date: Thu, 2 Mar 2023 15:26:46 -0500
|
||||
Subject: chore: defer USB service GetDevices request until USB service is
|
||||
ready.
|
||||
|
||||
On macOS we need to wait until the USB service is ready before the list of
|
||||
devices is available. This should no longer be necessary if/when
|
||||
https://crbug.com/1096743 is completed.
|
||||
|
||||
diff --git a/services/device/usb/usb_service_impl.cc b/services/device/usb/usb_service_impl.cc
|
||||
index 99456d1baa098e8a48b4a31cc8f5661586f7fc82..11d98208c85093598813897a144812c76bc67bea 100644
|
||||
--- a/services/device/usb/usb_service_impl.cc
|
||||
+++ b/services/device/usb/usb_service_impl.cc
|
||||
@@ -198,7 +198,7 @@ void UsbServiceImpl::GetDevices(GetDevicesCallback callback) {
|
||||
return;
|
||||
}
|
||||
|
||||
- if (enumeration_in_progress_) {
|
||||
+ if (enumeration_in_progress_ || !enumeration_ready_) {
|
||||
pending_enumeration_callbacks_.push_back(std::move(callback));
|
||||
return;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
|
||||
From: Cheng Zhao <zcbenz@gmail.com>
|
||||
Date: Wed, 15 Feb 2023 11:30:56 +0900
|
||||
Subject: fix: restoring a X11 window should not remove its previous maximized
|
||||
state
|
||||
|
||||
On Linux after minimizing a maximized window, it will have both the
|
||||
"maximized" and "hidden" states, and restoring the window should only remove
|
||||
the "hidden" state, which makes it back a maximized window.
|
||||
|
||||
However in the implementation of `X11Window::Restore`, both "maximized" and
|
||||
"hidden" states are removed, and a maximized window that was minimized will
|
||||
be resized to its normal size after calling Restore, while the correct
|
||||
behavior should be going back to the maximized state.
|
||||
|
||||
Backported from:
|
||||
https://chromium-review.googlesource.com/c/chromium/src/+/4252946
|
||||
|
||||
diff --git a/ui/ozone/platform/x11/x11_window.cc b/ui/ozone/platform/x11/x11_window.cc
|
||||
index cbf300db6ec3aa6c108233006c8249231b9a8aa1..f681a199951f448604f887e1c1c64250608f095e 100644
|
||||
--- a/ui/ozone/platform/x11/x11_window.cc
|
||||
+++ b/ui/ozone/platform/x11/x11_window.cc
|
||||
@@ -731,11 +731,16 @@ void X11Window::Minimize() {
|
||||
}
|
||||
|
||||
void X11Window::Restore() {
|
||||
- should_maximize_after_map_ = false;
|
||||
- restore_in_flight_ = true;
|
||||
- SetWMSpecState(false, x11::GetAtom("_NET_WM_STATE_MAXIMIZED_VERT"),
|
||||
- x11::GetAtom("_NET_WM_STATE_MAXIMIZED_HORZ"));
|
||||
- SetWMSpecState(false, x11::GetAtom("_NET_WM_STATE_HIDDEN"), x11::Atom::None);
|
||||
+ if (IsMinimized()) {
|
||||
+ restore_in_flight_ = true;
|
||||
+ SetWMSpecState(false, x11::GetAtom("_NET_WM_STATE_HIDDEN"),
|
||||
+ x11::Atom::None);
|
||||
+ } else if (IsMaximized()) {
|
||||
+ restore_in_flight_ = true;
|
||||
+ should_maximize_after_map_ = false;
|
||||
+ SetWMSpecState(false, x11::GetAtom("_NET_WM_STATE_MAXIMIZED_VERT"),
|
||||
+ x11::GetAtom("_NET_WM_STATE_MAXIMIZED_HORZ"));
|
||||
+ }
|
||||
}
|
||||
|
||||
PlatformWindowState X11Window::GetPlatformWindowState() const {
|
||||
@@ -1890,6 +1895,10 @@ bool X11Window::IsMinimized() const {
|
||||
}
|
||||
|
||||
bool X11Window::IsMaximized() const {
|
||||
+ // In X11, if a maximized window is minimized, it will have both the "hidden"
|
||||
+ // and "maximized" states.
|
||||
+ if (IsMinimized())
|
||||
+ return false;
|
||||
return (HasWMSpecProperty(window_properties_,
|
||||
x11::GetAtom("_NET_WM_STATE_MAXIMIZED_VERT")) &&
|
||||
HasWMSpecProperty(window_properties_,
|
||||
@@ -222,10 +222,159 @@ index f35d9ef2a2df3db8ecbf1d7b909c7b1cf33f3cd9..a710b8b4f851666fd65bb37f69ec2fa7
|
||||
|
||||
bool SandboxCompiler::CompilePolicyToProto(mac::SandboxPolicy& policy,
|
||||
diff --git a/sandbox/mac/seatbelt.cc b/sandbox/mac/seatbelt.cc
|
||||
index 15c835e118456394c0a00ac98c11241c14ca75bd..49332a94219fc3e64ab05baa04681325edddfeb0 100644
|
||||
index 15c835e118456394c0a00ac98c11241c14ca75bd..83759e5fbc252fa57ca2fa122873dfac3d61d46d 100644
|
||||
--- a/sandbox/mac/seatbelt.cc
|
||||
+++ b/sandbox/mac/seatbelt.cc
|
||||
@@ -175,7 +175,11 @@ void Seatbelt::FreeError(char* errorbuf) {
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
extern "C" {
|
||||
#include <sandbox.h>
|
||||
-
|
||||
+#if !IS_MAS_BUILD()
|
||||
int sandbox_init_with_parameters(const char* profile,
|
||||
uint64_t flags,
|
||||
const char* const parameters[],
|
||||
@@ -40,13 +40,13 @@ sandbox_profile_t* sandbox_compile_string(const char* data,
|
||||
char** error);
|
||||
int sandbox_apply(sandbox_profile_t*);
|
||||
void sandbox_free_profile(sandbox_profile_t*);
|
||||
-
|
||||
+#endif
|
||||
} // extern "C"
|
||||
|
||||
namespace sandbox {
|
||||
|
||||
namespace {
|
||||
-
|
||||
+#if !IS_MAS_BUILD()
|
||||
bool HandleSandboxResult(int rv, char* errorbuf, std::string* error) {
|
||||
if (rv == 0) {
|
||||
if (error)
|
||||
@@ -74,36 +74,48 @@ bool HandleSandboxErrno(int rv, const char* message, std::string* error) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
-
|
||||
+#endif
|
||||
} // namespace
|
||||
|
||||
// static
|
||||
Seatbelt::Parameters Seatbelt::Parameters::Create() {
|
||||
Parameters params;
|
||||
+#if !IS_MAS_BUILD()
|
||||
params.params_ = ::sandbox_create_params();
|
||||
+#endif
|
||||
return params;
|
||||
}
|
||||
|
||||
Seatbelt::Parameters::Parameters() = default;
|
||||
|
||||
Seatbelt::Parameters::Parameters(Seatbelt::Parameters&& other) {
|
||||
+#if !IS_MAS_BUILD()
|
||||
params_ = std::exchange(other.params_, nullptr);
|
||||
+#endif
|
||||
}
|
||||
|
||||
Seatbelt::Parameters& Seatbelt::Parameters::operator=(
|
||||
Seatbelt::Parameters&& other) {
|
||||
+#if !IS_MAS_BUILD()
|
||||
params_ = std::exchange(other.params_, nullptr);
|
||||
+#endif
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool Seatbelt::Parameters::Set(const char* key, const char* value) {
|
||||
+#if !IS_MAS_BUILD()
|
||||
return ::sandbox_set_param(params_, key, value) == 0;
|
||||
+#else
|
||||
+ return true;
|
||||
+#endif
|
||||
}
|
||||
|
||||
Seatbelt::Parameters::~Parameters() {
|
||||
+#if !IS_MAS_BUILD()
|
||||
if (params_) {
|
||||
::sandbox_free_params(params_);
|
||||
}
|
||||
+#endif
|
||||
}
|
||||
|
||||
// Initialize the static member variables.
|
||||
@@ -114,6 +126,7 @@ const char* Seatbelt::kProfilePureComputation = kSBXProfilePureComputation;
|
||||
|
||||
// static
|
||||
bool Seatbelt::Init(const char* profile, uint64_t flags, std::string* error) {
|
||||
+#if !IS_MAS_BUILD()
|
||||
// OS X deprecated these functions, but did not provide a suitable replacement,
|
||||
// so ignore the deprecation warning.
|
||||
#pragma clang diagnostic push
|
||||
@@ -122,6 +135,9 @@ bool Seatbelt::Init(const char* profile, uint64_t flags, std::string* error) {
|
||||
int rv = ::sandbox_init(profile, flags, &errorbuf);
|
||||
return HandleSandboxResult(rv, errorbuf, error);
|
||||
#pragma clang diagnostic pop
|
||||
+#else
|
||||
+ return true;
|
||||
+#endif
|
||||
}
|
||||
|
||||
// static
|
||||
@@ -129,10 +145,14 @@ bool Seatbelt::InitWithParams(const char* profile,
|
||||
uint64_t flags,
|
||||
const char* const parameters[],
|
||||
std::string* error) {
|
||||
+#if !IS_MAS_BUILD()
|
||||
char* errorbuf = nullptr;
|
||||
int rv =
|
||||
::sandbox_init_with_parameters(profile, flags, parameters, &errorbuf);
|
||||
return HandleSandboxResult(rv, errorbuf, error);
|
||||
+#else
|
||||
+ return true;
|
||||
+#endif
|
||||
}
|
||||
|
||||
// static
|
||||
@@ -140,6 +160,7 @@ bool Seatbelt::Compile(const char* profile,
|
||||
const Seatbelt::Parameters& params,
|
||||
std::string& compiled_profile,
|
||||
std::string* error) {
|
||||
+#if !IS_MAS_BUILD()
|
||||
char* errorbuf = nullptr;
|
||||
sandbox_profile_t* sandbox_profile =
|
||||
::sandbox_compile_string(profile, params.params(), &errorbuf);
|
||||
@@ -149,33 +170,44 @@ bool Seatbelt::Compile(const char* profile,
|
||||
compiled_profile.assign(reinterpret_cast<const char*>(sandbox_profile->data),
|
||||
sandbox_profile->size);
|
||||
::sandbox_free_profile(sandbox_profile);
|
||||
+#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
// static
|
||||
bool Seatbelt::ApplyCompiledProfile(const std::string& profile,
|
||||
std::string* error) {
|
||||
+#if !IS_MAS_BUILD()
|
||||
sandbox_profile_t sbox_profile = {
|
||||
.builtin = nullptr,
|
||||
.data = reinterpret_cast<const uint8_t*>(profile.data()),
|
||||
.size = profile.size()};
|
||||
return HandleSandboxErrno(::sandbox_apply(&sbox_profile),
|
||||
"sandbox_apply: ", error);
|
||||
+#else
|
||||
+ return true;
|
||||
+#endif
|
||||
}
|
||||
|
||||
// static
|
||||
void Seatbelt::FreeError(char* errorbuf) {
|
||||
+#if !IS_MAS_BUILD()
|
||||
// OS X deprecated these functions, but did not provide a suitable replacement,
|
||||
// so ignore the deprecation warning.
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
return ::sandbox_free_error(errorbuf);
|
||||
#pragma clang diagnostic pop
|
||||
+#endif
|
||||
}
|
||||
|
||||
// static
|
||||
bool Seatbelt::IsSandboxed() {
|
||||
|
||||
@@ -21,5 +21,7 @@
|
||||
|
||||
"src/electron/patches/Mantle": "src/third_party/squirrel.mac/vendor/Mantle",
|
||||
|
||||
"src/electron/patches/ReactiveObjC": "src/third_party/squirrel.mac/vendor/ReactiveObjC"
|
||||
"src/electron/patches/ReactiveObjC": "src/third_party/squirrel.mac/vendor/ReactiveObjC",
|
||||
|
||||
"src/electron/patches/webrtc": "src/third_party/webrtc"
|
||||
}
|
||||
|
||||
@@ -25,7 +25,6 @@ build_ensure_native_module_compilation_fails_if_not_using_a_new.patch
|
||||
fix_override_createjob_in_node_platform.patch
|
||||
v8_api_advance_api_deprecation.patch
|
||||
fixup_for_error_declaration_shadows_a_local_variable.patch
|
||||
fixup_for_wc_98-compat-extra-semi.patch
|
||||
fix_parallel_test-v8-stats.patch
|
||||
fix_expose_the_built-in_electron_module_via_the_esm_loader.patch
|
||||
heap_remove_allocationspace_map_space_enum_constant.patch
|
||||
@@ -36,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
|
||||
|
||||
@@ -2118,7 +2118,7 @@ index 0000000000000000000000000000000000000000..d1d6b51e8c0c5bc6a5d09e217eb30483
|
||||
+ args = rebase_path(inputs + outputs, root_build_dir)
|
||||
+}
|
||||
diff --git a/src/node_version.h b/src/node_version.h
|
||||
index c42b070a3367283155f9ff6b861b9f0160b5e9ed..ff8a64174e6f09af533b2fe05b2fe6e600624910 100644
|
||||
index 46e039093716576d3c382dea0cb4bafd42d99799..ff9296f5abac9afda03e457c107f9666e792c21f 100644
|
||||
--- a/src/node_version.h
|
||||
+++ b/src/node_version.h
|
||||
@@ -89,7 +89,10 @@
|
||||
|
||||
@@ -40,7 +40,7 @@ index b661dc4a1b3149e780eef46033e70e68038417b0..15b6155017233ed9d4c60c2453f498ba
|
||||
'defines': [
|
||||
'V8_COMPRESS_POINTERS',
|
||||
diff --git a/configure.py b/configure.py
|
||||
index 171afd04030e6933da054db866d44428ae808acf..363bf746101c85630a6c52146303986e7e0dcdce 100755
|
||||
index bfa20f5fc7a64b30b464327f4086a027e9a23359..f9d849260c3d7b1368d375125ae587eaa396c49e 100755
|
||||
--- a/configure.py
|
||||
+++ b/configure.py
|
||||
@@ -1517,6 +1517,7 @@ def configure_library(lib, output, pkgname=None):
|
||||
|
||||
@@ -42,7 +42,7 @@ index 2c2f3218a8ae387802af3d154ede601aedcb52dd..b661dc4a1b3149e780eef46033e70e68
|
||||
'defines': ['V8_31BIT_SMIS_ON_64BIT_ARCH'],
|
||||
}],
|
||||
diff --git a/configure.py b/configure.py
|
||||
index 0a45c07f587ed8d21dff45d523b7074606c586ac..171afd04030e6933da054db866d44428ae808acf 100755
|
||||
index 62c01aaf6a386d24e82289554520140f03699c95..bfa20f5fc7a64b30b464327f4086a027e9a23359 100755
|
||||
--- a/configure.py
|
||||
+++ b/configure.py
|
||||
@@ -1530,6 +1530,7 @@ def configure_v8(o):
|
||||
|
||||
@@ -8,10 +8,10 @@ they use themselves as the entry point. We should try to upstream some form
|
||||
of this.
|
||||
|
||||
diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js
|
||||
index 207142322bba89e94f4e3052a22bef6ffebcdc39..c83d8b0db630d3fc26fb273170945c872bede091 100644
|
||||
index c19cd5e5d8a818c52406c78b95d96bae1b1f41bd..88df0c4b6f995c993c330963ff0c730e00c5b8ec 100644
|
||||
--- a/lib/internal/modules/cjs/loader.js
|
||||
+++ b/lib/internal/modules/cjs/loader.js
|
||||
@@ -1200,6 +1200,13 @@ Module.prototype._compile = function(content, filename) {
|
||||
@@ -1228,6 +1228,13 @@ Module.prototype._compile = function(content, filename) {
|
||||
if (getOptionValue('--inspect-brk') && process._eval == null) {
|
||||
if (!resolvedArgv) {
|
||||
// We enter the repl if we're not given a filename argument.
|
||||
|
||||
@@ -715,10 +715,10 @@ index 008ab129f0e019c659eecf5a76b7eb412c947fe3..6688f5d916f50e1e4fcfff1619c8634a
|
||||
|
||||
cipher.end('Papaya!'); // Should not cause an unhandled exception.
|
||||
diff --git a/test/parallel/test-crypto-x509.js b/test/parallel/test-crypto-x509.js
|
||||
index 6d92e97115fd537b0469f69132e591d8b1c6a43f..cdeed19099c351e3c3ec3c2d78e12b64098ddc6a 100644
|
||||
index 2f2e443a7f6482c26f3a065520c8764d8402a91f..ccfe79ac65a223139f293f7dd034096fcdbc81ab 100644
|
||||
--- a/test/parallel/test-crypto-x509.js
|
||||
+++ b/test/parallel/test-crypto-x509.js
|
||||
@@ -110,7 +110,7 @@ const der = Buffer.from(
|
||||
@@ -111,7 +111,7 @@ const der = Buffer.from(
|
||||
'5A:42:63:E0:21:2F:D6:70:63:07:96:6F:27:A7:78:12:08:02:7A:8B'
|
||||
);
|
||||
assert.strictEqual(x509.keyUsage, undefined);
|
||||
@@ -727,7 +727,7 @@ index 6d92e97115fd537b0469f69132e591d8b1c6a43f..cdeed19099c351e3c3ec3c2d78e12b64
|
||||
|
||||
assert.deepStrictEqual(x509.raw, der);
|
||||
|
||||
@@ -209,6 +209,16 @@ const der = Buffer.from(
|
||||
@@ -253,6 +253,16 @@ oans248kpal88CGqsN2so/wZKxVnpiXlPHMdiNL7hRSUqlHkUi07FrP2Htg8kjI=
|
||||
});
|
||||
mc.port2.postMessage(x509);
|
||||
|
||||
@@ -744,7 +744,7 @@ index 6d92e97115fd537b0469f69132e591d8b1c6a43f..cdeed19099c351e3c3ec3c2d78e12b64
|
||||
// Verify that legacy encoding works
|
||||
const legacyObjectCheck = {
|
||||
subject: Object.assign(Object.create(null), {
|
||||
@@ -233,16 +243,8 @@ const der = Buffer.from(
|
||||
@@ -277,16 +287,8 @@ oans248kpal88CGqsN2so/wZKxVnpiXlPHMdiNL7hRSUqlHkUi07FrP2Htg8kjI=
|
||||
'OCSP - URI': ['http://ocsp.nodejs.org/'],
|
||||
'CA Issuers - URI': ['http://ca.nodejs.org/ca.cert']
|
||||
}),
|
||||
@@ -762,7 +762,7 @@ index 6d92e97115fd537b0469f69132e591d8b1c6a43f..cdeed19099c351e3c3ec3c2d78e12b64
|
||||
exponent: '0x10001',
|
||||
valid_from: 'Sep 3 21:40:37 2022 GMT',
|
||||
valid_to: 'Jun 17 21:40:37 2296 GMT',
|
||||
@@ -254,7 +256,7 @@ const der = Buffer.from(
|
||||
@@ -298,7 +300,7 @@ oans248kpal88CGqsN2so/wZKxVnpiXlPHMdiNL7hRSUqlHkUi07FrP2Htg8kjI=
|
||||
'51:62:18:39:E2:E2:77:F5:86:11:E8:C0:CA:54:43:7C:76:83:19:05:D0:03:' +
|
||||
'24:21:B8:EB:14:61:FB:24:16:EB:BD:51:1A:17:91:04:30:03:EB:68:5F:DC:' +
|
||||
'86:E1:D1:7C:FB:AF:78:ED:63:5F:29:9C:32:AF:A1:8E:22:96:D1:02',
|
||||
@@ -771,7 +771,7 @@ index 6d92e97115fd537b0469f69132e591d8b1c6a43f..cdeed19099c351e3c3ec3c2d78e12b64
|
||||
};
|
||||
|
||||
const legacyObject = x509.toLegacyObject();
|
||||
@@ -263,7 +265,7 @@ const der = Buffer.from(
|
||||
@@ -307,7 +309,7 @@ oans248kpal88CGqsN2so/wZKxVnpiXlPHMdiNL7hRSUqlHkUi07FrP2Htg8kjI=
|
||||
assert.deepStrictEqual(legacyObject.subject, legacyObjectCheck.subject);
|
||||
assert.deepStrictEqual(legacyObject.issuer, legacyObjectCheck.issuer);
|
||||
assert.deepStrictEqual(legacyObject.infoAccess, legacyObjectCheck.infoAccess);
|
||||
@@ -780,7 +780,7 @@ index 6d92e97115fd537b0469f69132e591d8b1c6a43f..cdeed19099c351e3c3ec3c2d78e12b64
|
||||
assert.strictEqual(legacyObject.bits, legacyObjectCheck.bits);
|
||||
assert.strictEqual(legacyObject.exponent, legacyObjectCheck.exponent);
|
||||
assert.strictEqual(legacyObject.valid_from, legacyObjectCheck.valid_from);
|
||||
@@ -272,7 +274,7 @@ const der = Buffer.from(
|
||||
@@ -316,7 +318,7 @@ oans248kpal88CGqsN2so/wZKxVnpiXlPHMdiNL7hRSUqlHkUi07FrP2Htg8kjI=
|
||||
assert.strictEqual(
|
||||
legacyObject.fingerprint256,
|
||||
legacyObjectCheck.fingerprint256);
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
|
||||
From: John Kleinschmidt <jkleinsc@electronjs.org>
|
||||
Date: Thu, 1 Sep 2022 21:55:57 -0400
|
||||
Subject: fixup for Wc++98-compat-extra-semi
|
||||
|
||||
Wc++98-compat-extra-semi is turned on for Electron so this
|
||||
patch fixes that error in node.
|
||||
|
||||
diff --git a/src/node_serdes.cc b/src/node_serdes.cc
|
||||
index 1cdd436b343861a96582a803b460aefe1e81cdd0..0249574c4431fb5b98852699f1368f71b49691c1 100644
|
||||
--- a/src/node_serdes.cc
|
||||
+++ b/src/node_serdes.cc
|
||||
@@ -32,7 +32,7 @@ namespace serdes {
|
||||
v8::ArrayBuffer::Allocator* GetAllocator() {
|
||||
static v8::ArrayBuffer::Allocator* allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator();
|
||||
return allocator;
|
||||
-};
|
||||
+}
|
||||
|
||||
class SerializerContext : public BaseObject,
|
||||
public ValueSerializer::Delegate {
|
||||
@@ -0,0 +1,44 @@
|
||||
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
|
||||
From: Shelley Vohr <shelley.vohr@gmail.com>
|
||||
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');
|
||||
@@ -6,10 +6,10 @@ Subject: Pass all globals through "require"
|
||||
(cherry picked from commit 7d015419cb7a0ecfe6728431a4ed2056cd411d62)
|
||||
|
||||
diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js
|
||||
index b942b37dd90498432728bf897fb6f694b7041ba5..9da60135ac79a2034a646c0a1380923f7fbfacab 100644
|
||||
index 42e5cc50105560174b3106898d20ef11ea37be85..6b9aef981cfa934e1321916828d4f921008134d6 100644
|
||||
--- a/lib/internal/modules/cjs/loader.js
|
||||
+++ b/lib/internal/modules/cjs/loader.js
|
||||
@@ -137,6 +137,13 @@ const {
|
||||
@@ -142,6 +142,13 @@ const {
|
||||
CHAR_FORWARD_SLASH,
|
||||
} = require('internal/constants');
|
||||
|
||||
@@ -23,7 +23,7 @@ index b942b37dd90498432728bf897fb6f694b7041ba5..9da60135ac79a2034a646c0a1380923f
|
||||
const {
|
||||
isProxy
|
||||
} = require('internal/util/types');
|
||||
@@ -1221,10 +1228,12 @@ Module.prototype._compile = function(content, filename) {
|
||||
@@ -1249,10 +1256,12 @@ Module.prototype._compile = function(content, filename) {
|
||||
if (requireDepth === 0) statCache = new SafeMap();
|
||||
if (inspectorWrapper) {
|
||||
result = inspectorWrapper(compiledWrapper, thisValue, exports,
|
||||
|
||||
@@ -22,7 +22,7 @@ index 81b441a554e34556fc41066fc8761c713acb0ced..7dd89d5f134b09da2678dd54fa913946
|
||||
// release cycle, remove the Proxy and setter and update the
|
||||
// getter to either return a read-only object or always return
|
||||
diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js
|
||||
index 9da60135ac79a2034a646c0a1380923f7fbfacab..207142322bba89e94f4e3052a22bef6ffebcdc39 100644
|
||||
index 6b9aef981cfa934e1321916828d4f921008134d6..c19cd5e5d8a818c52406c78b95d96bae1b1f41bd 100644
|
||||
--- a/lib/internal/modules/cjs/loader.js
|
||||
+++ b/lib/internal/modules/cjs/loader.js
|
||||
@@ -94,7 +94,7 @@ const fs = require('fs');
|
||||
@@ -34,7 +34,7 @@ index 9da60135ac79a2034a646c0a1380923f7fbfacab..207142322bba89e94f4e3052a22bef6f
|
||||
const packageJsonReader = require('internal/modules/package_json_reader');
|
||||
const { safeGetenv } = internalBinding('credentials');
|
||||
const {
|
||||
@@ -171,7 +171,7 @@ function stat(filename) {
|
||||
@@ -190,7 +190,7 @@ function stat(filename) {
|
||||
const result = statCache.get(filename);
|
||||
if (result !== undefined) return result;
|
||||
}
|
||||
|
||||
@@ -155,7 +155,7 @@ index ece9a4cfd45bf885169fdd278e09c467c6b4bbab..0c0dac67c0834ab7feba426079629245
|
||||
|
||||
// Delegate to V8's allocator for compatibility with the V8 memory cage.
|
||||
diff --git a/src/node_serdes.cc b/src/node_serdes.cc
|
||||
index 6864f2d88b34abfa4090780d6993684cd0b366a3..1cdd436b343861a96582a803b460aefe1e81cdd0 100644
|
||||
index 6864f2d88b34abfa4090780d6993684cd0b366a3..0249574c4431fb5b98852699f1368f71b49691c1 100644
|
||||
--- a/src/node_serdes.cc
|
||||
+++ b/src/node_serdes.cc
|
||||
@@ -29,6 +29,11 @@ using v8::ValueSerializer;
|
||||
@@ -165,7 +165,7 @@ index 6864f2d88b34abfa4090780d6993684cd0b366a3..1cdd436b343861a96582a803b460aefe
|
||||
+v8::ArrayBuffer::Allocator* GetAllocator() {
|
||||
+ static v8::ArrayBuffer::Allocator* allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator();
|
||||
+ return allocator;
|
||||
+};
|
||||
+}
|
||||
+
|
||||
class SerializerContext : public BaseObject,
|
||||
public ValueSerializer::Delegate {
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
fix_fallback_to_x11_capturer_on_wayland.patch
|
||||
|
||||
58
patches/webrtc/fix_fallback_to_x11_capturer_on_wayland.patch
Normal file
58
patches/webrtc/fix_fallback_to_x11_capturer_on_wayland.patch
Normal file
@@ -0,0 +1,58 @@
|
||||
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
|
||||
From: VerteDinde <keeleymhammond@gmail.com>
|
||||
Date: Sun, 5 Mar 2023 21:04:37 -0800
|
||||
Subject: fix: fallback to X11 capturer on Wayland
|
||||
|
||||
CL: https://webrtc-review.googlesource.com/c/src/+/279163
|
||||
|
||||
Desktop Capturer behaves inconsistently on Wayland. PipeWire does not
|
||||
always successfully start; if it does not, we return a nullptr rather
|
||||
than falling back on the X11 capturer, crashing the application.
|
||||
|
||||
If the X11 capturer is enabled, we should at minimum try to fallback
|
||||
to X11 for desktop capturer. This patch re-enables that fallback,
|
||||
which was previously default behavior.
|
||||
|
||||
This patch can be removed when 1) this fix is upstreamed, or 2) the
|
||||
stability of PipeWire initialization is improved upstream.
|
||||
|
||||
Patch_Filename: fix_fallback_to_x11_desktop_capturer_wayland.patch
|
||||
|
||||
diff --git a/modules/desktop_capture/screen_capturer_linux.cc b/modules/desktop_capture/screen_capturer_linux.cc
|
||||
index 44993837e8bbd84a11ec9d187349a95f83258910..cd9f8b0be6a19d057fe9150382fb72bc4032b343 100644
|
||||
--- a/modules/desktop_capture/screen_capturer_linux.cc
|
||||
+++ b/modules/desktop_capture/screen_capturer_linux.cc
|
||||
@@ -34,11 +34,10 @@ std::unique_ptr<DesktopCapturer> DesktopCapturer::CreateRawScreenCapturer(
|
||||
#endif // defined(WEBRTC_USE_PIPEWIRE)
|
||||
|
||||
#if defined(WEBRTC_USE_X11)
|
||||
- if (!DesktopCapturer::IsRunningUnderWayland())
|
||||
- return ScreenCapturerX11::CreateRawScreenCapturer(options);
|
||||
-#endif // defined(WEBRTC_USE_X11)
|
||||
-
|
||||
+ return ScreenCapturerX11::CreateRawScreenCapturer(options);
|
||||
+#else
|
||||
return nullptr;
|
||||
+#endif // defined(WEBRTC_USE_X11)
|
||||
}
|
||||
|
||||
} // namespace webrtc
|
||||
diff --git a/modules/desktop_capture/window_capturer_linux.cc b/modules/desktop_capture/window_capturer_linux.cc
|
||||
index 4205bf9bc0eede48cdc39353c77ceb6e7529fd51..785dc01a1911fd027401b1461223668333e05558 100644
|
||||
--- a/modules/desktop_capture/window_capturer_linux.cc
|
||||
+++ b/modules/desktop_capture/window_capturer_linux.cc
|
||||
@@ -34,11 +34,10 @@ std::unique_ptr<DesktopCapturer> DesktopCapturer::CreateRawWindowCapturer(
|
||||
#endif // defined(WEBRTC_USE_PIPEWIRE)
|
||||
|
||||
#if defined(WEBRTC_USE_X11)
|
||||
- if (!DesktopCapturer::IsRunningUnderWayland())
|
||||
- return WindowCapturerX11::CreateRawWindowCapturer(options);
|
||||
-#endif // defined(WEBRTC_USE_X11)
|
||||
-
|
||||
+ return WindowCapturerX11::CreateRawWindowCapturer(options);
|
||||
+#else
|
||||
return nullptr;
|
||||
+#endif // defined(WEBRTC_USE_X11)
|
||||
}
|
||||
|
||||
} // namespace webrtc
|
||||
@@ -30,10 +30,6 @@ def get_target_arch():
|
||||
return arch
|
||||
|
||||
|
||||
def get_env_var(name):
|
||||
return os.environ.get('ELECTRON_' + name, '')
|
||||
|
||||
|
||||
def enable_verbose_mode():
|
||||
print('Running in verbose mode')
|
||||
global verbose_mode
|
||||
|
||||
@@ -121,11 +121,6 @@ class TestsList():
|
||||
for binary in binaries])
|
||||
return suite_returncode
|
||||
|
||||
def run_only(self, binary_name, output_dir=None, verbosity=Verbosity.CHATTY,
|
||||
disabled_tests_policy=DisabledTestsPolicy.DISABLE):
|
||||
return self.run([binary_name], output_dir, verbosity,
|
||||
disabled_tests_policy)
|
||||
|
||||
def run_all(self, output_dir=None, verbosity=Verbosity.CHATTY,
|
||||
disabled_tests_policy=DisabledTestsPolicy.DISABLE):
|
||||
return self.run(self.get_for_current_platform(), output_dir, verbosity,
|
||||
|
||||
@@ -25,12 +25,9 @@ ELECTRON_DIR = os.path.abspath(
|
||||
TS_NODE = os.path.join(ELECTRON_DIR, 'node_modules', '.bin', 'ts-node')
|
||||
SRC_DIR = os.path.abspath(os.path.join(__file__, '..', '..', '..', '..'))
|
||||
|
||||
NPM = 'npm'
|
||||
if sys.platform in ['win32', 'cygwin']:
|
||||
NPM += '.cmd'
|
||||
TS_NODE += '.cmd'
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def scoped_cwd(path):
|
||||
cwd = os.getcwd()
|
||||
@@ -41,18 +38,6 @@ def scoped_cwd(path):
|
||||
os.chdir(cwd)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def scoped_env(key, value):
|
||||
origin = ''
|
||||
if key in os.environ:
|
||||
origin = os.environ[key]
|
||||
os.environ[key] = value
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
os.environ[key] = origin
|
||||
|
||||
|
||||
def download(text, url, path):
|
||||
safe_mkdir(os.path.dirname(path))
|
||||
with open(path, 'wb') as local_file:
|
||||
|
||||
@@ -22,10 +22,7 @@ process.env.PATH = `${process.env.PATH}${path.delimiter}${DEPOT_TOOLS}`;
|
||||
const IGNORELIST = new Set([
|
||||
['shell', 'browser', 'resources', 'win', 'resource.h'],
|
||||
['shell', 'common', 'node_includes.h'],
|
||||
['spec', 'fixtures', 'pages', 'jquery-3.6.0.min.js'],
|
||||
['spec', 'ts-smoke', 'electron', 'main.ts'],
|
||||
['spec', 'ts-smoke', 'electron', 'renderer.ts'],
|
||||
['spec', 'ts-smoke', 'runner.js']
|
||||
['spec', 'fixtures', 'pages', 'jquery-3.6.0.min.js']
|
||||
].map(tokens => path.join(ELECTRON_ROOT, ...tokens)));
|
||||
|
||||
const IS_WINDOWS = process.platform === 'win32';
|
||||
|
||||
@@ -134,9 +134,6 @@
|
||||
"parallel/test-webcrypto-export-import-cfrg",
|
||||
"parallel/test-webcrypto-keygen",
|
||||
"parallel/test-webcrypto-sign-verify-eddsa",
|
||||
"parallel/test-worker-debug",
|
||||
"parallel/test-worker-init-failure",
|
||||
"parallel/test-worker-stdio",
|
||||
"parallel/test-zlib-unused-weak",
|
||||
"report/test-report-fatalerror-oomerror-set",
|
||||
"report/test-report-fatalerror-oomerror-directory",
|
||||
|
||||
@@ -14,8 +14,8 @@ const ROLLER_BRANCH_PATTERN = /^roller\/chromium$/;
|
||||
|
||||
const DEFAULT_BUILD_CLOUD_ID = '1598';
|
||||
const DEFAULT_BUILD_CLOUD = 'electronhq-16-core';
|
||||
const DEFAULT_BAKE_BASE_IMAGE = 'e-110.0.5451.0';
|
||||
const DEFAULT_BUILD_IMAGE = 'e-110.0.5451.0';
|
||||
const DEFAULT_BAKE_BASE_IMAGE = 'e-111.0.5560.0-node18';
|
||||
const DEFAULT_BUILD_IMAGE = 'e-111.0.5560.0-node18';
|
||||
|
||||
const appveyorBakeJob = 'electron-bake-image';
|
||||
const appVeyorJobs = {
|
||||
|
||||
@@ -13,6 +13,7 @@ const fs = require('fs');
|
||||
const { execSync } = require('child_process');
|
||||
const got = require('got');
|
||||
const path = require('path');
|
||||
const semver = require('semver');
|
||||
const temp = require('temp').track();
|
||||
const { URL } = require('url');
|
||||
const { BlobServiceClient } = require('@azure/storage-blob');
|
||||
@@ -317,12 +318,23 @@ function saveShaSumFile (checksums, fileName) {
|
||||
}
|
||||
|
||||
async function publishRelease (release) {
|
||||
let makeLatest = false;
|
||||
if (!release.prerelease) {
|
||||
const currentLatest = await octokit.repos.getLatestRelease({
|
||||
owner: 'electron',
|
||||
repo: targetRepo
|
||||
});
|
||||
|
||||
makeLatest = semver.gte(release.tag_name, currentLatest.data.tag_name);
|
||||
}
|
||||
|
||||
return octokit.repos.updateRelease({
|
||||
owner: 'electron',
|
||||
repo: targetRepo,
|
||||
release_id: release.id,
|
||||
tag_name: release.tag_name,
|
||||
draft: false
|
||||
draft: false,
|
||||
make_latest: makeLatest ? 'true' : 'false'
|
||||
}).catch(err => {
|
||||
console.log(`${fail} Error publishing release:`, err);
|
||||
process.exit(1);
|
||||
|
||||
@@ -17,7 +17,8 @@ sys.path.append(
|
||||
|
||||
from zipfile import ZipFile
|
||||
from lib.config import PLATFORM, get_target_arch, \
|
||||
get_zip_name, enable_verbose_mode, get_platform_key
|
||||
get_zip_name, enable_verbose_mode, \
|
||||
is_verbose_mode, get_platform_key
|
||||
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
|
||||
@@ -383,7 +384,14 @@ def upload_sha256_checksum(version, file_path, key_prefix=None):
|
||||
def get_release(version):
|
||||
script_path = os.path.join(
|
||||
ELECTRON_DIR, 'script', 'release', 'find-github-release.js')
|
||||
release_info = execute(['node', script_path, version])
|
||||
|
||||
# Strip warnings from stdout to ensure the only output is the desired object
|
||||
release_env = os.environ.copy()
|
||||
release_env['NODE_NO_WARNINGS'] = '1'
|
||||
release_info = execute(['node', script_path, version], release_env)
|
||||
if is_verbose_mode():
|
||||
print('Release info for version: {}:\n'.format(version))
|
||||
print(release_info)
|
||||
release = json.loads(release_info)
|
||||
return release
|
||||
|
||||
|
||||
@@ -56,7 +56,8 @@ REM Install Windows SDK
|
||||
choco install windows-sdk-10-version-2104-all
|
||||
|
||||
REM Install nodejs python git and yarn needed dependencies
|
||||
choco install -y nodejs-lts python2 git yarn
|
||||
choco install -y --force nodejs --version=18.12.1
|
||||
choco install -y python2 git yarn
|
||||
choco install python --version 3.7.9
|
||||
call C:\ProgramData\chocolatey\bin\RefreshEnv.cmd
|
||||
SET PATH=C:\Python27\;C:\Python27\Scripts;C:\Python39\;C:\Python39\Scripts;%PATH%
|
||||
|
||||
@@ -260,37 +260,9 @@ int NodeMain(int argc, char* argv[]) {
|
||||
v8::HandleScope scope(isolate);
|
||||
node::LoadEnvironment(env, node::StartExecutionCallback{});
|
||||
|
||||
env->set_trace_sync_io(env->options()->trace_sync_io);
|
||||
|
||||
{
|
||||
v8::SealHandleScope seal(isolate);
|
||||
bool more;
|
||||
env->performance_state()->Mark(
|
||||
node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_START);
|
||||
do {
|
||||
uv_run(env->event_loop(), UV_RUN_DEFAULT);
|
||||
|
||||
gin_env.platform()->DrainTasks(isolate);
|
||||
|
||||
more = uv_loop_alive(env->event_loop());
|
||||
if (more && !env->is_stopping())
|
||||
continue;
|
||||
|
||||
if (!uv_loop_alive(env->event_loop())) {
|
||||
EmitBeforeExit(env);
|
||||
}
|
||||
|
||||
// Emit `beforeExit` if the loop became alive either after emitting
|
||||
// event, or after running some callbacks.
|
||||
more = uv_loop_alive(env->event_loop());
|
||||
} while (more && !env->is_stopping());
|
||||
env->performance_state()->Mark(
|
||||
node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_EXIT);
|
||||
}
|
||||
|
||||
env->set_trace_sync_io(false);
|
||||
|
||||
exit_code = node::EmitExit(env);
|
||||
// Potential reasons we get Nothing here may include: the env
|
||||
// is stopping, or the user hooks process.emit('exit').
|
||||
exit_code = node::SpinEventLoop(env).FromMaybe(1);
|
||||
|
||||
node::ResetStdio();
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
#include "shell/common/gin_converters/gfx_converter.h"
|
||||
#include "shell/common/gin_converters/image_converter.h"
|
||||
#include "shell/common/gin_converters/native_window_converter.h"
|
||||
#include "shell/common/gin_converters/optional_converter.h"
|
||||
#include "shell/common/gin_converters/value_converter.h"
|
||||
#include "shell/common/gin_helper/dictionary.h"
|
||||
#include "shell/common/gin_helper/object_template_builder.h"
|
||||
@@ -876,17 +877,12 @@ bool BaseWindow::GetWindowButtonVisibility() const {
|
||||
return window_->GetWindowButtonVisibility();
|
||||
}
|
||||
|
||||
void BaseWindow::SetTrafficLightPosition(const gfx::Point& position) {
|
||||
// For backward compatibility we treat (0, 0) as resetting to default.
|
||||
if (position.IsOrigin())
|
||||
window_->SetTrafficLightPosition(absl::nullopt);
|
||||
else
|
||||
window_->SetTrafficLightPosition(position);
|
||||
void BaseWindow::SetWindowButtonPosition(absl::optional<gfx::Point> position) {
|
||||
window_->SetWindowButtonPosition(std::move(position));
|
||||
}
|
||||
|
||||
gfx::Point BaseWindow::GetTrafficLightPosition() const {
|
||||
// For backward compatibility we treat default value as (0, 0).
|
||||
return window_->GetTrafficLightPosition().value_or(gfx::Point());
|
||||
absl::optional<gfx::Point> BaseWindow::GetWindowButtonPosition() const {
|
||||
return window_->GetWindowButtonPosition();
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -1271,12 +1267,6 @@ void BaseWindow::BuildPrototype(v8::Isolate* isolate,
|
||||
.SetMethod("setAutoHideCursor", &BaseWindow::SetAutoHideCursor)
|
||||
#endif
|
||||
.SetMethod("setVibrancy", &BaseWindow::SetVibrancy)
|
||||
#if BUILDFLAG(IS_MAC)
|
||||
.SetMethod("setTrafficLightPosition",
|
||||
&BaseWindow::SetTrafficLightPosition)
|
||||
.SetMethod("getTrafficLightPosition",
|
||||
&BaseWindow::GetTrafficLightPosition)
|
||||
#endif
|
||||
|
||||
#if BUILDFLAG(IS_MAC)
|
||||
.SetMethod("isHiddenInMissionControl",
|
||||
@@ -1299,6 +1289,10 @@ void BaseWindow::BuildPrototype(v8::Isolate* isolate,
|
||||
&BaseWindow::SetWindowButtonVisibility)
|
||||
.SetMethod("_getWindowButtonVisibility",
|
||||
&BaseWindow::GetWindowButtonVisibility)
|
||||
.SetMethod("setWindowButtonPosition",
|
||||
&BaseWindow::SetWindowButtonPosition)
|
||||
.SetMethod("getWindowButtonPosition",
|
||||
&BaseWindow::GetWindowButtonPosition)
|
||||
.SetProperty("excludedFromShownWindowsMenu",
|
||||
&BaseWindow::IsExcludedFromShownWindowsMenu,
|
||||
&BaseWindow::SetExcludedFromShownWindowsMenu)
|
||||
|
||||
@@ -195,8 +195,8 @@ class BaseWindow : public gin_helper::TrackableObject<BaseWindow>,
|
||||
std::string GetAlwaysOnTopLevel();
|
||||
void SetWindowButtonVisibility(bool visible);
|
||||
bool GetWindowButtonVisibility() const;
|
||||
void SetTrafficLightPosition(const gfx::Point& position);
|
||||
gfx::Point GetTrafficLightPosition() const;
|
||||
void SetWindowButtonPosition(absl::optional<gfx::Point> position);
|
||||
absl::optional<gfx::Point> GetWindowButtonPosition() const;
|
||||
#endif
|
||||
|
||||
#if BUILDFLAG(IS_MAC)
|
||||
|
||||
@@ -126,6 +126,9 @@ BrowserView::~BrowserView() {
|
||||
}
|
||||
|
||||
void BrowserView::WebContentsDestroyed() {
|
||||
if (owner_window())
|
||||
owner_window()->window()->RemoveDraggableRegionProvider(this);
|
||||
|
||||
api_web_contents_ = nullptr;
|
||||
web_contents_.Reset();
|
||||
Unpin();
|
||||
|
||||
@@ -198,7 +198,11 @@ void BrowserWindow::OnCloseButtonClicked(bool* prevent_default) {
|
||||
|
||||
// Trigger beforeunload events for associated BrowserViews.
|
||||
for (NativeBrowserView* view : window_->browser_views()) {
|
||||
auto* vwc = view->GetInspectableWebContents()->GetWebContents();
|
||||
auto* iwc = view->GetInspectableWebContents();
|
||||
if (!iwc)
|
||||
continue;
|
||||
|
||||
auto* vwc = iwc->GetWebContents();
|
||||
auto* api_web_contents = api::WebContents::From(vwc);
|
||||
|
||||
// Required to make beforeunload handler work.
|
||||
|
||||
@@ -128,10 +128,13 @@ bool MatchesCookie(const base::Value::Dict& filter,
|
||||
!MatchesDomain(*str, cookie.Domain()))
|
||||
return false;
|
||||
absl::optional<bool> secure_filter = filter.FindBool("secure");
|
||||
if (secure_filter && *secure_filter == cookie.IsSecure())
|
||||
if (secure_filter && *secure_filter != cookie.IsSecure())
|
||||
return false;
|
||||
absl::optional<bool> session_filter = filter.FindBool("session");
|
||||
if (session_filter && *session_filter != !cookie.IsPersistent())
|
||||
if (session_filter && *session_filter == cookie.IsPersistent())
|
||||
return false;
|
||||
absl::optional<bool> httpOnly_filter = filter.FindBool("httpOnly");
|
||||
if (httpOnly_filter && *httpOnly_filter != cookie.IsHttpOnly())
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -207,27 +207,31 @@ void DesktopCapturer::StartHandling(bool capture_window,
|
||||
// Initialize the source list.
|
||||
// Apply the new thumbnail size and restart capture.
|
||||
if (capture_window) {
|
||||
window_capturer_ = std::make_unique<NativeDesktopMediaList>(
|
||||
DesktopMediaList::Type::kWindow,
|
||||
content::desktop_capture::CreateWindowCapturer());
|
||||
window_capturer_->SetThumbnailSize(thumbnail_size);
|
||||
window_capturer_->Update(
|
||||
base::BindOnce(&DesktopCapturer::UpdateSourcesList,
|
||||
weak_ptr_factory_.GetWeakPtr(),
|
||||
window_capturer_.get()),
|
||||
/* refresh_thumbnails = */ true);
|
||||
if (auto capturer = content::desktop_capture::CreateWindowCapturer();
|
||||
capturer) {
|
||||
window_capturer_ = std::make_unique<NativeDesktopMediaList>(
|
||||
DesktopMediaList::Type::kWindow, std::move(capturer));
|
||||
window_capturer_->SetThumbnailSize(thumbnail_size);
|
||||
window_capturer_->Update(
|
||||
base::BindOnce(&DesktopCapturer::UpdateSourcesList,
|
||||
weak_ptr_factory_.GetWeakPtr(),
|
||||
window_capturer_.get()),
|
||||
/* refresh_thumbnails = */ true);
|
||||
}
|
||||
}
|
||||
|
||||
if (capture_screen) {
|
||||
screen_capturer_ = std::make_unique<NativeDesktopMediaList>(
|
||||
DesktopMediaList::Type::kScreen,
|
||||
content::desktop_capture::CreateScreenCapturer());
|
||||
screen_capturer_->SetThumbnailSize(thumbnail_size);
|
||||
screen_capturer_->Update(
|
||||
base::BindOnce(&DesktopCapturer::UpdateSourcesList,
|
||||
weak_ptr_factory_.GetWeakPtr(),
|
||||
screen_capturer_.get()),
|
||||
/* refresh_thumbnails = */ true);
|
||||
if (auto capturer = content::desktop_capture::CreateScreenCapturer();
|
||||
capturer) {
|
||||
screen_capturer_ = std::make_unique<NativeDesktopMediaList>(
|
||||
DesktopMediaList::Type::kScreen, std::move(capturer));
|
||||
screen_capturer_->SetThumbnailSize(thumbnail_size);
|
||||
screen_capturer_->Update(
|
||||
base::BindOnce(&DesktopCapturer::UpdateSourcesList,
|
||||
weak_ptr_factory_.GetWeakPtr(),
|
||||
screen_capturer_.get()),
|
||||
/* refresh_thumbnails = */ true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
// Copyright (c) 2018 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "shell/browser/api/event.h"
|
||||
#include "shell/common/gin_helper/dictionary.h"
|
||||
#include "shell/common/gin_helper/event_emitter.h"
|
||||
#include "shell/common/node_includes.h"
|
||||
|
||||
namespace {
|
||||
|
||||
v8::Local<v8::Object> CreateWithSender(v8::Isolate* isolate,
|
||||
v8::Local<v8::Object> sender) {
|
||||
return gin_helper::internal::CreateCustomEvent(isolate, sender);
|
||||
}
|
||||
|
||||
void Initialize(v8::Local<v8::Object> exports,
|
||||
v8::Local<v8::Value> unused,
|
||||
v8::Local<v8::Context> context,
|
||||
void* priv) {
|
||||
gin_helper::Dictionary dict(context->GetIsolate(), exports);
|
||||
dict.SetMethod("createWithSender", &CreateWithSender);
|
||||
dict.SetMethod("createEmpty", &gin_helper::Event::Create);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_event, Initialize)
|
||||
@@ -1178,8 +1178,7 @@ gin::Handle<Session> Session::CreateFrom(
|
||||
// to use partition strings, instead of using the Session object directly.
|
||||
handle->Pin(isolate);
|
||||
|
||||
App::Get()->EmitCustomEvent("session-created",
|
||||
handle.ToV8().As<v8::Object>());
|
||||
App::Get()->EmitWithoutEvent("session-created", handle);
|
||||
|
||||
return handle;
|
||||
}
|
||||
@@ -1204,10 +1203,16 @@ gin::Handle<Session> Session::FromPartition(v8::Isolate* isolate,
|
||||
return CreateFrom(isolate, browser_context);
|
||||
}
|
||||
|
||||
gin::ObjectTemplateBuilder Session::GetObjectTemplateBuilder(
|
||||
v8::Isolate* isolate) {
|
||||
return gin_helper::EventEmitterMixin<Session>::GetObjectTemplateBuilder(
|
||||
isolate)
|
||||
// static
|
||||
gin::Handle<Session> Session::New() {
|
||||
gin_helper::ErrorThrower(JavascriptEnvironment::GetIsolate())
|
||||
.ThrowError("Session objects cannot be created with 'new'");
|
||||
return gin::Handle<Session>();
|
||||
}
|
||||
|
||||
void Session::FillObjectTemplate(v8::Isolate* isolate,
|
||||
v8::Local<v8::ObjectTemplate> templ) {
|
||||
gin::ObjectTemplateBuilder(isolate, "Session", templ)
|
||||
.SetMethod("resolveProxy", &Session::ResolveProxy)
|
||||
.SetMethod("getCacheSize", &Session::GetCacheSize)
|
||||
.SetMethod("clearCache", &Session::ClearCache)
|
||||
@@ -1277,7 +1282,8 @@ gin::ObjectTemplateBuilder Session::GetObjectTemplateBuilder(
|
||||
.SetProperty("protocol", &Session::Protocol)
|
||||
.SetProperty("serviceWorkers", &Session::ServiceWorkerContext)
|
||||
.SetProperty("webRequest", &Session::WebRequest)
|
||||
.SetProperty("storagePath", &Session::GetPath);
|
||||
.SetProperty("storagePath", &Session::GetPath)
|
||||
.Build();
|
||||
}
|
||||
|
||||
const char* Session::GetTypeName() {
|
||||
@@ -1308,6 +1314,7 @@ void Initialize(v8::Local<v8::Object> exports,
|
||||
void* priv) {
|
||||
v8::Isolate* isolate = context->GetIsolate();
|
||||
gin_helper::Dictionary dict(isolate, exports);
|
||||
dict.Set("Session", Session::GetConstructor(context));
|
||||
dict.SetMethod("fromPartition", &FromPartition);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
#include "shell/browser/event_emitter_mixin.h"
|
||||
#include "shell/browser/net/resolve_proxy_helper.h"
|
||||
#include "shell/common/gin_helper/cleaned_up_at_exit.h"
|
||||
#include "shell/common/gin_helper/constructible.h"
|
||||
#include "shell/common/gin_helper/error_thrower.h"
|
||||
#include "shell/common/gin_helper/function_template_extensions.h"
|
||||
#include "shell/common/gin_helper/pinnable.h"
|
||||
@@ -57,6 +58,7 @@ namespace api {
|
||||
|
||||
class Session : public gin::Wrappable<Session>,
|
||||
public gin_helper::Pinnable<Session>,
|
||||
public gin_helper::Constructible<Session>,
|
||||
public gin_helper::EventEmitterMixin<Session>,
|
||||
public gin_helper::CleanedUpAtExit,
|
||||
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
|
||||
@@ -71,6 +73,7 @@ class Session : public gin::Wrappable<Session>,
|
||||
static gin::Handle<Session> CreateFrom(
|
||||
v8::Isolate* isolate,
|
||||
ElectronBrowserContext* browser_context);
|
||||
static gin::Handle<Session> New(); // Dummy, do not use!
|
||||
|
||||
static Session* FromBrowserContext(content::BrowserContext* context);
|
||||
|
||||
@@ -83,8 +86,7 @@ class Session : public gin::Wrappable<Session>,
|
||||
|
||||
// gin::Wrappable
|
||||
static gin::WrapperInfo kWrapperInfo;
|
||||
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
|
||||
v8::Isolate* isolate) override;
|
||||
static void FillObjectTemplate(v8::Isolate*, v8::Local<v8::ObjectTemplate>);
|
||||
const char* GetTypeName() override;
|
||||
|
||||
// Methods.
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
#include "net/base/mac/url_conversions.h"
|
||||
#include "shell/browser/mac/dict_util.h"
|
||||
#include "shell/browser/mac/electron_application.h"
|
||||
#include "shell/browser/ui/cocoa/NSColor+Hex.h"
|
||||
#include "shell/common/color_util.h"
|
||||
#include "shell/common/gin_converters/gurl_converter.h"
|
||||
#include "shell/common/gin_converters/value_converter.h"
|
||||
|
||||
@@ -97,19 +97,19 @@ void Tray::OnClicked(const gfx::Rect& bounds,
|
||||
int modifiers) {
|
||||
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
|
||||
v8::HandleScope scope(isolate);
|
||||
EmitCustomEvent("click", CreateEventFromFlags(modifiers), bounds, location);
|
||||
EmitWithoutEvent("click", CreateEventFromFlags(modifiers), bounds, location);
|
||||
}
|
||||
|
||||
void Tray::OnDoubleClicked(const gfx::Rect& bounds, int modifiers) {
|
||||
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
|
||||
v8::HandleScope scope(isolate);
|
||||
EmitCustomEvent("double-click", CreateEventFromFlags(modifiers), bounds);
|
||||
EmitWithoutEvent("double-click", CreateEventFromFlags(modifiers), bounds);
|
||||
}
|
||||
|
||||
void Tray::OnRightClicked(const gfx::Rect& bounds, int modifiers) {
|
||||
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
|
||||
v8::HandleScope scope(isolate);
|
||||
EmitCustomEvent("right-click", CreateEventFromFlags(modifiers), bounds);
|
||||
EmitWithoutEvent("right-click", CreateEventFromFlags(modifiers), bounds);
|
||||
}
|
||||
|
||||
void Tray::OnBalloonShow() {
|
||||
@@ -139,31 +139,31 @@ void Tray::OnDropText(const std::string& text) {
|
||||
void Tray::OnMouseEntered(const gfx::Point& location, int modifiers) {
|
||||
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
|
||||
v8::HandleScope scope(isolate);
|
||||
EmitCustomEvent("mouse-enter", CreateEventFromFlags(modifiers), location);
|
||||
EmitWithoutEvent("mouse-enter", CreateEventFromFlags(modifiers), location);
|
||||
}
|
||||
|
||||
void Tray::OnMouseExited(const gfx::Point& location, int modifiers) {
|
||||
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
|
||||
v8::HandleScope scope(isolate);
|
||||
EmitCustomEvent("mouse-leave", CreateEventFromFlags(modifiers), location);
|
||||
EmitWithoutEvent("mouse-leave", CreateEventFromFlags(modifiers), location);
|
||||
}
|
||||
|
||||
void Tray::OnMouseMoved(const gfx::Point& location, int modifiers) {
|
||||
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
|
||||
v8::HandleScope scope(isolate);
|
||||
EmitCustomEvent("mouse-move", CreateEventFromFlags(modifiers), location);
|
||||
EmitWithoutEvent("mouse-move", CreateEventFromFlags(modifiers), location);
|
||||
}
|
||||
|
||||
void Tray::OnMouseUp(const gfx::Point& location, int modifiers) {
|
||||
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
|
||||
v8::HandleScope scope(isolate);
|
||||
EmitCustomEvent("mouse-up", CreateEventFromFlags(modifiers), location);
|
||||
EmitWithoutEvent("mouse-up", CreateEventFromFlags(modifiers), location);
|
||||
}
|
||||
|
||||
void Tray::OnMouseDown(const gfx::Point& location, int modifiers) {
|
||||
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
|
||||
v8::HandleScope scope(isolate);
|
||||
EmitCustomEvent("mouse-down", CreateEventFromFlags(modifiers), location);
|
||||
EmitWithoutEvent("mouse-down", CreateEventFromFlags(modifiers), location);
|
||||
}
|
||||
|
||||
void Tray::OnDragEntered() {
|
||||
|
||||
@@ -18,20 +18,27 @@
|
||||
#include "mojo/public/cpp/system/data_pipe_producer.h"
|
||||
#include "net/base/load_flags.h"
|
||||
#include "net/http/http_util.h"
|
||||
#include "net/url_request/redirect_util.h"
|
||||
#include "services/network/public/cpp/resource_request.h"
|
||||
#include "services/network/public/cpp/simple_url_loader.h"
|
||||
#include "services/network/public/cpp/url_util.h"
|
||||
#include "services/network/public/cpp/wrapper_shared_url_loader_factory.h"
|
||||
#include "services/network/public/mojom/chunked_data_pipe_getter.mojom.h"
|
||||
#include "services/network/public/mojom/http_raw_headers.mojom.h"
|
||||
#include "services/network/public/mojom/url_loader_factory.mojom.h"
|
||||
#include "shell/browser/api/electron_api_session.h"
|
||||
#include "shell/browser/electron_browser_context.h"
|
||||
#include "shell/browser/javascript_environment.h"
|
||||
#include "shell/browser/net/asar/asar_url_loader_factory.h"
|
||||
#include "shell/browser/protocol_registry.h"
|
||||
#include "shell/common/gin_converters/callback_converter.h"
|
||||
#include "shell/common/gin_converters/gurl_converter.h"
|
||||
#include "shell/common/gin_converters/net_converter.h"
|
||||
#include "shell/common/gin_helper/dictionary.h"
|
||||
#include "shell/common/gin_helper/object_template_builder.h"
|
||||
#include "shell/common/node_includes.h"
|
||||
#include "third_party/blink/public/common/loader/referrer_utils.h"
|
||||
#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom.h"
|
||||
|
||||
namespace gin {
|
||||
|
||||
@@ -59,15 +66,84 @@ struct Converter<network::mojom::CredentialsMode> {
|
||||
*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
|
||||
// "same-origin" is technically a member of this enum as well, but it
|
||||
// doesn't make sense in the context of `net.request()`, so don't convert
|
||||
// it.
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace gin
|
||||
|
||||
namespace electron::api {
|
||||
@@ -265,34 +341,49 @@ gin::WrapperInfo SimpleURLLoaderWrapper::kWrapperInfo = {
|
||||
gin::kEmbedderNativeGin};
|
||||
|
||||
SimpleURLLoaderWrapper::SimpleURLLoaderWrapper(
|
||||
ElectronBrowserContext* browser_context,
|
||||
std::unique_ptr<network::ResourceRequest> request,
|
||||
network::mojom::URLLoaderFactory* url_loader_factory,
|
||||
int options) {
|
||||
if (!request->trusted_params)
|
||||
request->trusted_params = network::ResourceRequest::TrustedParams();
|
||||
int options)
|
||||
: browser_context_(browser_context),
|
||||
request_options_(options),
|
||||
request_(std::move(request)) {
|
||||
if (!request_->trusted_params)
|
||||
request_->trusted_params = network::ResourceRequest::TrustedParams();
|
||||
mojo::PendingRemote<network::mojom::URLLoaderNetworkServiceObserver>
|
||||
url_loader_network_observer_remote;
|
||||
url_loader_network_observer_receivers_.Add(
|
||||
this,
|
||||
url_loader_network_observer_remote.InitWithNewPipeAndPassReceiver());
|
||||
request->trusted_params->url_loader_network_observer =
|
||||
request_->trusted_params->url_loader_network_observer =
|
||||
std::move(url_loader_network_observer_remote);
|
||||
// Chromium filters headers using browser rules, while for net module we have
|
||||
// every header passed. The following setting will allow us to capture the
|
||||
// raw headers in the URLLoader.
|
||||
request->trusted_params->report_raw_headers = true;
|
||||
// SimpleURLLoader wants to control the request body itself. We have other
|
||||
// ideas.
|
||||
auto request_body = std::move(request->request_body);
|
||||
auto* request_ref = request.get();
|
||||
request_->trusted_params->report_raw_headers = true;
|
||||
Start();
|
||||
}
|
||||
|
||||
void SimpleURLLoaderWrapper::Start() {
|
||||
// Make a copy of the request; we'll need to re-send it if we get redirected.
|
||||
auto request = std::make_unique<network::ResourceRequest>();
|
||||
*request = *request_;
|
||||
|
||||
// SimpleURLLoader has no way to set a data pipe as the request body, which
|
||||
// we need to do for streaming upload, so instead we "cheat" and pretend to
|
||||
// SimpleURLLoader like there is no request_body when we construct it. Later,
|
||||
// we will sneakily put the request_body back while it isn't looking.
|
||||
scoped_refptr<network::ResourceRequestBody> request_body =
|
||||
std::move(request->request_body);
|
||||
|
||||
network::ResourceRequest* request_ref = request.get();
|
||||
loader_ =
|
||||
network::SimpleURLLoader::Create(std::move(request), kTrafficAnnotation);
|
||||
if (request_body) {
|
||||
|
||||
if (request_body)
|
||||
request_ref->request_body = std::move(request_body);
|
||||
}
|
||||
|
||||
loader_->SetAllowHttpErrorResults(true);
|
||||
loader_->SetURLLoaderFactoryOptions(options);
|
||||
loader_->SetURLLoaderFactoryOptions(request_options_);
|
||||
loader_->SetOnResponseStartedCallback(base::BindOnce(
|
||||
&SimpleURLLoaderWrapper::OnResponseStarted, base::Unretained(this)));
|
||||
loader_->SetOnRedirectCallback(base::BindRepeating(
|
||||
@@ -302,7 +393,8 @@ SimpleURLLoaderWrapper::SimpleURLLoaderWrapper(
|
||||
loader_->SetOnDownloadProgressCallback(base::BindRepeating(
|
||||
&SimpleURLLoaderWrapper::OnDownloadProgress, base::Unretained(this)));
|
||||
|
||||
loader_->DownloadAsStream(url_loader_factory, this);
|
||||
url_loader_factory_ = GetURLLoaderFactoryForURL(request_ref->url);
|
||||
loader_->DownloadAsStream(url_loader_factory_.get(), this);
|
||||
}
|
||||
|
||||
void SimpleURLLoaderWrapper::Pin() {
|
||||
@@ -387,6 +479,42 @@ void SimpleURLLoaderWrapper::Cancel() {
|
||||
// This ensures that no further callbacks will be called, so there's no need
|
||||
// for additional guards.
|
||||
}
|
||||
scoped_refptr<network::SharedURLLoaderFactory>
|
||||
SimpleURLLoaderWrapper::GetURLLoaderFactoryForURL(const GURL& url) {
|
||||
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory;
|
||||
auto* protocol_registry =
|
||||
ProtocolRegistry::FromBrowserContext(browser_context_);
|
||||
// Explicitly handle intercepted protocols here, even though
|
||||
// ProxyingURLLoaderFactory would handle them later on, so that we can
|
||||
// correctly intercept file:// scheme URLs.
|
||||
if (protocol_registry->IsProtocolIntercepted(url.scheme())) {
|
||||
auto& protocol_handler =
|
||||
protocol_registry->intercept_handlers().at(url.scheme());
|
||||
mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote =
|
||||
ElectronURLLoaderFactory::Create(protocol_handler.first,
|
||||
protocol_handler.second);
|
||||
url_loader_factory = network::SharedURLLoaderFactory::Create(
|
||||
std::make_unique<network::WrapperPendingSharedURLLoaderFactory>(
|
||||
std::move(pending_remote)));
|
||||
} else if (protocol_registry->IsProtocolRegistered(url.scheme())) {
|
||||
auto& protocol_handler = protocol_registry->handlers().at(url.scheme());
|
||||
mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote =
|
||||
ElectronURLLoaderFactory::Create(protocol_handler.first,
|
||||
protocol_handler.second);
|
||||
url_loader_factory = network::SharedURLLoaderFactory::Create(
|
||||
std::make_unique<network::WrapperPendingSharedURLLoaderFactory>(
|
||||
std::move(pending_remote)));
|
||||
} else if (url.SchemeIsFile()) {
|
||||
mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote =
|
||||
AsarURLLoaderFactory::Create();
|
||||
url_loader_factory = network::SharedURLLoaderFactory::Create(
|
||||
std::make_unique<network::WrapperPendingSharedURLLoaderFactory>(
|
||||
std::move(pending_remote)));
|
||||
} else {
|
||||
url_loader_factory = browser_context_->GetURLLoaderFactory();
|
||||
}
|
||||
return url_loader_factory;
|
||||
}
|
||||
|
||||
// static
|
||||
gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
|
||||
@@ -401,6 +529,9 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
|
||||
opts.Get("url", &request->url);
|
||||
request->site_for_cookies = net::SiteForCookies::FromUrl(request->url);
|
||||
opts.Get("referrer", &request->referrer);
|
||||
request->referrer_policy =
|
||||
blink::ReferrerUtils::GetDefaultNetReferrerPolicy();
|
||||
opts.Get("referrerPolicy", &request->referrer_policy);
|
||||
std::string origin;
|
||||
opts.Get("origin", &origin);
|
||||
if (!origin.empty()) {
|
||||
@@ -484,6 +615,36 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
|
||||
}
|
||||
}
|
||||
|
||||
blink::mojom::FetchCacheMode cache_mode =
|
||||
blink::mojom::FetchCacheMode::kDefault;
|
||||
opts.Get("cache", &cache_mode);
|
||||
switch (cache_mode) {
|
||||
case blink::mojom::FetchCacheMode::kNoStore:
|
||||
request->load_flags |= net::LOAD_DISABLE_CACHE;
|
||||
break;
|
||||
case blink::mojom::FetchCacheMode::kValidateCache:
|
||||
request->load_flags |= net::LOAD_VALIDATE_CACHE;
|
||||
break;
|
||||
case blink::mojom::FetchCacheMode::kBypassCache:
|
||||
request->load_flags |= net::LOAD_BYPASS_CACHE;
|
||||
break;
|
||||
case blink::mojom::FetchCacheMode::kForceCache:
|
||||
request->load_flags |= net::LOAD_SKIP_CACHE_VALIDATION;
|
||||
break;
|
||||
case blink::mojom::FetchCacheMode::kOnlyIfCached:
|
||||
request->load_flags |=
|
||||
net::LOAD_ONLY_FROM_CACHE | net::LOAD_SKIP_CACHE_VALIDATION;
|
||||
break;
|
||||
case blink::mojom::FetchCacheMode::kUnspecifiedOnlyIfCachedStrict:
|
||||
request->load_flags |= net::LOAD_ONLY_FROM_CACHE;
|
||||
break;
|
||||
case blink::mojom::FetchCacheMode::kDefault:
|
||||
break;
|
||||
case blink::mojom::FetchCacheMode::kUnspecifiedForceCacheMiss:
|
||||
request->load_flags |= net::LOAD_ONLY_FROM_CACHE | net::LOAD_BYPASS_CACHE;
|
||||
break;
|
||||
}
|
||||
|
||||
bool use_session_cookies = false;
|
||||
opts.Get("useSessionCookies", &use_session_cookies);
|
||||
int options = 0;
|
||||
@@ -530,12 +691,9 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
|
||||
session = Session::FromPartition(args->isolate(), "");
|
||||
}
|
||||
|
||||
auto url_loader_factory = session->browser_context()->GetURLLoaderFactory();
|
||||
|
||||
auto ret = gin::CreateHandle(
|
||||
args->isolate(),
|
||||
new SimpleURLLoaderWrapper(std::move(request), url_loader_factory.get(),
|
||||
options));
|
||||
args->isolate(), new SimpleURLLoaderWrapper(session->browser_context(),
|
||||
std::move(request), options));
|
||||
ret->Pin();
|
||||
if (!chunk_pipe_getter.IsEmpty()) {
|
||||
ret->PinBodyGetter(chunk_pipe_getter);
|
||||
@@ -587,6 +745,45 @@ void SimpleURLLoaderWrapper::OnRedirect(
|
||||
const network::mojom::URLResponseHead& response_head,
|
||||
std::vector<std::string>* removed_headers) {
|
||||
Emit("redirect", redirect_info, response_head.headers.get());
|
||||
|
||||
if (!loader_)
|
||||
// The redirect was aborted by JS.
|
||||
return;
|
||||
|
||||
// Optimization: if both the old and new URLs are handled by the network
|
||||
// service, just FollowRedirect.
|
||||
if (network::IsURLHandledByNetworkService(redirect_info.new_url) &&
|
||||
network::IsURLHandledByNetworkService(request_->url))
|
||||
return;
|
||||
|
||||
// Otherwise, restart the request (potentially picking a new
|
||||
// URLLoaderFactory). See
|
||||
// https://source.chromium.org/chromium/chromium/src/+/main:content/browser/loader/navigation_url_loader_impl.cc;l=534-550;drc=fbaec92ad5982f83aa4544d5c88d66d08034a9f4
|
||||
|
||||
bool should_clear_upload = false;
|
||||
net::RedirectUtil::UpdateHttpRequest(
|
||||
request_->url, request_->method, redirect_info, *removed_headers,
|
||||
/* modified_headers = */ absl::nullopt, &request_->headers,
|
||||
&should_clear_upload);
|
||||
if (should_clear_upload) {
|
||||
// The request body is no longer applicable.
|
||||
request_->request_body.reset();
|
||||
}
|
||||
|
||||
request_->url = redirect_info.new_url;
|
||||
request_->method = redirect_info.new_method;
|
||||
request_->site_for_cookies = redirect_info.new_site_for_cookies;
|
||||
|
||||
// See if navigation network isolation key needs to be updated.
|
||||
request_->trusted_params->isolation_info =
|
||||
request_->trusted_params->isolation_info.CreateForRedirect(
|
||||
url::Origin::Create(request_->url));
|
||||
|
||||
request_->referrer = GURL(redirect_info.new_referrer);
|
||||
request_->referrer_policy = redirect_info.new_referrer_policy;
|
||||
request_->navigation_redirect_chain.push_back(redirect_info.new_url);
|
||||
|
||||
Start();
|
||||
}
|
||||
|
||||
void SimpleURLLoaderWrapper::OnUploadProgress(uint64_t position,
|
||||
|
||||
@@ -31,8 +31,13 @@ class Handle;
|
||||
namespace network {
|
||||
class SimpleURLLoader;
|
||||
struct ResourceRequest;
|
||||
class SharedURLLoaderFactory;
|
||||
} // namespace network
|
||||
|
||||
namespace electron {
|
||||
class ElectronBrowserContext;
|
||||
}
|
||||
|
||||
namespace electron::api {
|
||||
|
||||
/** Wraps a SimpleURLLoader to make it usable from JavaScript */
|
||||
@@ -54,8 +59,8 @@ class SimpleURLLoaderWrapper
|
||||
const char* GetTypeName() override;
|
||||
|
||||
private:
|
||||
SimpleURLLoaderWrapper(std::unique_ptr<network::ResourceRequest> request,
|
||||
network::mojom::URLLoaderFactory* url_loader_factory,
|
||||
SimpleURLLoaderWrapper(ElectronBrowserContext* browser_context,
|
||||
std::unique_ptr<network::ResourceRequest> request,
|
||||
int options);
|
||||
|
||||
// SimpleURLLoaderStreamConsumer:
|
||||
@@ -99,6 +104,9 @@ class SimpleURLLoaderWrapper
|
||||
mojo::PendingReceiver<network::mojom::URLLoaderNetworkServiceObserver>
|
||||
observer) override;
|
||||
|
||||
scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactoryForURL(
|
||||
const GURL& url);
|
||||
|
||||
// SimpleURLLoader callbacks
|
||||
void OnResponseStarted(const GURL& final_url,
|
||||
const network::mojom::URLResponseHead& response_head);
|
||||
@@ -112,6 +120,10 @@ class SimpleURLLoaderWrapper
|
||||
void Pin();
|
||||
void PinBodyGetter(v8::Local<v8::Value>);
|
||||
|
||||
ElectronBrowserContext* browser_context_;
|
||||
int request_options_;
|
||||
std::unique_ptr<network::ResourceRequest> request_;
|
||||
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
|
||||
std::unique_ptr<network::SimpleURLLoader> loader_;
|
||||
v8::Global<v8::Value> pinned_wrapper_;
|
||||
v8::Global<v8::Value> pinned_chunk_pipe_getter_;
|
||||
|
||||
@@ -203,13 +203,13 @@ void UtilityProcessWrapper::OnServiceProcessLaunched(
|
||||
pid_ = process.Pid();
|
||||
GetAllUtilityProcessWrappers().AddWithID(this, pid_);
|
||||
if (stdout_read_fd_ != -1) {
|
||||
EmitWithoutCustomEvent("stdout", stdout_read_fd_);
|
||||
EmitWithoutEvent("stdout", stdout_read_fd_);
|
||||
}
|
||||
if (stderr_read_fd_ != -1) {
|
||||
EmitWithoutCustomEvent("stderr", stderr_read_fd_);
|
||||
EmitWithoutEvent("stderr", stderr_read_fd_);
|
||||
}
|
||||
// Emit 'spawn' event
|
||||
EmitWithoutCustomEvent("spawn");
|
||||
EmitWithoutEvent("spawn");
|
||||
}
|
||||
|
||||
void UtilityProcessWrapper::OnServiceProcessDisconnected(
|
||||
@@ -219,7 +219,7 @@ void UtilityProcessWrapper::OnServiceProcessDisconnected(
|
||||
GetAllUtilityProcessWrappers().Remove(pid_);
|
||||
CloseConnectorPort();
|
||||
// Emit 'exit' event
|
||||
EmitWithoutCustomEvent("exit", error_code);
|
||||
EmitWithoutEvent("exit", error_code);
|
||||
Unpin();
|
||||
}
|
||||
|
||||
@@ -238,7 +238,7 @@ void UtilityProcessWrapper::Shutdown(int exit_code) {
|
||||
node_service_remote_.reset();
|
||||
CloseConnectorPort();
|
||||
// Emit 'exit' event
|
||||
EmitWithoutCustomEvent("exit", exit_code);
|
||||
EmitWithoutEvent("exit", exit_code);
|
||||
Unpin();
|
||||
}
|
||||
|
||||
@@ -311,7 +311,7 @@ bool UtilityProcessWrapper::Accept(mojo::Message* mojo_message) {
|
||||
v8::HandleScope handle_scope(isolate);
|
||||
v8::Local<v8::Value> message_value =
|
||||
electron::DeserializeV8Value(isolate, message);
|
||||
EmitWithoutCustomEvent("message", message_value);
|
||||
EmitWithoutEvent("message", message_value);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -112,6 +112,7 @@
|
||||
#include "shell/common/gin_converters/gurl_converter.h"
|
||||
#include "shell/common/gin_converters/image_converter.h"
|
||||
#include "shell/common/gin_converters/net_converter.h"
|
||||
#include "shell/common/gin_converters/optional_converter.h"
|
||||
#include "shell/common/gin_converters/value_converter.h"
|
||||
#include "shell/common/gin_helper/dictionary.h"
|
||||
#include "shell/common/gin_helper/object_template_builder.h"
|
||||
@@ -1305,7 +1306,10 @@ Profile* WebContents::GetProfile() {
|
||||
}
|
||||
|
||||
bool WebContents::IsFullscreen() const {
|
||||
return owner_window_ && owner_window_->IsFullscreen();
|
||||
if (!owner_window())
|
||||
return false;
|
||||
|
||||
return owner_window()->IsFullscreen() || is_html_fullscreen();
|
||||
}
|
||||
|
||||
void WebContents::EnterFullscreen(const GURL& url,
|
||||
@@ -1351,7 +1355,7 @@ void WebContents::OnEnterFullscreenModeForTab(
|
||||
content::RenderFrameHost* requesting_frame,
|
||||
const blink::mojom::FullscreenOptions& options,
|
||||
bool allowed) {
|
||||
if (!allowed || !owner_window_)
|
||||
if (!allowed || !owner_window())
|
||||
return;
|
||||
|
||||
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
|
||||
@@ -1375,7 +1379,7 @@ void WebContents::OnEnterFullscreenModeForTab(
|
||||
}
|
||||
|
||||
void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
|
||||
if (!owner_window_)
|
||||
if (!owner_window())
|
||||
return;
|
||||
|
||||
// This needs to be called before we exit fullscreen on the native window,
|
||||
@@ -1503,7 +1507,14 @@ content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
|
||||
}
|
||||
|
||||
void WebContents::OnAudioStateChanged(bool audible) {
|
||||
Emit("-audio-state-changed", audible);
|
||||
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
|
||||
v8::HandleScope handle_scope(isolate);
|
||||
gin::Handle<gin_helper::internal::Event> event =
|
||||
gin_helper::internal::Event::New(isolate);
|
||||
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
|
||||
gin::Dictionary dict(isolate, event_object);
|
||||
dict.Set("audible", audible);
|
||||
EmitWithoutEvent("audio-state-changed", event);
|
||||
}
|
||||
|
||||
void WebContents::BeforeUnloadFired(bool proceed,
|
||||
@@ -1616,8 +1627,7 @@ void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host,
|
||||
//
|
||||
// |old_host| can be a nullptr so we use |new_host| for looking up the
|
||||
// WebFrameMain instance.
|
||||
auto* web_frame =
|
||||
WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId());
|
||||
auto* web_frame = WebFrameMain::FromRenderFrameHost(new_host);
|
||||
if (web_frame) {
|
||||
web_frame->UpdateRenderFrameHost(new_host);
|
||||
}
|
||||
@@ -1756,7 +1766,7 @@ void WebContents::DidStopLoading() {
|
||||
}
|
||||
|
||||
bool WebContents::EmitNavigationEvent(
|
||||
const std::string& event,
|
||||
const std::string& event_name,
|
||||
content::NavigationHandle* navigation_handle) {
|
||||
bool is_main_frame = navigation_handle->IsInMainFrame();
|
||||
int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId();
|
||||
@@ -1777,8 +1787,30 @@ bool WebContents::EmitNavigationEvent(
|
||||
}
|
||||
bool is_same_document = navigation_handle->IsSameDocument();
|
||||
auto url = navigation_handle->GetURL();
|
||||
return Emit(event, url, is_same_document, is_main_frame, frame_process_id,
|
||||
frame_routing_id);
|
||||
content::RenderFrameHost* initiator_frame_host =
|
||||
navigation_handle->GetInitiatorFrameToken().has_value()
|
||||
? content::RenderFrameHost::FromFrameToken(
|
||||
navigation_handle->GetInitiatorProcessID(),
|
||||
navigation_handle->GetInitiatorFrameToken().value())
|
||||
: nullptr;
|
||||
|
||||
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
|
||||
v8::HandleScope handle_scope(isolate);
|
||||
|
||||
gin::Handle<gin_helper::internal::Event> event =
|
||||
gin_helper::internal::Event::New(isolate);
|
||||
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
|
||||
|
||||
gin_helper::Dictionary dict(isolate, event_object);
|
||||
dict.Set("url", url);
|
||||
dict.Set("isSameDocument", is_same_document);
|
||||
dict.Set("isMainFrame", is_main_frame);
|
||||
dict.Set("frame", frame_host);
|
||||
dict.SetGetter("initiator", initiator_frame_host);
|
||||
|
||||
EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame,
|
||||
frame_process_id, frame_routing_id);
|
||||
return event->GetDefaultPrevented();
|
||||
}
|
||||
|
||||
void WebContents::Message(bool internal,
|
||||
@@ -1812,6 +1844,88 @@ void WebContents::OnFirstNonEmptyLayout(
|
||||
}
|
||||
}
|
||||
|
||||
// This object wraps the InvokeCallback so that if it gets GC'd by V8, we can
|
||||
// still call the callback and send an error. Not doing so causes a Mojo DCHECK,
|
||||
// since Mojo requires callbacks to be called before they are destroyed.
|
||||
class ReplyChannel : public gin::Wrappable<ReplyChannel> {
|
||||
public:
|
||||
using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback;
|
||||
static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate,
|
||||
InvokeCallback callback) {
|
||||
return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback)));
|
||||
}
|
||||
|
||||
// gin::Wrappable
|
||||
static gin::WrapperInfo kWrapperInfo;
|
||||
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
|
||||
v8::Isolate* isolate) override {
|
||||
return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate)
|
||||
.SetMethod("sendReply", &ReplyChannel::SendReply);
|
||||
}
|
||||
const char* GetTypeName() override { return "ReplyChannel"; }
|
||||
|
||||
void SendError(const std::string& msg) {
|
||||
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
|
||||
// If there's no current context, it means we're shutting down, so we
|
||||
// don't need to send an event.
|
||||
if (!isolate->GetCurrentContext().IsEmpty()) {
|
||||
v8::HandleScope scope(isolate);
|
||||
auto message = gin::DataObjectBuilder(isolate).Set("error", msg).Build();
|
||||
SendReply(isolate, message);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
explicit ReplyChannel(InvokeCallback callback)
|
||||
: callback_(std::move(callback)) {}
|
||||
~ReplyChannel() override {
|
||||
if (callback_)
|
||||
SendError("reply was never sent");
|
||||
}
|
||||
|
||||
bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) {
|
||||
if (!callback_)
|
||||
return false;
|
||||
blink::CloneableMessage message;
|
||||
if (!gin::ConvertFromV8(isolate, arg, &message)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::move(callback_).Run(std::move(message));
|
||||
return true;
|
||||
}
|
||||
|
||||
InvokeCallback callback_;
|
||||
};
|
||||
|
||||
gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin};
|
||||
|
||||
gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender(
|
||||
v8::Isolate* isolate,
|
||||
content::RenderFrameHost* frame,
|
||||
electron::mojom::ElectronApiIPC::InvokeCallback callback) {
|
||||
v8::Local<v8::Object> wrapper;
|
||||
if (!GetWrapper(isolate).ToLocal(&wrapper)) {
|
||||
if (callback) {
|
||||
// We must always invoke the callback if present.
|
||||
ReplyChannel::Create(isolate, std::move(callback))
|
||||
->SendError("WebContents was destroyed");
|
||||
}
|
||||
return gin::Handle<gin_helper::internal::Event>();
|
||||
}
|
||||
gin::Handle<gin_helper::internal::Event> event =
|
||||
gin_helper::internal::Event::New(isolate);
|
||||
gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>());
|
||||
if (callback)
|
||||
dict.Set("_replyChannel",
|
||||
ReplyChannel::Create(isolate, std::move(callback)));
|
||||
if (frame) {
|
||||
dict.Set("frameId", frame->GetRoutingID());
|
||||
dict.Set("processId", frame->GetProcess()->GetID());
|
||||
}
|
||||
return event;
|
||||
}
|
||||
|
||||
void WebContents::ReceivePostMessage(
|
||||
const std::string& channel,
|
||||
blink::TransferableMessage message,
|
||||
@@ -3509,18 +3623,26 @@ v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
|
||||
flags = base::File::AddFlagsForPassingToUntrustedProcess(flags);
|
||||
base::File file(file_path, flags);
|
||||
if (!file.IsValid()) {
|
||||
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
|
||||
promise.RejectWithErrorMessage(
|
||||
"Failed to take heap snapshot with invalid file path " +
|
||||
#if BUILDFLAG(IS_WIN)
|
||||
base::WideToUTF8(file_path.value()));
|
||||
#else
|
||||
file_path.value());
|
||||
#endif
|
||||
return handle;
|
||||
}
|
||||
|
||||
auto* frame_host = web_contents()->GetPrimaryMainFrame();
|
||||
if (!frame_host) {
|
||||
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
|
||||
promise.RejectWithErrorMessage(
|
||||
"Failed to take heap snapshot with invalid webContents main frame");
|
||||
return handle;
|
||||
}
|
||||
|
||||
if (!frame_host->IsRenderFrameLive()) {
|
||||
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
|
||||
promise.RejectWithErrorMessage(
|
||||
"Failed to take heap snapshot with nonexistent render frame");
|
||||
return handle;
|
||||
}
|
||||
|
||||
@@ -3540,7 +3662,7 @@ v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
|
||||
if (success) {
|
||||
promise.Resolve();
|
||||
} else {
|
||||
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
|
||||
promise.RejectWithErrorMessage("Failed to take heap snapshot");
|
||||
}
|
||||
},
|
||||
base::Owned(std::move(electron_renderer)), std::move(promise)));
|
||||
@@ -3580,14 +3702,14 @@ void WebContents::EnumerateDirectory(
|
||||
bool WebContents::IsFullscreenForTabOrPending(
|
||||
const content::WebContents* source) {
|
||||
if (!owner_window())
|
||||
return html_fullscreen_;
|
||||
return is_html_fullscreen();
|
||||
|
||||
bool in_transition = owner_window()->fullscreen_transition_state() !=
|
||||
NativeWindow::FullScreenTransitionState::NONE;
|
||||
bool is_html_transition = owner_window()->fullscreen_transition_type() ==
|
||||
NativeWindow::FullScreenTransitionType::HTML;
|
||||
|
||||
return html_fullscreen_ || (in_transition && is_html_transition);
|
||||
return is_html_fullscreen() || (in_transition && is_html_transition);
|
||||
}
|
||||
|
||||
bool WebContents::TakeFocus(content::WebContents* source, bool reverse) {
|
||||
@@ -3877,7 +3999,7 @@ void WebContents::OnDevToolsSearchCompleted(
|
||||
|
||||
void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) {
|
||||
// Window is already in fullscreen mode, save the state.
|
||||
if (enter_fullscreen && owner_window_->IsFullscreen()) {
|
||||
if (enter_fullscreen && owner_window()->IsFullscreen()) {
|
||||
native_fullscreen_ = true;
|
||||
UpdateHtmlApiFullscreen(true);
|
||||
return;
|
||||
|
||||
@@ -352,20 +352,26 @@ class WebContents : public ExclusiveAccessContext,
|
||||
// this.emit(name, new Event(sender, message), args...);
|
||||
template <typename... Args>
|
||||
bool EmitWithSender(base::StringPiece name,
|
||||
content::RenderFrameHost* sender,
|
||||
content::RenderFrameHost* frame,
|
||||
electron::mojom::ElectronApiIPC::InvokeCallback callback,
|
||||
Args&&... args) {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
|
||||
v8::HandleScope handle_scope(isolate);
|
||||
v8::Local<v8::Object> wrapper;
|
||||
if (!GetWrapper(isolate).ToLocal(&wrapper))
|
||||
|
||||
gin::Handle<gin_helper::internal::Event> event =
|
||||
MakeEventWithSender(isolate, frame, std::move(callback));
|
||||
if (event.IsEmpty())
|
||||
return false;
|
||||
v8::Local<v8::Object> event = gin_helper::internal::CreateNativeEvent(
|
||||
isolate, wrapper, sender, std::move(callback));
|
||||
return EmitCustomEvent(name, event, std::forward<Args>(args)...);
|
||||
EmitWithoutEvent(name, event, std::forward<Args>(args)...);
|
||||
return event->GetDefaultPrevented();
|
||||
}
|
||||
|
||||
gin::Handle<gin_helper::internal::Event> MakeEventWithSender(
|
||||
v8::Isolate* isolate,
|
||||
content::RenderFrameHost* frame,
|
||||
electron::mojom::ElectronApiIPC::InvokeCallback callback);
|
||||
|
||||
WebContents* embedder() { return embedder_; }
|
||||
|
||||
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
|
||||
@@ -436,7 +442,13 @@ class WebContents : public ExclusiveAccessContext,
|
||||
// content::RenderWidgetHost::InputEventObserver:
|
||||
void OnInputEvent(const blink::WebInputEvent& event) override;
|
||||
|
||||
SkRegion* draggable_region() { return draggable_region_.get(); }
|
||||
SkRegion* draggable_region() {
|
||||
return force_non_draggable_ ? nullptr : draggable_region_.get();
|
||||
}
|
||||
|
||||
void SetForceNonDraggable(bool force_non_draggable) {
|
||||
force_non_draggable_ = force_non_draggable;
|
||||
}
|
||||
|
||||
// disable copy
|
||||
WebContents(const WebContents&) = delete;
|
||||
@@ -820,6 +832,8 @@ class WebContents : public ExclusiveAccessContext,
|
||||
|
||||
std::unique_ptr<SkRegion> draggable_region_;
|
||||
|
||||
bool force_non_draggable_ = false;
|
||||
|
||||
base::WeakPtrFactory<WebContents> weak_factory_{this};
|
||||
};
|
||||
|
||||
|
||||
@@ -94,17 +94,34 @@ struct UserData : public base::SupportsUserData::Data {
|
||||
WebRequest* data;
|
||||
};
|
||||
|
||||
// Test whether the URL of |request| matches |patterns|.
|
||||
bool MatchesFilterCondition(extensions::WebRequestInfo* info,
|
||||
const std::set<URLPattern>& patterns) {
|
||||
if (patterns.empty())
|
||||
return true;
|
||||
|
||||
for (const auto& pattern : patterns) {
|
||||
if (pattern.MatchesURL(info->url))
|
||||
return true;
|
||||
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;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Convert HttpResponseHeaders to V8.
|
||||
@@ -247,17 +264,54 @@ void ReadFromResponse(v8::Isolate* isolate,
|
||||
|
||||
gin::WrapperInfo WebRequest::kWrapperInfo = {gin::kEmbedderNativeGin};
|
||||
|
||||
WebRequest::SimpleListenerInfo::SimpleListenerInfo(
|
||||
std::set<URLPattern> patterns_,
|
||||
SimpleListener listener_)
|
||||
: url_patterns(std::move(patterns_)), listener(listener_) {}
|
||||
WebRequest::RequestFilter::RequestFilter(
|
||||
std::set<URLPattern> url_patterns,
|
||||
std::set<extensions::WebRequestResourceType> types)
|
||||
: url_patterns_(std::move(url_patterns)), types_(std::move(types)) {}
|
||||
WebRequest::RequestFilter::RequestFilter(const RequestFilter&) = default;
|
||||
WebRequest::RequestFilter::RequestFilter() = default;
|
||||
WebRequest::RequestFilter::~RequestFilter() = default;
|
||||
|
||||
void WebRequest::RequestFilter::AddUrlPattern(URLPattern pattern) {
|
||||
url_patterns_.emplace(std::move(pattern));
|
||||
}
|
||||
|
||||
void WebRequest::RequestFilter::AddType(
|
||||
extensions::WebRequestResourceType type) {
|
||||
types_.insert(type);
|
||||
}
|
||||
|
||||
bool WebRequest::RequestFilter::MatchesURL(const GURL& url) const {
|
||||
if (url_patterns_.empty())
|
||||
return true;
|
||||
|
||||
for (const auto& pattern : url_patterns_) {
|
||||
if (pattern.MatchesURL(url))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool WebRequest::RequestFilter::MatchesType(
|
||||
extensions::WebRequestResourceType type) const {
|
||||
return types_.empty() || types_.find(type) != types_.end();
|
||||
}
|
||||
|
||||
bool WebRequest::RequestFilter::MatchesRequest(
|
||||
extensions::WebRequestInfo* info) const {
|
||||
return MatchesURL(info->url) && MatchesType(info->web_request_type);
|
||||
}
|
||||
|
||||
WebRequest::SimpleListenerInfo::SimpleListenerInfo(RequestFilter filter_,
|
||||
SimpleListener listener_)
|
||||
: filter(std::move(filter_)), listener(listener_) {}
|
||||
WebRequest::SimpleListenerInfo::SimpleListenerInfo() = default;
|
||||
WebRequest::SimpleListenerInfo::~SimpleListenerInfo() = default;
|
||||
|
||||
WebRequest::ResponseListenerInfo::ResponseListenerInfo(
|
||||
std::set<URLPattern> patterns_,
|
||||
RequestFilter filter_,
|
||||
ResponseListener listener_)
|
||||
: url_patterns(std::move(patterns_)), listener(listener_) {}
|
||||
: filter(std::move(filter_)), listener(listener_) {}
|
||||
WebRequest::ResponseListenerInfo::ResponseListenerInfo() = default;
|
||||
WebRequest::ResponseListenerInfo::~ResponseListenerInfo() = default;
|
||||
|
||||
@@ -392,8 +446,8 @@ void WebRequest::SetListener(Event event,
|
||||
gin::Arguments* args) {
|
||||
v8::Local<v8::Value> arg;
|
||||
|
||||
// { urls }.
|
||||
std::set<std::string> filter_patterns;
|
||||
// { urls, types }.
|
||||
std::set<std::string> filter_patterns, filter_types;
|
||||
gin::Dictionary dict(args->isolate());
|
||||
if (args->GetNext(&arg) && !arg->IsFunction()) {
|
||||
// Note that gin treats Function as Dictionary when doing conversions, so we
|
||||
@@ -404,16 +458,18 @@ void WebRequest::SetListener(Event event,
|
||||
args->ThrowTypeError("Parameter 'filter' must have property 'urls'.");
|
||||
return;
|
||||
}
|
||||
dict.Get("types", &filter_types);
|
||||
args->GetNext(&arg);
|
||||
}
|
||||
}
|
||||
|
||||
std::set<URLPattern> patterns;
|
||||
RequestFilter filter;
|
||||
|
||||
for (const std::string& filter_pattern : filter_patterns) {
|
||||
URLPattern pattern(URLPattern::SCHEME_ALL);
|
||||
const URLPattern::ParseResult result = pattern.Parse(filter_pattern);
|
||||
if (result == URLPattern::ParseResult::kSuccess) {
|
||||
patterns.insert(pattern);
|
||||
filter.AddUrlPattern(std::move(pattern));
|
||||
} else {
|
||||
const char* error_type = URLPattern::GetParseResultString(result);
|
||||
args->ThrowTypeError("Invalid url pattern " + filter_pattern + ": " +
|
||||
@@ -422,6 +478,16 @@ void WebRequest::SetListener(Event event,
|
||||
}
|
||||
}
|
||||
|
||||
for (const std::string& filter_type : filter_types) {
|
||||
auto type = ParseResourceType(filter_type);
|
||||
if (type != extensions::WebRequestResourceType::OTHER) {
|
||||
filter.AddType(type);
|
||||
} else {
|
||||
args->ThrowTypeError("Invalid type " + filter_type);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Function or null.
|
||||
Listener listener;
|
||||
if (arg.IsEmpty() ||
|
||||
@@ -433,7 +499,7 @@ void WebRequest::SetListener(Event event,
|
||||
if (listener.is_null())
|
||||
listeners->erase(event);
|
||||
else
|
||||
(*listeners)[event] = {std::move(patterns), std::move(listener)};
|
||||
(*listeners)[event] = {std::move(filter), std::move(listener)};
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
@@ -445,7 +511,7 @@ void WebRequest::HandleSimpleEvent(SimpleEvent event,
|
||||
return;
|
||||
|
||||
const auto& info = iter->second;
|
||||
if (!MatchesFilterCondition(request_info, info.url_patterns))
|
||||
if (!info.filter.MatchesRequest(request_info))
|
||||
return;
|
||||
|
||||
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
|
||||
@@ -466,7 +532,7 @@ int WebRequest::HandleResponseEvent(ResponseEvent event,
|
||||
return net::OK;
|
||||
|
||||
const auto& info = iter->second;
|
||||
if (!MatchesFilterCondition(request_info, info.url_patterns))
|
||||
if (!info.filter.MatchesRequest(request_info))
|
||||
return net::OK;
|
||||
|
||||
callbacks_[request_info->id] = std::move(callback);
|
||||
|
||||
@@ -123,20 +123,41 @@ class WebRequest : public gin::Wrappable<WebRequest>, public WebRequestAPI {
|
||||
template <typename T>
|
||||
void OnListenerResult(uint64_t id, T out, v8::Local<v8::Value> response);
|
||||
|
||||
class RequestFilter {
|
||||
public:
|
||||
RequestFilter(std::set<URLPattern>,
|
||||
std::set<extensions::WebRequestResourceType>);
|
||||
RequestFilter(const RequestFilter&);
|
||||
RequestFilter();
|
||||
~RequestFilter();
|
||||
|
||||
void AddUrlPattern(URLPattern pattern);
|
||||
void AddType(extensions::WebRequestResourceType type);
|
||||
|
||||
bool MatchesRequest(extensions::WebRequestInfo* info) const;
|
||||
|
||||
private:
|
||||
bool MatchesURL(const GURL& url) const;
|
||||
bool MatchesType(extensions::WebRequestResourceType type) const;
|
||||
|
||||
std::set<URLPattern> url_patterns_;
|
||||
std::set<extensions::WebRequestResourceType> types_;
|
||||
};
|
||||
|
||||
struct SimpleListenerInfo {
|
||||
std::set<URLPattern> url_patterns;
|
||||
RequestFilter filter;
|
||||
SimpleListener listener;
|
||||
|
||||
SimpleListenerInfo(std::set<URLPattern>, SimpleListener);
|
||||
SimpleListenerInfo(RequestFilter, SimpleListener);
|
||||
SimpleListenerInfo();
|
||||
~SimpleListenerInfo();
|
||||
};
|
||||
|
||||
struct ResponseListenerInfo {
|
||||
std::set<URLPattern> url_patterns;
|
||||
RequestFilter filter;
|
||||
ResponseListener listener;
|
||||
|
||||
ResponseListenerInfo(std::set<URLPattern>, ResponseListener);
|
||||
ResponseListenerInfo(RequestFilter, ResponseListener);
|
||||
ResponseListenerInfo();
|
||||
~ResponseListenerInfo();
|
||||
};
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
// Copyright (c) 2014 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "shell/browser/api/event.h"
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "gin/data_object_builder.h"
|
||||
#include "gin/object_template_builder.h"
|
||||
#include "shell/browser/javascript_environment.h"
|
||||
#include "shell/common/gin_converters/blink_converter.h"
|
||||
#include "shell/common/gin_converters/std_converter.h"
|
||||
|
||||
namespace gin_helper {
|
||||
|
||||
gin::WrapperInfo Event::kWrapperInfo = {gin::kEmbedderNativeGin};
|
||||
|
||||
Event::Event() = default;
|
||||
|
||||
Event::~Event() {
|
||||
if (callback_) {
|
||||
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
|
||||
// If there's no current context, it means we're shutting down, so we don't
|
||||
// need to send an event.
|
||||
if (!isolate->GetCurrentContext().IsEmpty()) {
|
||||
v8::HandleScope scope(isolate);
|
||||
auto message = gin::DataObjectBuilder(isolate)
|
||||
.Set("error", "reply was never sent")
|
||||
.Build();
|
||||
SendReply(isolate, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Event::SetCallback(InvokeCallback callback) {
|
||||
DCHECK(!callback_);
|
||||
callback_ = std::move(callback);
|
||||
}
|
||||
|
||||
void Event::PreventDefault(v8::Isolate* isolate) {
|
||||
v8::Local<v8::Object> self = GetWrapper(isolate).ToLocalChecked();
|
||||
self->Set(isolate->GetCurrentContext(),
|
||||
gin::StringToV8(isolate, "defaultPrevented"), v8::True(isolate))
|
||||
.Check();
|
||||
}
|
||||
|
||||
bool Event::SendReply(v8::Isolate* isolate, v8::Local<v8::Value> result) {
|
||||
if (!callback_)
|
||||
return false;
|
||||
|
||||
blink::CloneableMessage message;
|
||||
if (!gin::ConvertFromV8(isolate, result, &message)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::move(callback_).Run(std::move(message));
|
||||
return true;
|
||||
}
|
||||
|
||||
gin::ObjectTemplateBuilder Event::GetObjectTemplateBuilder(
|
||||
v8::Isolate* isolate) {
|
||||
return gin::Wrappable<Event>::GetObjectTemplateBuilder(isolate)
|
||||
.SetMethod("preventDefault", &Event::PreventDefault)
|
||||
.SetMethod("sendReply", &Event::SendReply);
|
||||
}
|
||||
|
||||
const char* Event::GetTypeName() {
|
||||
return "Event";
|
||||
}
|
||||
|
||||
// static
|
||||
gin::Handle<Event> Event::Create(v8::Isolate* isolate) {
|
||||
return gin::CreateHandle(isolate, new Event());
|
||||
}
|
||||
|
||||
} // namespace gin_helper
|
||||
@@ -1,52 +0,0 @@
|
||||
// Copyright (c) 2014 GitHub, 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_EVENT_H_
|
||||
#define ELECTRON_SHELL_BROWSER_API_EVENT_H_
|
||||
|
||||
#include "electron/shell/common/api/api.mojom.h"
|
||||
#include "gin/handle.h"
|
||||
#include "gin/wrappable.h"
|
||||
|
||||
namespace gin_helper {
|
||||
|
||||
class Event : public gin::Wrappable<Event> {
|
||||
public:
|
||||
using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback;
|
||||
|
||||
static gin::WrapperInfo kWrapperInfo;
|
||||
|
||||
static gin::Handle<Event> Create(v8::Isolate* isolate);
|
||||
|
||||
// Pass the callback to be invoked.
|
||||
void SetCallback(InvokeCallback callback);
|
||||
|
||||
// event.PreventDefault().
|
||||
void PreventDefault(v8::Isolate* isolate);
|
||||
|
||||
// event.sendReply(value), used for replying to synchronous messages and
|
||||
// `invoke` calls.
|
||||
bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> result);
|
||||
|
||||
// disable copy
|
||||
Event(const Event&) = delete;
|
||||
Event& operator=(const Event&) = delete;
|
||||
|
||||
protected:
|
||||
Event();
|
||||
~Event() override;
|
||||
|
||||
// gin::Wrappable:
|
||||
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
|
||||
v8::Isolate* isolate) override;
|
||||
const char* GetTypeName() override;
|
||||
|
||||
private:
|
||||
// Replier for the synchronous messages.
|
||||
InvokeCallback callback_;
|
||||
};
|
||||
|
||||
} // namespace gin_helper
|
||||
|
||||
#endif // ELECTRON_SHELL_BROWSER_API_EVENT_H_
|
||||
@@ -61,7 +61,7 @@ class MessagePort : public gin::Wrappable<MessagePort>, mojo::MessageReceiver {
|
||||
// The blink version of MessagePort uses the very nice "ActiveScriptWrapper"
|
||||
// class, which keeps the object alive through the V8 embedder hooks into the
|
||||
// GC lifecycle: see
|
||||
// https://source.chromium.org/chromium/chromium/src/+/master:third_party/blink/renderer/platform/heap/thread_state.cc;l=258;drc=b892cf58e162a8f66cd76d7472f129fe0fb6a7d1
|
||||
// https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/heap/thread_state.cc;l=258;drc=b892cf58e162a8f66cd76d7472f129fe0fb6a7d1
|
||||
// We do not have that luxury, so we brutishly use v8::Global to accomplish
|
||||
// something similar. Critically, whenever the value of
|
||||
// "HasPendingActivity()" changes, we must call Pin() or Unpin() as
|
||||
|
||||
@@ -363,7 +363,7 @@ class Browser : public WindowListObserver {
|
||||
base::Time last_dock_show_;
|
||||
#endif
|
||||
|
||||
base::Value about_panel_options_;
|
||||
base::Value::Dict about_panel_options_;
|
||||
|
||||
#if BUILDFLAG(IS_WIN)
|
||||
void UpdateBadgeContents(HWND hwnd,
|
||||
|
||||
@@ -162,31 +162,25 @@ bool Browser::IsEmojiPanelSupported() {
|
||||
void Browser::ShowAboutPanel() {
|
||||
const auto& opts = about_panel_options_;
|
||||
|
||||
if (!opts.is_dict()) {
|
||||
LOG(WARNING) << "Called showAboutPanel(), but didn't use "
|
||||
"setAboutPanelSettings() first";
|
||||
return;
|
||||
}
|
||||
|
||||
GtkWidget* dialogWidget = gtk_about_dialog_new();
|
||||
GtkAboutDialog* dialog = GTK_ABOUT_DIALOG(dialogWidget);
|
||||
|
||||
const std::string* str;
|
||||
const base::Value* val;
|
||||
const base::Value::List* list;
|
||||
|
||||
if ((str = opts.FindStringKey("applicationName"))) {
|
||||
if ((str = opts.FindString("applicationName"))) {
|
||||
gtk_about_dialog_set_program_name(dialog, str->c_str());
|
||||
}
|
||||
if ((str = opts.FindStringKey("applicationVersion"))) {
|
||||
if ((str = opts.FindString("applicationVersion"))) {
|
||||
gtk_about_dialog_set_version(dialog, str->c_str());
|
||||
}
|
||||
if ((str = opts.FindStringKey("copyright"))) {
|
||||
if ((str = opts.FindString("copyright"))) {
|
||||
gtk_about_dialog_set_copyright(dialog, str->c_str());
|
||||
}
|
||||
if ((str = opts.FindStringKey("website"))) {
|
||||
if ((str = opts.FindString("website"))) {
|
||||
gtk_about_dialog_set_website(dialog, str->c_str());
|
||||
}
|
||||
if ((str = opts.FindStringKey("iconPath"))) {
|
||||
if ((str = opts.FindString("iconPath"))) {
|
||||
GError* error = nullptr;
|
||||
constexpr int width = 64; // width of about panel icon in pixels
|
||||
constexpr int height = 64; // height of about panel icon in pixels
|
||||
@@ -203,9 +197,9 @@ void Browser::ShowAboutPanel() {
|
||||
}
|
||||
}
|
||||
|
||||
if ((val = opts.FindListKey("authors"))) {
|
||||
if ((list = opts.FindList("authors"))) {
|
||||
std::vector<const char*> cstrs;
|
||||
for (const auto& authorVal : val->GetList()) {
|
||||
for (const auto& authorVal : *list) {
|
||||
if (authorVal.is_string()) {
|
||||
cstrs.push_back(authorVal.GetString().c_str());
|
||||
}
|
||||
@@ -218,12 +212,15 @@ void Browser::ShowAboutPanel() {
|
||||
}
|
||||
}
|
||||
|
||||
gtk_dialog_run(GTK_DIALOG(dialog));
|
||||
gtk_widget_destroy(dialogWidget);
|
||||
// destroy the widget when it closes
|
||||
g_signal_connect_swapped(dialogWidget, "response",
|
||||
G_CALLBACK(gtk_widget_destroy), dialogWidget);
|
||||
|
||||
gtk_widget_show_all(dialogWidget);
|
||||
}
|
||||
|
||||
void Browser::SetAboutPanelOptions(base::Value::Dict options) {
|
||||
about_panel_options_ = base::Value(std::move(options));
|
||||
about_panel_options_ = std::move(options);
|
||||
}
|
||||
|
||||
} // namespace electron
|
||||
|
||||
@@ -513,8 +513,7 @@ void Browser::DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) {
|
||||
}
|
||||
|
||||
void Browser::ShowAboutPanel() {
|
||||
NSDictionary* options =
|
||||
DictionaryValueToNSDictionary(about_panel_options_.GetDict());
|
||||
NSDictionary* options = DictionaryValueToNSDictionary(about_panel_options_);
|
||||
|
||||
// Credits must be a NSAttributedString instead of NSString
|
||||
NSString* credits = (NSString*)options[@"Credits"];
|
||||
@@ -537,13 +536,13 @@ void Browser::ShowAboutPanel() {
|
||||
}
|
||||
|
||||
void Browser::SetAboutPanelOptions(base::Value::Dict options) {
|
||||
about_panel_options_.GetDict().clear();
|
||||
about_panel_options_.clear();
|
||||
|
||||
for (const auto pair : options) {
|
||||
std::string key = pair.first;
|
||||
if (!key.empty() && pair.second.is_string()) {
|
||||
key[0] = base::ToUpperASCII(key[0]);
|
||||
about_panel_options_.GetDict().Set(key, pair.second.Clone());
|
||||
about_panel_options_.Set(key, pair.second.Clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "base/functional/bind.h"
|
||||
#include "shell/browser/browser.h"
|
||||
|
||||
// must come before other includes. fixes bad #defines from <shlwapi.h>.
|
||||
@@ -734,30 +735,29 @@ void Browser::ShowEmojiPanel() {
|
||||
}
|
||||
|
||||
void Browser::ShowAboutPanel() {
|
||||
base::Value dict(base::Value::Type::DICTIONARY);
|
||||
base::Value::Dict dict;
|
||||
std::string aboutMessage = "";
|
||||
gfx::ImageSkia image;
|
||||
|
||||
// grab defaults from Windows .EXE file
|
||||
std::unique_ptr<FileVersionInfo> exe_info = FetchFileVersionInfo();
|
||||
dict.SetStringKey("applicationName", exe_info->file_description());
|
||||
dict.SetStringKey("applicationVersion", exe_info->product_version());
|
||||
dict.Set("applicationName", exe_info->file_description());
|
||||
dict.Set("applicationVersion", exe_info->product_version());
|
||||
|
||||
if (about_panel_options_.is_dict()) {
|
||||
dict.MergeDictionary(&about_panel_options_);
|
||||
}
|
||||
// Merge user-provided options, overwriting any of the above
|
||||
dict.Merge(about_panel_options_.Clone());
|
||||
|
||||
std::vector<std::string> stringOptions = {
|
||||
"applicationName", "applicationVersion", "copyright", "credits"};
|
||||
|
||||
const std::string* str;
|
||||
for (std::string opt : stringOptions) {
|
||||
if ((str = dict.FindStringKey(opt))) {
|
||||
if ((str = dict.FindString(opt))) {
|
||||
aboutMessage.append(*str).append("\r\n");
|
||||
}
|
||||
}
|
||||
|
||||
if ((str = dict.FindStringKey("iconPath"))) {
|
||||
if ((str = dict.FindString("iconPath"))) {
|
||||
base::FilePath path = base::FilePath::FromUTF8Unsafe(*str);
|
||||
electron::util::PopulateImageSkiaRepsFromPath(&image, path);
|
||||
}
|
||||
@@ -766,11 +766,12 @@ void Browser::ShowAboutPanel() {
|
||||
settings.message = aboutMessage;
|
||||
settings.icon = image;
|
||||
settings.type = electron::MessageBoxType::kInformation;
|
||||
electron::ShowMessageBoxSync(settings);
|
||||
electron::ShowMessageBox(settings,
|
||||
base::BindOnce([](int, bool) { /* do nothing. */ }));
|
||||
}
|
||||
|
||||
void Browser::SetAboutPanelOptions(base::Value::Dict options) {
|
||||
about_panel_options_ = base::Value(std::move(options));
|
||||
about_panel_options_ = std::move(options);
|
||||
}
|
||||
|
||||
} // namespace electron
|
||||
|
||||
@@ -501,13 +501,16 @@ void ElectronBrowserContext::DisplayMediaDeviceChosen(
|
||||
devices.audio_device =
|
||||
blink::MediaStreamDevice(request.audio_type, id, name);
|
||||
} else if (result_dict.Get("audio", &rfh)) {
|
||||
devices.audio_device = blink::MediaStreamDevice(
|
||||
request.audio_type,
|
||||
content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(),
|
||||
rfh->GetRoutingID(),
|
||||
/* disable_local_echo= */ true)
|
||||
.ToString(),
|
||||
"Tab audio");
|
||||
bool enable_local_echo = false;
|
||||
result_dict.Get("enableLocalEcho", &enable_local_echo);
|
||||
bool disable_local_echo = !enable_local_echo;
|
||||
devices.audio_device =
|
||||
blink::MediaStreamDevice(request.audio_type,
|
||||
content::WebContentsMediaCaptureId(
|
||||
rfh->GetProcess()->GetID(),
|
||||
rfh->GetRoutingID(), disable_local_echo)
|
||||
.ToString(),
|
||||
"Tab audio");
|
||||
} else if (result_dict.Get("audio", &id)) {
|
||||
devices.audio_device =
|
||||
blink::MediaStreamDevice(request.audio_type, id, "System audio");
|
||||
|
||||
@@ -270,7 +270,7 @@ void ElectronBrowserMainParts::PostEarlyInitialization() {
|
||||
|
||||
v8::HandleScope scope(js_env_->isolate());
|
||||
|
||||
node_bindings_->Initialize();
|
||||
node_bindings_->Initialize(js_env_->isolate()->GetCurrentContext());
|
||||
// Create the global environment.
|
||||
node::Environment* env = node_bindings_->CreateEnvironment(
|
||||
js_env_->isolate()->GetCurrentContext(), js_env_->platform());
|
||||
@@ -279,7 +279,7 @@ void ElectronBrowserMainParts::PostEarlyInitialization() {
|
||||
env->set_trace_sync_io(env->options()->trace_sync_io);
|
||||
|
||||
// We do not want to crash the main process on unhandled rejections.
|
||||
env->options()->unhandled_rejections = "warn";
|
||||
env->options()->unhandled_rejections = "warn-with-error-code";
|
||||
|
||||
// Add Electron extended APIs.
|
||||
electron_bindings_->BindTo(js_env_->isolate(), env->process_object());
|
||||
@@ -561,7 +561,7 @@ void ElectronBrowserMainParts::PostCreateMainMessageLoop() {
|
||||
config->main_thread_runner =
|
||||
base::SingleThreadTaskRunner::GetCurrentDefault();
|
||||
// c.f.
|
||||
// https://source.chromium.org/chromium/chromium/src/+/master:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1
|
||||
// https://source.chromium.org/chromium/chromium/src/+/main:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1
|
||||
config->should_use_preference =
|
||||
command_line.HasSwitch(::switches::kEnableEncryptionSelection);
|
||||
base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path);
|
||||
|
||||
@@ -7,16 +7,14 @@
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "gin/handle.h"
|
||||
#include "gin/object_template_builder.h"
|
||||
#include "shell/browser/javascript_environment.h"
|
||||
#include "shell/common/gin_helper/event.h"
|
||||
#include "shell/common/gin_helper/event_emitter.h"
|
||||
|
||||
namespace gin_helper {
|
||||
|
||||
namespace internal {
|
||||
v8::Local<v8::FunctionTemplate> GetEventEmitterTemplate(v8::Isolate* isolate);
|
||||
} // namespace internal
|
||||
|
||||
template <typename T>
|
||||
class EventEmitterMixin {
|
||||
public:
|
||||
@@ -33,14 +31,15 @@ class EventEmitterMixin {
|
||||
v8::Local<v8::Object> wrapper;
|
||||
if (!static_cast<T*>(this)->GetWrapper(isolate).ToLocal(&wrapper))
|
||||
return false;
|
||||
v8::Local<v8::Object> event = internal::CreateCustomEvent(isolate, wrapper);
|
||||
return EmitWithEvent(isolate, wrapper, name, event,
|
||||
std::forward<Args>(args)...);
|
||||
gin::Handle<internal::Event> event = internal::Event::New(isolate);
|
||||
gin_helper::EmitEvent(isolate, wrapper, name, event,
|
||||
std::forward<Args>(args)...);
|
||||
return event->GetDefaultPrevented();
|
||||
}
|
||||
|
||||
// this.emit(name, args...);
|
||||
template <typename... Args>
|
||||
void EmitWithoutCustomEvent(base::StringPiece name, Args&&... args) {
|
||||
void EmitWithoutEvent(base::StringPiece name, Args&&... args) {
|
||||
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
|
||||
v8::HandleScope handle_scope(isolate);
|
||||
v8::Local<v8::Object> wrapper;
|
||||
@@ -49,20 +48,6 @@ class EventEmitterMixin {
|
||||
gin_helper::EmitEvent(isolate, wrapper, name, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
// this.emit(name, event, args...);
|
||||
template <typename... Args>
|
||||
bool EmitCustomEvent(base::StringPiece name,
|
||||
v8::Local<v8::Object> custom_event,
|
||||
Args&&... args) {
|
||||
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
|
||||
v8::HandleScope scope(isolate);
|
||||
v8::Local<v8::Object> wrapper;
|
||||
if (!static_cast<T*>(this)->GetWrapper(isolate).ToLocal(&wrapper))
|
||||
return false;
|
||||
return EmitWithEvent(isolate, wrapper, name, custom_event,
|
||||
std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
protected:
|
||||
EventEmitterMixin() = default;
|
||||
|
||||
@@ -82,25 +67,6 @@ class EventEmitterMixin {
|
||||
static_cast<T*>(this)->GetTypeName(),
|
||||
constructor->InstanceTemplate());
|
||||
}
|
||||
|
||||
private:
|
||||
// this.emit(name, event, args...);
|
||||
template <typename... Args>
|
||||
static bool EmitWithEvent(v8::Isolate* isolate,
|
||||
v8::Local<v8::Object> wrapper,
|
||||
base::StringPiece name,
|
||||
v8::Local<v8::Object> event,
|
||||
Args&&... args) {
|
||||
auto context = isolate->GetCurrentContext();
|
||||
gin_helper::EmitEvent(isolate, wrapper, name, event,
|
||||
std::forward<Args>(args)...);
|
||||
v8::Local<v8::Value> defaultPrevented;
|
||||
if (event->Get(context, gin::StringToV8(isolate, "defaultPrevented"))
|
||||
.ToLocal(&defaultPrevented)) {
|
||||
return defaultPrevented->BooleanValue(isolate);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace gin_helper
|
||||
|
||||
@@ -36,11 +36,6 @@ void InitializeFeatureList() {
|
||||
disable_features +=
|
||||
std::string(",") + features::kSpareRendererForSitePerProcess.name;
|
||||
|
||||
#if BUILDFLAG(IS_MAC)
|
||||
// Needed for WebUSB implementation
|
||||
enable_features += std::string(",") + device::kNewUsbBackend.name;
|
||||
#endif
|
||||
|
||||
#if !BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
|
||||
disable_features += std::string(",") + media::kPictureInPicture.name;
|
||||
#endif
|
||||
|
||||
@@ -219,8 +219,8 @@ class NativeWindow : public base::SupportsUserData,
|
||||
#if BUILDFLAG(IS_MAC)
|
||||
virtual void SetWindowButtonVisibility(bool visible) = 0;
|
||||
virtual bool GetWindowButtonVisibility() const = 0;
|
||||
virtual void SetTrafficLightPosition(absl::optional<gfx::Point> position) = 0;
|
||||
virtual absl::optional<gfx::Point> GetTrafficLightPosition() const = 0;
|
||||
virtual void SetWindowButtonPosition(absl::optional<gfx::Point> position) = 0;
|
||||
virtual absl::optional<gfx::Point> GetWindowButtonPosition() const = 0;
|
||||
virtual void RedrawTrafficLights() = 0;
|
||||
virtual void UpdateFrame() = 0;
|
||||
#endif
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user