mirror of
https://github.com/electron/electron.git
synced 2026-02-19 03:14:51 -05:00
Compare commits
192 Commits
v23.0.0-be
...
v9.0.0-bet
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d888dc7b5 | ||
|
|
1024544573 | ||
|
|
ebbd3081b9 | ||
|
|
dc3dc81beb | ||
|
|
6babb8a9fe | ||
|
|
088e23d604 | ||
|
|
d0a764bd16 | ||
|
|
d47b788e03 | ||
|
|
a985865f65 | ||
|
|
729019b974 | ||
|
|
e83d6be20c | ||
|
|
69eddfb2f9 | ||
|
|
71c3c2b65e | ||
|
|
cf230bc709 | ||
|
|
6d3a6ce307 | ||
|
|
3d8b2af151 | ||
|
|
45174dfc19 | ||
|
|
5bdb5b821b | ||
|
|
0cce079c8f | ||
|
|
0c67a1de8c | ||
|
|
963ef4dbe7 | ||
|
|
e559af3616 | ||
|
|
ed2bc5a4aa | ||
|
|
edb22be8d4 | ||
|
|
74d391baae | ||
|
|
b35a98ce2a | ||
|
|
9bc01adbd5 | ||
|
|
af43d065d2 | ||
|
|
6f4412a317 | ||
|
|
f0a34a2f91 | ||
|
|
30e68263ed | ||
|
|
73a6d507a7 | ||
|
|
ff6e411973 | ||
|
|
fe5af34acc | ||
|
|
cd359127c9 | ||
|
|
248beeb7a5 | ||
|
|
bb2773bf66 | ||
|
|
914a8d02b4 | ||
|
|
27367fb553 | ||
|
|
f193d9a34f | ||
|
|
bcb7fbd9c5 | ||
|
|
9762f6e7fd | ||
|
|
aef7986c64 | ||
|
|
82b65dcca7 | ||
|
|
afeda19d15 | ||
|
|
1c791f9056 | ||
|
|
359110a651 | ||
|
|
7894ae9c01 | ||
|
|
ab41460616 | ||
|
|
8a4d41cd46 | ||
|
|
41f33edd9e | ||
|
|
21f78af43f | ||
|
|
c09bfb5a79 | ||
|
|
fb5871ccf0 | ||
|
|
f255d47073 | ||
|
|
050844dc38 | ||
|
|
317f1a3d3a | ||
|
|
b4675ce0ae | ||
|
|
3f6227c61a | ||
|
|
bfc069e5c0 | ||
|
|
6cb495034e | ||
|
|
6d2cf47797 | ||
|
|
e06880a90e | ||
|
|
0600420bac | ||
|
|
a6ff42c190 | ||
|
|
969579070f | ||
|
|
9ee656f856 | ||
|
|
7e4475cf51 | ||
|
|
79d9bd3a29 | ||
|
|
50debf8595 | ||
|
|
2d68a4d2ee | ||
|
|
6ce0062c0e | ||
|
|
86aa0dfc45 | ||
|
|
792fe833d1 | ||
|
|
9b14ae770d | ||
|
|
5a34ad4e21 | ||
|
|
edd7e97dd9 | ||
|
|
b92734d912 | ||
|
|
dc25ad2ef0 | ||
|
|
54a8258c1c | ||
|
|
02eff88e1b | ||
|
|
09ca564bf4 | ||
|
|
54e31956f8 | ||
|
|
c6539f0d01 | ||
|
|
bef8448393 | ||
|
|
27619e8ab0 | ||
|
|
89c23f313f | ||
|
|
a9b9016b99 | ||
|
|
f1c1542958 | ||
|
|
cb90ef47bb | ||
|
|
a345fe2b4f | ||
|
|
0cf02dd78b | ||
|
|
3d941fc464 | ||
|
|
d32e1f8d97 | ||
|
|
b798e1ff54 | ||
|
|
bcb1d529ff | ||
|
|
e217a9416a | ||
|
|
4be52b8f78 | ||
|
|
2bc7aaf2ef | ||
|
|
1114954cbf | ||
|
|
a76ea622b9 | ||
|
|
7ee7890fd8 | ||
|
|
851ed7a6e7 | ||
|
|
16c4d6e487 | ||
|
|
56c0ba138b | ||
|
|
1883edd869 | ||
|
|
9b5f2159a2 | ||
|
|
60f16eaf95 | ||
|
|
0f08c6c874 | ||
|
|
e227578ae0 | ||
|
|
f413cda758 | ||
|
|
c41b543842 | ||
|
|
7bb430dc44 | ||
|
|
231f5af1a1 | ||
|
|
539ca773de | ||
|
|
1fc197bedb | ||
|
|
926bea232d | ||
|
|
db664f3433 | ||
|
|
9ec73a3dcf | ||
|
|
c1c1ac2b2e | ||
|
|
9c931136d0 | ||
|
|
f01ee72ea5 | ||
|
|
f6b4c39195 | ||
|
|
578f59532d | ||
|
|
dcf9e4b2dd | ||
|
|
2021f25453 | ||
|
|
faee8a092d | ||
|
|
3d65d84193 | ||
|
|
5e05df9f71 | ||
|
|
df2d03fe9b | ||
|
|
80967287ad | ||
|
|
2855f1d237 | ||
|
|
5e25649e77 | ||
|
|
3e90e523eb | ||
|
|
c702aec1f8 | ||
|
|
ede40f260e | ||
|
|
ca53cc8380 | ||
|
|
7ec9b4e252 | ||
|
|
0d7e13d2a6 | ||
|
|
a5c56684b9 | ||
|
|
68d96459c3 | ||
|
|
6cf4757019 | ||
|
|
6e80d6fba5 | ||
|
|
ec07954d5d | ||
|
|
7fd2d39f72 | ||
|
|
64880c75a3 | ||
|
|
cc94689db1 | ||
|
|
806e483049 | ||
|
|
8129e92d2b | ||
|
|
660706ba2c | ||
|
|
2feca9d35a | ||
|
|
3a4118703a | ||
|
|
bd669f72ee | ||
|
|
1f3c3eee83 | ||
|
|
6e84ebee8e | ||
|
|
f22376ef32 | ||
|
|
324b49a5eb | ||
|
|
0e9727e8d5 | ||
|
|
44ee90e5cf | ||
|
|
2b9ef75d82 | ||
|
|
4dc2b4d55f | ||
|
|
69f77d309d | ||
|
|
9cd1744a2b | ||
|
|
c6e411173e | ||
|
|
8b11adc6f2 | ||
|
|
57ec30e459 | ||
|
|
c4a836f95a | ||
|
|
9b2de2583e | ||
|
|
7b2bfb4a0f | ||
|
|
0e31826043 | ||
|
|
7b3c073b3e | ||
|
|
2dc900b95d | ||
|
|
f41423501a | ||
|
|
07d9728b63 | ||
|
|
d4c90e80a5 | ||
|
|
91141028e6 | ||
|
|
9d69d4b9ef | ||
|
|
d57d5c544e | ||
|
|
74d4dab157 | ||
|
|
94246dabe3 | ||
|
|
4fe91e56ac | ||
|
|
0d7440d676 | ||
|
|
60edd2d3b1 | ||
|
|
d4d06660f3 | ||
|
|
8d8f15121b | ||
|
|
1f8cb5144d | ||
|
|
667ee359a1 | ||
|
|
4b009159ba | ||
|
|
89f66bd00c | ||
|
|
2d542c6028 | ||
|
|
68346fec55 | ||
|
|
23f32ca9f3 |
File diff suppressed because it is too large
Load Diff
@@ -6,9 +6,11 @@
|
||||
"browser": true
|
||||
},
|
||||
"rules": {
|
||||
"semi": ["error", "always"],
|
||||
"no-var": "error",
|
||||
"no-unused-vars": 0,
|
||||
"no-global-assign": 0,
|
||||
"guard-for-in": 2,
|
||||
"@typescript-eslint/no-unused-vars": ["error", {
|
||||
"vars": "all",
|
||||
"args": "after-used",
|
||||
|
||||
1
.gitattributes
vendored
1
.gitattributes
vendored
@@ -1,3 +1,4 @@
|
||||
# `git apply` and friends don't understand CRLF, even on windows. Force those
|
||||
# files to be checked out with LF endings even if core.autocrlf is true.
|
||||
*.patch text eol=lf
|
||||
patches/**/.patches merge=union
|
||||
|
||||
59
BUILD.gn
59
BUILD.gn
@@ -3,6 +3,7 @@ import("//build/config/ui.gni")
|
||||
import("//build/config/win/manifest.gni")
|
||||
import("//components/spellcheck/spellcheck_build_features.gni")
|
||||
import("//content/public/app/mac_helpers.gni")
|
||||
import("//extensions/buildflags/buildflags.gni")
|
||||
import("//pdf/features.gni")
|
||||
import("//ppapi/buildflags/buildflags.gni")
|
||||
import("//printing/buildflags/buildflags.gni")
|
||||
@@ -58,6 +59,17 @@ if (is_mas_build) {
|
||||
"It doesn't make sense to build a MAS build on a non-mac platform")
|
||||
}
|
||||
|
||||
if (enable_pdf_viewer) {
|
||||
assert(enable_pdf, "PDF viewer support requires enable_pdf=true")
|
||||
assert(enable_electron_extensions,
|
||||
"PDF viewer support requires enable_electron_extensions=true")
|
||||
}
|
||||
|
||||
if (enable_electron_extensions) {
|
||||
assert(enable_extensions,
|
||||
"Chrome extension support requires enable_extensions=true")
|
||||
}
|
||||
|
||||
config("branding") {
|
||||
defines = [
|
||||
"ELECTRON_PRODUCT_NAME=\"$electron_product_name\"",
|
||||
@@ -224,7 +236,6 @@ grit("resources") {
|
||||
]
|
||||
|
||||
# Mojo manifest overlays are generated.
|
||||
source_is_generated = true
|
||||
grit_flags = [
|
||||
"-E",
|
||||
"target_gen_dir=" + rebase_path(target_gen_dir, root_build_dir),
|
||||
@@ -331,7 +342,9 @@ source_set("electron_lib") {
|
||||
"//components/network_hints/common:mojo_bindings",
|
||||
"//components/network_hints/renderer",
|
||||
"//components/network_session_configurator/common",
|
||||
"//components/pref_registry",
|
||||
"//components/prefs",
|
||||
"//components/user_prefs",
|
||||
"//components/viz/host",
|
||||
"//components/viz/service",
|
||||
"//content/public/browser",
|
||||
@@ -494,15 +507,21 @@ source_set("electron_lib") {
|
||||
deps += [
|
||||
":libnotify_loader",
|
||||
"//build/config/linux/gtk",
|
||||
"//chrome/browser/ui/gtk",
|
||||
"//dbus",
|
||||
"//device/bluetooth",
|
||||
"//third_party/breakpad:client",
|
||||
"//ui/events/devices/x11",
|
||||
"//ui/events/platform/x11",
|
||||
"//ui/gtk",
|
||||
"//ui/views/controls/webview",
|
||||
"//ui/wm",
|
||||
]
|
||||
if (use_x11) {
|
||||
deps += [
|
||||
"//ui/gfx/x",
|
||||
"//ui/gtk:x",
|
||||
]
|
||||
}
|
||||
configs += [ ":gio_unix" ]
|
||||
include_dirs += [ "//third_party/breakpad" ]
|
||||
configs += [ "//build/config/linux:x11" ]
|
||||
@@ -629,25 +648,29 @@ source_set("electron_lib") {
|
||||
deps += [ "//components/printing/common:mojo_interfaces" ]
|
||||
}
|
||||
|
||||
deps += [ "shell/common/extensions/api:extensions_features" ]
|
||||
deps += [ "shell/common/extensions/api" ]
|
||||
deps += [
|
||||
"//components/pref_registry",
|
||||
"//components/user_prefs",
|
||||
"//extensions/browser",
|
||||
"//extensions/browser:core_api_provider",
|
||||
"//extensions/common",
|
||||
"//extensions/common:core_api_provider",
|
||||
"//extensions/renderer",
|
||||
]
|
||||
if (enable_electron_extensions) {
|
||||
sources += filenames.lib_sources_extensions
|
||||
deps += [
|
||||
"shell/browser/extensions/api:api_registration",
|
||||
"shell/common/extensions/api",
|
||||
"shell/common/extensions/api:extensions_features",
|
||||
"//chrome/browser/resources:component_extension_resources",
|
||||
"//components/zoom",
|
||||
"//extensions/browser",
|
||||
"//extensions/browser:core_api_provider",
|
||||
"//extensions/common",
|
||||
"//extensions/common:core_api_provider",
|
||||
"//extensions/renderer",
|
||||
]
|
||||
}
|
||||
|
||||
if (enable_pdf) {
|
||||
# Printing depends on some //pdf code, so it needs to be built even if the
|
||||
# pdf viewer isn't enabled.
|
||||
deps += [ "//pdf" ]
|
||||
deps += [
|
||||
"//pdf",
|
||||
"//pdf:features",
|
||||
]
|
||||
}
|
||||
if (enable_pdf_viewer) {
|
||||
deps += [
|
||||
@@ -728,9 +751,14 @@ if (is_mac) {
|
||||
sources = [
|
||||
"$root_out_dir/egl_intermediates/libswiftshader_libEGL.dylib",
|
||||
"$root_out_dir/egl_intermediates/libswiftshader_libGLESv2.dylib",
|
||||
"$root_out_dir/vk_intermediates/libvk_swiftshader.dylib",
|
||||
"$root_out_dir/vk_intermediates/vk_swiftshader_icd.json",
|
||||
]
|
||||
outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ]
|
||||
public_deps = [ "//ui/gl:swiftshader_library_copy" ]
|
||||
public_deps = [
|
||||
"//ui/gl:swiftshader_egl_library_copy",
|
||||
"//ui/gl:swiftshader_vk_library_copy",
|
||||
]
|
||||
}
|
||||
}
|
||||
group("electron_angle_library") {
|
||||
@@ -783,6 +811,7 @@ if (is_mac) {
|
||||
|
||||
include_dirs = [ "." ]
|
||||
sources = filenames.framework_sources
|
||||
libs = []
|
||||
|
||||
if (enable_osr) {
|
||||
libs += [ "IOSurface.framework" ]
|
||||
|
||||
4
DEPS
4
DEPS
@@ -12,7 +12,7 @@ gclient_gn_args = [
|
||||
|
||||
vars = {
|
||||
'chromium_version':
|
||||
'2102ff0fb03469ca5ff317a168e6ad99ca0f23f1',
|
||||
'83.0.4103.34',
|
||||
'node_version':
|
||||
'v12.14.1',
|
||||
'nan_version':
|
||||
@@ -155,3 +155,5 @@ hooks = [
|
||||
recursedeps = [
|
||||
'src',
|
||||
]
|
||||
|
||||
# Touch DEPS again to bust cache
|
||||
|
||||
@@ -1 +1 @@
|
||||
9.0.0-nightly.20200205
|
||||
9.0.0-beta.22
|
||||
24
appveyor.yml
24
appveyor.yml
@@ -118,19 +118,29 @@ build_script:
|
||||
}
|
||||
}
|
||||
- ps: >-
|
||||
if (Test-Path 'env:RAW_GOMA_AUTH') {
|
||||
$env:GOMA_OAUTH2_CONFIG_FILE = "$pwd\.goma_oauth2_config"
|
||||
$env:RAW_GOMA_AUTH | Set-Content $env:GOMA_OAUTH2_CONFIG_FILE
|
||||
.\src\electron\script\start-goma.ps1 -gomaDir "$pwd\src\electron\external_binaries\goma"
|
||||
if ($env:GN_CONFIG -ne 'release') {
|
||||
if (Test-Path 'env:RAW_GOMA_AUTH') {
|
||||
$env:GOMA_OAUTH2_CONFIG_FILE = "$pwd\.goma_oauth2_config"
|
||||
$env:RAW_GOMA_AUTH | Set-Content $env:GOMA_OAUTH2_CONFIG_FILE
|
||||
}
|
||||
git clone https://github.com/electron/build-tools.git
|
||||
cd build-tools
|
||||
npm install
|
||||
mkdir third_party
|
||||
node -e "require('./src/utils/goma.js').downloadAndPrepare()"
|
||||
$env:GN_GOMA_FILE = node -e "console.log(require('./src/utils/goma.js').gnFilePath)"
|
||||
$env:LOCAL_GOMA_DIR = node -e "console.log(require('./src/utils/goma.js').dir)"
|
||||
cd ..
|
||||
.\src\electron\script\start-goma.ps1 -gomaDir $env:LOCAL_GOMA_DIR
|
||||
}
|
||||
- cd src
|
||||
- set BUILD_CONFIG_PATH=//electron/build/args/%GN_CONFIG%.gn
|
||||
- if DEFINED RAW_GOMA_AUTH (gn gen out/Default "--args=import(\"%BUILD_CONFIG_PATH%\") import(\"//electron/build/args/goma.gn\") %GN_EXTRA_ARGS% ") else (gn gen out/Default "--args=import(\"%BUILD_CONFIG_PATH%\") %GN_EXTRA_ARGS% cc_wrapper=\"%SCCACHE_PATH%\"")
|
||||
- if DEFINED GN_GOMA_FILE (gn gen out/Default "--args=import(\"%BUILD_CONFIG_PATH%\") import(\"%GN_GOMA_FILE%\") %GN_EXTRA_ARGS% ") else (gn gen out/Default "--args=import(\"%BUILD_CONFIG_PATH%\") %GN_EXTRA_ARGS% cc_wrapper=\"%SCCACHE_PATH%\"")
|
||||
- gn check out/Default //electron:electron_lib
|
||||
- gn check out/Default //electron:electron_app
|
||||
- gn check out/Default //electron:manifests
|
||||
- gn check out/Default //electron/shell/common/api:mojo
|
||||
- if DEFINED RAW_GOMA_AUTH (ninja -j 300 -C out/Default electron:electron_app) else (ninja -C out/Default electron:electron_app)
|
||||
- if DEFINED GN_GOMA_FILE (ninja -j 300 -C out/Default electron:electron_app) else (ninja -C out/Default electron:electron_app)
|
||||
- if "%GN_CONFIG%"=="testing" ( python C:\depot_tools\post_build_ninja_summary.py -C out\Default )
|
||||
- gn gen out/ffmpeg "--args=import(\"//electron/build/args/ffmpeg.gn\") %GN_EXTRA_ARGS%"
|
||||
- ninja -C out/ffmpeg electron:electron_ffmpeg_zip
|
||||
@@ -140,7 +150,7 @@ build_script:
|
||||
- ninja -C out/Default electron:hunspell_dictionaries_zip
|
||||
- ninja -C out/Default electron:electron_chromedriver_zip
|
||||
- ninja -C out/Default third_party/electron_node:headers
|
||||
- if DEFINED RAW_GOMA_AUTH (python electron\external_binaries\goma\goma_ctl.py stat)
|
||||
- if "%GN_CONFIG%"=="testing" ( python %LOCAL_GOMA_DIR%\goma_ctl.py stat )
|
||||
- python electron/build/profile_toolchain.py --output-json=out/Default/windows_toolchain_profile.json
|
||||
- appveyor PushArtifact out/Default/windows_toolchain_profile.json
|
||||
- appveyor PushArtifact out/Default/dist.zip
|
||||
|
||||
@@ -2,7 +2,7 @@ is_electron_build = true
|
||||
root_extra_deps = [ "//electron" ]
|
||||
|
||||
# Registry of NMVs --> https://github.com/nodejs/node/blob/master/doc/abi_version_registry.json
|
||||
node_module_version = 76
|
||||
node_module_version = 80
|
||||
|
||||
v8_promise_internal_field_count = 1
|
||||
v8_typed_array_max_size_in_heap = 0
|
||||
@@ -20,8 +20,3 @@ angle_enable_vulkan_validation_layers = false
|
||||
dawn_enable_vulkan_validation_layers = false
|
||||
|
||||
is_cfi = false
|
||||
|
||||
# TODO: disabled due to crashes. re-enable.
|
||||
enable_osr = false
|
||||
|
||||
enable_electron_extensions = true
|
||||
|
||||
@@ -14,7 +14,7 @@ declare_args() {
|
||||
|
||||
enable_view_api = false
|
||||
|
||||
enable_pdf_viewer = false
|
||||
enable_pdf_viewer = true
|
||||
|
||||
enable_tts = true
|
||||
|
||||
@@ -32,7 +32,7 @@ declare_args() {
|
||||
enable_pepper_flash = true
|
||||
|
||||
# Enable Chrome extensions support.
|
||||
enable_electron_extensions = false
|
||||
enable_electron_extensions = true
|
||||
|
||||
# Enable Spellchecker support
|
||||
enable_builtin_spellchecker = true
|
||||
|
||||
@@ -51,8 +51,8 @@ static_library("chrome") {
|
||||
"//chrome/browser/ssl/security_state_tab_helper.cc",
|
||||
"//chrome/browser/ssl/security_state_tab_helper.h",
|
||||
"//chrome/browser/ssl/tls_deprecation_config.cc",
|
||||
"//chrome/browser/ui/autofill/popup_view_common.cc",
|
||||
"//chrome/browser/ui/autofill/popup_view_common.h",
|
||||
"//chrome/browser/ui/views/autofill/autofill_popup_view_utils.cc",
|
||||
"//chrome/browser/ui/views/autofill/autofill_popup_view_utils.h",
|
||||
"//chrome/browser/win/chrome_process_finder.cc",
|
||||
"//chrome/browser/win/chrome_process_finder.h",
|
||||
"//extensions/browser/app_window/size_constraints.cc",
|
||||
@@ -68,8 +68,8 @@ static_library("chrome") {
|
||||
]
|
||||
deps = [
|
||||
"//chrome/browser:resource_prefetch_predictor_proto",
|
||||
"//chrome/browser/ssl:proto",
|
||||
"//components/feature_engagement:buildflags",
|
||||
"//components/optimization_guide/proto:optimization_guide_proto",
|
||||
]
|
||||
|
||||
if (is_linux) {
|
||||
@@ -110,11 +110,15 @@ static_library("chrome") {
|
||||
]
|
||||
|
||||
if (use_aura) {
|
||||
sources += [
|
||||
"//chrome/browser/platform_util_aura.cc",
|
||||
"//chrome/browser/ui/views/color_chooser_aura.cc",
|
||||
"//chrome/browser/ui/views/color_chooser_aura.h",
|
||||
]
|
||||
sources += [ "//chrome/browser/platform_util_aura.cc" ]
|
||||
|
||||
if (!is_win) {
|
||||
sources += [
|
||||
"//chrome/browser/ui/views/color_chooser_aura.cc",
|
||||
"//chrome/browser/ui/views/color_chooser_aura.h",
|
||||
]
|
||||
}
|
||||
|
||||
deps += [ "//components/feature_engagement" ]
|
||||
}
|
||||
|
||||
@@ -233,11 +237,24 @@ static_library("chrome") {
|
||||
|
||||
if (enable_electron_extensions) {
|
||||
sources += [
|
||||
"//chrome/browser/extensions/chrome_url_request_util.cc",
|
||||
"//chrome/browser/extensions/chrome_url_request_util.h",
|
||||
"//chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.cc",
|
||||
"//chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.h",
|
||||
"//chrome/renderer/extensions/extension_hooks_delegate.cc",
|
||||
"//chrome/renderer/extensions/extension_hooks_delegate.h",
|
||||
"//chrome/renderer/extensions/tabs_hooks_delegate.cc",
|
||||
"//chrome/renderer/extensions/tabs_hooks_delegate.h",
|
||||
]
|
||||
|
||||
if (enable_pdf_viewer) {
|
||||
sources += [
|
||||
"//chrome/browser/pdf/pdf_extension_util.cc",
|
||||
"//chrome/browser/pdf/pdf_extension_util.h",
|
||||
"//chrome/renderer/pepper/chrome_pdf_print_client.cc",
|
||||
"//chrome/renderer/pepper/chrome_pdf_print_client.h",
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,6 +278,9 @@ source_set("plugins") {
|
||||
"//ppapi/proxy:ipc",
|
||||
"//services/device/public/mojom",
|
||||
]
|
||||
if (enable_pdf_viewer) {
|
||||
deps += [ "//components/pdf/browser" ]
|
||||
}
|
||||
if (enable_pepper_flash) {
|
||||
sources += [
|
||||
"//chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc",
|
||||
@@ -293,8 +313,6 @@ source_set("plugins") {
|
||||
sources += [
|
||||
"//chrome/renderer/pepper/pepper_flash_drm_renderer_host.cc",
|
||||
"//chrome/renderer/pepper/pepper_flash_drm_renderer_host.h",
|
||||
"//chrome/renderer/pepper/pepper_flash_font_file_host.cc",
|
||||
"//chrome/renderer/pepper/pepper_flash_font_file_host.h",
|
||||
"//chrome/renderer/pepper/pepper_flash_fullscreen_host.cc",
|
||||
"//chrome/renderer/pepper/pepper_flash_fullscreen_host.h",
|
||||
"//chrome/renderer/pepper/pepper_flash_menu_host.cc",
|
||||
@@ -303,6 +321,15 @@ source_set("plugins") {
|
||||
"//chrome/renderer/pepper/pepper_flash_renderer_host.h",
|
||||
]
|
||||
}
|
||||
if (enable_pepper_flash || enable_pdf_viewer) {
|
||||
sources += [
|
||||
"//chrome/renderer/pepper/pepper_flash_font_file_host.cc",
|
||||
"//chrome/renderer/pepper/pepper_flash_font_file_host.h",
|
||||
]
|
||||
if (enable_pdf_viewer) {
|
||||
deps += [ "//components/pdf/renderer" ]
|
||||
}
|
||||
}
|
||||
deps += [
|
||||
"//components/strings",
|
||||
"//media:media_buildflags",
|
||||
|
||||
@@ -1,48 +1,48 @@
|
||||
import { app, dialog, BrowserWindow, shell, ipcMain } from 'electron'
|
||||
import * as path from 'path'
|
||||
import { app, dialog, BrowserWindow, shell, ipcMain } from 'electron';
|
||||
import * as path from 'path';
|
||||
|
||||
let mainWindow: BrowserWindow | null = null
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', () => {
|
||||
app.quit()
|
||||
})
|
||||
app.quit();
|
||||
});
|
||||
|
||||
function decorateURL (url: string) {
|
||||
// safely add `?utm_source=default_app
|
||||
const parsedUrl = new URL(url)
|
||||
parsedUrl.searchParams.append('utm_source', 'default_app')
|
||||
return parsedUrl.toString()
|
||||
const parsedUrl = new URL(url);
|
||||
parsedUrl.searchParams.append('utm_source', 'default_app');
|
||||
return parsedUrl.toString();
|
||||
}
|
||||
|
||||
// Find the shortest path to the electron binary
|
||||
const absoluteElectronPath = process.execPath
|
||||
const relativeElectronPath = path.relative(process.cwd(), absoluteElectronPath)
|
||||
const absoluteElectronPath = process.execPath;
|
||||
const relativeElectronPath = path.relative(process.cwd(), absoluteElectronPath);
|
||||
const electronPath = absoluteElectronPath.length < relativeElectronPath.length
|
||||
? absoluteElectronPath
|
||||
: relativeElectronPath
|
||||
: relativeElectronPath;
|
||||
|
||||
const indexPath = path.resolve(app.getAppPath(), 'index.html')
|
||||
const indexPath = path.resolve(app.getAppPath(), 'index.html');
|
||||
|
||||
function isTrustedSender (webContents: Electron.WebContents) {
|
||||
if (webContents !== (mainWindow && mainWindow.webContents)) {
|
||||
return false
|
||||
return false;
|
||||
}
|
||||
|
||||
const parsedUrl = new URL(webContents.getURL())
|
||||
const parsedUrl = new URL(webContents.getURL());
|
||||
const urlPath = process.platform === 'win32'
|
||||
// Strip the prefixed "/" that occurs on windows
|
||||
? path.resolve(parsedUrl.pathname.substr(1))
|
||||
: parsedUrl.pathname
|
||||
return parsedUrl.protocol === 'file:' && urlPath === indexPath
|
||||
: parsedUrl.pathname;
|
||||
return parsedUrl.protocol === 'file:' && urlPath === indexPath;
|
||||
}
|
||||
|
||||
ipcMain.handle('bootstrap', (event) => {
|
||||
return isTrustedSender(event.sender) ? electronPath : null
|
||||
})
|
||||
return isTrustedSender(event.sender) ? electronPath : null;
|
||||
});
|
||||
|
||||
async function createWindow () {
|
||||
await app.whenReady()
|
||||
await app.whenReady();
|
||||
|
||||
const options: Electron.BrowserWindowConstructorOptions = {
|
||||
width: 900,
|
||||
@@ -57,46 +57,46 @@ async function createWindow () {
|
||||
},
|
||||
useContentSize: true,
|
||||
show: false
|
||||
}
|
||||
};
|
||||
|
||||
if (process.platform === 'linux') {
|
||||
options.icon = path.join(__dirname, 'icon.png')
|
||||
options.icon = path.join(__dirname, 'icon.png');
|
||||
}
|
||||
|
||||
mainWindow = new BrowserWindow(options)
|
||||
mainWindow.on('ready-to-show', () => mainWindow!.show())
|
||||
mainWindow = new BrowserWindow(options);
|
||||
mainWindow.on('ready-to-show', () => mainWindow!.show());
|
||||
|
||||
mainWindow.webContents.on('new-window', (event, url) => {
|
||||
event.preventDefault()
|
||||
shell.openExternal(decorateURL(url))
|
||||
})
|
||||
event.preventDefault();
|
||||
shell.openExternal(decorateURL(url));
|
||||
});
|
||||
|
||||
mainWindow.webContents.session.setPermissionRequestHandler((webContents, permission, done) => {
|
||||
const parsedUrl = new URL(webContents.getURL())
|
||||
const parsedUrl = new URL(webContents.getURL());
|
||||
|
||||
const options: Electron.MessageBoxOptions = {
|
||||
title: 'Permission Request',
|
||||
message: `Allow '${parsedUrl.origin}' to access '${permission}'?`,
|
||||
buttons: ['OK', 'Cancel'],
|
||||
cancelId: 1
|
||||
}
|
||||
};
|
||||
|
||||
dialog.showMessageBox(mainWindow!, options).then(({ response }) => {
|
||||
done(response === 0)
|
||||
})
|
||||
})
|
||||
done(response === 0);
|
||||
});
|
||||
});
|
||||
|
||||
return mainWindow
|
||||
return mainWindow;
|
||||
}
|
||||
|
||||
export const loadURL = async (appUrl: string) => {
|
||||
mainWindow = await createWindow()
|
||||
mainWindow.loadURL(appUrl)
|
||||
mainWindow.focus()
|
||||
}
|
||||
mainWindow = await createWindow();
|
||||
mainWindow.loadURL(appUrl);
|
||||
mainWindow.focus();
|
||||
};
|
||||
|
||||
export const loadFile = async (appPath: string) => {
|
||||
mainWindow = await createWindow()
|
||||
mainWindow.loadFile(appPath)
|
||||
mainWindow.focus()
|
||||
}
|
||||
mainWindow = await createWindow();
|
||||
mainWindow.loadFile(appPath);
|
||||
mainWindow.focus();
|
||||
};
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { app, dialog } from 'electron'
|
||||
import { app, dialog } from 'electron';
|
||||
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import * as url from 'url'
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as url from 'url';
|
||||
|
||||
type DefaultAppOptions = {
|
||||
file: null | string;
|
||||
@@ -14,10 +14,10 @@ type DefaultAppOptions = {
|
||||
modules: string[];
|
||||
}
|
||||
|
||||
const Module = require('module')
|
||||
const Module = require('module');
|
||||
|
||||
// Parse command line options.
|
||||
const argv = process.argv.slice(1)
|
||||
const argv = process.argv.slice(1);
|
||||
|
||||
const option: DefaultAppOptions = {
|
||||
file: null,
|
||||
@@ -27,50 +27,50 @@ const option: DefaultAppOptions = {
|
||||
interactive: false,
|
||||
abi: false,
|
||||
modules: []
|
||||
}
|
||||
};
|
||||
|
||||
let nextArgIsRequire = false
|
||||
let nextArgIsRequire = false;
|
||||
|
||||
for (const arg of argv) {
|
||||
if (nextArgIsRequire) {
|
||||
option.modules.push(arg)
|
||||
nextArgIsRequire = false
|
||||
continue
|
||||
option.modules.push(arg);
|
||||
nextArgIsRequire = false;
|
||||
continue;
|
||||
} else if (arg === '--version' || arg === '-v') {
|
||||
option.version = true
|
||||
break
|
||||
option.version = true;
|
||||
break;
|
||||
} else if (arg.match(/^--app=/)) {
|
||||
option.file = arg.split('=')[1]
|
||||
break
|
||||
option.file = arg.split('=')[1];
|
||||
break;
|
||||
} else if (arg === '--interactive' || arg === '-i' || arg === '-repl') {
|
||||
option.interactive = true
|
||||
option.interactive = true;
|
||||
} else if (arg === '--test-type=webdriver') {
|
||||
option.webdriver = true
|
||||
option.webdriver = true;
|
||||
} else if (arg === '--require' || arg === '-r') {
|
||||
nextArgIsRequire = true
|
||||
continue
|
||||
nextArgIsRequire = true;
|
||||
continue;
|
||||
} else if (arg === '--abi' || arg === '-a') {
|
||||
option.abi = true
|
||||
continue
|
||||
option.abi = true;
|
||||
continue;
|
||||
} else if (arg === '--no-help') {
|
||||
option.noHelp = true
|
||||
continue
|
||||
option.noHelp = true;
|
||||
continue;
|
||||
} else if (arg[0] === '-') {
|
||||
continue
|
||||
continue;
|
||||
} else {
|
||||
option.file = arg
|
||||
break
|
||||
option.file = arg;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (nextArgIsRequire) {
|
||||
console.error('Invalid Usage: --require [file]\n\n"file" is required')
|
||||
process.exit(1)
|
||||
console.error('Invalid Usage: --require [file]\n\n"file" is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Set up preload modules
|
||||
if (option.modules.length > 0) {
|
||||
Module._preloadModules(option.modules)
|
||||
Module._preloadModules(option.modules);
|
||||
}
|
||||
|
||||
function loadApplicationPackage (packagePath: string) {
|
||||
@@ -79,102 +79,102 @@ function loadApplicationPackage (packagePath: string) {
|
||||
configurable: false,
|
||||
enumerable: true,
|
||||
value: true
|
||||
})
|
||||
});
|
||||
|
||||
try {
|
||||
// Override app name and version.
|
||||
packagePath = path.resolve(packagePath)
|
||||
const packageJsonPath = path.join(packagePath, 'package.json')
|
||||
let appPath
|
||||
packagePath = path.resolve(packagePath);
|
||||
const packageJsonPath = path.join(packagePath, 'package.json');
|
||||
let appPath;
|
||||
if (fs.existsSync(packageJsonPath)) {
|
||||
let packageJson
|
||||
let packageJson;
|
||||
try {
|
||||
packageJson = require(packageJsonPath)
|
||||
packageJson = require(packageJsonPath);
|
||||
} catch (e) {
|
||||
showErrorMessage(`Unable to parse ${packageJsonPath}\n\n${e.message}`)
|
||||
return
|
||||
showErrorMessage(`Unable to parse ${packageJsonPath}\n\n${e.message}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (packageJson.version) {
|
||||
app.setVersion(packageJson.version)
|
||||
app.setVersion(packageJson.version);
|
||||
}
|
||||
if (packageJson.productName) {
|
||||
app.name = packageJson.productName
|
||||
app.name = packageJson.productName;
|
||||
} else if (packageJson.name) {
|
||||
app.name = packageJson.name
|
||||
app.name = packageJson.name;
|
||||
}
|
||||
appPath = packagePath
|
||||
appPath = packagePath;
|
||||
}
|
||||
|
||||
try {
|
||||
const filePath = Module._resolveFilename(packagePath, module, true)
|
||||
app._setDefaultAppPaths(appPath || path.dirname(filePath))
|
||||
const filePath = Module._resolveFilename(packagePath, module, true);
|
||||
app._setDefaultAppPaths(appPath || path.dirname(filePath));
|
||||
} catch (e) {
|
||||
showErrorMessage(`Unable to find Electron app at ${packagePath}\n\n${e.message}`)
|
||||
return
|
||||
showErrorMessage(`Unable to find Electron app at ${packagePath}\n\n${e.message}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Run the app.
|
||||
Module._load(packagePath, module, true)
|
||||
Module._load(packagePath, module, true);
|
||||
} catch (e) {
|
||||
console.error('App threw an error during load')
|
||||
console.error(e.stack || e)
|
||||
throw e
|
||||
console.error('App threw an error during load');
|
||||
console.error(e.stack || e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
function showErrorMessage (message: string) {
|
||||
app.focus()
|
||||
dialog.showErrorBox('Error launching app', message)
|
||||
process.exit(1)
|
||||
app.focus();
|
||||
dialog.showErrorBox('Error launching app', message);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
async function loadApplicationByURL (appUrl: string) {
|
||||
const { loadURL } = await import('./default_app')
|
||||
loadURL(appUrl)
|
||||
const { loadURL } = await import('./default_app');
|
||||
loadURL(appUrl);
|
||||
}
|
||||
|
||||
async function loadApplicationByFile (appPath: string) {
|
||||
const { loadFile } = await import('./default_app')
|
||||
loadFile(appPath)
|
||||
const { loadFile } = await import('./default_app');
|
||||
loadFile(appPath);
|
||||
}
|
||||
|
||||
function startRepl () {
|
||||
if (process.platform === 'win32') {
|
||||
console.error('Electron REPL not currently supported on Windows')
|
||||
process.exit(1)
|
||||
console.error('Electron REPL not currently supported on Windows');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// prevent quitting
|
||||
app.on('window-all-closed', () => {})
|
||||
app.on('window-all-closed', () => {});
|
||||
|
||||
const repl = require('repl')
|
||||
const repl = require('repl');
|
||||
repl.start('> ').on('exit', () => {
|
||||
process.exit(0)
|
||||
})
|
||||
process.exit(0);
|
||||
});
|
||||
}
|
||||
|
||||
// Start the specified app if there is one specified in command line, otherwise
|
||||
// start the default app.
|
||||
if (option.file && !option.webdriver) {
|
||||
const file = option.file
|
||||
const protocol = url.parse(file).protocol
|
||||
const extension = path.extname(file)
|
||||
const file = option.file;
|
||||
const protocol = url.parse(file).protocol;
|
||||
const extension = path.extname(file);
|
||||
if (protocol === 'http:' || protocol === 'https:' || protocol === 'file:' || protocol === 'chrome:') {
|
||||
loadApplicationByURL(file)
|
||||
loadApplicationByURL(file);
|
||||
} else if (extension === '.html' || extension === '.htm') {
|
||||
loadApplicationByFile(path.resolve(file))
|
||||
loadApplicationByFile(path.resolve(file));
|
||||
} else {
|
||||
loadApplicationPackage(file)
|
||||
loadApplicationPackage(file);
|
||||
}
|
||||
} else if (option.version) {
|
||||
console.log('v' + process.versions.electron)
|
||||
process.exit(0)
|
||||
console.log('v' + process.versions.electron);
|
||||
process.exit(0);
|
||||
} else if (option.abi) {
|
||||
console.log(process.versions.modules)
|
||||
process.exit(0)
|
||||
console.log(process.versions.modules);
|
||||
process.exit(0);
|
||||
} else if (option.interactive) {
|
||||
startRepl()
|
||||
startRepl();
|
||||
} else {
|
||||
if (!option.noHelp) {
|
||||
const welcomeMessage = `
|
||||
@@ -192,10 +192,10 @@ Options:
|
||||
-i, --interactive Open a REPL to the main process.
|
||||
-r, --require Module to preload (option can be repeated).
|
||||
-v, --version Print the version.
|
||||
-a, --abi Print the Node ABI version.`
|
||||
-a, --abi Print the Node ABI version.`;
|
||||
|
||||
console.log(welcomeMessage)
|
||||
console.log(welcomeMessage);
|
||||
}
|
||||
|
||||
loadApplicationByFile('index.html')
|
||||
loadApplicationByFile('index.html');
|
||||
}
|
||||
|
||||
@@ -1,53 +1,53 @@
|
||||
import { ipcRenderer, contextBridge } from 'electron'
|
||||
import { ipcRenderer, contextBridge } from 'electron';
|
||||
|
||||
async function getOcticonSvg (name: string) {
|
||||
try {
|
||||
const response = await fetch(`octicon/${name}.svg`)
|
||||
const div = document.createElement('div')
|
||||
div.innerHTML = await response.text()
|
||||
return div
|
||||
const response = await fetch(`octicon/${name}.svg`);
|
||||
const div = document.createElement('div');
|
||||
div.innerHTML = await response.text();
|
||||
return div;
|
||||
} catch {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadSVG (element: HTMLSpanElement) {
|
||||
for (const cssClass of element.classList) {
|
||||
if (cssClass.startsWith('octicon-')) {
|
||||
const icon = await getOcticonSvg(cssClass.substr(8))
|
||||
const icon = await getOcticonSvg(cssClass.substr(8));
|
||||
if (icon) {
|
||||
for (const elemClass of element.classList) {
|
||||
icon.classList.add(elemClass)
|
||||
icon.classList.add(elemClass);
|
||||
}
|
||||
element.before(icon)
|
||||
element.remove()
|
||||
break
|
||||
element.before(icon);
|
||||
element.remove();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function initialize () {
|
||||
const electronPath = await ipcRenderer.invoke('bootstrap')
|
||||
const electronPath = await ipcRenderer.invoke('bootstrap');
|
||||
|
||||
function replaceText (selector: string, text: string) {
|
||||
const element = document.querySelector<HTMLElement>(selector)
|
||||
const element = document.querySelector<HTMLElement>(selector);
|
||||
if (element) {
|
||||
element.innerText = text
|
||||
element.innerText = text;
|
||||
}
|
||||
}
|
||||
|
||||
replaceText('.electron-version', `Electron v${process.versions.electron}`)
|
||||
replaceText('.chrome-version', `Chromium v${process.versions.chrome}`)
|
||||
replaceText('.node-version', `Node v${process.versions.node}`)
|
||||
replaceText('.v8-version', `v8 v${process.versions.v8}`)
|
||||
replaceText('.command-example', `${electronPath} path-to-app`)
|
||||
replaceText('.electron-version', `Electron v${process.versions.electron}`);
|
||||
replaceText('.chrome-version', `Chromium v${process.versions.chrome}`);
|
||||
replaceText('.node-version', `Node v${process.versions.node}`);
|
||||
replaceText('.v8-version', `v8 v${process.versions.v8}`);
|
||||
replaceText('.command-example', `${electronPath} path-to-app`);
|
||||
|
||||
for (const element of document.querySelectorAll<HTMLSpanElement>('.octicon')) {
|
||||
loadSVG(element)
|
||||
loadSVG(element);
|
||||
}
|
||||
}
|
||||
|
||||
contextBridge.exposeInMainWorld('electronDefaultApp', {
|
||||
initialize
|
||||
})
|
||||
});
|
||||
|
||||
@@ -54,7 +54,7 @@ The `Super` key is mapped to the `Windows` key on Windows and Linux and
|
||||
* `0` to `9`
|
||||
* `A` to `Z`
|
||||
* `F1` to `F24`
|
||||
* Punctuations like `~`, `!`, `@`, `#`, `$`, etc.
|
||||
* Punctuation like `~`, `!`, `@`, `#`, `$`, etc.
|
||||
* `Plus`
|
||||
* `Space`
|
||||
* `Tab`
|
||||
|
||||
@@ -75,7 +75,7 @@ Returns:
|
||||
* `event` Event
|
||||
|
||||
Emitted when all windows have been closed and the application will quit.
|
||||
Calling `event.preventDefault()` will prevent the default behaviour, which is
|
||||
Calling `event.preventDefault()` will prevent the default behavior, which is
|
||||
terminating the application.
|
||||
|
||||
See the description of the `window-all-closed` event for the differences between
|
||||
@@ -204,7 +204,7 @@ Returns:
|
||||
[`NSUserActivity.activityType`][activity-type].
|
||||
* `userInfo` unknown - Contains app-specific state stored by the activity.
|
||||
|
||||
Emitted when [Handoff][handoff] is about to be resumed on another device. If you need to update the state to be transferred, you should call `event.preventDefault()` immediately, construct a new `userInfo` dictionary and call `app.updateCurrentActiviy()` in a timely manner. Otherwise, the operation will fail and `continue-activity-error` will be called.
|
||||
Emitted when [Handoff][handoff] is about to be resumed on another device. If you need to update the state to be transferred, you should call `event.preventDefault()` immediately, construct a new `userInfo` dictionary and call `app.updateCurrentActivity()` in a timely manner. Otherwise, the operation will fail and `continue-activity-error` will be called.
|
||||
|
||||
### Event: 'new-window-for-tab' _macOS_
|
||||
|
||||
@@ -659,8 +659,6 @@ to the npm modules spec. You should usually also specify a `productName`
|
||||
field, which is your application's full capitalized name, and which will be
|
||||
preferred over `name` by Electron.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
### `app.setName(name)`
|
||||
|
||||
* `name` String
|
||||
@@ -669,8 +667,6 @@ Overrides the current application's name.
|
||||
|
||||
**Note:** This function overrides the name used internally by Electron; it does not affect the name that the OS uses.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
### `app.getLocale()`
|
||||
|
||||
Returns `String` - The current application locale. Possible return values are documented [here](locales.md).
|
||||
@@ -703,34 +699,34 @@ Clears the recent documents list.
|
||||
|
||||
### `app.setAsDefaultProtocolClient(protocol[, path, args])`
|
||||
|
||||
* `protocol` String - The name of your protocol, without `://`. If you want your
|
||||
app to handle `electron://` links, call this method with `electron` as the
|
||||
parameter.
|
||||
* `path` String (optional) _Windows_ - Defaults to `process.execPath`
|
||||
* `args` String[] (optional) _Windows_ - Defaults to an empty array
|
||||
* `protocol` String - The name of your protocol, without `://`. For example,
|
||||
if you want your app to handle `electron://` links, call this method with
|
||||
`electron` as the parameter.
|
||||
* `path` String (optional) _Windows_ - The path to the Electron executable.
|
||||
Defaults to `process.execPath`
|
||||
* `args` String[] (optional) _Windows_ - Arguments passed to the executable.
|
||||
Defaults to an empty array
|
||||
|
||||
Returns `Boolean` - Whether the call succeeded.
|
||||
|
||||
This method sets the current executable as the default handler for a protocol
|
||||
(aka URI scheme). It allows you to integrate your app deeper into the operating
|
||||
system. Once registered, all links with `your-protocol://` will be opened with
|
||||
the current executable. The whole link, including protocol, will be passed to
|
||||
your application as a parameter.
|
||||
|
||||
On Windows, you can provide optional parameters path, the path to your executable,
|
||||
and args, an array of arguments to be passed to your executable when it launches.
|
||||
Sets the current executable as the default handler for a protocol (aka URI
|
||||
scheme). It allows you to integrate your app deeper into the operating system.
|
||||
Once registered, all links with `your-protocol://` will be opened with the
|
||||
current executable. The whole link, including protocol, will be passed to your
|
||||
application as a parameter.
|
||||
|
||||
**Note:** On macOS, you can only register protocols that have been added to
|
||||
your app's `info.plist`, which can not be modified at runtime. You can however
|
||||
change the file with a simple text editor or script during build time.
|
||||
Please refer to [Apple's documentation][CFBundleURLTypes] for details.
|
||||
your app's `info.plist`, which cannot be modified at runtime. However, you can
|
||||
change the file during build time via [Electron Forge][electron-forge],
|
||||
[Electron Packager][electron-packager], or by editing `info.plist` with a text
|
||||
editor. Please refer to [Apple's documentation][CFBundleURLTypes] for details.
|
||||
|
||||
**Note:** In a Windows Store environment (when packaged as an `appx`) this API
|
||||
will return `true` for all calls but the registry key it sets won't be accessible
|
||||
by other applications. In order to register your Windows Store application
|
||||
as a default protocol handler you must [declare the protocol in your manifest](https://docs.microsoft.com/en-us/uwp/schemas/appxpackage/uapmanifestschema/element-uap-protocol).
|
||||
|
||||
The API uses the Windows Registry and LSSetDefaultHandlerForURLScheme internally.
|
||||
The API uses the Windows Registry and `LSSetDefaultHandlerForURLScheme` internally.
|
||||
|
||||
### `app.removeAsDefaultProtocolClient(protocol[, path, args])` _macOS_ _Windows_
|
||||
|
||||
@@ -749,10 +745,8 @@ protocol (aka URI scheme). If so, it will remove the app as the default handler.
|
||||
* `path` String (optional) _Windows_ - Defaults to `process.execPath`
|
||||
* `args` String[] (optional) _Windows_ - Defaults to an empty array
|
||||
|
||||
Returns `Boolean`
|
||||
|
||||
This method checks if the current executable is the default handler for a protocol
|
||||
(aka URI scheme). If so, it will return true. Otherwise, it will return false.
|
||||
Returns `Boolean` - Whether the current executable is the default handler for a
|
||||
protocol (aka URI scheme).
|
||||
|
||||
**Note:** On macOS, you can use this method to check if the app has been
|
||||
registered as the default protocol handler for a protocol. You can also verify
|
||||
@@ -760,7 +754,7 @@ this by checking `~/Library/Preferences/com.apple.LaunchServices.plist` on the
|
||||
macOS machine. Please refer to
|
||||
[Apple's documentation][LSCopyDefaultHandlerForURLScheme] for details.
|
||||
|
||||
The API uses the Windows Registry and LSCopyDefaultHandlerForURLScheme internally.
|
||||
The API uses the Windows Registry and `LSCopyDefaultHandlerForURLScheme` internally.
|
||||
|
||||
### `app.getApplicationNameForProtocol(url)`
|
||||
|
||||
@@ -1027,7 +1021,7 @@ This method can only be called before app is ready.
|
||||
|
||||
By default, Chromium disables 3D APIs (e.g. WebGL) until restart on a per
|
||||
domain basis if the GPU processes crashes too frequently. This function
|
||||
disables that behaviour.
|
||||
disables that behavior.
|
||||
|
||||
This method can only be called before app is ready.
|
||||
|
||||
@@ -1091,14 +1085,10 @@ On macOS, it shows on the dock icon. On Linux, it only works for Unity launcher.
|
||||
**Note:** Unity launcher requires the existence of a `.desktop` file to work,
|
||||
for more information please read [Desktop Environment Integration][unity-requirement].
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
### `app.getBadgeCount()` _Linux_ _macOS_
|
||||
|
||||
Returns `Integer` - The current value displayed in the counter badge.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
### `app.isUnityRunning()` _Linux_
|
||||
|
||||
Returns `Boolean` - Whether the current desktop environment is Unity launcher.
|
||||
@@ -1173,8 +1163,6 @@ technologies, such as screen readers, has been detected. See
|
||||
https://www.chromium.org/developers/design-documents/accessibility for more
|
||||
details.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
### `app.setAccessibilitySupportEnabled(enabled)` _macOS_ _Windows_
|
||||
|
||||
* `enabled` Boolean - Enable or disable [accessibility tree](https://developers.google.com/web/fundamentals/accessibility/semantics-builtin/the-accessibility-tree) rendering
|
||||
@@ -1186,8 +1174,6 @@ This API must be called after the `ready` event is emitted.
|
||||
|
||||
**Note:** Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
### `app.showAboutPanel()`
|
||||
|
||||
Show the app's about panel options. These options can be overridden with `app.setAboutPanelOptions(options)`.
|
||||
@@ -1204,7 +1190,7 @@ Show the app's about panel options. These options can be overridden with `app.se
|
||||
* `website` String (optional) _Linux_ - The app's website.
|
||||
* `iconPath` String (optional) _Linux_ _Windows_ - Path to the app's icon. On Linux, will be shown as 64x64 pixels while retaining aspect ratio.
|
||||
|
||||
Set the about panel options. This will override the values defined in the app's `.plist` file on MacOS. See the [Apple docs][about-panel-options] for more details. On Linux, values must be set in order to be shown; there are no defaults.
|
||||
Set the about panel options. This will override the values defined in the app's `.plist` file on macOS. See the [Apple docs][about-panel-options] for more details. On Linux, values must be set in order to be shown; there are no defaults.
|
||||
|
||||
If you do not set `credits` but still wish to surface them in your app, AppKit will look for a file named "Credits.html", "Credits.rtf", and "Credits.rtfd", in that order, in the bundle returned by the NSBundle class method main. The first file found is used, and if none is found, the info area is left blank. See Apple [documentation](https://developer.apple.com/documentation/appkit/nsaboutpaneloptioncredits?language=objc) for more information.
|
||||
|
||||
@@ -1327,6 +1313,8 @@ A `Boolean` property that returns `true` if the app is packaged, `false` otherw
|
||||
[dock-menu]:https://developer.apple.com/macos/human-interface-guidelines/menus/dock-menus/
|
||||
[tasks]:https://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks
|
||||
[app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx
|
||||
[electron-forge]: https://www.electronforge.io/
|
||||
[electron-packager]: https://github.com/electron/electron-packager
|
||||
[CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115
|
||||
[LSCopyDefaultHandlerForURLScheme]: https://developer.apple.com/library/mac/documentation/Carbon/Reference/LaunchServicesReference/#//apple_ref/c/func/LSCopyDefaultHandlerForURLScheme
|
||||
[handoff]: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html
|
||||
|
||||
@@ -177,7 +177,7 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
|
||||
* `simpleFullscreen` Boolean (optional) - Use pre-Lion fullscreen on macOS. Default is `false`.
|
||||
* `skipTaskbar` Boolean (optional) - Whether to show the window in taskbar. Default is
|
||||
`false`.
|
||||
* `kiosk` Boolean (optional) - The kiosk mode. Default is `false`.
|
||||
* `kiosk` Boolean (optional) - Whether the window is in kiosk mode. Default is `false`.
|
||||
* `title` String (optional) - Default window title. Default is `"Electron"`. If the HTML tag `<title>` is defined in the HTML file loaded by `loadURL()`, this property will be ignored.
|
||||
* `icon` ([NativeImage](native-image.md) | String) (optional) - The window icon. On Windows it is
|
||||
recommended to use `ICO` icons to get best visual effects, you can also
|
||||
@@ -207,7 +207,7 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
|
||||
* `opacity` Number (optional) - Set the initial opacity of the window, between 0.0 (fully
|
||||
transparent) and 1.0 (fully opaque). This is only implemented on Windows and macOS.
|
||||
* `darkTheme` Boolean (optional) - Forces using dark theme for the window, only works on
|
||||
some GTK+3 desktop environments. Default is `false`.
|
||||
some GTK desktop environments. Default is `false`.
|
||||
* `transparent` Boolean (optional) - Makes the window [transparent](frameless-window.md#transparent-window).
|
||||
Default is `false`. On Windows, does not work unless the window is frameless.
|
||||
* `type` String (optional) - The type of window, default is normal window. See more about
|
||||
@@ -289,7 +289,7 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
|
||||
between the web pages even when you specified different values for them,
|
||||
including but not limited to `preload`, `sandbox` and `nodeIntegration`.
|
||||
So it is suggested to use exact same `webPreferences` for web pages with
|
||||
the same `affinity`. _This property is experimental_
|
||||
the same `affinity`. _Deprecated_
|
||||
* `zoomFactor` Number (optional) - The default zoom factor of the page, `3.0` represents
|
||||
`300%`. Default is `1.0`.
|
||||
* `javascript` Boolean (optional) - Enables JavaScript support. Default is `true`.
|
||||
@@ -369,6 +369,8 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
|
||||
consecutive dialog protection is triggered. If not defined the default
|
||||
message would be used, note that currently the default message is in
|
||||
English and not localized.
|
||||
* `disableDialogs` Boolean (optional) - Whether to disable dialogs
|
||||
completely. Overrides `safeDialogs`. Default is `false`.
|
||||
* `navigateOnDragDrop` Boolean (optional) - Whether dragging and dropping a
|
||||
file or link onto the page causes a navigation. Default is `false`.
|
||||
* `autoplayPolicy` String (optional) - Autoplay policy to apply to
|
||||
@@ -621,6 +623,12 @@ Returns:
|
||||
|
||||
Emitted on 3-finger swipe. Possible directions are `up`, `right`, `down`, `left`.
|
||||
|
||||
The method underlying this event is built to handle older macOS-style trackpad swiping,
|
||||
where the content on the screen doesn't move with the swipe. Most macOS trackpads are not
|
||||
configured to allow this kind of swiping anymore, so in order for it to emit properly the
|
||||
'Swipe between pages' preference in `System Preferences > Trackpad > More Gestures` must be
|
||||
set to 'Swipe with two or three fingers'.
|
||||
|
||||
#### Event: 'rotate-gesture' _macOS_
|
||||
|
||||
Returns:
|
||||
@@ -795,6 +803,51 @@ A `Boolean` property that determines whether the window menu bar should hide its
|
||||
If the menu bar is already visible, setting this property to `true` won't
|
||||
hide it immediately.
|
||||
|
||||
#### `win.simpleFullScreen`
|
||||
|
||||
A `Boolean` property that determines whether the window is in simple (pre-Lion) fullscreen mode.
|
||||
|
||||
#### `win.fullScreen`
|
||||
|
||||
A `Boolean` property that determines whether the window is in fullscreen mode.
|
||||
|
||||
#### `win.visibleOnAllWorkspaces`
|
||||
|
||||
A `Boolean` property that determines whether the window is visible on all workspaces.
|
||||
|
||||
**Note:** Always returns false on Windows.
|
||||
|
||||
#### `win.shadow`
|
||||
|
||||
A `Boolean` property that determines whether the window has a shadow.
|
||||
|
||||
#### `win.menuBarVisible` _Windows_ _Linux_
|
||||
|
||||
A `Boolean` property that determines whether the menu bar should be visible.
|
||||
|
||||
**Note:** If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key.
|
||||
|
||||
#### `win.kiosk`
|
||||
|
||||
A `Boolean` property that determines whether the window is in kiosk mode.
|
||||
|
||||
#### `win.documentEdited` _macOS_
|
||||
|
||||
A `Boolean` property that specifies whether the window’s document has been edited.
|
||||
|
||||
The icon in title bar will become gray when set to `true`.
|
||||
|
||||
#### `win.representedFilename` _macOS_
|
||||
|
||||
A `String` property that determines the pathname of the file the window represents,
|
||||
and the icon of the file will show in window's title bar.
|
||||
|
||||
#### `win.title`
|
||||
|
||||
A `String` property that determines the title of the native window.
|
||||
|
||||
**Note:** The title of the web page can be different from the title of the native window.
|
||||
|
||||
#### `win.minimizable`
|
||||
|
||||
A `Boolean` property that determines whether the window can be manually minimized by user.
|
||||
@@ -950,7 +1003,7 @@ Returns `Boolean` - Whether the window is in fullscreen mode.
|
||||
|
||||
Enters or leaves simple fullscreen mode.
|
||||
|
||||
Simple fullscreen mode emulates the native fullscreen behavior found in versions of Mac OS X prior to Lion (10.7).
|
||||
Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7).
|
||||
|
||||
#### `win.isSimpleFullScreen()` _macOS_
|
||||
|
||||
@@ -1113,15 +1166,11 @@ Returns `Integer[]` - Contains the window's maximum width and height.
|
||||
|
||||
* `resizable` Boolean
|
||||
|
||||
Sets whether the window can be manually resized by user.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
Sets whether the window can be manually resized by the user.
|
||||
|
||||
#### `win.isResizable()`
|
||||
|
||||
Returns `Boolean` - Whether the window can be manually resized by user.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
Returns `Boolean` - Whether the window can be manually resized by the user.
|
||||
|
||||
#### `win.setMovable(movable)` _macOS_ _Windows_
|
||||
|
||||
@@ -1129,41 +1178,29 @@ Returns `Boolean` - Whether the window can be manually resized by user.
|
||||
|
||||
Sets whether the window can be moved by user. On Linux does nothing.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `win.isMovable()` _macOS_ _Windows_
|
||||
|
||||
Returns `Boolean` - Whether the window can be moved by user.
|
||||
|
||||
On Linux always returns `true`.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `win.setMinimizable(minimizable)` _macOS_ _Windows_
|
||||
|
||||
* `minimizable` Boolean
|
||||
|
||||
Sets whether the window can be manually minimized by user. On Linux does
|
||||
nothing.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
Sets whether the window can be manually minimized by user. On Linux does nothing.
|
||||
|
||||
#### `win.isMinimizable()` _macOS_ _Windows_
|
||||
|
||||
Returns `Boolean` - Whether the window can be manually minimized by user
|
||||
Returns `Boolean` - Whether the window can be manually minimized by the user.
|
||||
|
||||
On Linux always returns `true`.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `win.setMaximizable(maximizable)` _macOS_ _Windows_
|
||||
|
||||
* `maximizable` Boolean
|
||||
|
||||
Sets whether the window can be manually maximized by user. On Linux does
|
||||
nothing.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
Sets whether the window can be manually maximized by user. On Linux does nothing.
|
||||
|
||||
#### `win.isMaximizable()` _macOS_ _Windows_
|
||||
|
||||
@@ -1171,23 +1208,15 @@ Returns `Boolean` - Whether the window can be manually maximized by user.
|
||||
|
||||
On Linux always returns `true`.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `win.setFullScreenable(fullscreenable)`
|
||||
|
||||
* `fullscreenable` Boolean
|
||||
|
||||
Sets whether the maximize/zoom window button toggles fullscreen mode or
|
||||
maximizes the window.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.
|
||||
|
||||
#### `win.isFullScreenable()`
|
||||
|
||||
Returns `Boolean` - Whether the maximize/zoom window button toggles fullscreen mode or
|
||||
maximizes the window.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
Returns `Boolean` - Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.
|
||||
|
||||
#### `win.setClosable(closable)` _macOS_ _Windows_
|
||||
|
||||
@@ -1195,16 +1224,12 @@ maximizes the window.
|
||||
|
||||
Sets whether the window can be manually closed by user. On Linux does nothing.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `win.isClosable()` _macOS_ _Windows_
|
||||
|
||||
Returns `Boolean` - Whether the window can be manually closed by user.
|
||||
|
||||
On Linux always returns `true`.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `win.setAlwaysOnTop(flag[, level][, relativeLevel])`
|
||||
|
||||
* `flag` Boolean
|
||||
@@ -1302,7 +1327,7 @@ Makes the window not show in the taskbar.
|
||||
|
||||
* `flag` Boolean
|
||||
|
||||
Enters or leaves the kiosk mode.
|
||||
Enters or leaves kiosk mode.
|
||||
|
||||
#### `win.isKiosk()`
|
||||
|
||||
@@ -1616,23 +1641,17 @@ This cannot be called when `titleBarStyle` is set to `customButtonsOnHover`.
|
||||
Sets whether the window menu bar should hide itself automatically. Once set the
|
||||
menu bar will only show when users press the single `Alt` key.
|
||||
|
||||
If the menu bar is already visible, calling `setAutoHideMenuBar(true)` won't
|
||||
hide it immediately.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
If the menu bar is already visible, calling `setAutoHideMenuBar(true)` won't hide it immediately.
|
||||
|
||||
#### `win.isMenuBarAutoHide()`
|
||||
|
||||
Returns `Boolean` - Whether menu bar automatically hides itself.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_
|
||||
|
||||
* `visible` Boolean
|
||||
|
||||
Sets whether the menu bar should be visible. If the menu bar is auto-hide, users
|
||||
can still bring up the menu bar by pressing the single `Alt` key.
|
||||
Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key.
|
||||
|
||||
#### `win.isMenuBarVisible()`
|
||||
|
||||
@@ -1748,6 +1767,17 @@ 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_
|
||||
|
||||
* `position` [Point](structures/point.md)
|
||||
|
||||
Set a custom position for the traffic light buttons. Can only be used with `titleBarStyle` set to `hidden`.
|
||||
|
||||
#### `win.getTrafficLightPosition()` _macOS_
|
||||
|
||||
Returns `Point` - The current position for the traffic light buttons. Can only be used with `titleBarStyle`
|
||||
set to `hidden`.
|
||||
|
||||
#### `win.setTouchBar(touchBar)` _macOS_ _Experimental_
|
||||
|
||||
* `touchBar` TouchBar | null
|
||||
|
||||
@@ -22,6 +22,9 @@ which the request is associated.
|
||||
with which the request is associated. Defaults to the empty string. The
|
||||
`session` option prevails on `partition`. Thus if a `session` is explicitly
|
||||
specified, `partition` is ignored.
|
||||
* `useSessionCookies` Boolean (optional) - Whether to send cookies with this
|
||||
request from the provided session. This will make the `net` request's
|
||||
cookie behavior match a `fetch` request. Default is `false`.
|
||||
* `protocol` String (optional) - The protocol scheme in the form 'scheme:'.
|
||||
Currently supported values are 'http:' or 'https:'. Defaults to 'http:'.
|
||||
* `host` String (optional) - The server host provided as a concatenation of
|
||||
|
||||
@@ -269,6 +269,7 @@ Shows a message box, it will block the process until the message box is closed.
|
||||
It returns the index of the clicked button.
|
||||
|
||||
The `browserWindow` argument allows the dialog to attach itself to a parent window, making it modal.
|
||||
If `browserWindow` is not shown dialog will not be attached to it. In such case It will be displayed as independed window.
|
||||
|
||||
### `dialog.showMessageBox([browserWindow, ]options)`
|
||||
|
||||
|
||||
@@ -82,16 +82,12 @@ The API is only available in session's `will-download` callback function.
|
||||
If user doesn't set the save path via the API, Electron will use the original
|
||||
routine to determine the save path; this usually prompts a save dialog.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md): use the `savePath` property instead.**
|
||||
|
||||
#### `downloadItem.getSavePath()`
|
||||
|
||||
Returns `String` - The save path of the download item. This will be either the path
|
||||
set via `downloadItem.setSavePath(path)` or the path selected from the shown
|
||||
save dialog.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md): use the `savePath` property instead.**
|
||||
|
||||
#### `downloadItem.setSaveDialogOptions(options)`
|
||||
|
||||
* `options` SaveDialogOptions - Set the save file dialog options. This object has the same
|
||||
|
||||
@@ -53,16 +53,23 @@ Unsupported options are:
|
||||
|
||||
### `GOOGLE_API_KEY`
|
||||
|
||||
You can provide an API key for making requests to Google's geocoding webservice. To do this, place the following code in your main process
|
||||
file, before opening any browser windows that will make geocoding requests:
|
||||
Geolocation support in Electron requires the use of Google Cloud Platform's
|
||||
geolocation webservice. To enable this feature, acquire a
|
||||
[Google API key](https://developers.google.com/maps/documentation/geolocation/get-api-key)
|
||||
and place the following code in your main process file, before opening any
|
||||
browser windows that will make geolocation requests:
|
||||
|
||||
```javascript
|
||||
process.env.GOOGLE_API_KEY = 'YOUR_KEY_HERE'
|
||||
```
|
||||
|
||||
For instructions on how to acquire a Google API key, visit [this page](https://developers.google.com/maps/documentation/javascript/get-api-key).
|
||||
By default, a newly generated Google API key may not be allowed to make
|
||||
geocoding requests. To enable geocoding requests, visit [this page](https://developers.google.com/maps/documentation/geocoding/get-api-key).
|
||||
By default, a newly generated Google API key may not be allowed to make geolocation requests.
|
||||
To enable the geolocation webservice for your project, enable it through the
|
||||
[API library](https://console.cloud.google.com/apis/library).
|
||||
|
||||
N.B. You will need to add a
|
||||
[Billing Account](https://cloud.google.com/billing/docs/how-to/payment-methods#add_a_payment_method)
|
||||
to the project associated to the API key for the geolocation webservice to work.
|
||||
|
||||
### `ELECTRON_NO_ASAR`
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ win.show()
|
||||
Uses custom drawn close, and miniaturize buttons that display
|
||||
when hovering in the top left of the window. The fullscreen button
|
||||
is not available due to restrictions of frameless windows as they
|
||||
interface with Apple's MacOS window masks. These custom buttons prevent
|
||||
interface with Apple's macOS window masks. These custom buttons prevent
|
||||
issues with mouse events that occur with the standard window toolbar buttons.
|
||||
This option is only applicable for frameless windows.
|
||||
|
||||
@@ -158,7 +158,7 @@ buttons in titlebar non-draggable.
|
||||
|
||||
## Text selection
|
||||
|
||||
In a frameless window the dragging behaviour may conflict with selecting text.
|
||||
In a frameless window the dragging behavior may conflict with selecting text.
|
||||
For example, when you drag the titlebar you may accidentally select the text on
|
||||
the titlebar. To prevent this, you need to disable text selection within a
|
||||
draggable area like this:
|
||||
|
||||
@@ -14,7 +14,7 @@ See [`Menu`](menu.md) for examples.
|
||||
* `menuItem` MenuItem
|
||||
* `browserWindow` [BrowserWindow](browser-window.md)
|
||||
* `event` [KeyboardEvent](structures/keyboard-event.md)
|
||||
* `role` String (optional) - Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `reload`, `forceReload`, `toggleDevTools`, `resetZoom`, `zoomIn`, `zoomOut`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`, `startSpeaking`, `stopSpeaking`, `minimize`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu`, `recentDocuments`, `toggleTabBar`, `selectNextTab`, `selectPreviousTab`, `mergeAllWindows`, `clearRecentDocuments`, `moveTabToNewWindow` or `windowMenu` - Define the action of the menu item, when specified the
|
||||
* `role` String (optional) - Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `reload`, `forceReload`, `toggleDevTools`, `resetZoom`, `zoomIn`, `zoomOut`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`, `startSpeaking`, `stopSpeaking`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu`, `recentDocuments`, `toggleTabBar`, `selectNextTab`, `selectPreviousTab`, `mergeAllWindows`, `clearRecentDocuments`, `moveTabToNewWindow` or `windowMenu` - Define the action of the menu item, when specified the
|
||||
`click` property will be ignored. See [roles](#roles).
|
||||
* `type` String (optional) - Can be `normal`, `separator`, `submenu`, `checkbox` or
|
||||
`radio`.
|
||||
@@ -117,7 +117,7 @@ When specifying a `role` on macOS, `label` and `accelerator` are the only
|
||||
options that will affect the menu item. All other options will be ignored.
|
||||
Lowercase `role`, e.g. `toggledevtools`, is still supported.
|
||||
|
||||
**Nota Bene:** The `enabled` and `visibility` properties are not available for top-level menu items in the tray on MacOS.
|
||||
**Nota Bene:** The `enabled` and `visibility` properties are not available for top-level menu items in the tray on macOS.
|
||||
|
||||
### Instance Properties
|
||||
|
||||
@@ -151,7 +151,7 @@ A `String` indicating the type of the item. Can be `normal`, `separator`, `subme
|
||||
|
||||
#### `menuItem.role`
|
||||
|
||||
A `String` (optional) indicating the item's role, if set. Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `reload`, `forceReload`, `toggleDevTools`, `resetZoom`, `zoomIn`, `zoomOut`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`, `startSpeaking`, `stopSpeaking`, `close`, `minimize`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu`, `recentDocuments`, `toggleTabBar`, `selectNextTab`, `selectPreviousTab`, `mergeAllWindows`, `clearRecentDocuments`, `moveTabToNewWindow` or `windowMenu`
|
||||
A `String` (optional) indicating the item's role, if set. Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `reload`, `forceReload`, `toggleDevTools`, `resetZoom`, `zoomIn`, `zoomOut`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`, `startSpeaking`, `stopSpeaking`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu`, `recentDocuments`, `toggleTabBar`, `selectNextTab`, `selectPreviousTab`, `mergeAllWindows`, `clearRecentDocuments`, `moveTabToNewWindow` or `windowMenu`
|
||||
|
||||
#### `menuItem.accelerator`
|
||||
|
||||
|
||||
@@ -5,14 +5,7 @@ The Electron team is currently undergoing an initiative to convert separate gett
|
||||
## Candidates
|
||||
|
||||
* `BrowserWindow`
|
||||
* `fullscreen`
|
||||
* `simpleFullscreen`
|
||||
* `alwaysOnTop`
|
||||
* `title`
|
||||
* `documentEdited`
|
||||
* `hasShadow`
|
||||
* `menubarVisible`
|
||||
* `visibleOnAllWorkspaces`
|
||||
* `crashReporter` module
|
||||
* `uploadToServer`
|
||||
* `webFrame` modules
|
||||
@@ -45,9 +38,3 @@ The Electron team is currently undergoing an initiative to convert separate gett
|
||||
* `isMacTemplateImage`
|
||||
* `SystemPreferences` module
|
||||
* `appLevelAppearance`
|
||||
* `webContents` module
|
||||
* `audioMuted`
|
||||
* `frameRate`
|
||||
* `userAgent`
|
||||
* `zoomFactor`
|
||||
* `zoomLevel`
|
||||
|
||||
@@ -276,14 +276,10 @@ Returns [`Size`](structures/size.md)
|
||||
|
||||
Marks the image as a template image.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `image.isTemplateImage()`
|
||||
|
||||
Returns `Boolean` - Whether the image is a template image.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `image.crop(rect)`
|
||||
|
||||
* `rect` [Rectangle](structures/rectangle.md) - The area of the image to crop.
|
||||
|
||||
@@ -51,7 +51,7 @@ app.whenReady().then(() => {
|
||||
|
||||
In the above code the [`BrowserWindow`](browser-window.md) that was created has Node.js disabled and can communicate
|
||||
only via IPC. The use of this option stops Electron from creating a Node.js runtime in the renderer. Also,
|
||||
within this new window `window.open` follows the native behaviour (by default Electron creates a [`BrowserWindow`](browser-window.md)
|
||||
within this new window `window.open` follows the native behavior (by default Electron creates a [`BrowserWindow`](browser-window.md)
|
||||
and returns a proxy to this via `window.open`).
|
||||
|
||||
[`app.enableSandbox`](app.md#appenablesandbox-experimental) can be used to force `sandbox: true` for all `BrowserWindow` instances.
|
||||
|
||||
62
docs/api/service-workers.md
Normal file
62
docs/api/service-workers.md
Normal file
@@ -0,0 +1,62 @@
|
||||
## Class: ServiceWorkers
|
||||
|
||||
> Query and receive events from a sessions active service workers.
|
||||
|
||||
Process: [Main](../glossary.md#main-process)
|
||||
|
||||
Instances of the `ServiceWorkers` class are accessed by using `serviceWorkers` property of
|
||||
a `Session`.
|
||||
|
||||
For example:
|
||||
|
||||
```javascript
|
||||
const { session } = require('electron')
|
||||
|
||||
// Get all service workers.
|
||||
console.log(session.defaultSession.serviceWorkers.getAllRunning())
|
||||
|
||||
// Handle logs and get service worker info
|
||||
session.defaultSession.serviceWorkers.on('console-message', (event, messageDetails) => {
|
||||
console.log(
|
||||
'Got service worker message',
|
||||
messageDetails,
|
||||
'from',
|
||||
session.defaultSession.serviceWorkers.getFromVersionID(messageDetails.versionId)
|
||||
)
|
||||
})
|
||||
```
|
||||
|
||||
### Instance Events
|
||||
|
||||
The following events are available on instances of `ServiceWorkers`:
|
||||
|
||||
#### Event: 'console-message'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `messageDetails` Object - Information about the console message
|
||||
* `message` String - The actual console message
|
||||
* `versionId` Number - The version ID of the service worker that sent the log message
|
||||
* `source` String - The type of source for this message. Can be `javascript`, `xml`, `network`, `console-api`, `storage`, `app-cache`, `rendering`, `security`, `deprecation`, `worker`, `violation`, `intervention`, `recommendation` or `other`.
|
||||
* `level` Number - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`.
|
||||
* `sourceUrl` String - The URL the message came from
|
||||
* `lineNumber` Number - The line number of the source that triggered this console message
|
||||
|
||||
Emitted when a service worker logs something to the console.
|
||||
|
||||
### Instance Methods
|
||||
|
||||
The following methods are available on instances of `ServiceWorkers`:
|
||||
|
||||
#### `serviceWorkers.getAllRunning()`
|
||||
|
||||
Returns `Record<Number, ServiceWorkerInfo>` - A [ServiceWorkerInfo](structures/service-worker-info.md) object where the keys are the service worker version ID and the values are the information about that service worker.
|
||||
|
||||
#### `serviceWorkers.getFromVersionID(versionId)`
|
||||
|
||||
* `versionId` Number
|
||||
|
||||
Returns [`ServiceWorkerInfo`](structures/service-worker-info.md) - Information about this service worker
|
||||
|
||||
If the service worker does not exist or is not running this method will throw an exception.
|
||||
@@ -105,6 +105,45 @@ Returns:
|
||||
Emitted when a render process requests preconnection to a URL, generally due to
|
||||
a [resource hint](https://w3c.github.io/resource-hints/).
|
||||
|
||||
#### Event: 'spellcheck-dictionary-initialized'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `languageCode` String - The language code of the dictionary file
|
||||
|
||||
Emitted when a hunspell dictionary file has been successfully initialized. This
|
||||
occurs after the file has been downloaded.
|
||||
|
||||
#### Event: 'spellcheck-dictionary-download-begin'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `languageCode` String - The language code of the dictionary file
|
||||
|
||||
Emitted when a hunspell dictionary file starts downloading
|
||||
|
||||
#### Event: 'spellcheck-dictionary-download-success'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `languageCode` String - The language code of the dictionary file
|
||||
|
||||
Emitted when a hunspell dictionary file has been successfully downloaded
|
||||
|
||||
#### Event: 'spellcheck-dictionary-download-failure'
|
||||
|
||||
Returns:
|
||||
|
||||
* `event` Event
|
||||
* `languageCode` String - The language code of the dictionary file
|
||||
|
||||
Emitted when a hunspell dictionary file download fails. For details
|
||||
on the failure you should collect a netlog and inspect the download
|
||||
request.
|
||||
|
||||
### Instance Methods
|
||||
|
||||
The following methods are available on instances of `Session`:
|
||||
@@ -483,18 +522,38 @@ setting with the current OS locale. This setting is persisted across restarts.
|
||||
By default Electron will download hunspell dictionaries from the Chromium CDN. If you want to override this
|
||||
behavior you can use this API to point the dictionary downloader at your own hosted version of the hunspell
|
||||
dictionaries. We publish a `hunspell_dictionaries.zip` file with each release which contains the files you need
|
||||
to host here.
|
||||
to host here, the file server must be **case insensitive** you must upload each file twice, once with the case it
|
||||
has in the ZIP file and once with the filename as all lower case.
|
||||
|
||||
If the files present in `hunspell_dictionaries.zip` are available at `https://example.com/dictionaries/language-code.bdic`
|
||||
then you should call this api with `ses.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/')`. Please
|
||||
note the trailing slash. The URL to the dictionaries is formed as `${url}${filename}`.
|
||||
|
||||
**Note:** On macOS the OS spellchecker is used and therefore we do not download any dictionary files. This API is a no-op on macOS.
|
||||
|
||||
#### `ses.listWordsInSpellCheckerDictionary()`
|
||||
|
||||
Returns `Promise<String[]>` - An array of all words in app's custom dictionary.
|
||||
Resolves when the full dictionary is loaded from disk.
|
||||
|
||||
#### `ses.addWordToSpellCheckerDictionary(word)`
|
||||
|
||||
* `word` String - The word you want to add to the dictionary
|
||||
|
||||
Returns `Boolean` - Whether the word was successfully written to the custom dictionary.
|
||||
Returns `Boolean` - Whether the word was successfully written to the custom dictionary. This API
|
||||
will not work on non-persistent (in-memory) sessions.
|
||||
|
||||
**Note:** On macOS and Windows 10 this word will be written to the OS custom dictionary as well
|
||||
|
||||
#### `ses.removeWordFromSpellCheckerDictionary(word)`
|
||||
|
||||
* `word` String - The word you want to remove from the dictionary
|
||||
|
||||
Returns `Boolean` - Whether the word was successfully removed from the custom dictionary. This API
|
||||
will not work on non-persistent (in-memory) sessions.
|
||||
|
||||
**Note:** On macOS and Windows 10 this word will be removed from the OS custom dictionary as well
|
||||
|
||||
#### `ses.loadExtension(path)`
|
||||
|
||||
* `path` String - Path to a directory containing an unpacked Chrome extension
|
||||
@@ -567,6 +626,10 @@ code to the `setSpellCheckerLanaguages` API that isn't in this array will result
|
||||
|
||||
A [`Cookies`](cookies.md) object for this session.
|
||||
|
||||
#### `ses.serviceWorkers` _Readonly_
|
||||
|
||||
A [`ServiceWorkers`](service-workers.md) object for this session.
|
||||
|
||||
#### `ses.webRequest` _Readonly_
|
||||
|
||||
A [`WebRequest`](web-request.md) object for this session.
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
# Extension Object
|
||||
|
||||
* `id` String
|
||||
* `manifest` any - Copy of the [extension's manifest data](https://developer.chrome.com/extensions/manifest).
|
||||
* `name` String
|
||||
* `path` String - The extension's file path.
|
||||
* `version` String
|
||||
* `url` String - The extension's `chrome-extension://` URL.
|
||||
|
||||
5
docs/api/structures/service-worker-info.md
Normal file
5
docs/api/structures/service-worker-info.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# ServiceWorkerInfo Object
|
||||
|
||||
* `scriptUrl` String - The full URL to the script that this service worker runs
|
||||
* `scope` String - The base URL that this service worker is active for.
|
||||
* `renderProcessId` Number - The virtual ID of the process that this service worker is running in. This is not an OS level PID. This aligns with the ID set used for `webContents.getProcessId()`.
|
||||
@@ -326,7 +326,7 @@ This API is only available on macOS 10.14 Mojave or newer.
|
||||
* `window-frame-text` - The text in the window's titlebar area.
|
||||
|
||||
Returns `String` - The system color setting in RGB hexadecimal form (`#ABCDEF`).
|
||||
See the [Windows docs][windows-colors] and the [MacOS docs][macos-colors] for more details.
|
||||
See the [Windows docs][windows-colors] and the [macOS docs][macos-colors] for more details.
|
||||
|
||||
The following colors are only available on macOS 10.14: `find-highlight`, `selected-content-background`, `separator`, `unemphasized-selected-content-background`, `unemphasized-selected-text-background`, and `unemphasized-selected-text`.
|
||||
|
||||
@@ -360,7 +360,7 @@ Returns `Boolean` - `true` if an inverted color scheme (a high contrast color sc
|
||||
|
||||
Returns `Boolean` - `true` if a high contrast theme is active, `false` otherwise.
|
||||
|
||||
**Depreacted:** Should use the new [`nativeTheme.shouldUseHighContrastColors`](native-theme.md#nativethemeshouldusehighcontrastcolors-macos-windows-readonly) API.
|
||||
**Deprecated:** Should use the new [`nativeTheme.shouldUseHighContrastColors`](native-theme.md#nativethemeshouldusehighcontrastcolors-macos-windows-readonly) API.
|
||||
|
||||
### `systemPreferences.getEffectiveAppearance()` _macOS_
|
||||
|
||||
@@ -369,16 +369,6 @@ Returns `String` - Can be `dark`, `light` or `unknown`.
|
||||
Gets the macOS appearance setting that is currently applied to your application,
|
||||
maps to [NSApplication.effectiveAppearance](https://developer.apple.com/documentation/appkit/nsapplication/2967171-effectiveappearance?language=objc)
|
||||
|
||||
Please note that until Electron is built targeting the 10.14 SDK, your application's
|
||||
`effectiveAppearance` will default to 'light' and won't inherit the OS preference. In
|
||||
the interim in order for your application to inherit the OS preference you must set the
|
||||
`NSRequiresAquaSystemAppearance` key in your apps `Info.plist` to `false`. If you are
|
||||
using `electron-packager` or `electron-forge` just set the `enableDarwinDarkMode`
|
||||
packager option to `true`. See the [Electron Packager API](https://github.com/electron/electron-packager/blob/master/docs/api.md#darwindarkmodesupport)
|
||||
for more details.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
### `systemPreferences.getAppLevelAppearance()` _macOS_ _Deprecated_
|
||||
|
||||
Returns `String` | `null` - Can be `dark`, `light` or `unknown`.
|
||||
@@ -387,8 +377,6 @@ Gets the macOS appearance setting that you have declared you want for
|
||||
your application, maps to [NSApplication.appearance](https://developer.apple.com/documentation/appkit/nsapplication/2967170-appearance?language=objc).
|
||||
You can use the `setAppLevelAppearance` API to set this value.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
### `systemPreferences.setAppLevelAppearance(appearance)` _macOS_ _Deprecated_
|
||||
|
||||
* `appearance` String | null - Can be `dark` or `light`
|
||||
@@ -396,16 +384,12 @@ You can use the `setAppLevelAppearance` API to set this value.
|
||||
Sets the appearance setting for your application, this should override the
|
||||
system default and override the value of `getEffectiveAppearance`.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
### `systemPreferences.canPromptTouchID()` _macOS_
|
||||
|
||||
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.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
### `systemPreferences.promptTouchID(reason)` _macOS_
|
||||
|
||||
* `reason` String - The reason you are asking for Touch ID authentication
|
||||
@@ -480,11 +464,3 @@ A `String` property that can be `dark`, `light` or `unknown`.
|
||||
|
||||
Returns the macOS appearance setting that is currently applied to your application,
|
||||
maps to [NSApplication.effectiveAppearance](https://developer.apple.com/documentation/appkit/nsapplication/2967171-effectiveappearance?language=objc)
|
||||
|
||||
Please note that until Electron is built targeting the 10.14 SDK, your application's
|
||||
`effectiveAppearance` will default to 'light' and won't inherit the OS preference. In
|
||||
the interim in order for your application to inherit the OS preference you must set the
|
||||
`NSRequiresAquaSystemAppearance` key in your apps `Info.plist` to `false`. If you are
|
||||
using `electron-packager` or `electron-forge` just set the `enableDarwinDarkMode`
|
||||
packager option to `true`. See the [Electron Packager API](https://github.com/electron/electron-packager/blob/master/docs/api.md#darwindarkmodesupport)
|
||||
for more details.
|
||||
|
||||
@@ -967,14 +967,10 @@ Returns `Boolean` - Whether the renderer process has crashed.
|
||||
|
||||
Overrides the user agent for this web page.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `contents.getUserAgent()`
|
||||
|
||||
Returns `String` - The user agent for this web page.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `contents.insertCSS(css[, options])`
|
||||
|
||||
* `css` String
|
||||
@@ -1054,33 +1050,27 @@ Ignore application menu shortcuts while this web contents is focused.
|
||||
|
||||
Mute the audio on the current web page.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `contents.isAudioMuted()`
|
||||
|
||||
Returns `Boolean` - Whether this page has been muted.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `contents.isCurrentlyAudible()`
|
||||
|
||||
Returns `Boolean` - Whether audio is currently playing.
|
||||
|
||||
#### `contents.setZoomFactor(factor)`
|
||||
|
||||
* `factor` Number - Zoom factor.
|
||||
* `factor` Double - Zoom factor; default is 1.0.
|
||||
|
||||
Changes the zoom factor to the specified factor. Zoom factor is
|
||||
zoom percent divided by 100, so 300% = 3.0.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
The factor must be greater than 0.0.
|
||||
|
||||
#### `contents.getZoomFactor()`
|
||||
|
||||
Returns `Number` - the current zoom factor.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `contents.setZoomLevel(level)`
|
||||
|
||||
* `level` Number - Zoom level.
|
||||
@@ -1090,14 +1080,10 @@ increment above or below represents zooming 20% larger or smaller to default
|
||||
limits of 300% and 50% of original size, respectively. The formula for this is
|
||||
`scale := 1.2 ^ level`.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `contents.getZoomLevel()`
|
||||
|
||||
Returns `Number` - the current zoom level.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)`
|
||||
|
||||
* `minimumLevel` Number
|
||||
@@ -1286,7 +1272,7 @@ Returns [`PrinterInfo[]`](structures/printer-info.md)
|
||||
`A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height`.
|
||||
* `callback` Function (optional)
|
||||
* `success` Boolean - Indicates success of the print call.
|
||||
* `failureReason` String - Called back if the print fails; can be `cancelled` or `failed`.
|
||||
* `failureReason` String - Error description called back if the print fails.
|
||||
|
||||
Prints window's web page. When `silent` is set to `true`, Electron will pick
|
||||
the system's default printer if `deviceName` is empty and the default settings for printing.
|
||||
@@ -1709,14 +1695,10 @@ Returns `Boolean` - If *offscreen rendering* is enabled returns whether it is cu
|
||||
If *offscreen rendering* is enabled sets the frame rate to the specified number.
|
||||
Only values between 1 and 60 are accepted.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `contents.getFrameRate()`
|
||||
|
||||
Returns `Integer` - If *offscreen rendering* is enabled returns the current frame rate.
|
||||
|
||||
**[Deprecated](modernization/property-updates.md)**
|
||||
|
||||
#### `contents.invalidate()`
|
||||
|
||||
Schedules a full repaint of the window this web contents is in.
|
||||
@@ -1822,7 +1804,7 @@ A [`WebContents`](web-contents.md) instance that might own this `WebContents`.
|
||||
|
||||
#### `contents.devToolsWebContents` _Readonly_
|
||||
|
||||
A `WebContents` of DevTools for this `WebContents`.
|
||||
A `WebContents | null` property that represents the of DevTools `WebContents` associated with a given `WebContents`.
|
||||
|
||||
**Note:** Users should never store this object because it may become `null`
|
||||
when the DevTools has been closed.
|
||||
|
||||
@@ -22,11 +22,13 @@ The `WebFrame` class has the following instance methods:
|
||||
|
||||
### `webFrame.setZoomFactor(factor)`
|
||||
|
||||
* `factor` Number - Zoom factor.
|
||||
* `factor` Double - Zoom factor; default is 1.0.
|
||||
|
||||
Changes the zoom factor to the specified factor. Zoom factor is
|
||||
zoom percent divided by 100, so 300% = 3.0.
|
||||
|
||||
The factor must be greater than 0.0.
|
||||
|
||||
### `webFrame.getZoomFactor()`
|
||||
|
||||
Returns `Number` - The current zoom factor.
|
||||
@@ -122,13 +124,20 @@ by its key, which is returned from `webFrame.insertCSS(css)`.
|
||||
|
||||
Inserts `text` to the focused element.
|
||||
|
||||
### `webFrame.executeJavaScript(code[, userGesture])`
|
||||
### `webFrame.executeJavaScript(code[, userGesture, callback])`
|
||||
|
||||
* `code` String
|
||||
* `userGesture` Boolean (optional) - Default is `false`.
|
||||
* `callback` Function (optional) - Called after script has been executed. Unless
|
||||
the frame is suspended (e.g. showing a modal alert), execution will be
|
||||
synchronous and the callback will be invoked before the method returns. For
|
||||
compatibility with an older version of this method, the error parameter is
|
||||
second.
|
||||
* `result` Any
|
||||
* `error` Error
|
||||
|
||||
Returns `Promise<any>` - A promise that resolves with the result of the executed code
|
||||
or is rejected if the result of the code is a rejected promise.
|
||||
Returns `Promise<any>` - A promise that resolves with the result of the executed
|
||||
code or is rejected if execution throws or results in a rejected promise.
|
||||
|
||||
Evaluates `code` in page.
|
||||
|
||||
@@ -136,14 +145,24 @@ In the browser window some HTML APIs like `requestFullScreen` can only be
|
||||
invoked by a gesture from the user. Setting `userGesture` to `true` will remove
|
||||
this limitation.
|
||||
|
||||
### `webFrame.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])`
|
||||
### `webFrame.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture, callback])`
|
||||
|
||||
* `worldId` Integer - The ID of the world to run the javascript in, `0` is the default world, `999` is the world used by Electrons `contextIsolation` feature. You can provide any integer here.
|
||||
* `worldId` Integer - The ID of the world to run the javascript
|
||||
in, `0` is the default main world (where content runs), `999` is the
|
||||
world used by Electron's `contextIsolation` feature. Accepts values
|
||||
in the range 1..536870911.
|
||||
* `scripts` [WebSource[]](structures/web-source.md)
|
||||
* `userGesture` Boolean (optional) - Default is `false`.
|
||||
* `callback` Function (optional) - Called after script has been executed. Unless
|
||||
the frame is suspended (e.g. showing a modal alert), execution will be
|
||||
synchronous and the callback will be invoked before the method returns. For
|
||||
compatibility with an older version of this method, the error parameter is
|
||||
second.
|
||||
* `result` Any
|
||||
* `error` Error
|
||||
|
||||
Returns `Promise<any>` - A promise that resolves with the result of the executed code
|
||||
or is rejected if the result of the code is a rejected promise.
|
||||
Returns `Promise<any>` - A promise that resolves with the result of the executed
|
||||
code or is rejected if execution throws or results in a rejected promise.
|
||||
|
||||
Works like `executeJavaScript` but evaluates `scripts` in an isolated context.
|
||||
|
||||
|
||||
@@ -146,6 +146,7 @@ response are visible by the time this listener is fired.
|
||||
* `timestamp` Double
|
||||
* `statusLine` String
|
||||
* `statusCode` Integer
|
||||
* `requestHeaders` Record<string, string>
|
||||
* `responseHeaders` Record<string, string[]> (optional)
|
||||
* `callback` Function
|
||||
* `headersReceivedResponse` Object
|
||||
@@ -228,6 +229,7 @@ redirect is about to occur.
|
||||
* `fromCache` Boolean
|
||||
* `statusCode` Integer
|
||||
* `statusLine` String
|
||||
* `error` String
|
||||
|
||||
The `listener` will be called with `listener(details)` when a request is
|
||||
completed.
|
||||
|
||||
@@ -25,7 +25,7 @@ Follow the guidelines below for building Electron on Linux.
|
||||
Doing so permits installing Node on your own home directory as a standard user.
|
||||
Or try repositories such as [NodeSource](https://nodesource.com/blog/nodejs-v012-iojs-and-the-nodesource-linux-repositories).
|
||||
* [clang](https://clang.llvm.org/get_started.html) 3.4 or later.
|
||||
* Development headers of GTK+ and libnotify.
|
||||
* Development headers of GTK 3 and libnotify.
|
||||
|
||||
On Ubuntu, install the following libraries:
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ $ pip install pyobjc
|
||||
If you're developing Electron and don't plan to redistribute your
|
||||
custom Electron build, you may skip this section.
|
||||
|
||||
Official Electron builds are built with [Xcode 9.4.1](http://adcdownload.apple.com/Developer_Tools/Xcode_9.4.1/Xcode_9.4.1.xip), and the MacOS 10.13 SDK. Building with a newer SDK works too, but the releases currently use the 10.13 SDK.
|
||||
Official Electron builds are built with [Xcode 9.4.1](http://adcdownload.apple.com/Developer_Tools/Xcode_9.4.1/Xcode_9.4.1.xip), and the macOS 10.13 SDK. Building with a newer SDK works too, but the releases currently use the 10.13 SDK.
|
||||
|
||||
## Building Electron
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ you prefer a graphical interface.
|
||||
tail calls, and other compiler optimizations.
|
||||
|
||||
* **Xcode**: In addition to Xcode, also install the Xcode command line tools.
|
||||
They include LLDB, the default debugger in Xcode on Mac OS X. It supports
|
||||
They include LLDB, the default debugger in Xcode on macOS. It supports
|
||||
debugging C, Objective-C and C++ on the desktop and iOS devices and simulator.
|
||||
|
||||
* **.lldbinit**: Create or edit `~/.lldbinit` to allow Chromium code to be properly source-mapped.
|
||||
|
||||
@@ -35,7 +35,7 @@ $ git fetch upstream
|
||||
|
||||
Build steps and dependencies differ slightly depending on your operating system.
|
||||
See these detailed guides on building Electron locally:
|
||||
* [Building on MacOS](https://electronjs.org/docs/development/build-instructions-macos)
|
||||
* [Building on macOS](https://electronjs.org/docs/development/build-instructions-macos)
|
||||
* [Building on Linux](https://electronjs.org/docs/development/build-instructions-linux)
|
||||
* [Building on Windows](https://electronjs.org/docs/development/build-instructions-windows)
|
||||
|
||||
|
||||
@@ -324,7 +324,7 @@ app.whenReady().then(() => {
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
const reopenMenuItem = findReopenMenuItem()
|
||||
if (reopenMenuItem) reopenMenuItem.enabled = true
|
||||
@@ -335,7 +335,7 @@ app.on('window-all-closed', function () {
|
||||
})
|
||||
|
||||
app.on('activate', function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// On macOS it is common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (mainWindow === null) {
|
||||
createWindow()
|
||||
|
||||
@@ -46,7 +46,7 @@ app.whenReady().then(createWindow)
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
@@ -54,7 +54,7 @@ app.on('window-all-closed', function () {
|
||||
})
|
||||
|
||||
app.on('activate', function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// On macOS it is common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (mainWindow === null) {
|
||||
createWindow()
|
||||
|
||||
@@ -37,7 +37,7 @@ app.whenReady().then(createWindow)
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
@@ -45,7 +45,7 @@ app.on('window-all-closed', function () {
|
||||
})
|
||||
|
||||
app.on('activate', function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// On macOS it is common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (mainWindow === null) {
|
||||
createWindow()
|
||||
|
||||
@@ -37,7 +37,7 @@ app.whenReady().then(createWindow)
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
@@ -45,7 +45,7 @@ app.on('window-all-closed', function () {
|
||||
})
|
||||
|
||||
app.on('activate', function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// On macOS it is common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (mainWindow === null) {
|
||||
createWindow()
|
||||
|
||||
@@ -37,7 +37,7 @@ app.whenReady().then(createWindow)
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
@@ -45,7 +45,7 @@ app.on('window-all-closed', function () {
|
||||
})
|
||||
|
||||
app.on('activate', function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// On macOS it is common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (mainWindow === null) {
|
||||
createWindow()
|
||||
|
||||
@@ -37,7 +37,7 @@ app.whenReady().then(createWindow)
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
@@ -45,7 +45,7 @@ app.on('window-all-closed', function () {
|
||||
})
|
||||
|
||||
app.on('activate', function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// On macOS it is common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (mainWindow === null) {
|
||||
createWindow()
|
||||
|
||||
@@ -36,7 +36,7 @@ app.whenReady().then(createWindow)
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
@@ -44,7 +44,7 @@ app.on('window-all-closed', function () {
|
||||
})
|
||||
|
||||
app.on('activate', function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// On macOS it is common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (mainWindow === null) {
|
||||
createWindow()
|
||||
|
||||
@@ -37,7 +37,7 @@ app.whenReady().then(createWindow)
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
@@ -45,7 +45,7 @@ app.on('window-all-closed', function () {
|
||||
})
|
||||
|
||||
app.on('activate', function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// On macOS it is common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (mainWindow === null) {
|
||||
createWindow()
|
||||
|
||||
@@ -37,7 +37,7 @@ app.whenReady().then(createWindow)
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
@@ -45,7 +45,7 @@ app.on('window-all-closed', function () {
|
||||
})
|
||||
|
||||
app.on('activate', function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// On macOS it is common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (mainWindow === null) {
|
||||
createWindow()
|
||||
|
||||
@@ -38,7 +38,7 @@ app.whenReady().then(createWindow)
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
@@ -46,7 +46,7 @@ app.on('window-all-closed', function () {
|
||||
})
|
||||
|
||||
app.on('activate', function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// On macOS it is common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (mainWindow === null) {
|
||||
createWindow()
|
||||
|
||||
@@ -38,7 +38,7 @@ app.whenReady().then(createWindow)
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
@@ -46,7 +46,7 @@ app.on('window-all-closed', function () {
|
||||
})
|
||||
|
||||
app.on('activate', function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// On macOS it is common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (mainWindow === null) {
|
||||
createWindow()
|
||||
|
||||
@@ -37,7 +37,7 @@ app.whenReady().then(createWindow)
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
@@ -45,7 +45,7 @@ app.on('window-all-closed', function () {
|
||||
})
|
||||
|
||||
app.on('activate', function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// On macOS it is common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (mainWindow === null) {
|
||||
createWindow()
|
||||
|
||||
@@ -37,7 +37,7 @@ app.whenReady().then(createWindow)
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
@@ -45,7 +45,7 @@ app.on('window-all-closed', function () {
|
||||
})
|
||||
|
||||
app.on('activate', function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// On macOS it is common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (mainWindow === null) {
|
||||
createWindow()
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
</head>
|
||||
<body>
|
||||
<h2>Create a new window</h2>
|
||||
<h3>Supports: Win, MacOS, Linux <span>|</span> Process: Main</h3>
|
||||
<h3>Supports: Win, macOS, Linux <span>|</span> Process: Main</h3>
|
||||
<button id="new-window">View Demo</button>
|
||||
<p>The <code>BrowserWindow</code> module gives you the ability to create new windows in your app. This main process module can be used from the renderer process with the <code>remote</code> module, as is shown in this demo.</p>
|
||||
<p>There are a lot of options when creating a new window. A few are in this demo, but visit the <a id="browser-window-link" href="">documentation<span>(opens in new window)</span></a>
|
||||
|
||||
@@ -37,7 +37,7 @@ app.whenReady().then(createWindow)
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
@@ -45,7 +45,7 @@ app.on('window-all-closed', function () {
|
||||
})
|
||||
|
||||
app.on('activate', function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// On macOS it is common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (mainWindow === null) {
|
||||
createWindow()
|
||||
|
||||
@@ -37,7 +37,7 @@ app.whenReady().then(createWindow)
|
||||
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit()
|
||||
@@ -45,7 +45,7 @@ app.on('window-all-closed', function () {
|
||||
})
|
||||
|
||||
app.on('activate', function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// On macOS it is common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (mainWindow === null) {
|
||||
createWindow()
|
||||
|
||||
@@ -76,7 +76,7 @@ that cache folder to provide custom builds of Electron or to avoid making contac
|
||||
with the network at all.
|
||||
|
||||
* Linux: `$XDG_CACHE_HOME` or `~/.cache/electron/`
|
||||
* MacOS: `~/Library/Caches/electron/`
|
||||
* macOS: `~/Library/Caches/electron/`
|
||||
* Windows: `$LOCALAPPDATA/electron/Cache` or `~/AppData/Local/electron/Cache/`
|
||||
|
||||
On environments that have been using older versions of Electron, you might find the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# MacOS Dock
|
||||
# macOS Dock
|
||||
|
||||
Electron has APIs to configure the app's icon in the macOS Dock. A macOS-only
|
||||
API exists to create a custom dock menu, but
|
||||
|
||||
@@ -1,29 +1,40 @@
|
||||
# Mojave Dark Mode
|
||||
# Supporting macOS Dark Mode
|
||||
|
||||
In macOS 10.14 Mojave, Apple introduced a new [system-wide dark mode](https://developer.apple.com/design/human-interface-guidelines/macos/visual-design/dark-mode/)
|
||||
for all macOS computers. If your app does have a dark mode, you can make your Electron app
|
||||
follow the system-wide dark mode setting using [the nativeTheme api](../api/native-theme.md).
|
||||
for all macOS computers. If your Electron app has a dark mode, you can make it follow the
|
||||
system-wide dark mode setting using [the `nativeTheme` api](../api/native-theme.md).
|
||||
|
||||
In macOS 10.15 Catalina, Apple introduced a new "automatic" dark mode option for all macOS computers. In order
|
||||
for the `nativeTheme.shouldUseDarkColors` and `Tray` APIs to work correctly in this mode on Catalina you need to either have `NSRequiresAquaSystemAppearance` set to `false` in your `Info.plist` file or be on Electron `>=7.0.0`.
|
||||
In macOS 10.15 Catalina, Apple introduced a new "automatic" dark mode option for all macOS computers.
|
||||
In order for the `nativeTheme.shouldUseDarkColors` and `Tray` APIs to work correctly in this mode on
|
||||
Catalina, you need to either have `NSRequiresAquaSystemAppearance` set to `false` in your
|
||||
`Info.plist` file, or be on Electron `>=7.0.0`. Both [Electron Packager][electron-packager] and
|
||||
[Electron Forge][electron-forge] have a [`darwinDarkModeSupport` option][packager-darwindarkmode-api]
|
||||
to automate the `Info.plist` changes during app build time.
|
||||
|
||||
## Automatically updating the native interfaces
|
||||
|
||||
"Native Interfaces" include the file picker, window border, dialogs, context menus and more; basically anything where
|
||||
the UI comes from macOS and not your app. The default behavior as of Electron 7.0.0 is to opt in to this automatic
|
||||
theming from the OS. If you wish to opt out you must set the `NSRequiresAquaSystemAppearance` key in the `Info.plist` file
|
||||
to `true`. Please note that once Electron starts building against the 10.14 SDK it will not be possible for you to opt
|
||||
out of this theming.
|
||||
"Native Interfaces" include the file picker, window border, dialogs, context menus and more; basically,
|
||||
anything where the UI comes from macOS and not your app. As of Electron 7.0.0, the default behavior
|
||||
is to opt in to this automatic theming from the OS. If you wish to opt out and are using Electron
|
||||
> 8.0.0, you must set the `NSRequiresAquaSystemAppearance` key in the `Info.plist` file to `true`.
|
||||
Please note that Electron 8.0.0 and above will not let your opt out of this theming, due to the use
|
||||
of the macOS 10.14 SDK.
|
||||
|
||||
## Automatically updating your own interfaces
|
||||
|
||||
If your app has its own dark mode you should toggle it on and off in sync with the system's dark mode setting. You can do
|
||||
this by listening for the theme updated event on Electron's `nativeTheme` module. E.g.
|
||||
If your app has its own dark mode, you should toggle it on and off in sync with the system's dark
|
||||
mode setting. You can do this by listening for the theme updated event on Electron's `nativeTheme` module.
|
||||
|
||||
```js
|
||||
For example:
|
||||
|
||||
```javascript
|
||||
const { nativeTheme } = require('electron')
|
||||
|
||||
nativeTheme.on('updated', function theThemeHasChanged () {
|
||||
updateMyAppTheme(nativeTheme.shouldUseDarkColors)
|
||||
})
|
||||
```
|
||||
|
||||
[electron-forge]: https://www.electronforge.io/
|
||||
[electron-packager]: https://github.com/electron/electron-packager
|
||||
[packager-darwindarkmode-api]: https://electron.github.io/electron-packager/master/interfaces/electronpackager.options.html#darwindarkmodesupport
|
||||
|
||||
@@ -49,7 +49,7 @@ The library file `widevinecdm.dll` will be under
|
||||
`Program Files(x86)/Google/Chrome/Application/CHROME_VERSION/WidevineCdm/_platform_specific/win_(x86|x64)/`
|
||||
directory.
|
||||
|
||||
### On MacOS
|
||||
### On macOS
|
||||
|
||||
The library file `libwidevinecdm.dylib` will be under
|
||||
`/Applications/Google Chrome.app/Contents/Versions/CHROME_VERSION/Google Chrome Framework.framework/Versions/A/Libraries/WidevineCdm/_platform_specific/mac_(x86|x64)/`
|
||||
|
||||
@@ -92,10 +92,14 @@ template("electron_extra_paks") {
|
||||
}
|
||||
if (enable_electron_extensions) {
|
||||
sources += [
|
||||
"$root_gen_dir/chrome/component_extension_resources.pak",
|
||||
"$root_gen_dir/extensions/extensions_renderer_resources.pak",
|
||||
"$root_gen_dir/extensions/extensions_resources.pak",
|
||||
]
|
||||
deps += [ "//extensions:extensions_resources" ]
|
||||
deps += [
|
||||
"//chrome/browser/resources:component_extension_resources",
|
||||
"//extensions:extensions_resources",
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,8 @@
|
||||
<part file="electron_strings.grdp" />
|
||||
</messages>
|
||||
<includes>
|
||||
<include name="IDR_CONTENT_SHELL_DEVTOOLS_DISCOVERY_PAGE" file="${target_gen_dir}\shell_devtools_discovery_page.html" use_base_dir="false" type="BINDATA" />
|
||||
<include name="IDR_CONTENT_SHELL_DEVTOOLS_DISCOVERY_PAGE" file="${target_gen_dir}/shell_devtools_discovery_page.html" use_base_dir="false" type="BINDATA" />
|
||||
<include name="IDR_PDF_MANIFEST" file="../chrome/browser/resources/pdf/manifest.json" type="BINDATA" />
|
||||
</includes>
|
||||
</release>
|
||||
</grit>
|
||||
|
||||
@@ -45,6 +45,7 @@ auto_filenames = {
|
||||
"docs/api/remote.md",
|
||||
"docs/api/sandbox-option.md",
|
||||
"docs/api/screen.md",
|
||||
"docs/api/service-workers.md",
|
||||
"docs/api/session.md",
|
||||
"docs/api/shell.md",
|
||||
"docs/api/structures",
|
||||
@@ -110,6 +111,7 @@ auto_filenames = {
|
||||
"docs/api/structures/remove-password.md",
|
||||
"docs/api/structures/scrubber-item.md",
|
||||
"docs/api/structures/segmented-control-segment.md",
|
||||
"docs/api/structures/service-worker-info.md",
|
||||
"docs/api/structures/shared-worker-info.md",
|
||||
"docs/api/structures/shortcut-details.md",
|
||||
"docs/api/structures/size.md",
|
||||
@@ -176,11 +178,8 @@ auto_filenames = {
|
||||
isolated_bundle_deps = [
|
||||
"lib/common/electron-binding-setup.ts",
|
||||
"lib/isolated_renderer/init.js",
|
||||
"lib/renderer/ipc-renderer-internal-utils.ts",
|
||||
"lib/renderer/ipc-renderer-internal.ts",
|
||||
"lib/renderer/web-view/web-view-constants.ts",
|
||||
"lib/renderer/web-view/web-view-element.ts",
|
||||
"lib/renderer/window-setup.ts",
|
||||
"package.json",
|
||||
"tsconfig.electron.json",
|
||||
"tsconfig.json",
|
||||
@@ -190,6 +189,7 @@ auto_filenames = {
|
||||
"lib/common/electron-binding-setup.ts",
|
||||
"lib/common/webpack-globals-provider.ts",
|
||||
"lib/content_script/init.js",
|
||||
"lib/renderer/api/context-bridge.ts",
|
||||
"lib/renderer/chrome-api.ts",
|
||||
"lib/renderer/extensions/event.ts",
|
||||
"lib/renderer/extensions/i18n.ts",
|
||||
|
||||
@@ -88,6 +88,8 @@ filenames = {
|
||||
"shell/browser/api/electron_api_protocol.h",
|
||||
"shell/browser/api/electron_api_screen.cc",
|
||||
"shell/browser/api/electron_api_screen.h",
|
||||
"shell/browser/api/electron_api_service_worker_context.cc",
|
||||
"shell/browser/api/electron_api_service_worker_context.h",
|
||||
"shell/browser/api/electron_api_session.cc",
|
||||
"shell/browser/api/electron_api_session.h",
|
||||
"shell/browser/api/electron_api_system_preferences.cc",
|
||||
@@ -234,12 +236,15 @@ filenames = {
|
||||
"shell/browser/net/node_stream_loader.h",
|
||||
"shell/browser/net/proxying_url_loader_factory.cc",
|
||||
"shell/browser/net/proxying_url_loader_factory.h",
|
||||
"shell/browser/net/proxying_websocket.cc",
|
||||
"shell/browser/net/proxying_websocket.h",
|
||||
"shell/browser/net/resolve_proxy_helper.cc",
|
||||
"shell/browser/net/resolve_proxy_helper.h",
|
||||
"shell/browser/net/system_network_context_manager.cc",
|
||||
"shell/browser/net/system_network_context_manager.h",
|
||||
"shell/browser/net/url_pipe_loader.cc",
|
||||
"shell/browser/net/url_pipe_loader.h",
|
||||
"shell/browser/net/web_request_api_interface.h",
|
||||
"shell/browser/network_hints_handler_impl.cc",
|
||||
"shell/browser/network_hints_handler_impl.h",
|
||||
"shell/browser/node_debugger.cc",
|
||||
@@ -276,6 +281,8 @@ filenames = {
|
||||
"shell/browser/notifications/win/win32_notification.h",
|
||||
"shell/browser/notifications/win/windows_toast_notification.cc",
|
||||
"shell/browser/notifications/win/windows_toast_notification.h",
|
||||
"shell/browser/plugins/plugin_utils.cc",
|
||||
"shell/browser/plugins/plugin_utils.h",
|
||||
"shell/browser/pref_store_delegate.cc",
|
||||
"shell/browser/pref_store_delegate.h",
|
||||
"shell/browser/relauncher.cc",
|
||||
@@ -472,8 +479,6 @@ filenames = {
|
||||
"shell/common/gin_converters/callback_converter.h",
|
||||
"shell/common/gin_converters/content_converter.cc",
|
||||
"shell/common/gin_converters/content_converter.h",
|
||||
"shell/common/gin_converters/extension_converter.cc",
|
||||
"shell/common/gin_converters/extension_converter.h",
|
||||
"shell/common/gin_converters/file_dialog_converter.cc",
|
||||
"shell/common/gin_converters/file_dialog_converter.h",
|
||||
"shell/common/gin_converters/file_path_converter.h",
|
||||
@@ -551,8 +556,11 @@ filenames = {
|
||||
"shell/common/skia_util.h",
|
||||
"shell/common/v8_value_converter.cc",
|
||||
"shell/common/v8_value_converter.h",
|
||||
"shell/renderer/api/context_bridge/render_frame_context_bridge_store.cc",
|
||||
"shell/renderer/api/context_bridge/render_frame_context_bridge_store.h",
|
||||
"shell/common/world_ids.h",
|
||||
"shell/renderer/api/context_bridge/object_cache.cc",
|
||||
"shell/renderer/api/context_bridge/object_cache.h",
|
||||
"shell/renderer/api/context_bridge/render_frame_function_store.cc",
|
||||
"shell/renderer/api/context_bridge/render_frame_function_store.h",
|
||||
"shell/renderer/api/electron_api_context_bridge.cc",
|
||||
"shell/renderer/api/electron_api_context_bridge.h",
|
||||
"shell/renderer/api/electron_api_renderer_ipc.cc",
|
||||
@@ -591,44 +599,56 @@ filenames = {
|
||||
]
|
||||
|
||||
lib_sources_extensions = [
|
||||
"shell/browser/extensions/api/i18n/i18n_api.cc",
|
||||
"shell/browser/extensions/api/i18n/i18n_api.h",
|
||||
"shell/browser/extensions/api/resources_private/resources_private_api.cc",
|
||||
"shell/browser/extensions/api/resources_private/resources_private_api.h",
|
||||
"shell/browser/extensions/api/runtime/electron_runtime_api_delegate.cc",
|
||||
"shell/browser/extensions/api/runtime/electron_runtime_api_delegate.h",
|
||||
"shell/browser/extensions/api/tabs/tabs_api.cc",
|
||||
"shell/browser/extensions/api/tabs/tabs_api.h",
|
||||
"shell/browser/extensions/electron_extensions_browser_client.cc",
|
||||
"shell/browser/extensions/electron_extensions_browser_client.h",
|
||||
"shell/browser/extensions/api/streams_private/streams_private_api.cc",
|
||||
"shell/browser/extensions/api/streams_private/streams_private_api.h",
|
||||
"shell/browser/extensions/electron_browser_context_keyed_service_factories.cc",
|
||||
"shell/browser/extensions/electron_browser_context_keyed_service_factories.h",
|
||||
"shell/browser/extensions/electron_component_extension_resource_manager.cc",
|
||||
"shell/browser/extensions/electron_component_extension_resource_manager.h",
|
||||
"shell/browser/extensions/electron_display_info_provider.cc",
|
||||
"shell/browser/extensions/electron_display_info_provider.h",
|
||||
"shell/browser/extensions/electron_extension_host_delegate.cc",
|
||||
"shell/browser/extensions/electron_extension_host_delegate.h",
|
||||
"shell/browser/extensions/electron_extension_loader.cc",
|
||||
"shell/browser/extensions/electron_extension_loader.h",
|
||||
"shell/browser/extensions/electron_extension_message_filter.cc",
|
||||
"shell/browser/extensions/electron_extension_message_filter.h",
|
||||
"shell/browser/extensions/electron_extension_system.cc",
|
||||
"shell/browser/extensions/electron_extension_system.h",
|
||||
"shell/browser/extensions/electron_extension_system_factory.cc",
|
||||
"shell/browser/extensions/electron_extension_system_factory.h",
|
||||
"shell/browser/extensions/electron_extension_web_contents_observer.cc",
|
||||
"shell/browser/extensions/electron_extension_web_contents_observer.h",
|
||||
"shell/browser/extensions/electron_navigation_ui_data.cc",
|
||||
"shell/browser/extensions/electron_navigation_ui_data.h",
|
||||
"shell/browser/extensions/electron_process_manager_delegate.cc",
|
||||
"shell/browser/extensions/electron_process_manager_delegate.h",
|
||||
"shell/browser/extensions/electron_extensions_api_client.cc",
|
||||
"shell/browser/extensions/electron_extensions_api_client.h",
|
||||
"shell/browser/extensions/electron_extensions_browser_api_provider.cc",
|
||||
"shell/browser/extensions/electron_extensions_browser_api_provider.h",
|
||||
"shell/browser/extensions/electron_extensions_browser_client.cc",
|
||||
"shell/browser/extensions/electron_extensions_browser_client.h",
|
||||
"shell/browser/extensions/electron_messaging_delegate.cc",
|
||||
"shell/browser/extensions/electron_messaging_delegate.h",
|
||||
"shell/browser/extensions/electron_navigation_ui_data.cc",
|
||||
"shell/browser/extensions/electron_navigation_ui_data.h",
|
||||
"shell/browser/extensions/electron_process_manager_delegate.cc",
|
||||
"shell/browser/extensions/electron_process_manager_delegate.h",
|
||||
"shell/common/extensions/electron_extensions_api_provider.cc",
|
||||
"shell/common/extensions/electron_extensions_api_provider.h",
|
||||
"shell/common/extensions/electron_extensions_client.cc",
|
||||
"shell/common/extensions/electron_extensions_client.h",
|
||||
"shell/renderer/extensions/electron_extensions_renderer_client.cc",
|
||||
"shell/renderer/extensions/electron_extensions_renderer_client.h",
|
||||
"shell/common/gin_converters/extension_converter.cc",
|
||||
"shell/common/gin_converters/extension_converter.h",
|
||||
"shell/renderer/extensions/electron_extensions_dispatcher_delegate.cc",
|
||||
"shell/renderer/extensions/electron_extensions_dispatcher_delegate.h",
|
||||
"shell/renderer/extensions/electron_extensions_renderer_client.cc",
|
||||
"shell/renderer/extensions/electron_extensions_renderer_client.h",
|
||||
]
|
||||
|
||||
app_sources = [
|
||||
|
||||
@@ -44,7 +44,7 @@ hunspell_dictionaries = [
|
||||
"//third_party/hunspell_dictionaries/ta-IN-3-0.bdic",
|
||||
"//third_party/hunspell_dictionaries/tg-TG-5-0.bdic",
|
||||
"//third_party/hunspell_dictionaries/tr-TR-4-0.bdic",
|
||||
"//third_party/hunspell_dictionaries/uk-UA-3-0.bdic",
|
||||
"//third_party/hunspell_dictionaries/uk-UA-4-0.bdic",
|
||||
"//third_party/hunspell_dictionaries/vi-VN-3-0.bdic",
|
||||
"//third_party/hunspell_dictionaries/xx-XX-3-0.bdic",
|
||||
]
|
||||
|
||||
@@ -1,21 +1,44 @@
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
import { deprecate, Menu } from 'electron'
|
||||
import { EventEmitter } from 'events'
|
||||
import { Menu } from 'electron';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
const bindings = process.electronBinding('app')
|
||||
const commandLine = process.electronBinding('command_line')
|
||||
const { app, App } = bindings
|
||||
const bindings = process.electronBinding('app');
|
||||
const commandLine = process.electronBinding('command_line');
|
||||
const { app, App } = bindings;
|
||||
|
||||
// Only one app object permitted.
|
||||
export default app
|
||||
export default app;
|
||||
|
||||
let dockMenu: Electron.Menu | null = null
|
||||
let dockMenu: Electron.Menu | null = null;
|
||||
|
||||
// App is an EventEmitter.
|
||||
Object.setPrototypeOf(App.prototype, EventEmitter.prototype)
|
||||
EventEmitter.call(app as any)
|
||||
Object.setPrototypeOf(App.prototype, EventEmitter.prototype);
|
||||
EventEmitter.call(app as any);
|
||||
|
||||
// Properties.
|
||||
|
||||
const nativeASGetter = app.isAccessibilitySupportEnabled;
|
||||
const nativeASSetter = app.setAccessibilitySupportEnabled;
|
||||
Object.defineProperty(App.prototype, 'accessibilitySupportEnabled', {
|
||||
get: () => nativeASGetter.call(app),
|
||||
set: (enabled) => nativeASSetter.call(app, enabled)
|
||||
});
|
||||
|
||||
const nativeBCGetter = app.getBadgeCount;
|
||||
const nativeBCSetter = app.setBadgeCount;
|
||||
Object.defineProperty(App.prototype, 'badgeCount', {
|
||||
get: () => nativeBCGetter.call(app),
|
||||
set: (count) => nativeBCSetter.call(app, count)
|
||||
});
|
||||
|
||||
const nativeNGetter = app.getName;
|
||||
const nativeNSetter = app.setName;
|
||||
Object.defineProperty(App.prototype, 'name', {
|
||||
get: () => nativeNGetter.call(app),
|
||||
set: (name) => nativeNSetter.call(app, name)
|
||||
});
|
||||
|
||||
Object.assign(app, {
|
||||
commandLine: {
|
||||
@@ -24,99 +47,94 @@ Object.assign(app, {
|
||||
appendSwitch: (theSwitch: string, value?: string) => commandLine.appendSwitch(String(theSwitch), typeof value === 'undefined' ? value : String(value)),
|
||||
appendArgument: (arg: string) => commandLine.appendArgument(String(arg))
|
||||
} as Electron.CommandLine
|
||||
})
|
||||
});
|
||||
|
||||
// we define this here because it'd be overly complicated to
|
||||
// do in native land
|
||||
Object.defineProperty(app, 'applicationMenu', {
|
||||
get () {
|
||||
return Menu.getApplicationMenu()
|
||||
return Menu.getApplicationMenu();
|
||||
},
|
||||
set (menu: Electron.Menu | null) {
|
||||
return Menu.setApplicationMenu(menu)
|
||||
return Menu.setApplicationMenu(menu);
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
App.prototype.isPackaged = (() => {
|
||||
const execFile = path.basename(process.execPath).toLowerCase()
|
||||
const execFile = path.basename(process.execPath).toLowerCase();
|
||||
if (process.platform === 'win32') {
|
||||
return execFile !== 'electron.exe'
|
||||
return execFile !== 'electron.exe';
|
||||
}
|
||||
return execFile !== 'electron'
|
||||
})()
|
||||
return execFile !== 'electron';
|
||||
})();
|
||||
|
||||
app._setDefaultAppPaths = (packagePath) => {
|
||||
// Set the user path according to application's name.
|
||||
app.setPath('userData', path.join(app.getPath('appData'), app.name!))
|
||||
app.setPath('userCache', path.join(app.getPath('cache'), app.name!))
|
||||
app.setAppPath(packagePath)
|
||||
app.setPath('userData', path.join(app.getPath('appData'), app.name!));
|
||||
app.setPath('userCache', path.join(app.getPath('cache'), app.name!));
|
||||
app.setAppPath(packagePath);
|
||||
|
||||
// Add support for --user-data-dir=
|
||||
if (app.commandLine.hasSwitch('user-data-dir')) {
|
||||
const userDataDir = app.commandLine.getSwitchValue('user-data-dir')
|
||||
if (path.isAbsolute(userDataDir)) app.setPath('userData', userDataDir)
|
||||
const userDataDir = app.commandLine.getSwitchValue('user-data-dir');
|
||||
if (path.isAbsolute(userDataDir)) app.setPath('userData', userDataDir);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (process.platform === 'darwin') {
|
||||
const setDockMenu = app.dock!.setMenu
|
||||
const setDockMenu = app.dock!.setMenu;
|
||||
app.dock!.setMenu = (menu) => {
|
||||
dockMenu = menu
|
||||
setDockMenu(menu)
|
||||
}
|
||||
app.dock!.getMenu = () => dockMenu
|
||||
dockMenu = menu;
|
||||
setDockMenu(menu);
|
||||
};
|
||||
app.dock!.getMenu = () => dockMenu;
|
||||
}
|
||||
|
||||
if (process.platform === 'linux') {
|
||||
const patternVmRSS = /^VmRSS:\s*(\d+) kB$/m
|
||||
const patternVmHWM = /^VmHWM:\s*(\d+) kB$/m
|
||||
const patternVmRSS = /^VmRSS:\s*(\d+) kB$/m;
|
||||
const patternVmHWM = /^VmHWM:\s*(\d+) kB$/m;
|
||||
|
||||
const getStatus = (pid: number) => {
|
||||
try {
|
||||
return fs.readFileSync(`/proc/${pid}/status`, 'utf8')
|
||||
return fs.readFileSync(`/proc/${pid}/status`, 'utf8');
|
||||
} catch {
|
||||
return ''
|
||||
return '';
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const getEntry = (file: string, pattern: RegExp) => {
|
||||
const match = file.match(pattern)
|
||||
return match ? parseInt(match[1], 10) : 0
|
||||
}
|
||||
const match = file.match(pattern);
|
||||
return match ? parseInt(match[1], 10) : 0;
|
||||
};
|
||||
|
||||
const getProcessMemoryInfo = (pid: number) => {
|
||||
const file = getStatus(pid)
|
||||
const file = getStatus(pid);
|
||||
|
||||
return {
|
||||
workingSetSize: getEntry(file, patternVmRSS),
|
||||
peakWorkingSetSize: getEntry(file, patternVmHWM)
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const nativeFn = app.getAppMetrics
|
||||
const nativeFn = app.getAppMetrics;
|
||||
app.getAppMetrics = () => {
|
||||
const metrics = nativeFn.call(app)
|
||||
const metrics = nativeFn.call(app);
|
||||
for (const metric of metrics) {
|
||||
metric.memory = getProcessMemoryInfo(metric.pid)
|
||||
metric.memory = getProcessMemoryInfo(metric.pid);
|
||||
}
|
||||
|
||||
return metrics
|
||||
}
|
||||
return metrics;
|
||||
};
|
||||
}
|
||||
|
||||
// Routes the events to webContents.
|
||||
const events = ['certificate-error', 'select-client-certificate']
|
||||
const events = ['certificate-error', 'select-client-certificate'];
|
||||
for (const name of events) {
|
||||
app.on(name as 'certificate-error', (event, webContents, ...args: any[]) => {
|
||||
webContents.emit(name, event, ...args)
|
||||
})
|
||||
webContents.emit(name, event, ...args);
|
||||
});
|
||||
}
|
||||
|
||||
// Property Deprecations
|
||||
deprecate.fnToProperty(App.prototype, 'accessibilitySupportEnabled', '_isAccessibilitySupportEnabled', '_setAccessibilitySupportEnabled')
|
||||
deprecate.fnToProperty(App.prototype, 'badgeCount', '_getBadgeCount', '_setBadgeCount')
|
||||
deprecate.fnToProperty(App.prototype, 'name', '_getName', '_setName')
|
||||
|
||||
// Wrappers for native classes.
|
||||
const { DownloadItem } = process.electronBinding('download_item')
|
||||
Object.setPrototypeOf(DownloadItem.prototype, EventEmitter.prototype)
|
||||
const { DownloadItem } = process.electronBinding('download_item');
|
||||
Object.setPrototypeOf(DownloadItem.prototype, EventEmitter.prototype);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
module.exports = require('@electron/internal/browser/api/auto-updater/auto-updater-win')
|
||||
module.exports = require('@electron/internal/browser/api/auto-updater/auto-updater-win');
|
||||
} else {
|
||||
module.exports = require('@electron/internal/browser/api/auto-updater/auto-updater-native')
|
||||
module.exports = require('@electron/internal/browser/api/auto-updater/auto-updater-native');
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const EventEmitter = require('events').EventEmitter
|
||||
const { autoUpdater, AutoUpdater } = process.electronBinding('auto_updater')
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
const { autoUpdater, AutoUpdater } = process.electronBinding('auto_updater');
|
||||
|
||||
// AutoUpdater is an EventEmitter.
|
||||
Object.setPrototypeOf(AutoUpdater.prototype, EventEmitter.prototype)
|
||||
EventEmitter.call(autoUpdater)
|
||||
Object.setPrototypeOf(AutoUpdater.prototype, EventEmitter.prototype);
|
||||
EventEmitter.call(autoUpdater);
|
||||
|
||||
module.exports = autoUpdater
|
||||
module.exports = autoUpdater;
|
||||
|
||||
@@ -1,74 +1,74 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const { app } = require('electron')
|
||||
const { EventEmitter } = require('events')
|
||||
const squirrelUpdate = require('@electron/internal/browser/api/auto-updater/squirrel-update-win')
|
||||
const { app } = require('electron');
|
||||
const { EventEmitter } = require('events');
|
||||
const squirrelUpdate = require('@electron/internal/browser/api/auto-updater/squirrel-update-win');
|
||||
|
||||
class AutoUpdater extends EventEmitter {
|
||||
quitAndInstall () {
|
||||
if (!this.updateAvailable) {
|
||||
return this.emitError('No update available, can\'t quit and install')
|
||||
return this.emitError('No update available, can\'t quit and install');
|
||||
}
|
||||
squirrelUpdate.processStart()
|
||||
app.quit()
|
||||
squirrelUpdate.processStart();
|
||||
app.quit();
|
||||
}
|
||||
|
||||
getFeedURL () {
|
||||
return this.updateURL
|
||||
return this.updateURL;
|
||||
}
|
||||
|
||||
setFeedURL (options) {
|
||||
let updateURL
|
||||
let updateURL;
|
||||
if (typeof options === 'object') {
|
||||
if (typeof options.url === 'string') {
|
||||
updateURL = options.url
|
||||
updateURL = options.url;
|
||||
} else {
|
||||
throw new Error('Expected options object to contain a \'url\' string property in setFeedUrl call')
|
||||
throw new Error('Expected options object to contain a \'url\' string property in setFeedUrl call');
|
||||
}
|
||||
} else if (typeof options === 'string') {
|
||||
updateURL = options
|
||||
updateURL = options;
|
||||
} else {
|
||||
throw new Error('Expected an options object with a \'url\' property to be provided')
|
||||
throw new Error('Expected an options object with a \'url\' property to be provided');
|
||||
}
|
||||
this.updateURL = updateURL
|
||||
this.updateURL = updateURL;
|
||||
}
|
||||
|
||||
checkForUpdates () {
|
||||
if (!this.updateURL) {
|
||||
return this.emitError('Update URL is not set')
|
||||
return this.emitError('Update URL is not set');
|
||||
}
|
||||
if (!squirrelUpdate.supported()) {
|
||||
return this.emitError('Can not find Squirrel')
|
||||
return this.emitError('Can not find Squirrel');
|
||||
}
|
||||
this.emit('checking-for-update')
|
||||
this.emit('checking-for-update');
|
||||
squirrelUpdate.checkForUpdate(this.updateURL, (error, update) => {
|
||||
if (error != null) {
|
||||
return this.emitError(error)
|
||||
return this.emitError(error);
|
||||
}
|
||||
if (update == null) {
|
||||
return this.emit('update-not-available')
|
||||
return this.emit('update-not-available');
|
||||
}
|
||||
this.updateAvailable = true
|
||||
this.emit('update-available')
|
||||
this.updateAvailable = true;
|
||||
this.emit('update-available');
|
||||
squirrelUpdate.update(this.updateURL, (error) => {
|
||||
if (error != null) {
|
||||
return this.emitError(error)
|
||||
return this.emitError(error);
|
||||
}
|
||||
const { releaseNotes, version } = update
|
||||
const { releaseNotes, version } = update;
|
||||
// Date is not available on Windows, so fake it.
|
||||
const date = new Date()
|
||||
const date = new Date();
|
||||
this.emit('update-downloaded', {}, releaseNotes, version, date, this.updateURL, () => {
|
||||
this.quitAndInstall()
|
||||
})
|
||||
})
|
||||
})
|
||||
this.quitAndInstall();
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Private: Emit both error object and message, this is to keep compatibility
|
||||
// with Old APIs.
|
||||
emitError (message) {
|
||||
this.emit('error', new Error(message), message)
|
||||
this.emit('error', new Error(message), message);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new AutoUpdater()
|
||||
module.exports = new AutoUpdater();
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const spawn = require('child_process').spawn
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const spawn = require('child_process').spawn;
|
||||
|
||||
// i.e. my-app/app-0.1.13/
|
||||
const appFolder = path.dirname(process.execPath)
|
||||
const appFolder = path.dirname(process.execPath);
|
||||
|
||||
// i.e. my-app/Update.exe
|
||||
const updateExe = path.resolve(appFolder, '..', 'Update.exe')
|
||||
const exeName = path.basename(process.execPath)
|
||||
let spawnedArgs = []
|
||||
let spawnedProcess
|
||||
const updateExe = path.resolve(appFolder, '..', 'Update.exe');
|
||||
const exeName = path.basename(process.execPath);
|
||||
let spawnedArgs = [];
|
||||
let spawnedProcess;
|
||||
|
||||
const isSameArgs = (args) => args.length === spawnedArgs.length && args.every((e, i) => e === spawnedArgs[i])
|
||||
const isSameArgs = (args) => args.length === spawnedArgs.length && args.every((e, i) => e === spawnedArgs[i]);
|
||||
|
||||
// Spawn a command and invoke the callback when it completes with an error
|
||||
// and the output from standard out.
|
||||
const spawnUpdate = function (args, detached, callback) {
|
||||
let error, errorEmitted, stderr, stdout
|
||||
let error, errorEmitted, stderr, stdout;
|
||||
|
||||
try {
|
||||
// Ensure we don't spawn multiple squirrel processes
|
||||
@@ -28,92 +28,92 @@ const spawnUpdate = function (args, detached, callback) {
|
||||
if (spawnedProcess && !isSameArgs(args)) {
|
||||
// Disabled for backwards compatibility:
|
||||
// eslint-disable-next-line standard/no-callback-literal
|
||||
return callback(`AutoUpdater process with arguments ${args} is already running`)
|
||||
return callback(`AutoUpdater process with arguments ${args} is already running`);
|
||||
} else if (!spawnedProcess) {
|
||||
spawnedProcess = spawn(updateExe, args, {
|
||||
detached: detached,
|
||||
windowsHide: true
|
||||
})
|
||||
spawnedArgs = args || []
|
||||
});
|
||||
spawnedArgs = args || [];
|
||||
}
|
||||
} catch (error1) {
|
||||
error = error1
|
||||
error = error1;
|
||||
|
||||
// Shouldn't happen, but still guard it.
|
||||
process.nextTick(function () {
|
||||
return callback(error)
|
||||
})
|
||||
return
|
||||
return callback(error);
|
||||
});
|
||||
return;
|
||||
}
|
||||
stdout = ''
|
||||
stderr = ''
|
||||
stdout = '';
|
||||
stderr = '';
|
||||
|
||||
spawnedProcess.stdout.on('data', (data) => { stdout += data })
|
||||
spawnedProcess.stderr.on('data', (data) => { stderr += data })
|
||||
spawnedProcess.stdout.on('data', (data) => { stdout += data; });
|
||||
spawnedProcess.stderr.on('data', (data) => { stderr += data; });
|
||||
|
||||
errorEmitted = false
|
||||
errorEmitted = false;
|
||||
spawnedProcess.on('error', (error) => {
|
||||
errorEmitted = true
|
||||
callback(error)
|
||||
})
|
||||
errorEmitted = true;
|
||||
callback(error);
|
||||
});
|
||||
|
||||
return spawnedProcess.on('exit', function (code, signal) {
|
||||
spawnedProcess = undefined
|
||||
spawnedArgs = []
|
||||
spawnedProcess = undefined;
|
||||
spawnedArgs = [];
|
||||
|
||||
// We may have already emitted an error.
|
||||
if (errorEmitted) {
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
// Process terminated with error.
|
||||
if (code !== 0) {
|
||||
// Disabled for backwards compatibility:
|
||||
// eslint-disable-next-line standard/no-callback-literal
|
||||
return callback(`Command failed: ${signal != null ? signal : code}\n${stderr}`)
|
||||
return callback(`Command failed: ${signal != null ? signal : code}\n${stderr}`);
|
||||
}
|
||||
|
||||
// Success.
|
||||
callback(null, stdout)
|
||||
})
|
||||
}
|
||||
callback(null, stdout);
|
||||
});
|
||||
};
|
||||
|
||||
// Start an instance of the installed app.
|
||||
exports.processStart = function () {
|
||||
return spawnUpdate(['--processStartAndWait', exeName], true, function () {})
|
||||
}
|
||||
return spawnUpdate(['--processStartAndWait', exeName], true, function () {});
|
||||
};
|
||||
|
||||
// Download the releases specified by the URL and write new results to stdout.
|
||||
exports.checkForUpdate = function (updateURL, callback) {
|
||||
return spawnUpdate(['--checkForUpdate', updateURL], false, function (error, stdout) {
|
||||
let ref, ref1, update
|
||||
let ref, ref1, update;
|
||||
if (error != null) {
|
||||
return callback(error)
|
||||
return callback(error);
|
||||
}
|
||||
try {
|
||||
// Last line of output is the JSON details about the releases
|
||||
const json = stdout.trim().split('\n').pop()
|
||||
update = (ref = JSON.parse(json)) != null ? (ref1 = ref.releasesToApply) != null ? typeof ref1.pop === 'function' ? ref1.pop() : void 0 : void 0 : void 0
|
||||
const json = stdout.trim().split('\n').pop();
|
||||
update = (ref = JSON.parse(json)) != null ? (ref1 = ref.releasesToApply) != null ? typeof ref1.pop === 'function' ? ref1.pop() : void 0 : void 0 : void 0;
|
||||
} catch {
|
||||
// Disabled for backwards compatibility:
|
||||
// eslint-disable-next-line standard/no-callback-literal
|
||||
return callback(`Invalid result:\n${stdout}`)
|
||||
return callback(`Invalid result:\n${stdout}`);
|
||||
}
|
||||
return callback(null, update)
|
||||
})
|
||||
}
|
||||
return callback(null, update);
|
||||
});
|
||||
};
|
||||
|
||||
// Update the application to the latest remote version specified by URL.
|
||||
exports.update = function (updateURL, callback) {
|
||||
return spawnUpdate(['--update', updateURL], false, callback)
|
||||
}
|
||||
return spawnUpdate(['--update', updateURL], false, callback);
|
||||
};
|
||||
|
||||
// Is the Update.exe installed with the current application?
|
||||
exports.supported = function () {
|
||||
try {
|
||||
fs.accessSync(updateExe, fs.R_OK)
|
||||
return true
|
||||
fs.accessSync(updateExe, fs.R_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const { EventEmitter } = require('events')
|
||||
const { BrowserView } = process.electronBinding('browser_view')
|
||||
const { EventEmitter } = require('events');
|
||||
const { BrowserView } = process.electronBinding('browser_view');
|
||||
|
||||
Object.setPrototypeOf(BrowserView.prototype, EventEmitter.prototype)
|
||||
Object.setPrototypeOf(BrowserView.prototype, EventEmitter.prototype);
|
||||
|
||||
BrowserView.fromWebContents = (webContents) => {
|
||||
for (const view of BrowserView.getAllViews()) {
|
||||
if (view.webContents.equal(webContents)) return view
|
||||
if (view.webContents.equal(webContents)) return view;
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
module.exports = BrowserView
|
||||
module.exports = BrowserView;
|
||||
|
||||
@@ -1,49 +1,49 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const electron = require('electron')
|
||||
const { WebContentsView, TopLevelWindow, deprecate } = electron
|
||||
const { BrowserWindow } = process.electronBinding('window')
|
||||
const electron = require('electron');
|
||||
const { WebContentsView, TopLevelWindow, deprecate } = electron;
|
||||
const { BrowserWindow } = process.electronBinding('window');
|
||||
|
||||
Object.setPrototypeOf(BrowserWindow.prototype, TopLevelWindow.prototype)
|
||||
Object.setPrototypeOf(BrowserWindow.prototype, TopLevelWindow.prototype);
|
||||
|
||||
BrowserWindow.prototype._init = function () {
|
||||
// Call parent class's _init.
|
||||
TopLevelWindow.prototype._init.call(this)
|
||||
TopLevelWindow.prototype._init.call(this);
|
||||
|
||||
// Avoid recursive require.
|
||||
const { app } = electron
|
||||
const { app } = electron;
|
||||
|
||||
// Create WebContentsView.
|
||||
this.setContentView(new WebContentsView(this.webContents))
|
||||
this.setContentView(new WebContentsView(this.webContents));
|
||||
|
||||
const nativeSetBounds = this.setBounds
|
||||
const nativeSetBounds = this.setBounds;
|
||||
this.setBounds = (bounds, ...opts) => {
|
||||
bounds = {
|
||||
...this.getBounds(),
|
||||
...bounds
|
||||
}
|
||||
nativeSetBounds.call(this, bounds, ...opts)
|
||||
}
|
||||
};
|
||||
nativeSetBounds.call(this, bounds, ...opts);
|
||||
};
|
||||
|
||||
// window.resizeTo(...)
|
||||
// window.moveTo(...)
|
||||
this.webContents.on('move', (event, size) => {
|
||||
this.setBounds(size)
|
||||
})
|
||||
this.setBounds(size);
|
||||
});
|
||||
|
||||
// Hide the auto-hide menu when webContents is focused.
|
||||
this.webContents.on('activate', () => {
|
||||
if (process.platform !== 'darwin' && this.autoHideMenuBar && this.isMenuBarVisible()) {
|
||||
this.setMenuBarVisibility(false)
|
||||
this.setMenuBarVisibility(false);
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
// Change window title to page title.
|
||||
this.webContents.on('page-title-updated', (event, title, ...args) => {
|
||||
// Route the event to BrowserWindow.
|
||||
this.emit('page-title-updated', event, title, ...args)
|
||||
if (!this.isDestroyed() && !event.defaultPrevented) this.setTitle(title)
|
||||
})
|
||||
this.emit('page-title-updated', event, title, ...args);
|
||||
if (!this.isDestroyed() && !event.defaultPrevented) this.setTitle(title);
|
||||
});
|
||||
|
||||
// Sometimes the webContents doesn't get focus when window is shown, so we
|
||||
// have to force focusing on webContents in this case. The safest way is to
|
||||
@@ -54,144 +54,135 @@ BrowserWindow.prototype._init = function () {
|
||||
// Finder, we still do it on all platforms in case of other bugs we don't
|
||||
// know.
|
||||
this.webContents.once('load-url', function () {
|
||||
this.focus()
|
||||
})
|
||||
this.focus();
|
||||
});
|
||||
|
||||
// Redirect focus/blur event to app instance too.
|
||||
this.on('blur', (event) => {
|
||||
app.emit('browser-window-blur', event, this)
|
||||
})
|
||||
app.emit('browser-window-blur', event, this);
|
||||
});
|
||||
this.on('focus', (event) => {
|
||||
app.emit('browser-window-focus', event, this)
|
||||
})
|
||||
app.emit('browser-window-focus', event, this);
|
||||
});
|
||||
|
||||
// Subscribe to visibilityState changes and pass to renderer process.
|
||||
let isVisible = this.isVisible() && !this.isMinimized()
|
||||
let isVisible = this.isVisible() && !this.isMinimized();
|
||||
const visibilityChanged = () => {
|
||||
const newState = this.isVisible() && !this.isMinimized()
|
||||
const newState = this.isVisible() && !this.isMinimized();
|
||||
if (isVisible !== newState) {
|
||||
isVisible = newState
|
||||
const visibilityState = isVisible ? 'visible' : 'hidden'
|
||||
this.webContents.emit('-window-visibility-change', visibilityState)
|
||||
isVisible = newState;
|
||||
const visibilityState = isVisible ? 'visible' : 'hidden';
|
||||
this.webContents.emit('-window-visibility-change', visibilityState);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const visibilityEvents = ['show', 'hide', 'minimize', 'maximize', 'restore']
|
||||
const visibilityEvents = ['show', 'hide', 'minimize', 'maximize', 'restore'];
|
||||
for (const event of visibilityEvents) {
|
||||
this.on(event, visibilityChanged)
|
||||
this.on(event, visibilityChanged);
|
||||
}
|
||||
|
||||
// Notify the creation of the window.
|
||||
const event = process.electronBinding('event').createEmpty()
|
||||
app.emit('browser-window-created', event, this)
|
||||
const event = process.electronBinding('event').createEmpty();
|
||||
app.emit('browser-window-created', event, this);
|
||||
|
||||
Object.defineProperty(this, 'devToolsWebContents', {
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
get () {
|
||||
return this.webContents.devToolsWebContents
|
||||
return this.webContents.devToolsWebContents;
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const isBrowserWindow = (win) => {
|
||||
return win && win.constructor.name === 'BrowserWindow'
|
||||
}
|
||||
return win && win.constructor.name === 'BrowserWindow';
|
||||
};
|
||||
|
||||
BrowserWindow.fromId = (id) => {
|
||||
const win = TopLevelWindow.fromId(id)
|
||||
return isBrowserWindow(win) ? win : null
|
||||
}
|
||||
const win = TopLevelWindow.fromId(id);
|
||||
return isBrowserWindow(win) ? win : null;
|
||||
};
|
||||
|
||||
BrowserWindow.getAllWindows = () => {
|
||||
return TopLevelWindow.getAllWindows().filter(isBrowserWindow)
|
||||
}
|
||||
return TopLevelWindow.getAllWindows().filter(isBrowserWindow);
|
||||
};
|
||||
|
||||
BrowserWindow.getFocusedWindow = () => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (window.isFocused() || window.isDevToolsFocused()) return window
|
||||
if (window.isFocused() || window.isDevToolsFocused()) return window;
|
||||
}
|
||||
return null
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
BrowserWindow.fromWebContents = (webContents) => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (window.webContents && window.webContents.equal(webContents)) return window
|
||||
if (window.webContents && window.webContents.equal(webContents)) return window;
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
BrowserWindow.fromBrowserView = (browserView) => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (window.getBrowserView() === browserView) return window
|
||||
if (window.getBrowserView() === browserView) return window;
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// Helpers.
|
||||
Object.assign(BrowserWindow.prototype, {
|
||||
loadURL (...args) {
|
||||
return this.webContents.loadURL(...args)
|
||||
return this.webContents.loadURL(...args);
|
||||
},
|
||||
getURL (...args) {
|
||||
return this.webContents.getURL()
|
||||
return this.webContents.getURL();
|
||||
},
|
||||
loadFile (...args) {
|
||||
return this.webContents.loadFile(...args)
|
||||
return this.webContents.loadFile(...args);
|
||||
},
|
||||
reload (...args) {
|
||||
return this.webContents.reload(...args)
|
||||
return this.webContents.reload(...args);
|
||||
},
|
||||
send (...args) {
|
||||
return this.webContents.send(...args)
|
||||
return this.webContents.send(...args);
|
||||
},
|
||||
openDevTools (...args) {
|
||||
return this.webContents.openDevTools(...args)
|
||||
return this.webContents.openDevTools(...args);
|
||||
},
|
||||
closeDevTools () {
|
||||
return this.webContents.closeDevTools()
|
||||
return this.webContents.closeDevTools();
|
||||
},
|
||||
isDevToolsOpened () {
|
||||
return this.webContents.isDevToolsOpened()
|
||||
return this.webContents.isDevToolsOpened();
|
||||
},
|
||||
isDevToolsFocused () {
|
||||
return this.webContents.isDevToolsFocused()
|
||||
return this.webContents.isDevToolsFocused();
|
||||
},
|
||||
toggleDevTools () {
|
||||
return this.webContents.toggleDevTools()
|
||||
return this.webContents.toggleDevTools();
|
||||
},
|
||||
inspectElement (...args) {
|
||||
return this.webContents.inspectElement(...args)
|
||||
return this.webContents.inspectElement(...args);
|
||||
},
|
||||
inspectSharedWorker () {
|
||||
return this.webContents.inspectSharedWorker()
|
||||
return this.webContents.inspectSharedWorker();
|
||||
},
|
||||
inspectServiceWorker () {
|
||||
return this.webContents.inspectServiceWorker()
|
||||
return this.webContents.inspectServiceWorker();
|
||||
},
|
||||
showDefinitionForSelection () {
|
||||
return this.webContents.showDefinitionForSelection()
|
||||
return this.webContents.showDefinitionForSelection();
|
||||
},
|
||||
capturePage (...args) {
|
||||
return this.webContents.capturePage(...args)
|
||||
return this.webContents.capturePage(...args);
|
||||
},
|
||||
setTouchBar (touchBar) {
|
||||
electron.TouchBar._setOnWindow(touchBar, this)
|
||||
electron.TouchBar._setOnWindow(touchBar, this);
|
||||
},
|
||||
setBackgroundThrottling (allowed) {
|
||||
this.webContents.setBackgroundThrottling(allowed)
|
||||
this.webContents.setBackgroundThrottling(allowed);
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
// Deprecations
|
||||
deprecate.fnToProperty(BrowserWindow.prototype, 'autoHideMenuBar', '_isMenuBarAutoHide', '_setAutoHideMenuBar')
|
||||
deprecate.fnToProperty(BrowserWindow.prototype, 'minimizable', '_isMinimizable', '_setMinimizable')
|
||||
deprecate.fnToProperty(BrowserWindow.prototype, 'maximizable', '_isMaximizable', '_setMaximizable')
|
||||
deprecate.fnToProperty(BrowserWindow.prototype, 'resizable', '_isResizable', '_setResizable')
|
||||
deprecate.fnToProperty(BrowserWindow.prototype, 'fullScreenable', '_isFullScreenable', '_setFullScreenable')
|
||||
deprecate.fnToProperty(BrowserWindow.prototype, 'closable', '_isClosable', '_setClosable')
|
||||
deprecate.fnToProperty(BrowserWindow.prototype, 'movable', '_isMovable', '_setMovable')
|
||||
|
||||
module.exports = BrowserWindow
|
||||
module.exports = BrowserWindow;
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
'use strict'
|
||||
module.exports = process.electronBinding('content_tracing')
|
||||
'use strict';
|
||||
module.exports = process.electronBinding('content_tracing');
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const CrashReporter = require('@electron/internal/common/crash-reporter')
|
||||
const { crashReporterInit } = require('@electron/internal/browser/crash-reporter-init')
|
||||
const CrashReporter = require('@electron/internal/common/crash-reporter');
|
||||
const { crashReporterInit } = require('@electron/internal/browser/crash-reporter-init');
|
||||
|
||||
class CrashReporterMain extends CrashReporter {
|
||||
init (options) {
|
||||
return crashReporterInit(options)
|
||||
return crashReporterInit(options);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new CrashReporterMain()
|
||||
module.exports = new CrashReporterMain();
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const { app, BrowserWindow, deprecate } = require('electron')
|
||||
const binding = process.electronBinding('dialog')
|
||||
const v8Util = process.electronBinding('v8_util')
|
||||
const { app, BrowserWindow, deprecate } = require('electron');
|
||||
const binding = process.electronBinding('dialog');
|
||||
const v8Util = process.electronBinding('v8_util');
|
||||
|
||||
const DialogType = {
|
||||
OPEN: 'OPEN',
|
||||
SAVE: 'SAVE'
|
||||
}
|
||||
};
|
||||
|
||||
const saveFileDialogProperties = {
|
||||
createDirectory: 1 << 0,
|
||||
@@ -15,7 +15,7 @@ const saveFileDialogProperties = {
|
||||
treatPackageAsDirectory: 1 << 2,
|
||||
showOverwriteConfirmation: 1 << 3,
|
||||
dontAddToRecent: 1 << 4
|
||||
}
|
||||
};
|
||||
|
||||
const openFileDialogProperties = {
|
||||
openFile: 1 << 0,
|
||||
@@ -27,15 +27,15 @@ const openFileDialogProperties = {
|
||||
noResolveAliases: 1 << 6, // macOS
|
||||
treatPackageAsDirectory: 1 << 7, // macOS
|
||||
dontAddToRecent: 1 << 8 // Windows
|
||||
}
|
||||
};
|
||||
|
||||
const normalizeAccessKey = (text) => {
|
||||
if (typeof text !== 'string') return text
|
||||
if (typeof text !== 'string') return text;
|
||||
|
||||
// macOS does not have access keys so remove single ampersands
|
||||
// and replace double ampersands with a single ampersand
|
||||
if (process.platform === 'darwin') {
|
||||
return text.replace(/&(&?)/g, '$1')
|
||||
return text.replace(/&(&?)/g, '$1');
|
||||
}
|
||||
|
||||
// Linux uses a single underscore as an access key prefix so escape
|
||||
@@ -44,41 +44,41 @@ const normalizeAccessKey = (text) => {
|
||||
// a single underscore
|
||||
if (process.platform === 'linux') {
|
||||
return text.replace(/_/g, '__').replace(/&(.?)/g, (match, after) => {
|
||||
if (after === '&') return after
|
||||
return `_${after}`
|
||||
})
|
||||
if (after === '&') return after;
|
||||
return `_${after}`;
|
||||
});
|
||||
}
|
||||
|
||||
return text
|
||||
}
|
||||
return text;
|
||||
};
|
||||
|
||||
const checkAppInitialized = function () {
|
||||
if (!app.isReady()) {
|
||||
throw new Error('dialog module can only be used after app is ready')
|
||||
throw new Error('dialog module can only be used after app is ready');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const setupDialogProperties = (type, properties) => {
|
||||
const dialogPropertiesTypes = (type === DialogType.OPEN) ? openFileDialogProperties : saveFileDialogProperties
|
||||
let dialogProperties = 0
|
||||
const dialogPropertiesTypes = (type === DialogType.OPEN) ? openFileDialogProperties : saveFileDialogProperties;
|
||||
let dialogProperties = 0;
|
||||
for (const prop in dialogPropertiesTypes) {
|
||||
if (properties.includes(prop)) {
|
||||
dialogProperties |= dialogPropertiesTypes[prop]
|
||||
dialogProperties |= dialogPropertiesTypes[prop];
|
||||
}
|
||||
}
|
||||
|
||||
return dialogProperties
|
||||
}
|
||||
return dialogProperties;
|
||||
};
|
||||
|
||||
const saveDialog = (sync, window, options) => {
|
||||
checkAppInitialized()
|
||||
checkAppInitialized();
|
||||
|
||||
if (window && window.constructor !== BrowserWindow) {
|
||||
options = window
|
||||
window = null
|
||||
options = window;
|
||||
window = null;
|
||||
}
|
||||
|
||||
if (options == null) options = { title: 'Save' }
|
||||
if (options == null) options = { title: 'Save' };
|
||||
|
||||
const {
|
||||
buttonLabel = '',
|
||||
@@ -90,33 +90,33 @@ const saveDialog = (sync, window, options) => {
|
||||
securityScopedBookmarks = false,
|
||||
nameFieldLabel = '',
|
||||
showsTagField = true
|
||||
} = options
|
||||
} = options;
|
||||
|
||||
if (typeof title !== 'string') throw new TypeError('Title must be a string')
|
||||
if (typeof buttonLabel !== 'string') throw new TypeError('Button label must be a string')
|
||||
if (typeof defaultPath !== 'string') throw new TypeError('Default path must be a string')
|
||||
if (typeof message !== 'string') throw new TypeError('Message must be a string')
|
||||
if (typeof nameFieldLabel !== 'string') throw new TypeError('Name field label must be a string')
|
||||
if (typeof title !== 'string') throw new TypeError('Title must be a string');
|
||||
if (typeof buttonLabel !== 'string') throw new TypeError('Button label must be a string');
|
||||
if (typeof defaultPath !== 'string') throw new TypeError('Default path must be a string');
|
||||
if (typeof message !== 'string') throw new TypeError('Message must be a string');
|
||||
if (typeof nameFieldLabel !== 'string') throw new TypeError('Name field label must be a string');
|
||||
|
||||
const settings = { buttonLabel, defaultPath, filters, title, message, securityScopedBookmarks, nameFieldLabel, showsTagField, window }
|
||||
settings.properties = setupDialogProperties(DialogType.SAVE, properties)
|
||||
const settings = { buttonLabel, defaultPath, filters, title, message, securityScopedBookmarks, nameFieldLabel, showsTagField, window };
|
||||
settings.properties = setupDialogProperties(DialogType.SAVE, properties);
|
||||
|
||||
return (sync) ? binding.showSaveDialogSync(settings) : binding.showSaveDialog(settings)
|
||||
}
|
||||
return (sync) ? binding.showSaveDialogSync(settings) : binding.showSaveDialog(settings);
|
||||
};
|
||||
|
||||
const openDialog = (sync, window, options) => {
|
||||
checkAppInitialized()
|
||||
checkAppInitialized();
|
||||
|
||||
if (window && window.constructor !== BrowserWindow) {
|
||||
options = window
|
||||
window = null
|
||||
options = window;
|
||||
window = null;
|
||||
}
|
||||
|
||||
if (options == null) {
|
||||
options = {
|
||||
title: 'Open',
|
||||
properties: ['openFile']
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const {
|
||||
@@ -127,33 +127,33 @@ const openDialog = (sync, window, options) => {
|
||||
title = '',
|
||||
message = '',
|
||||
securityScopedBookmarks = false
|
||||
} = options
|
||||
} = options;
|
||||
|
||||
if (!Array.isArray(properties)) throw new TypeError('Properties must be an array')
|
||||
if (!Array.isArray(properties)) throw new TypeError('Properties must be an array');
|
||||
|
||||
if (typeof title !== 'string') throw new TypeError('Title must be a string')
|
||||
if (typeof buttonLabel !== 'string') throw new TypeError('Button label must be a string')
|
||||
if (typeof defaultPath !== 'string') throw new TypeError('Default path must be a string')
|
||||
if (typeof message !== 'string') throw new TypeError('Message must be a string')
|
||||
if (typeof title !== 'string') throw new TypeError('Title must be a string');
|
||||
if (typeof buttonLabel !== 'string') throw new TypeError('Button label must be a string');
|
||||
if (typeof defaultPath !== 'string') throw new TypeError('Default path must be a string');
|
||||
if (typeof message !== 'string') throw new TypeError('Message must be a string');
|
||||
|
||||
const settings = { title, buttonLabel, defaultPath, filters, message, securityScopedBookmarks, window }
|
||||
settings.properties = setupDialogProperties(DialogType.OPEN, properties)
|
||||
const settings = { title, buttonLabel, defaultPath, filters, message, securityScopedBookmarks, window };
|
||||
settings.properties = setupDialogProperties(DialogType.OPEN, properties);
|
||||
|
||||
return (sync) ? binding.showOpenDialogSync(settings) : binding.showOpenDialog(settings)
|
||||
}
|
||||
return (sync) ? binding.showOpenDialogSync(settings) : binding.showOpenDialog(settings);
|
||||
};
|
||||
|
||||
const messageBox = (sync, window, options) => {
|
||||
checkAppInitialized()
|
||||
checkAppInitialized();
|
||||
|
||||
if (window && window.constructor !== BrowserWindow) {
|
||||
options = window
|
||||
window = null
|
||||
options = window;
|
||||
window = null;
|
||||
}
|
||||
|
||||
if (options == null) options = { type: 'none' }
|
||||
if (options == null) options = { type: 'none' };
|
||||
|
||||
const messageBoxTypes = ['none', 'info', 'warning', 'error', 'question']
|
||||
const messageBoxOptions = { noLink: 1 << 0 }
|
||||
const messageBoxTypes = ['none', 'info', 'warning', 'error', 'question'];
|
||||
const messageBoxOptions = { noLink: 1 << 0 };
|
||||
|
||||
let {
|
||||
buttons = [],
|
||||
@@ -167,32 +167,32 @@ const messageBox = (sync, window, options) => {
|
||||
message = '',
|
||||
title = '',
|
||||
type = 'none'
|
||||
} = options
|
||||
} = options;
|
||||
|
||||
const messageBoxType = messageBoxTypes.indexOf(type)
|
||||
if (messageBoxType === -1) throw new TypeError('Invalid message box type')
|
||||
if (!Array.isArray(buttons)) throw new TypeError('Buttons must be an array')
|
||||
if (options.normalizeAccessKeys) buttons = buttons.map(normalizeAccessKey)
|
||||
if (typeof title !== 'string') throw new TypeError('Title must be a string')
|
||||
if (typeof noLink !== 'boolean') throw new TypeError('noLink must be a boolean')
|
||||
if (typeof message !== 'string') throw new TypeError('Message must be a string')
|
||||
if (typeof detail !== 'string') throw new TypeError('Detail must be a string')
|
||||
if (typeof checkboxLabel !== 'string') throw new TypeError('checkboxLabel must be a string')
|
||||
const messageBoxType = messageBoxTypes.indexOf(type);
|
||||
if (messageBoxType === -1) throw new TypeError('Invalid message box type');
|
||||
if (!Array.isArray(buttons)) throw new TypeError('Buttons must be an array');
|
||||
if (options.normalizeAccessKeys) buttons = buttons.map(normalizeAccessKey);
|
||||
if (typeof title !== 'string') throw new TypeError('Title must be a string');
|
||||
if (typeof noLink !== 'boolean') throw new TypeError('noLink must be a boolean');
|
||||
if (typeof message !== 'string') throw new TypeError('Message must be a string');
|
||||
if (typeof detail !== 'string') throw new TypeError('Detail must be a string');
|
||||
if (typeof checkboxLabel !== 'string') throw new TypeError('checkboxLabel must be a string');
|
||||
|
||||
checkboxChecked = !!checkboxChecked
|
||||
checkboxChecked = !!checkboxChecked;
|
||||
if (checkboxChecked && !checkboxLabel) {
|
||||
throw new Error('checkboxChecked requires that checkboxLabel also be passed')
|
||||
throw new Error('checkboxChecked requires that checkboxLabel also be passed');
|
||||
}
|
||||
|
||||
// Choose a default button to get selected when dialog is cancelled.
|
||||
if (cancelId == null) {
|
||||
// If the defaultId is set to 0, ensure the cancel button is a different index (1)
|
||||
cancelId = (defaultId === 0 && buttons.length > 1) ? 1 : 0
|
||||
cancelId = (defaultId === 0 && buttons.length > 1) ? 1 : 0;
|
||||
for (let i = 0; i < buttons.length; i++) {
|
||||
const text = buttons[i].toLowerCase()
|
||||
const text = buttons[i].toLowerCase();
|
||||
if (text === 'cancel' || text === 'no') {
|
||||
cancelId = i
|
||||
break
|
||||
cancelId = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -210,57 +210,57 @@ const messageBox = (sync, window, options) => {
|
||||
checkboxLabel,
|
||||
checkboxChecked,
|
||||
icon
|
||||
}
|
||||
};
|
||||
|
||||
if (sync) {
|
||||
return binding.showMessageBoxSync(settings)
|
||||
return binding.showMessageBoxSync(settings);
|
||||
} else {
|
||||
return binding.showMessageBox(settings)
|
||||
return binding.showMessageBox(settings);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
showOpenDialog: function (window, options) {
|
||||
return openDialog(false, window, options)
|
||||
return openDialog(false, window, options);
|
||||
},
|
||||
|
||||
showOpenDialogSync: function (window, options) {
|
||||
return openDialog(true, window, options)
|
||||
return openDialog(true, window, options);
|
||||
},
|
||||
|
||||
showSaveDialog: function (window, options) {
|
||||
return saveDialog(false, window, options)
|
||||
return saveDialog(false, window, options);
|
||||
},
|
||||
|
||||
showSaveDialogSync: function (window, options) {
|
||||
return saveDialog(true, window, options)
|
||||
return saveDialog(true, window, options);
|
||||
},
|
||||
|
||||
showMessageBox: function (window, options) {
|
||||
return messageBox(false, window, options)
|
||||
return messageBox(false, window, options);
|
||||
},
|
||||
|
||||
showMessageBoxSync: function (window, options) {
|
||||
return messageBox(true, window, options)
|
||||
return messageBox(true, window, options);
|
||||
},
|
||||
|
||||
showErrorBox: function (...args) {
|
||||
return binding.showErrorBox(...args)
|
||||
return binding.showErrorBox(...args);
|
||||
},
|
||||
|
||||
showCertificateTrustDialog: function (window, options) {
|
||||
if (window && window.constructor !== BrowserWindow) options = window
|
||||
if (window && window.constructor !== BrowserWindow) options = window;
|
||||
if (options == null || typeof options !== 'object') {
|
||||
throw new TypeError('options must be an object')
|
||||
throw new TypeError('options must be an object');
|
||||
}
|
||||
|
||||
const { certificate, message = '' } = options
|
||||
const { certificate, message = '' } = options;
|
||||
if (certificate == null || typeof certificate !== 'object') {
|
||||
throw new TypeError('certificate must be an object')
|
||||
throw new TypeError('certificate must be an object');
|
||||
}
|
||||
|
||||
if (typeof message !== 'string') throw new TypeError('message must be a string')
|
||||
if (typeof message !== 'string') throw new TypeError('message must be a string');
|
||||
|
||||
return binding.showCertificateTrustDialog(window, certificate, message)
|
||||
return binding.showCertificateTrustDialog(window, certificate, message);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { defineProperties } from '@electron/internal/common/define-properties'
|
||||
import { commonModuleList } from '@electron/internal/common/api/module-list'
|
||||
import { browserModuleList } from '@electron/internal/browser/api/module-list'
|
||||
import { defineProperties } from '@electron/internal/common/define-properties';
|
||||
import { commonModuleList } from '@electron/internal/common/api/module-list';
|
||||
import { browserModuleList } from '@electron/internal/browser/api/module-list';
|
||||
|
||||
module.exports = {}
|
||||
module.exports = {};
|
||||
|
||||
defineProperties(module.exports, commonModuleList)
|
||||
defineProperties(module.exports, browserModuleList)
|
||||
defineProperties(module.exports, commonModuleList);
|
||||
defineProperties(module.exports, browserModuleList);
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
module.exports = process.electronBinding('global_shortcut').globalShortcut
|
||||
module.exports = process.electronBinding('global_shortcut').globalShortcut;
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const { deprecate } = require('electron')
|
||||
const { deprecate } = require('electron');
|
||||
|
||||
if (process.platform === 'darwin') {
|
||||
const { EventEmitter } = require('events')
|
||||
const { inAppPurchase, InAppPurchase } = process.electronBinding('in_app_purchase')
|
||||
const { EventEmitter } = require('events');
|
||||
const { inAppPurchase, InAppPurchase } = process.electronBinding('in_app_purchase');
|
||||
|
||||
// inAppPurchase is an EventEmitter.
|
||||
Object.setPrototypeOf(InAppPurchase.prototype, EventEmitter.prototype)
|
||||
EventEmitter.call(inAppPurchase)
|
||||
Object.setPrototypeOf(InAppPurchase.prototype, EventEmitter.prototype);
|
||||
EventEmitter.call(inAppPurchase);
|
||||
|
||||
module.exports = inAppPurchase
|
||||
module.exports = inAppPurchase;
|
||||
} else {
|
||||
module.exports = {
|
||||
purchaseProduct: (productID, quantity, callback) => {
|
||||
throw new Error('The inAppPurchase module can only be used on macOS')
|
||||
throw new Error('The inAppPurchase module can only be used on macOS');
|
||||
},
|
||||
canMakePayments: () => false,
|
||||
getReceiptURL: () => ''
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { IpcMainImpl } from '@electron/internal/browser/ipc-main-impl'
|
||||
import { IpcMainImpl } from '@electron/internal/browser/ipc-main-impl';
|
||||
|
||||
const ipcMain = new IpcMainImpl()
|
||||
const ipcMain = new IpcMainImpl();
|
||||
|
||||
// Do not throw exception when channel name is "error".
|
||||
ipcMain.on('error', () => {})
|
||||
ipcMain.on('error', () => {});
|
||||
|
||||
export default ipcMain
|
||||
export default ipcMain;
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const { app } = require('electron')
|
||||
const { app } = require('electron');
|
||||
|
||||
const isMac = process.platform === 'darwin'
|
||||
const isWindows = process.platform === 'win32'
|
||||
const isLinux = process.platform === 'linux'
|
||||
const isMac = process.platform === 'darwin';
|
||||
const isWindows = process.platform === 'win32';
|
||||
const isLinux = process.platform === 'linux';
|
||||
|
||||
const roles = {
|
||||
about: {
|
||||
get label () {
|
||||
return isLinux ? 'About' : `About ${app.name}`
|
||||
return isLinux ? 'About' : `About ${app.name}`;
|
||||
}
|
||||
},
|
||||
close: {
|
||||
@@ -38,7 +38,7 @@ const roles = {
|
||||
accelerator: 'Shift+CmdOrCtrl+R',
|
||||
nonNativeMacOSRole: true,
|
||||
windowMethod: (window) => {
|
||||
window.webContents.reloadIgnoringCache()
|
||||
window.webContents.reloadIgnoringCache();
|
||||
}
|
||||
},
|
||||
front: {
|
||||
@@ -49,7 +49,7 @@ const roles = {
|
||||
},
|
||||
hide: {
|
||||
get label () {
|
||||
return `Hide ${app.name}`
|
||||
return `Hide ${app.name}`;
|
||||
},
|
||||
accelerator: 'Command+H'
|
||||
},
|
||||
@@ -77,9 +77,9 @@ const roles = {
|
||||
quit: {
|
||||
get label () {
|
||||
switch (process.platform) {
|
||||
case 'darwin': return `Quit ${app.name}`
|
||||
case 'win32': return 'Exit'
|
||||
default: return 'Quit'
|
||||
case 'darwin': return `Quit ${app.name}`;
|
||||
case 'win32': return 'Exit';
|
||||
default: return 'Quit';
|
||||
}
|
||||
},
|
||||
accelerator: isWindows ? undefined : 'CommandOrControl+Q',
|
||||
@@ -101,7 +101,7 @@ const roles = {
|
||||
accelerator: 'CommandOrControl+0',
|
||||
nonNativeMacOSRole: true,
|
||||
webContentsMethod: (webContents) => {
|
||||
webContents.zoomLevel = 0
|
||||
webContents.zoomLevel = 0;
|
||||
}
|
||||
},
|
||||
selectall: {
|
||||
@@ -134,7 +134,7 @@ const roles = {
|
||||
label: 'Toggle Full Screen',
|
||||
accelerator: isMac ? 'Control+Command+F' : 'F11',
|
||||
windowMethod: (window) => {
|
||||
window.setFullScreen(!window.isFullScreen())
|
||||
window.setFullScreen(!window.isFullScreen());
|
||||
}
|
||||
},
|
||||
undo: {
|
||||
@@ -156,7 +156,7 @@ const roles = {
|
||||
accelerator: 'CommandOrControl+Plus',
|
||||
nonNativeMacOSRole: true,
|
||||
webContentsMethod: (webContents) => {
|
||||
webContents.zoomLevel += 0.5
|
||||
webContents.zoomLevel += 0.5;
|
||||
}
|
||||
},
|
||||
zoomout: {
|
||||
@@ -164,13 +164,13 @@ const roles = {
|
||||
accelerator: 'CommandOrControl+-',
|
||||
nonNativeMacOSRole: true,
|
||||
webContentsMethod: (webContents) => {
|
||||
webContents.zoomLevel -= 0.5
|
||||
webContents.zoomLevel -= 0.5;
|
||||
}
|
||||
},
|
||||
// App submenu should be used for Mac only
|
||||
appmenu: {
|
||||
get label () {
|
||||
return app.name
|
||||
return app.name;
|
||||
},
|
||||
submenu: [
|
||||
{ role: 'about' },
|
||||
@@ -249,71 +249,71 @@ const roles = {
|
||||
])
|
||||
]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
exports.roleList = roles
|
||||
exports.roleList = roles;
|
||||
|
||||
const canExecuteRole = (role) => {
|
||||
if (!roles.hasOwnProperty(role)) return false
|
||||
if (!isMac) return true
|
||||
if (!roles.hasOwnProperty(role)) return false;
|
||||
if (!isMac) return true;
|
||||
|
||||
// macOS handles all roles natively except for a few
|
||||
return roles[role].nonNativeMacOSRole
|
||||
}
|
||||
return roles[role].nonNativeMacOSRole;
|
||||
};
|
||||
|
||||
exports.getDefaultLabel = (role) => {
|
||||
return roles.hasOwnProperty(role) ? roles[role].label : ''
|
||||
}
|
||||
return roles.hasOwnProperty(role) ? roles[role].label : '';
|
||||
};
|
||||
|
||||
exports.getDefaultAccelerator = (role) => {
|
||||
if (roles.hasOwnProperty(role)) return roles[role].accelerator
|
||||
}
|
||||
if (roles.hasOwnProperty(role)) return roles[role].accelerator;
|
||||
};
|
||||
|
||||
exports.shouldRegisterAccelerator = (role) => {
|
||||
const hasRoleRegister = roles.hasOwnProperty(role) && roles[role].registerAccelerator !== undefined
|
||||
return hasRoleRegister ? roles[role].registerAccelerator : true
|
||||
}
|
||||
const hasRoleRegister = roles.hasOwnProperty(role) && roles[role].registerAccelerator !== undefined;
|
||||
return hasRoleRegister ? roles[role].registerAccelerator : true;
|
||||
};
|
||||
|
||||
exports.getDefaultSubmenu = (role) => {
|
||||
if (!roles.hasOwnProperty(role)) return
|
||||
if (!roles.hasOwnProperty(role)) return;
|
||||
|
||||
let { submenu } = roles[role]
|
||||
let { submenu } = roles[role];
|
||||
|
||||
// remove null items from within the submenu
|
||||
if (Array.isArray(submenu)) {
|
||||
submenu = submenu.filter((item) => item != null)
|
||||
submenu = submenu.filter((item) => item != null);
|
||||
}
|
||||
|
||||
return submenu
|
||||
}
|
||||
return submenu;
|
||||
};
|
||||
|
||||
exports.execute = (role, focusedWindow, focusedWebContents) => {
|
||||
if (!canExecuteRole(role)) return false
|
||||
if (!canExecuteRole(role)) return false;
|
||||
|
||||
const { appMethod, webContentsMethod, windowMethod } = roles[role]
|
||||
const { appMethod, webContentsMethod, windowMethod } = roles[role];
|
||||
|
||||
if (appMethod) {
|
||||
app[appMethod]()
|
||||
return true
|
||||
app[appMethod]();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (windowMethod && focusedWindow != null) {
|
||||
if (typeof windowMethod === 'function') {
|
||||
windowMethod(focusedWindow)
|
||||
windowMethod(focusedWindow);
|
||||
} else {
|
||||
focusedWindow[windowMethod]()
|
||||
focusedWindow[windowMethod]();
|
||||
}
|
||||
return true
|
||||
return true;
|
||||
}
|
||||
|
||||
if (webContentsMethod && focusedWebContents != null) {
|
||||
if (typeof webContentsMethod === 'function') {
|
||||
webContentsMethod(focusedWebContents)
|
||||
webContentsMethod(focusedWebContents);
|
||||
} else {
|
||||
focusedWebContents[webContentsMethod]()
|
||||
focusedWebContents[webContentsMethod]();
|
||||
}
|
||||
return true
|
||||
return true;
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -1,87 +1,87 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const roles = require('@electron/internal/browser/api/menu-item-roles')
|
||||
const roles = require('@electron/internal/browser/api/menu-item-roles');
|
||||
|
||||
let nextCommandId = 0
|
||||
let nextCommandId = 0;
|
||||
|
||||
const MenuItem = function (options) {
|
||||
const { Menu } = require('electron')
|
||||
const { Menu } = require('electron');
|
||||
|
||||
// Preserve extra fields specified by user
|
||||
for (const key in options) {
|
||||
if (!(key in this)) this[key] = options[key]
|
||||
if (!(key in this)) this[key] = options[key];
|
||||
}
|
||||
if (typeof this.role === 'string' || this.role instanceof String) {
|
||||
this.role = this.role.toLowerCase()
|
||||
this.role = this.role.toLowerCase();
|
||||
}
|
||||
this.submenu = this.submenu || roles.getDefaultSubmenu(this.role)
|
||||
this.submenu = this.submenu || roles.getDefaultSubmenu(this.role);
|
||||
if (this.submenu != null && this.submenu.constructor !== Menu) {
|
||||
this.submenu = Menu.buildFromTemplate(this.submenu)
|
||||
this.submenu = Menu.buildFromTemplate(this.submenu);
|
||||
}
|
||||
if (this.type == null && this.submenu != null) {
|
||||
this.type = 'submenu'
|
||||
this.type = 'submenu';
|
||||
}
|
||||
if (this.type === 'submenu' && (this.submenu == null || this.submenu.constructor !== Menu)) {
|
||||
throw new Error('Invalid submenu')
|
||||
throw new Error('Invalid submenu');
|
||||
}
|
||||
|
||||
this.overrideReadOnlyProperty('type', 'normal')
|
||||
this.overrideReadOnlyProperty('role')
|
||||
this.overrideReadOnlyProperty('accelerator')
|
||||
this.overrideReadOnlyProperty('icon')
|
||||
this.overrideReadOnlyProperty('submenu')
|
||||
this.overrideReadOnlyProperty('type', 'normal');
|
||||
this.overrideReadOnlyProperty('role');
|
||||
this.overrideReadOnlyProperty('accelerator');
|
||||
this.overrideReadOnlyProperty('icon');
|
||||
this.overrideReadOnlyProperty('submenu');
|
||||
|
||||
this.overrideProperty('label', roles.getDefaultLabel(this.role))
|
||||
this.overrideProperty('sublabel', '')
|
||||
this.overrideProperty('toolTip', '')
|
||||
this.overrideProperty('enabled', true)
|
||||
this.overrideProperty('visible', true)
|
||||
this.overrideProperty('checked', false)
|
||||
this.overrideProperty('acceleratorWorksWhenHidden', true)
|
||||
this.overrideProperty('registerAccelerator', roles.shouldRegisterAccelerator(this.role))
|
||||
this.overrideProperty('label', roles.getDefaultLabel(this.role));
|
||||
this.overrideProperty('sublabel', '');
|
||||
this.overrideProperty('toolTip', '');
|
||||
this.overrideProperty('enabled', true);
|
||||
this.overrideProperty('visible', true);
|
||||
this.overrideProperty('checked', false);
|
||||
this.overrideProperty('acceleratorWorksWhenHidden', true);
|
||||
this.overrideProperty('registerAccelerator', roles.shouldRegisterAccelerator(this.role));
|
||||
|
||||
if (!MenuItem.types.includes(this.type)) {
|
||||
throw new Error(`Unknown menu item type: ${this.type}`)
|
||||
throw new Error(`Unknown menu item type: ${this.type}`);
|
||||
}
|
||||
|
||||
this.overrideReadOnlyProperty('commandId', ++nextCommandId)
|
||||
this.overrideReadOnlyProperty('commandId', ++nextCommandId);
|
||||
|
||||
const click = options.click
|
||||
const click = options.click;
|
||||
this.click = (event, focusedWindow, focusedWebContents) => {
|
||||
// Manually flip the checked flags when clicked.
|
||||
if (this.type === 'checkbox' || this.type === 'radio') {
|
||||
this.checked = !this.checked
|
||||
this.checked = !this.checked;
|
||||
}
|
||||
|
||||
if (!roles.execute(this.role, focusedWindow, focusedWebContents)) {
|
||||
if (typeof click === 'function') {
|
||||
click(this, focusedWindow, event)
|
||||
click(this, focusedWindow, event);
|
||||
} else if (typeof this.selector === 'string' && process.platform === 'darwin') {
|
||||
Menu.sendActionToFirstResponder(this.selector)
|
||||
Menu.sendActionToFirstResponder(this.selector);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
MenuItem.types = ['normal', 'separator', 'submenu', 'checkbox', 'radio']
|
||||
MenuItem.types = ['normal', 'separator', 'submenu', 'checkbox', 'radio'];
|
||||
|
||||
MenuItem.prototype.getDefaultRoleAccelerator = function () {
|
||||
return roles.getDefaultAccelerator(this.role)
|
||||
}
|
||||
return roles.getDefaultAccelerator(this.role);
|
||||
};
|
||||
|
||||
MenuItem.prototype.overrideProperty = function (name, defaultValue = null) {
|
||||
if (this[name] == null) {
|
||||
this[name] = defaultValue
|
||||
this[name] = defaultValue;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
MenuItem.prototype.overrideReadOnlyProperty = function (name, defaultValue) {
|
||||
this.overrideProperty(name, defaultValue)
|
||||
this.overrideProperty(name, defaultValue);
|
||||
Object.defineProperty(this, name, {
|
||||
enumerable: true,
|
||||
writable: false,
|
||||
value: this[name]
|
||||
})
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = MenuItem
|
||||
module.exports = MenuItem;
|
||||
|
||||
@@ -1,41 +1,41 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
function splitArray (arr, predicate) {
|
||||
const result = arr.reduce((multi, item) => {
|
||||
const current = multi[multi.length - 1]
|
||||
const current = multi[multi.length - 1];
|
||||
if (predicate(item)) {
|
||||
if (current.length > 0) multi.push([])
|
||||
if (current.length > 0) multi.push([]);
|
||||
} else {
|
||||
current.push(item)
|
||||
current.push(item);
|
||||
}
|
||||
return multi
|
||||
}, [[]])
|
||||
return multi;
|
||||
}, [[]]);
|
||||
|
||||
if (result[result.length - 1].length === 0) {
|
||||
return result.slice(0, result.length - 1)
|
||||
return result.slice(0, result.length - 1);
|
||||
}
|
||||
return result
|
||||
return result;
|
||||
}
|
||||
|
||||
function joinArrays (arrays, joinIDs) {
|
||||
return arrays.reduce((joined, arr, i) => {
|
||||
if (i > 0 && arr.length) {
|
||||
if (joinIDs.length > 0) {
|
||||
joined.push(joinIDs[0])
|
||||
joinIDs.splice(0, 1)
|
||||
joined.push(joinIDs[0]);
|
||||
joinIDs.splice(0, 1);
|
||||
} else {
|
||||
joined.push({ type: 'separator' })
|
||||
joined.push({ type: 'separator' });
|
||||
}
|
||||
}
|
||||
return joined.concat(arr)
|
||||
}, [])
|
||||
return joined.concat(arr);
|
||||
}, []);
|
||||
}
|
||||
|
||||
function pushOntoMultiMap (map, key, value) {
|
||||
if (!map.has(key)) {
|
||||
map.set(key, [])
|
||||
map.set(key, []);
|
||||
}
|
||||
map.get(key).push(value)
|
||||
map.get(key).push(value);
|
||||
}
|
||||
|
||||
function indexOfGroupContainingID (groups, id, ignoreGroup) {
|
||||
@@ -45,102 +45,102 @@ function indexOfGroupContainingID (groups, id, ignoreGroup) {
|
||||
candidateGroup.some(
|
||||
candidateItem => candidateItem.id === id
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Sort nodes topologically using a depth-first approach. Encountered cycles
|
||||
// are broken.
|
||||
function sortTopologically (originalOrder, edgesById) {
|
||||
const sorted = []
|
||||
const marked = new Set()
|
||||
const sorted = [];
|
||||
const marked = new Set();
|
||||
|
||||
const visit = (mark) => {
|
||||
if (marked.has(mark)) return
|
||||
marked.add(mark)
|
||||
const edges = edgesById.get(mark)
|
||||
if (marked.has(mark)) return;
|
||||
marked.add(mark);
|
||||
const edges = edgesById.get(mark);
|
||||
if (edges != null) {
|
||||
edges.forEach(visit)
|
||||
edges.forEach(visit);
|
||||
}
|
||||
sorted.push(mark)
|
||||
}
|
||||
sorted.push(mark);
|
||||
};
|
||||
|
||||
originalOrder.forEach(visit)
|
||||
return sorted
|
||||
originalOrder.forEach(visit);
|
||||
return sorted;
|
||||
}
|
||||
|
||||
function attemptToMergeAGroup (groups) {
|
||||
for (let i = 0; i < groups.length; i++) {
|
||||
const group = groups[i]
|
||||
const group = groups[i];
|
||||
for (const item of group) {
|
||||
const toIDs = [...(item.before || []), ...(item.after || [])]
|
||||
const toIDs = [...(item.before || []), ...(item.after || [])];
|
||||
for (const id of toIDs) {
|
||||
const index = indexOfGroupContainingID(groups, id, group)
|
||||
if (index === -1) continue
|
||||
const mergeTarget = groups[index]
|
||||
const index = indexOfGroupContainingID(groups, id, group);
|
||||
if (index === -1) continue;
|
||||
const mergeTarget = groups[index];
|
||||
|
||||
mergeTarget.push(...group)
|
||||
groups.splice(i, 1)
|
||||
return true
|
||||
mergeTarget.push(...group);
|
||||
groups.splice(i, 1);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
return false;
|
||||
}
|
||||
|
||||
function mergeGroups (groups) {
|
||||
let merged = true
|
||||
let merged = true;
|
||||
while (merged) {
|
||||
merged = attemptToMergeAGroup(groups)
|
||||
merged = attemptToMergeAGroup(groups);
|
||||
}
|
||||
return groups
|
||||
return groups;
|
||||
}
|
||||
|
||||
function sortItemsInGroup (group) {
|
||||
const originalOrder = group.map((node, i) => i)
|
||||
const edges = new Map()
|
||||
const idToIndex = new Map(group.map((item, i) => [item.id, i]))
|
||||
const originalOrder = group.map((node, i) => i);
|
||||
const edges = new Map();
|
||||
const idToIndex = new Map(group.map((item, i) => [item.id, i]));
|
||||
|
||||
group.forEach((item, i) => {
|
||||
if (item.before) {
|
||||
item.before.forEach(toID => {
|
||||
const to = idToIndex.get(toID)
|
||||
const to = idToIndex.get(toID);
|
||||
if (to != null) {
|
||||
pushOntoMultiMap(edges, to, i)
|
||||
pushOntoMultiMap(edges, to, i);
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
if (item.after) {
|
||||
item.after.forEach(toID => {
|
||||
const to = idToIndex.get(toID)
|
||||
const to = idToIndex.get(toID);
|
||||
if (to != null) {
|
||||
pushOntoMultiMap(edges, i, to)
|
||||
pushOntoMultiMap(edges, i, to);
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
const sortedNodes = sortTopologically(originalOrder, edges)
|
||||
return sortedNodes.map(i => group[i])
|
||||
const sortedNodes = sortTopologically(originalOrder, edges);
|
||||
return sortedNodes.map(i => group[i]);
|
||||
}
|
||||
|
||||
function findEdgesInGroup (groups, i, edges) {
|
||||
const group = groups[i]
|
||||
const group = groups[i];
|
||||
for (const item of group) {
|
||||
if (item.beforeGroupContaining) {
|
||||
for (const id of item.beforeGroupContaining) {
|
||||
const to = indexOfGroupContainingID(groups, id, group)
|
||||
const to = indexOfGroupContainingID(groups, id, group);
|
||||
if (to !== -1) {
|
||||
pushOntoMultiMap(edges, to, i)
|
||||
return
|
||||
pushOntoMultiMap(edges, to, i);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (item.afterGroupContaining) {
|
||||
for (const id of item.afterGroupContaining) {
|
||||
const to = indexOfGroupContainingID(groups, id, group)
|
||||
const to = indexOfGroupContainingID(groups, id, group);
|
||||
if (to !== -1) {
|
||||
pushOntoMultiMap(edges, i, to)
|
||||
return
|
||||
pushOntoMultiMap(edges, i, to);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -148,29 +148,29 @@ function findEdgesInGroup (groups, i, edges) {
|
||||
}
|
||||
|
||||
function sortGroups (groups) {
|
||||
const originalOrder = groups.map((item, i) => i)
|
||||
const edges = new Map()
|
||||
const originalOrder = groups.map((item, i) => i);
|
||||
const edges = new Map();
|
||||
|
||||
for (let i = 0; i < groups.length; i++) {
|
||||
findEdgesInGroup(groups, i, edges)
|
||||
findEdgesInGroup(groups, i, edges);
|
||||
}
|
||||
|
||||
const sortedGroupIndexes = sortTopologically(originalOrder, edges)
|
||||
return sortedGroupIndexes.map(i => groups[i])
|
||||
const sortedGroupIndexes = sortTopologically(originalOrder, edges);
|
||||
return sortedGroupIndexes.map(i => groups[i]);
|
||||
}
|
||||
|
||||
function sortMenuItems (menuItems) {
|
||||
const isSeparator = (item) => item.type === 'separator'
|
||||
const separators = menuItems.filter(i => i.type === 'separator')
|
||||
const isSeparator = (item) => item.type === 'separator';
|
||||
const separators = menuItems.filter(i => i.type === 'separator');
|
||||
|
||||
// Split the items into their implicit groups based upon separators.
|
||||
const groups = splitArray(menuItems, isSeparator)
|
||||
const mergedGroups = mergeGroups(groups)
|
||||
const mergedGroupsWithSortedItems = mergedGroups.map(sortItemsInGroup)
|
||||
const sortedGroups = sortGroups(mergedGroupsWithSortedItems)
|
||||
const groups = splitArray(menuItems, isSeparator);
|
||||
const mergedGroups = mergeGroups(groups);
|
||||
const mergedGroupsWithSortedItems = mergedGroups.map(sortItemsInGroup);
|
||||
const sortedGroups = sortGroups(mergedGroupsWithSortedItems);
|
||||
|
||||
const joined = joinArrays(sortedGroups, separators)
|
||||
return joined
|
||||
const joined = joinArrays(sortedGroups, separators);
|
||||
return joined;
|
||||
}
|
||||
|
||||
module.exports = { sortMenuItems }
|
||||
module.exports = { sortMenuItems };
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const { TopLevelWindow, MenuItem, webContents } = require('electron')
|
||||
const { sortMenuItems } = require('@electron/internal/browser/api/menu-utils')
|
||||
const EventEmitter = require('events').EventEmitter
|
||||
const v8Util = process.electronBinding('v8_util')
|
||||
const bindings = process.electronBinding('menu')
|
||||
const { TopLevelWindow, MenuItem, webContents } = require('electron');
|
||||
const { sortMenuItems } = require('@electron/internal/browser/api/menu-utils');
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
const v8Util = process.electronBinding('v8_util');
|
||||
const bindings = process.electronBinding('menu');
|
||||
|
||||
const { Menu } = bindings
|
||||
let applicationMenu = null
|
||||
let groupIdIndex = 0
|
||||
const { Menu } = bindings;
|
||||
let applicationMenu = null;
|
||||
let groupIdIndex = 0;
|
||||
|
||||
Object.setPrototypeOf(Menu.prototype, EventEmitter.prototype)
|
||||
Object.setPrototypeOf(Menu.prototype, EventEmitter.prototype);
|
||||
|
||||
// Menu Delegate.
|
||||
// This object should hold no reference to |Menu| to avoid cyclic reference.
|
||||
@@ -20,172 +20,172 @@ const delegate = {
|
||||
shouldCommandIdWorkWhenHidden: (menu, id) => menu.commandsMap[id] ? menu.commandsMap[id].acceleratorWorksWhenHidden : undefined,
|
||||
isCommandIdVisible: (menu, id) => menu.commandsMap[id] ? menu.commandsMap[id].visible : undefined,
|
||||
getAcceleratorForCommandId: (menu, id, useDefaultAccelerator) => {
|
||||
const command = menu.commandsMap[id]
|
||||
if (!command) return
|
||||
if (command.accelerator != null) return command.accelerator
|
||||
if (useDefaultAccelerator) return command.getDefaultRoleAccelerator()
|
||||
const command = menu.commandsMap[id];
|
||||
if (!command) return;
|
||||
if (command.accelerator != null) return command.accelerator;
|
||||
if (useDefaultAccelerator) return command.getDefaultRoleAccelerator();
|
||||
},
|
||||
shouldRegisterAcceleratorForCommandId: (menu, id) => menu.commandsMap[id] ? menu.commandsMap[id].registerAccelerator : undefined,
|
||||
executeCommand: (menu, event, id) => {
|
||||
const command = menu.commandsMap[id]
|
||||
if (!command) return
|
||||
command.click(event, TopLevelWindow.getFocusedWindow(), webContents.getFocusedWebContents())
|
||||
const command = menu.commandsMap[id];
|
||||
if (!command) return;
|
||||
command.click(event, TopLevelWindow.getFocusedWindow(), webContents.getFocusedWebContents());
|
||||
},
|
||||
menuWillShow: (menu) => {
|
||||
// Ensure radio groups have at least one menu item selected
|
||||
for (const id in menu.groupsMap) {
|
||||
const found = menu.groupsMap[id].find(item => item.checked) || null
|
||||
if (!found) v8Util.setHiddenValue(menu.groupsMap[id][0], 'checked', true)
|
||||
for (const id of Object.keys(menu.groupsMap)) {
|
||||
const found = menu.groupsMap[id].find(item => item.checked) || null;
|
||||
if (!found) v8Util.setHiddenValue(menu.groupsMap[id][0], 'checked', true);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/* Instance Methods */
|
||||
|
||||
Menu.prototype._init = function () {
|
||||
this.commandsMap = {}
|
||||
this.groupsMap = {}
|
||||
this.items = []
|
||||
this.delegate = delegate
|
||||
}
|
||||
this.commandsMap = {};
|
||||
this.groupsMap = {};
|
||||
this.items = [];
|
||||
this.delegate = delegate;
|
||||
};
|
||||
|
||||
Menu.prototype.popup = function (options = {}) {
|
||||
if (options == null || typeof options !== 'object') {
|
||||
throw new TypeError('Options must be an object')
|
||||
throw new TypeError('Options must be an object');
|
||||
}
|
||||
let { window, x, y, positioningItem, callback } = options
|
||||
let { window, x, y, positioningItem, callback } = options;
|
||||
|
||||
// no callback passed
|
||||
if (!callback || typeof callback !== 'function') callback = () => {}
|
||||
if (!callback || typeof callback !== 'function') callback = () => {};
|
||||
|
||||
// set defaults
|
||||
if (typeof x !== 'number') x = -1
|
||||
if (typeof y !== 'number') y = -1
|
||||
if (typeof positioningItem !== 'number') positioningItem = -1
|
||||
if (typeof x !== 'number') x = -1;
|
||||
if (typeof y !== 'number') y = -1;
|
||||
if (typeof positioningItem !== 'number') positioningItem = -1;
|
||||
|
||||
// find which window to use
|
||||
const wins = TopLevelWindow.getAllWindows()
|
||||
const wins = TopLevelWindow.getAllWindows();
|
||||
if (!wins || wins.indexOf(window) === -1) {
|
||||
window = TopLevelWindow.getFocusedWindow()
|
||||
window = TopLevelWindow.getFocusedWindow();
|
||||
if (!window && wins && wins.length > 0) {
|
||||
window = wins[0]
|
||||
window = wins[0];
|
||||
}
|
||||
if (!window) {
|
||||
throw new Error(`Cannot open Menu without a TopLevelWindow present`)
|
||||
throw new Error(`Cannot open Menu without a TopLevelWindow present`);
|
||||
}
|
||||
}
|
||||
|
||||
this.popupAt(window, x, y, positioningItem, callback)
|
||||
return { browserWindow: window, x, y, position: positioningItem }
|
||||
}
|
||||
this.popupAt(window, x, y, positioningItem, callback);
|
||||
return { browserWindow: window, x, y, position: positioningItem };
|
||||
};
|
||||
|
||||
Menu.prototype.closePopup = function (window) {
|
||||
if (window instanceof TopLevelWindow) {
|
||||
this.closePopupAt(window.id)
|
||||
this.closePopupAt(window.id);
|
||||
} else {
|
||||
// Passing -1 (invalid) would make closePopupAt close the all menu runners
|
||||
// belong to this menu.
|
||||
this.closePopupAt(-1)
|
||||
this.closePopupAt(-1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Menu.prototype.getMenuItemById = function (id) {
|
||||
const items = this.items
|
||||
const items = this.items;
|
||||
|
||||
let found = items.find(item => item.id === id) || null
|
||||
let found = items.find(item => item.id === id) || null;
|
||||
for (let i = 0; !found && i < items.length; i++) {
|
||||
if (items[i].submenu) {
|
||||
found = items[i].submenu.getMenuItemById(id)
|
||||
found = items[i].submenu.getMenuItemById(id);
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
return found;
|
||||
};
|
||||
|
||||
Menu.prototype.append = function (item) {
|
||||
return this.insert(this.getItemCount(), item)
|
||||
}
|
||||
return this.insert(this.getItemCount(), item);
|
||||
};
|
||||
|
||||
Menu.prototype.insert = function (pos, item) {
|
||||
if ((item ? item.constructor : void 0) !== MenuItem) {
|
||||
throw new TypeError('Invalid item')
|
||||
throw new TypeError('Invalid item');
|
||||
}
|
||||
|
||||
if (pos < 0) {
|
||||
throw new RangeError(`Position ${pos} cannot be less than 0`)
|
||||
throw new RangeError(`Position ${pos} cannot be less than 0`);
|
||||
} else if (pos > this.getItemCount()) {
|
||||
throw new RangeError(`Position ${pos} cannot be greater than the total MenuItem count`)
|
||||
throw new RangeError(`Position ${pos} cannot be greater than the total MenuItem count`);
|
||||
}
|
||||
|
||||
// insert item depending on its type
|
||||
insertItemByType.call(this, item, pos)
|
||||
insertItemByType.call(this, item, pos);
|
||||
|
||||
// set item properties
|
||||
if (item.sublabel) this.setSublabel(pos, item.sublabel)
|
||||
if (item.toolTip) this.setToolTip(pos, item.toolTip)
|
||||
if (item.icon) this.setIcon(pos, item.icon)
|
||||
if (item.role) this.setRole(pos, item.role)
|
||||
if (item.sublabel) this.setSublabel(pos, item.sublabel);
|
||||
if (item.toolTip) this.setToolTip(pos, item.toolTip);
|
||||
if (item.icon) this.setIcon(pos, item.icon);
|
||||
if (item.role) this.setRole(pos, item.role);
|
||||
|
||||
// Make menu accessable to items.
|
||||
item.overrideReadOnlyProperty('menu', this)
|
||||
item.overrideReadOnlyProperty('menu', this);
|
||||
|
||||
// Remember the items.
|
||||
this.items.splice(pos, 0, item)
|
||||
this.commandsMap[item.commandId] = item
|
||||
}
|
||||
this.items.splice(pos, 0, item);
|
||||
this.commandsMap[item.commandId] = item;
|
||||
};
|
||||
|
||||
Menu.prototype._callMenuWillShow = function () {
|
||||
if (this.delegate) this.delegate.menuWillShow(this)
|
||||
if (this.delegate) this.delegate.menuWillShow(this);
|
||||
this.items.forEach(item => {
|
||||
if (item.submenu) item.submenu._callMenuWillShow()
|
||||
})
|
||||
}
|
||||
if (item.submenu) item.submenu._callMenuWillShow();
|
||||
});
|
||||
};
|
||||
|
||||
/* Static Methods */
|
||||
|
||||
Menu.getApplicationMenu = () => applicationMenu
|
||||
Menu.getApplicationMenu = () => applicationMenu;
|
||||
|
||||
Menu.sendActionToFirstResponder = bindings.sendActionToFirstResponder
|
||||
Menu.sendActionToFirstResponder = bindings.sendActionToFirstResponder;
|
||||
|
||||
// set application menu with a preexisting menu
|
||||
Menu.setApplicationMenu = function (menu) {
|
||||
if (menu && menu.constructor !== Menu) {
|
||||
throw new TypeError('Invalid menu')
|
||||
throw new TypeError('Invalid menu');
|
||||
}
|
||||
|
||||
applicationMenu = menu
|
||||
v8Util.setHiddenValue(global, 'applicationMenuSet', true)
|
||||
applicationMenu = menu;
|
||||
v8Util.setHiddenValue(global, 'applicationMenuSet', true);
|
||||
|
||||
if (process.platform === 'darwin') {
|
||||
if (!menu) return
|
||||
menu._callMenuWillShow()
|
||||
bindings.setApplicationMenu(menu)
|
||||
if (!menu) return;
|
||||
menu._callMenuWillShow();
|
||||
bindings.setApplicationMenu(menu);
|
||||
} else {
|
||||
const windows = TopLevelWindow.getAllWindows()
|
||||
return windows.map(w => w.setMenu(menu))
|
||||
const windows = TopLevelWindow.getAllWindows();
|
||||
return windows.map(w => w.setMenu(menu));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Menu.buildFromTemplate = function (template) {
|
||||
if (!Array.isArray(template)) {
|
||||
throw new TypeError('Invalid template for Menu: Menu template must be an array')
|
||||
throw new TypeError('Invalid template for Menu: Menu template must be an array');
|
||||
}
|
||||
if (!areValidTemplateItems(template)) {
|
||||
throw new TypeError('Invalid template for MenuItem: must have at least one of label, role or type')
|
||||
throw new TypeError('Invalid template for MenuItem: must have at least one of label, role or type');
|
||||
}
|
||||
const filtered = removeExtraSeparators(template)
|
||||
const sorted = sortTemplate(filtered)
|
||||
const filtered = removeExtraSeparators(template);
|
||||
const sorted = sortTemplate(filtered);
|
||||
|
||||
const menu = new Menu()
|
||||
const menu = new Menu();
|
||||
sorted.forEach(item => {
|
||||
if (item instanceof MenuItem) {
|
||||
menu.append(item)
|
||||
menu.append(item);
|
||||
} else {
|
||||
menu.append(new MenuItem(item))
|
||||
menu.append(new MenuItem(item));
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
return menu
|
||||
}
|
||||
return menu;
|
||||
};
|
||||
|
||||
/* Helper Functions */
|
||||
|
||||
@@ -196,51 +196,50 @@ function areValidTemplateItems (template) {
|
||||
typeof item === 'object' &&
|
||||
(item.hasOwnProperty('label') ||
|
||||
item.hasOwnProperty('role') ||
|
||||
item.type === 'separator'))
|
||||
item.type === 'separator'));
|
||||
}
|
||||
|
||||
function sortTemplate (template) {
|
||||
const sorted = sortMenuItems(template)
|
||||
for (const id in sorted) {
|
||||
const item = sorted[id]
|
||||
const sorted = sortMenuItems(template);
|
||||
for (const item of sorted) {
|
||||
if (Array.isArray(item.submenu)) {
|
||||
item.submenu = sortTemplate(item.submenu)
|
||||
item.submenu = sortTemplate(item.submenu);
|
||||
}
|
||||
}
|
||||
return sorted
|
||||
return sorted;
|
||||
}
|
||||
|
||||
// Search between separators to find a radio menu item and return its group id
|
||||
function generateGroupId (items, pos) {
|
||||
if (pos > 0) {
|
||||
for (let idx = pos - 1; idx >= 0; idx--) {
|
||||
if (items[idx].type === 'radio') return items[idx].groupId
|
||||
if (items[idx].type === 'separator') break
|
||||
if (items[idx].type === 'radio') return items[idx].groupId;
|
||||
if (items[idx].type === 'separator') break;
|
||||
}
|
||||
} else if (pos < items.length) {
|
||||
for (let idx = pos; idx <= items.length - 1; idx++) {
|
||||
if (items[idx].type === 'radio') return items[idx].groupId
|
||||
if (items[idx].type === 'separator') break
|
||||
if (items[idx].type === 'radio') return items[idx].groupId;
|
||||
if (items[idx].type === 'separator') break;
|
||||
}
|
||||
}
|
||||
groupIdIndex += 1
|
||||
return groupIdIndex
|
||||
groupIdIndex += 1;
|
||||
return groupIdIndex;
|
||||
}
|
||||
|
||||
function removeExtraSeparators (items) {
|
||||
// fold adjacent separators together
|
||||
let ret = items.filter((e, idx, arr) => {
|
||||
if (e.visible === false) return true
|
||||
return e.type !== 'separator' || idx === 0 || arr[idx - 1].type !== 'separator'
|
||||
})
|
||||
if (e.visible === false) return true;
|
||||
return e.type !== 'separator' || idx === 0 || arr[idx - 1].type !== 'separator';
|
||||
});
|
||||
|
||||
// remove edge separators
|
||||
ret = ret.filter((e, idx, arr) => {
|
||||
if (e.visible === false) return true
|
||||
return e.type !== 'separator' || (idx !== 0 && idx !== arr.length - 1)
|
||||
})
|
||||
if (e.visible === false) return true;
|
||||
return e.type !== 'separator' || (idx !== 0 && idx !== arr.length - 1);
|
||||
});
|
||||
|
||||
return ret
|
||||
return ret;
|
||||
}
|
||||
|
||||
function insertItemByType (item, pos) {
|
||||
@@ -251,28 +250,28 @@ function insertItemByType (item, pos) {
|
||||
submenu: () => this.insertSubMenu(pos, item.commandId, item.label, item.submenu),
|
||||
radio: () => {
|
||||
// Grouping radio menu items
|
||||
item.overrideReadOnlyProperty('groupId', generateGroupId(this.items, pos))
|
||||
item.overrideReadOnlyProperty('groupId', generateGroupId(this.items, pos));
|
||||
if (this.groupsMap[item.groupId] == null) {
|
||||
this.groupsMap[item.groupId] = []
|
||||
this.groupsMap[item.groupId] = [];
|
||||
}
|
||||
this.groupsMap[item.groupId].push(item)
|
||||
this.groupsMap[item.groupId].push(item);
|
||||
|
||||
// Setting a radio menu item should flip other items in the group.
|
||||
v8Util.setHiddenValue(item, 'checked', item.checked)
|
||||
v8Util.setHiddenValue(item, 'checked', item.checked);
|
||||
Object.defineProperty(item, 'checked', {
|
||||
enumerable: true,
|
||||
get: () => v8Util.getHiddenValue(item, 'checked'),
|
||||
set: () => {
|
||||
this.groupsMap[item.groupId].forEach(other => {
|
||||
if (other !== item) v8Util.setHiddenValue(other, 'checked', false)
|
||||
})
|
||||
v8Util.setHiddenValue(item, 'checked', true)
|
||||
if (other !== item) v8Util.setHiddenValue(other, 'checked', false);
|
||||
});
|
||||
v8Util.setHiddenValue(item, 'checked', true);
|
||||
}
|
||||
})
|
||||
this.insertRadioItem(pos, item.commandId, item.label, item.groupId)
|
||||
});
|
||||
this.insertRadioItem(pos, item.commandId, item.label, item.groupId);
|
||||
}
|
||||
}
|
||||
types[item.type]()
|
||||
};
|
||||
types[item.type]();
|
||||
}
|
||||
|
||||
module.exports = Menu
|
||||
module.exports = Menu;
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
// TODO: Figure out a way to not duplicate this information between here and module-list
|
||||
// It is currently duplicated as module-list "require"s all the browser API file and the
|
||||
// remote module in the renderer process depends on that file. As a result webpack
|
||||
// includes all the browser API files in the renderer process as well and we want to avoid that
|
||||
|
||||
const features = process.electronBinding('features')
|
||||
const features = process.electronBinding('features');
|
||||
|
||||
// Browser side modules, please sort alphabetically.
|
||||
module.exports = [
|
||||
@@ -37,7 +37,7 @@ module.exports = [
|
||||
{ name: 'View' },
|
||||
{ name: 'webContents' },
|
||||
{ name: 'WebContentsView' }
|
||||
]
|
||||
];
|
||||
|
||||
if (features.isViewApiEnabled()) {
|
||||
module.exports.push(
|
||||
@@ -48,5 +48,5 @@ if (features.isViewApiEnabled()) {
|
||||
{ name: 'MdTextButton' },
|
||||
{ name: 'ResizeArea' },
|
||||
{ name: 'TextField' }
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// TODO: Updating this file also required updating the module-keys file
|
||||
|
||||
const features = process.electronBinding('features')
|
||||
const features = process.electronBinding('features');
|
||||
|
||||
// Browser side modules, please sort alphabetically.
|
||||
export const browserModuleList: ElectronInternal.ModuleEntry[] = [
|
||||
@@ -32,7 +32,7 @@ export const browserModuleList: ElectronInternal.ModuleEntry[] = [
|
||||
{ name: 'View', loader: () => require('./view') },
|
||||
{ name: 'webContents', loader: () => require('./web-contents') },
|
||||
{ name: 'WebContentsView', loader: () => require('./web-contents-view') }
|
||||
]
|
||||
];
|
||||
|
||||
if (features.isViewApiEnabled()) {
|
||||
browserModuleList.push(
|
||||
@@ -43,5 +43,5 @@ if (features.isViewApiEnabled()) {
|
||||
{ name: 'MdTextButton', loader: () => require('./views/md-text-button') },
|
||||
{ name: 'ResizeArea', loader: () => require('./views/resize-area') },
|
||||
{ name: 'TextField', loader: () => require('./views/text-field') }
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { EventEmitter } from 'events'
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
const { NativeTheme, nativeTheme } = process.electronBinding('native_theme')
|
||||
const { NativeTheme, nativeTheme } = process.electronBinding('native_theme');
|
||||
|
||||
Object.setPrototypeOf(NativeTheme.prototype, EventEmitter.prototype)
|
||||
EventEmitter.call(nativeTheme as any)
|
||||
Object.setPrototypeOf(NativeTheme.prototype, EventEmitter.prototype);
|
||||
EventEmitter.call(nativeTheme as any);
|
||||
|
||||
module.exports = nativeTheme
|
||||
module.exports = nativeTheme;
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
// TODO(deepak1556): Deprecate and remove standalone netLog module,
|
||||
// it is now a property of session module.
|
||||
const { app, session } = require('electron')
|
||||
const { app, session } = require('electron');
|
||||
|
||||
// Fallback to default session.
|
||||
Object.setPrototypeOf(module.exports, new Proxy({}, {
|
||||
get (target, property) {
|
||||
if (!app.isReady()) return
|
||||
if (!app.isReady()) return;
|
||||
|
||||
const netLog = session.defaultSession.netLog
|
||||
const netLog = session.defaultSession.netLog;
|
||||
|
||||
if (!Object.getPrototypeOf(netLog).hasOwnProperty(property)) return
|
||||
if (!Object.getPrototypeOf(netLog).hasOwnProperty(property)) return;
|
||||
|
||||
// check for properties on the prototype chain that aren't functions
|
||||
if (typeof netLog[property] !== 'function') return netLog[property]
|
||||
if (typeof netLog[property] !== 'function') return netLog[property];
|
||||
|
||||
// Returning a native function directly would throw error.
|
||||
return (...args) => netLog[property](...args)
|
||||
return (...args) => netLog[property](...args);
|
||||
},
|
||||
|
||||
ownKeys () {
|
||||
if (!app.isReady()) return []
|
||||
if (!app.isReady()) return [];
|
||||
|
||||
return Object.getOwnPropertyNames(Object.getPrototypeOf(session.defaultSession.netLog))
|
||||
return Object.getOwnPropertyNames(Object.getPrototypeOf(session.defaultSession.netLog));
|
||||
},
|
||||
|
||||
getOwnPropertyDescriptor (target) {
|
||||
return { configurable: true, enumerable: true }
|
||||
return { configurable: true, enumerable: true };
|
||||
}
|
||||
}))
|
||||
}));
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const url = require('url')
|
||||
const { EventEmitter } = require('events')
|
||||
const { Readable, Writable } = require('stream')
|
||||
const { app } = require('electron')
|
||||
const { Session } = process.electronBinding('session')
|
||||
const { net, Net, _isValidHeaderName, _isValidHeaderValue } = process.electronBinding('net')
|
||||
const { URLLoader } = net
|
||||
const url = require('url');
|
||||
const { EventEmitter } = require('events');
|
||||
const { Readable, Writable } = require('stream');
|
||||
const { app } = require('electron');
|
||||
const { Session } = process.electronBinding('session');
|
||||
const { net, Net, _isValidHeaderName, _isValidHeaderValue } = process.electronBinding('net');
|
||||
const { URLLoader } = net;
|
||||
|
||||
Object.setPrototypeOf(URLLoader.prototype, EventEmitter.prototype)
|
||||
Object.setPrototypeOf(URLLoader.prototype, EventEmitter.prototype);
|
||||
|
||||
const kSupportedProtocols = new Set(['http:', 'https:'])
|
||||
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
|
||||
@@ -33,27 +33,27 @@ const discardableDuplicateHeaders = new Set([
|
||||
'server',
|
||||
'age',
|
||||
'expires'
|
||||
])
|
||||
]);
|
||||
|
||||
class IncomingMessage extends Readable {
|
||||
constructor (responseHead) {
|
||||
super()
|
||||
this._shouldPush = false
|
||||
this._data = []
|
||||
this._responseHead = responseHead
|
||||
super();
|
||||
this._shouldPush = false;
|
||||
this._data = [];
|
||||
this._responseHead = responseHead;
|
||||
}
|
||||
|
||||
get statusCode () {
|
||||
return this._responseHead.statusCode
|
||||
return this._responseHead.statusCode;
|
||||
}
|
||||
|
||||
get statusMessage () {
|
||||
return this._responseHead.statusMessage
|
||||
return this._responseHead.statusMessage;
|
||||
}
|
||||
|
||||
get headers () {
|
||||
const filteredHeaders = {}
|
||||
const { rawHeaders } = this._responseHead
|
||||
const filteredHeaders = {};
|
||||
const { rawHeaders } = this._responseHead;
|
||||
rawHeaders.forEach(header => {
|
||||
if (Object.prototype.hasOwnProperty.call(filteredHeaders, header.key) &&
|
||||
discardableDuplicateHeaders.has(header.key)) {
|
||||
@@ -63,145 +63,145 @@ class IncomingMessage extends Readable {
|
||||
// keep set-cookie as an array per Node.js rules
|
||||
// see https://nodejs.org/api/http.html#http_message_headers
|
||||
if (Object.prototype.hasOwnProperty.call(filteredHeaders, header.key)) {
|
||||
filteredHeaders[header.key].push(header.value)
|
||||
filteredHeaders[header.key].push(header.value);
|
||||
} else {
|
||||
filteredHeaders[header.key] = [header.value]
|
||||
filteredHeaders[header.key] = [header.value];
|
||||
}
|
||||
} else {
|
||||
// for non-cookie headers, the values are joined together with ', '
|
||||
if (Object.prototype.hasOwnProperty.call(filteredHeaders, header.key)) {
|
||||
filteredHeaders[header.key] += `, ${header.value}`
|
||||
filteredHeaders[header.key] += `, ${header.value}`;
|
||||
} else {
|
||||
filteredHeaders[header.key] = header.value
|
||||
filteredHeaders[header.key] = header.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
return filteredHeaders
|
||||
});
|
||||
return filteredHeaders;
|
||||
}
|
||||
|
||||
get httpVersion () {
|
||||
return `${this.httpVersionMajor}.${this.httpVersionMinor}`
|
||||
return `${this.httpVersionMajor}.${this.httpVersionMinor}`;
|
||||
}
|
||||
|
||||
get httpVersionMajor () {
|
||||
return this._responseHead.httpVersion.major
|
||||
return this._responseHead.httpVersion.major;
|
||||
}
|
||||
|
||||
get httpVersionMinor () {
|
||||
return this._responseHead.httpVersion.minor
|
||||
return this._responseHead.httpVersion.minor;
|
||||
}
|
||||
|
||||
get rawTrailers () {
|
||||
throw new Error('HTTP trailers are not supported')
|
||||
throw new Error('HTTP trailers are not supported');
|
||||
}
|
||||
|
||||
get trailers () {
|
||||
throw new Error('HTTP trailers are not supported')
|
||||
throw new Error('HTTP trailers are not supported');
|
||||
}
|
||||
|
||||
_storeInternalData (chunk) {
|
||||
this._data.push(chunk)
|
||||
this._pushInternalData()
|
||||
this._data.push(chunk);
|
||||
this._pushInternalData();
|
||||
}
|
||||
|
||||
_pushInternalData () {
|
||||
while (this._shouldPush && this._data.length > 0) {
|
||||
const chunk = this._data.shift()
|
||||
this._shouldPush = this.push(chunk)
|
||||
const chunk = this._data.shift();
|
||||
this._shouldPush = this.push(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
_read () {
|
||||
this._shouldPush = true
|
||||
this._pushInternalData()
|
||||
this._shouldPush = true;
|
||||
this._pushInternalData();
|
||||
}
|
||||
}
|
||||
|
||||
/** Writable stream that buffers up everything written to it. */
|
||||
class SlurpStream extends Writable {
|
||||
constructor () {
|
||||
super()
|
||||
this._data = Buffer.alloc(0)
|
||||
super();
|
||||
this._data = Buffer.alloc(0);
|
||||
}
|
||||
_write (chunk, encoding, callback) {
|
||||
this._data = Buffer.concat([this._data, chunk])
|
||||
callback()
|
||||
this._data = Buffer.concat([this._data, chunk]);
|
||||
callback();
|
||||
}
|
||||
data () { return this._data }
|
||||
data () { return this._data; }
|
||||
}
|
||||
|
||||
class ChunkedBodyStream extends Writable {
|
||||
constructor (clientRequest) {
|
||||
super()
|
||||
this._clientRequest = clientRequest
|
||||
super();
|
||||
this._clientRequest = clientRequest;
|
||||
}
|
||||
|
||||
_write (chunk, encoding, callback) {
|
||||
if (this._downstream) {
|
||||
this._downstream.write(chunk).then(callback, callback)
|
||||
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
|
||||
this._pendingChunk = chunk;
|
||||
this._pendingCallback = callback;
|
||||
|
||||
// The first write to a chunked body stream begins the request.
|
||||
this._clientRequest._startRequest()
|
||||
this._clientRequest._startRequest();
|
||||
}
|
||||
}
|
||||
|
||||
_final (callback) {
|
||||
this._downstream.done()
|
||||
callback()
|
||||
this._downstream.done();
|
||||
callback();
|
||||
}
|
||||
|
||||
startReading (pipe) {
|
||||
if (this._downstream) {
|
||||
throw new Error('two startReading calls???')
|
||||
throw new Error('two startReading calls???');
|
||||
}
|
||||
this._downstream = pipe
|
||||
this._downstream = pipe;
|
||||
if (this._pendingChunk) {
|
||||
const doneWriting = (maybeError) => {
|
||||
const cb = this._pendingCallback
|
||||
delete this._pendingCallback
|
||||
delete this._pendingChunk
|
||||
cb(maybeError)
|
||||
}
|
||||
this._downstream.write(this._pendingChunk).then(doneWriting, doneWriting)
|
||||
const cb = this._pendingCallback;
|
||||
delete this._pendingCallback;
|
||||
delete this._pendingChunk;
|
||||
cb(maybeError);
|
||||
};
|
||||
this._downstream.write(this._pendingChunk).then(doneWriting, doneWriting);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parseOptions (options) {
|
||||
if (typeof options === 'string') {
|
||||
options = url.parse(options)
|
||||
options = url.parse(options);
|
||||
} else {
|
||||
options = { ...options }
|
||||
options = { ...options };
|
||||
}
|
||||
|
||||
const method = (options.method || 'GET').toUpperCase()
|
||||
let urlStr = options.url
|
||||
const method = (options.method || 'GET').toUpperCase();
|
||||
let urlStr = options.url;
|
||||
|
||||
if (!urlStr) {
|
||||
const urlObj = {}
|
||||
const protocol = options.protocol || 'http:'
|
||||
const urlObj = {};
|
||||
const protocol = options.protocol || 'http:';
|
||||
if (!kSupportedProtocols.has(protocol)) {
|
||||
throw new Error('Protocol "' + protocol + '" not supported')
|
||||
throw new Error('Protocol "' + protocol + '" not supported');
|
||||
}
|
||||
urlObj.protocol = protocol
|
||||
urlObj.protocol = protocol;
|
||||
|
||||
if (options.host) {
|
||||
urlObj.host = options.host
|
||||
urlObj.host = options.host;
|
||||
} else {
|
||||
if (options.hostname) {
|
||||
urlObj.hostname = options.hostname
|
||||
urlObj.hostname = options.hostname;
|
||||
} else {
|
||||
urlObj.hostname = 'localhost'
|
||||
urlObj.hostname = 'localhost';
|
||||
}
|
||||
|
||||
if (options.port) {
|
||||
urlObj.port = options.port
|
||||
urlObj.port = options.port;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,203 +212,204 @@ function parseOptions (options) {
|
||||
// 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')
|
||||
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 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'
|
||||
const redirectPolicy = options.redirect || 'follow';
|
||||
if (!['follow', 'error', 'manual'].includes(redirectPolicy)) {
|
||||
throw new Error('redirect mode should be one of follow, error or manual')
|
||||
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')
|
||||
throw new TypeError('headers must be an object');
|
||||
}
|
||||
|
||||
const urlLoaderOptions = {
|
||||
method: method,
|
||||
url: urlStr,
|
||||
redirectPolicy,
|
||||
extraHeaders: options.headers || {}
|
||||
}
|
||||
extraHeaders: options.headers || {},
|
||||
useSessionCookies: options.useSessionCookies || false
|
||||
};
|
||||
for (const [name, value] of Object.entries(urlLoaderOptions.extraHeaders)) {
|
||||
if (!_isValidHeaderName(name)) {
|
||||
throw new Error(`Invalid header name: '${name}'`)
|
||||
throw new Error(`Invalid header name: '${name}'`);
|
||||
}
|
||||
if (!_isValidHeaderValue(value.toString())) {
|
||||
throw new Error(`Invalid value for header '${name}': '${value}'`)
|
||||
throw new Error(`Invalid value for header '${name}': '${value}'`);
|
||||
}
|
||||
}
|
||||
if (options.session) {
|
||||
if (options.session instanceof Session) {
|
||||
urlLoaderOptions.session = options.session
|
||||
urlLoaderOptions.session = options.session;
|
||||
} else {
|
||||
throw new TypeError('`session` should be an instance of the Session class')
|
||||
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
|
||||
urlLoaderOptions.partition = options.partition;
|
||||
} else {
|
||||
throw new TypeError('`partition` should be a string')
|
||||
throw new TypeError('`partition` should be a string');
|
||||
}
|
||||
}
|
||||
return urlLoaderOptions
|
||||
return urlLoaderOptions;
|
||||
}
|
||||
|
||||
class ClientRequest extends Writable {
|
||||
constructor (options, callback) {
|
||||
super({ autoDestroy: true })
|
||||
super({ autoDestroy: true });
|
||||
|
||||
if (!app.isReady()) {
|
||||
throw new Error('net module can only be used after app is ready')
|
||||
throw new Error('net module can only be used after app is ready');
|
||||
}
|
||||
|
||||
if (callback) {
|
||||
this.once('response', callback)
|
||||
this.once('response', callback);
|
||||
}
|
||||
|
||||
const { redirectPolicy, ...urlLoaderOptions } = parseOptions(options)
|
||||
this._urlLoaderOptions = urlLoaderOptions
|
||||
this._redirectPolicy = redirectPolicy
|
||||
this._started = false
|
||||
const { redirectPolicy, ...urlLoaderOptions } = parseOptions(options);
|
||||
this._urlLoaderOptions = urlLoaderOptions;
|
||||
this._redirectPolicy = redirectPolicy;
|
||||
this._started = false;
|
||||
}
|
||||
|
||||
set chunkedEncoding (value) {
|
||||
if (this._started) {
|
||||
throw new Error('chunkedEncoding can only be set before the request is 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')
|
||||
throw new Error('chunkedEncoding can only be set once');
|
||||
}
|
||||
this._chunkedEncoding = !!value
|
||||
this._chunkedEncoding = !!value;
|
||||
if (this._chunkedEncoding) {
|
||||
this._body = new ChunkedBodyStream(this)
|
||||
this._body = new ChunkedBodyStream(this);
|
||||
this._urlLoaderOptions.body = (pipe) => {
|
||||
this._body.startReading(pipe)
|
||||
}
|
||||
this._body.startReading(pipe);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
setHeader (name, value) {
|
||||
if (typeof name !== 'string') {
|
||||
throw new TypeError('`name` should be a string in setHeader(name, value)')
|
||||
throw new TypeError('`name` should be a string in setHeader(name, value)');
|
||||
}
|
||||
if (value == null) {
|
||||
throw new Error('`value` required in setHeader("' + name + '", value)')
|
||||
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')
|
||||
throw new Error('Can\'t set headers after they are sent');
|
||||
}
|
||||
if (!_isValidHeaderName(name)) {
|
||||
throw new Error(`Invalid header name: '${name}'`)
|
||||
throw new Error(`Invalid header name: '${name}'`);
|
||||
}
|
||||
if (!_isValidHeaderValue(value.toString())) {
|
||||
throw new Error(`Invalid value for header '${name}': '${value}'`)
|
||||
throw new Error(`Invalid value for header '${name}': '${value}'`);
|
||||
}
|
||||
|
||||
const key = name.toLowerCase()
|
||||
this._urlLoaderOptions.extraHeaders[key] = value
|
||||
const key = name.toLowerCase();
|
||||
this._urlLoaderOptions.extraHeaders[key] = value;
|
||||
}
|
||||
|
||||
getHeader (name) {
|
||||
if (name == null) {
|
||||
throw new Error('`name` is required for getHeader(name)')
|
||||
throw new Error('`name` is required for getHeader(name)');
|
||||
}
|
||||
|
||||
const key = name.toLowerCase()
|
||||
return this._urlLoaderOptions.extraHeaders[key]
|
||||
const key = name.toLowerCase();
|
||||
return this._urlLoaderOptions.extraHeaders[key];
|
||||
}
|
||||
|
||||
removeHeader (name) {
|
||||
if (name == null) {
|
||||
throw new Error('`name` is required for removeHeader(name)')
|
||||
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')
|
||||
throw new Error('Can\'t remove headers after they are sent');
|
||||
}
|
||||
|
||||
const key = name.toLowerCase()
|
||||
delete this._urlLoaderOptions.extraHeaders[key]
|
||||
const key = name.toLowerCase();
|
||||
delete this._urlLoaderOptions.extraHeaders[key];
|
||||
}
|
||||
|
||||
_write (chunk, encoding, callback) {
|
||||
this._firstWrite = true
|
||||
this._firstWrite = true;
|
||||
if (!this._body) {
|
||||
this._body = new SlurpStream()
|
||||
this._body = new SlurpStream();
|
||||
this._body.on('finish', () => {
|
||||
this._urlLoaderOptions.body = this._body.data()
|
||||
this._startRequest()
|
||||
})
|
||||
this._urlLoaderOptions.body = this._body.data();
|
||||
this._startRequest();
|
||||
});
|
||||
}
|
||||
// TODO: is this the right way to forward to another stream?
|
||||
this._body.write(chunk, encoding, callback)
|
||||
this._body.write(chunk, encoding, callback);
|
||||
}
|
||||
|
||||
_final (callback) {
|
||||
if (this._body) {
|
||||
// TODO: is this the right way to forward to another stream?
|
||||
this._body.end(callback)
|
||||
this._body.end(callback);
|
||||
} else {
|
||||
// end() called without a body, go ahead and start the request
|
||||
this._startRequest()
|
||||
callback()
|
||||
this._startRequest();
|
||||
callback();
|
||||
}
|
||||
}
|
||||
|
||||
_startRequest () {
|
||||
this._started = true
|
||||
this._started = true;
|
||||
const stringifyValues = (obj) => {
|
||||
const ret = {}
|
||||
for (const k in obj) {
|
||||
ret[k] = obj[k].toString()
|
||||
const ret = {};
|
||||
for (const k of Object.keys(obj)) {
|
||||
ret[k] = obj[k].toString();
|
||||
}
|
||||
return ret
|
||||
}
|
||||
const opts = { ...this._urlLoaderOptions, extraHeaders: stringifyValues(this._urlLoaderOptions.extraHeaders) }
|
||||
this._urlLoader = new URLLoader(opts)
|
||||
return ret;
|
||||
};
|
||||
const opts = { ...this._urlLoaderOptions, extraHeaders: stringifyValues(this._urlLoaderOptions.extraHeaders) };
|
||||
this._urlLoader = new URLLoader(opts);
|
||||
this._urlLoader.on('response-started', (event, finalUrl, responseHead) => {
|
||||
const response = this._response = new IncomingMessage(responseHead)
|
||||
this.emit('response', response)
|
||||
})
|
||||
const response = this._response = new IncomingMessage(responseHead);
|
||||
this.emit('response', response);
|
||||
});
|
||||
this._urlLoader.on('data', (event, data) => {
|
||||
this._response._storeInternalData(Buffer.from(data))
|
||||
})
|
||||
this._response._storeInternalData(Buffer.from(data));
|
||||
});
|
||||
this._urlLoader.on('complete', () => {
|
||||
if (this._response) { this._response._storeInternalData(null) }
|
||||
})
|
||||
if (this._response) { this._response._storeInternalData(null); }
|
||||
});
|
||||
this._urlLoader.on('error', (event, netErrorString) => {
|
||||
const error = new Error(netErrorString)
|
||||
if (this._response) this._response.destroy(error)
|
||||
this._die(error)
|
||||
})
|
||||
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)
|
||||
const handled = this.emit('login', authInfo, callback);
|
||||
if (!handled) {
|
||||
// If there were no listeners, cancel the authentication request.
|
||||
callback()
|
||||
callback();
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
this._urlLoader.on('redirect', (event, redirectInfo, headers) => {
|
||||
const { statusCode, newMethod, newUrl } = redirectInfo
|
||||
const { statusCode, newMethod, newUrl } = redirectInfo;
|
||||
if (this._redirectPolicy === 'error') {
|
||||
this._die(new Error(`Attempted to redirect, but redirect policy was '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 }
|
||||
let _followRedirect = false;
|
||||
this._followRedirectCb = () => { _followRedirect = true; };
|
||||
try {
|
||||
this.emit('redirect', statusCode, newMethod, newUrl, headers)
|
||||
this.emit('redirect', statusCode, newMethod, newUrl, headers);
|
||||
} finally {
|
||||
this._followRedirectCb = null
|
||||
this._followRedirectCb = null;
|
||||
if (!_followRedirect && !this._aborted) {
|
||||
this._die(new Error('Redirect was cancelled'))
|
||||
this._die(new Error('Redirect was cancelled'));
|
||||
}
|
||||
}
|
||||
} else if (this._redirectPolicy === 'follow') {
|
||||
@@ -416,61 +417,61 @@ class ClientRequest extends Writable {
|
||||
// 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)
|
||||
this._followRedirectCb = () => {};
|
||||
this.emit('redirect', statusCode, newMethod, newUrl, headers);
|
||||
} finally {
|
||||
this._followRedirectCb = null
|
||||
this._followRedirectCb = null;
|
||||
}
|
||||
} else {
|
||||
this._die(new Error(`Unexpected redirect policy '${this._redirectPolicy}'`))
|
||||
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._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
|
||||
this._response.emit('download-progress', current); // Undocumented, for now
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
followRedirect () {
|
||||
if (this._followRedirectCb) {
|
||||
this._followRedirectCb()
|
||||
this._followRedirectCb();
|
||||
} else {
|
||||
throw new Error('followRedirect() called, but was not waiting for a redirect')
|
||||
throw new Error('followRedirect() called, but was not waiting for a redirect');
|
||||
}
|
||||
}
|
||||
|
||||
abort () {
|
||||
if (!this._aborted) {
|
||||
process.nextTick(() => { this.emit('abort') })
|
||||
process.nextTick(() => { this.emit('abort'); });
|
||||
}
|
||||
this._aborted = true
|
||||
this._die()
|
||||
this._aborted = true;
|
||||
this._die();
|
||||
}
|
||||
|
||||
_die (err) {
|
||||
this.destroy(err)
|
||||
this.destroy(err);
|
||||
if (this._urlLoader) {
|
||||
this._urlLoader.cancel()
|
||||
if (this._response) this._response.destroy(err)
|
||||
this._urlLoader.cancel();
|
||||
if (this._response) this._response.destroy(err);
|
||||
}
|
||||
}
|
||||
|
||||
getUploadProgress () {
|
||||
return this._uploadProgress ? { ...this._uploadProgress } : { active: false }
|
||||
return this._uploadProgress ? { ...this._uploadProgress } : { active: false };
|
||||
}
|
||||
}
|
||||
|
||||
Net.prototype.request = function (options, callback) {
|
||||
return new ClientRequest(options, callback)
|
||||
}
|
||||
return new ClientRequest(options, callback);
|
||||
};
|
||||
|
||||
net.ClientRequest = ClientRequest
|
||||
net.ClientRequest = ClientRequest;
|
||||
|
||||
module.exports = net
|
||||
module.exports = net;
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const { EventEmitter } = require('events')
|
||||
const { Notification, isSupported } = process.electronBinding('notification')
|
||||
const { EventEmitter } = require('events');
|
||||
const { Notification, isSupported } = process.electronBinding('notification');
|
||||
|
||||
Object.setPrototypeOf(Notification.prototype, EventEmitter.prototype)
|
||||
Object.setPrototypeOf(Notification.prototype, EventEmitter.prototype);
|
||||
|
||||
Notification.isSupported = isSupported
|
||||
Notification.isSupported = isSupported;
|
||||
|
||||
module.exports = Notification
|
||||
module.exports = Notification;
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
import { createLazyInstance } from '../utils'
|
||||
import { createLazyInstance } from '../utils';
|
||||
|
||||
const { EventEmitter } = require('events')
|
||||
const { createPowerMonitor, PowerMonitor } = process.electronBinding('power_monitor')
|
||||
const { EventEmitter } = require('events');
|
||||
const { createPowerMonitor, PowerMonitor } = process.electronBinding('power_monitor');
|
||||
|
||||
// PowerMonitor is an EventEmitter.
|
||||
Object.setPrototypeOf(PowerMonitor.prototype, EventEmitter.prototype)
|
||||
Object.setPrototypeOf(PowerMonitor.prototype, EventEmitter.prototype);
|
||||
|
||||
const powerMonitor = createLazyInstance(createPowerMonitor, PowerMonitor, true)
|
||||
const powerMonitor = createLazyInstance(createPowerMonitor, PowerMonitor, true);
|
||||
|
||||
if (process.platform === 'linux') {
|
||||
// In order to delay system shutdown when e.preventDefault() is invoked
|
||||
@@ -18,21 +18,21 @@ if (process.platform === 'linux') {
|
||||
//
|
||||
// So here we watch for 'shutdown' listeners to be added or removed and
|
||||
// set or unset our shutdown delay lock accordingly.
|
||||
const { app } = require('electron')
|
||||
const { app } = require('electron');
|
||||
app.whenReady().then(() => {
|
||||
powerMonitor.on('newListener', (event: string) => {
|
||||
// whenever the listener count is incremented to one...
|
||||
if (event === 'shutdown' && powerMonitor.listenerCount('shutdown') === 0) {
|
||||
powerMonitor.blockShutdown()
|
||||
powerMonitor.blockShutdown();
|
||||
}
|
||||
})
|
||||
});
|
||||
powerMonitor.on('removeListener', (event: string) => {
|
||||
// whenever the listener count is decremented to zero...
|
||||
if (event === 'shutdown' && powerMonitor.listenerCount('shutdown') === 0) {
|
||||
powerMonitor.unblockShutdown()
|
||||
powerMonitor.unblockShutdown();
|
||||
}
|
||||
})
|
||||
})
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = powerMonitor
|
||||
module.exports = powerMonitor;
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
module.exports = process.electronBinding('power_save_blocker').powerSaveBlocker
|
||||
module.exports = process.electronBinding('power_save_blocker').powerSaveBlocker;
|
||||
|
||||
@@ -1,29 +1,29 @@
|
||||
import { app, session } from 'electron'
|
||||
import { app, session } from 'electron';
|
||||
|
||||
// Global protocol APIs.
|
||||
const protocol = process.electronBinding('protocol')
|
||||
const protocol = process.electronBinding('protocol');
|
||||
|
||||
// Fallback protocol APIs of default session.
|
||||
Object.setPrototypeOf(protocol, new Proxy({}, {
|
||||
get (_target, property) {
|
||||
if (!app.isReady()) return
|
||||
if (!app.isReady()) return;
|
||||
|
||||
const protocol = session.defaultSession!.protocol
|
||||
if (!Object.getPrototypeOf(protocol).hasOwnProperty(property)) return
|
||||
const protocol = session.defaultSession!.protocol;
|
||||
if (!Object.getPrototypeOf(protocol).hasOwnProperty(property)) return;
|
||||
|
||||
// Returning a native function directly would throw error.
|
||||
return (...args: any[]) => (protocol[property as keyof Electron.Protocol] as Function)(...args)
|
||||
return (...args: any[]) => (protocol[property as keyof Electron.Protocol] as Function)(...args);
|
||||
},
|
||||
|
||||
ownKeys () {
|
||||
if (!app.isReady()) return []
|
||||
if (!app.isReady()) return [];
|
||||
|
||||
return Object.getOwnPropertyNames(Object.getPrototypeOf(session.defaultSession!.protocol))
|
||||
return Object.getOwnPropertyNames(Object.getPrototypeOf(session.defaultSession!.protocol));
|
||||
},
|
||||
|
||||
getOwnPropertyDescriptor () {
|
||||
return { configurable: true, enumerable: true }
|
||||
return { configurable: true, enumerable: true };
|
||||
}
|
||||
}))
|
||||
}));
|
||||
|
||||
export default protocol
|
||||
export default protocol;
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
import { createLazyInstance } from '../utils'
|
||||
const { EventEmitter } = require('events')
|
||||
const { Screen, createScreen } = process.electronBinding('screen')
|
||||
import { createLazyInstance } from '../utils';
|
||||
const { EventEmitter } = require('events');
|
||||
const { Screen, createScreen } = process.electronBinding('screen');
|
||||
|
||||
// Screen is an EventEmitter.
|
||||
Object.setPrototypeOf(Screen.prototype, EventEmitter.prototype)
|
||||
Object.setPrototypeOf(Screen.prototype, EventEmitter.prototype);
|
||||
|
||||
module.exports = createLazyInstance(createScreen, Screen, true)
|
||||
module.exports = createLazyInstance(createScreen, Screen, true);
|
||||
|
||||
@@ -1,53 +1,54 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const { EventEmitter } = require('events')
|
||||
const { app, deprecate } = require('electron')
|
||||
const { fromPartition, Session, Cookies, NetLog, Protocol } = process.electronBinding('session')
|
||||
const { EventEmitter } = require('events');
|
||||
const { app, deprecate } = require('electron');
|
||||
const { fromPartition, Session, Cookies, NetLog, Protocol, ServiceWorkerContext } = process.electronBinding('session');
|
||||
|
||||
// Public API.
|
||||
Object.defineProperties(exports, {
|
||||
defaultSession: {
|
||||
enumerable: true,
|
||||
get () { return fromPartition('') }
|
||||
get () { return fromPartition(''); }
|
||||
},
|
||||
fromPartition: {
|
||||
enumerable: true,
|
||||
value: fromPartition
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
Object.setPrototypeOf(Session.prototype, EventEmitter.prototype)
|
||||
Object.setPrototypeOf(Cookies.prototype, EventEmitter.prototype)
|
||||
Object.setPrototypeOf(Cookies.prototype, EventEmitter.prototype);
|
||||
Object.setPrototypeOf(ServiceWorkerContext.prototype, EventEmitter.prototype);
|
||||
Object.setPrototypeOf(Session.prototype, EventEmitter.prototype);
|
||||
|
||||
Session.prototype._init = function () {
|
||||
app.emit('session-created', this)
|
||||
}
|
||||
app.emit('session-created', this);
|
||||
};
|
||||
|
||||
const _originalStartLogging = NetLog.prototype.startLogging
|
||||
const _originalStartLogging = NetLog.prototype.startLogging;
|
||||
NetLog.prototype.startLogging = function (path, ...args) {
|
||||
this._currentlyLoggingPath = path
|
||||
this._currentlyLoggingPath = path;
|
||||
try {
|
||||
return _originalStartLogging.call(this, path, ...args)
|
||||
return _originalStartLogging.call(this, path, ...args);
|
||||
} catch (e) {
|
||||
this._currentlyLoggingPath = null
|
||||
throw e
|
||||
this._currentlyLoggingPath = null;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const _originalStopLogging = NetLog.prototype.stopLogging
|
||||
const _originalStopLogging = NetLog.prototype.stopLogging;
|
||||
NetLog.prototype.stopLogging = function () {
|
||||
const logPath = this._currentlyLoggingPath
|
||||
this._currentlyLoggingPath = null
|
||||
return _originalStopLogging.call(this).then(() => logPath)
|
||||
}
|
||||
const logPath = this._currentlyLoggingPath;
|
||||
this._currentlyLoggingPath = null;
|
||||
return _originalStopLogging.call(this).then(() => logPath);
|
||||
};
|
||||
|
||||
const currentlyLoggingPathDeprecated = deprecate.warnOnce('currentlyLoggingPath')
|
||||
const currentlyLoggingPathDeprecated = deprecate.warnOnce('currentlyLoggingPath');
|
||||
Object.defineProperties(NetLog.prototype, {
|
||||
currentlyLoggingPath: {
|
||||
enumerable: true,
|
||||
get () {
|
||||
currentlyLoggingPathDeprecated()
|
||||
return this._currentlyLoggingPath == null ? '' : this._currentlyLoggingPath
|
||||
currentlyLoggingPathDeprecated();
|
||||
return this._currentlyLoggingPath == null ? '' : this._currentlyLoggingPath;
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
@@ -1,42 +1,41 @@
|
||||
import { EventEmitter } from 'events'
|
||||
import { deprecate } from 'electron'
|
||||
const { systemPreferences, SystemPreferences } = process.electronBinding('system_preferences')
|
||||
import { EventEmitter } from 'events';
|
||||
import { deprecate } from 'electron';
|
||||
const { systemPreferences, SystemPreferences } = process.electronBinding('system_preferences');
|
||||
|
||||
// SystemPreferences is an EventEmitter.
|
||||
Object.setPrototypeOf(SystemPreferences.prototype, EventEmitter.prototype)
|
||||
EventEmitter.call(systemPreferences)
|
||||
Object.setPrototypeOf(SystemPreferences.prototype, EventEmitter.prototype);
|
||||
EventEmitter.call(systemPreferences);
|
||||
|
||||
if ('appLevelAppearance' in systemPreferences) {
|
||||
deprecate.fnToProperty(
|
||||
SystemPreferences.prototype,
|
||||
'appLevelAppearance',
|
||||
'_getAppLevelAppearance',
|
||||
'_setAppLevelAppearance'
|
||||
)
|
||||
if ('getAppLevelAppearance' in systemPreferences) {
|
||||
const nativeALAGetter = systemPreferences.getAppLevelAppearance;
|
||||
const nativeALASetter = systemPreferences.setAppLevelAppearance;
|
||||
Object.defineProperty(SystemPreferences.prototype, 'appLevelAppearance', {
|
||||
get: () => nativeALAGetter.call(systemPreferences),
|
||||
set: (appearance) => nativeALASetter.call(systemPreferences, appearance)
|
||||
});
|
||||
}
|
||||
|
||||
if ('effectiveAppearance' in systemPreferences) {
|
||||
deprecate.fnToProperty(
|
||||
SystemPreferences.prototype,
|
||||
'effectiveAppearance',
|
||||
'_getEffectiveAppearance'
|
||||
)
|
||||
if ('getEffectiveAppearance' in systemPreferences) {
|
||||
const nativeEAGetter = systemPreferences.getAppLevelAppearance;
|
||||
Object.defineProperty(SystemPreferences.prototype, 'effectiveAppearance', {
|
||||
get: () => nativeEAGetter.call(systemPreferences)
|
||||
});
|
||||
}
|
||||
|
||||
SystemPreferences.prototype.isDarkMode = deprecate.moveAPI(
|
||||
SystemPreferences.prototype.isDarkMode,
|
||||
'systemPreferences.isDarkMode()',
|
||||
'nativeTheme.shouldUseDarkColors'
|
||||
)
|
||||
);
|
||||
SystemPreferences.prototype.isInvertedColorScheme = deprecate.moveAPI(
|
||||
SystemPreferences.prototype.isInvertedColorScheme,
|
||||
'systemPreferences.isInvertedColorScheme()',
|
||||
'nativeTheme.shouldUseInvertedColorScheme'
|
||||
)
|
||||
);
|
||||
SystemPreferences.prototype.isHighContrastColorScheme = deprecate.moveAPI(
|
||||
SystemPreferences.prototype.isHighContrastColorScheme,
|
||||
'systemPreferences.isHighContrastColorScheme()',
|
||||
'nativeTheme.shouldUseHighContrastColors'
|
||||
)
|
||||
);
|
||||
|
||||
module.exports = systemPreferences
|
||||
module.exports = systemPreferences;
|
||||
|
||||
@@ -1,24 +1,106 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const electron = require('electron')
|
||||
const { EventEmitter } = require('events')
|
||||
const { TopLevelWindow } = process.electronBinding('top_level_window')
|
||||
const electron = require('electron');
|
||||
const { EventEmitter } = require('events');
|
||||
const { TopLevelWindow } = process.electronBinding('top_level_window');
|
||||
|
||||
Object.setPrototypeOf(TopLevelWindow.prototype, EventEmitter.prototype)
|
||||
Object.setPrototypeOf(TopLevelWindow.prototype, EventEmitter.prototype);
|
||||
|
||||
TopLevelWindow.prototype._init = function () {
|
||||
// Avoid recursive require.
|
||||
const { app } = electron
|
||||
const { app } = electron;
|
||||
|
||||
// Simulate the application menu on platforms other than macOS.
|
||||
if (process.platform !== 'darwin') {
|
||||
const menu = app.applicationMenu
|
||||
if (menu) this.setMenu(menu)
|
||||
const menu = app.applicationMenu;
|
||||
if (menu) this.setMenu(menu);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Properties
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'autoHideMenuBar', {
|
||||
get: function () { return this.isMenuBarAutoHide(); },
|
||||
set: function (autoHide) { this.setAutoHideMenuBar(autoHide); }
|
||||
});
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'visibleOnAllWorkspaces', {
|
||||
get: function () { return this.isVisibleOnAllWorkspaces(); },
|
||||
set: function (visible) { this.setVisibleOnAllWorkspaces(visible); }
|
||||
});
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'fullScreen', {
|
||||
get: function () { return this.isFullScreen(); },
|
||||
set: function (full) { this.setFullScreen(full); }
|
||||
});
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'simpleFullScreen', {
|
||||
get: function () { return this.isSimpleFullScreen(); },
|
||||
set: function (simple) { this.setSimpleFullScreen(simple); }
|
||||
});
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'kiosk', {
|
||||
get: function () { return this.isKiosk(); },
|
||||
set: function (kiosk) { this.setKiosk(kiosk); }
|
||||
});
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'documentEdited', {
|
||||
get: function () { return this.isFullscreen(); },
|
||||
set: function (edited) { this.setDocumentEdited(edited); }
|
||||
});
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'shadow', {
|
||||
get: function () { return this.hasShadow(); },
|
||||
set: function (shadow) { this.setHasShadow(shadow); }
|
||||
});
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'representedFilename', {
|
||||
get: function () { return this.getRepresentedFilename(); },
|
||||
set: function (filename) { this.setRepresentedFilename(filename); }
|
||||
});
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'minimizable', {
|
||||
get: function () { return this.isMinimizable(); },
|
||||
set: function (min) { this.setMinimizable(min); }
|
||||
});
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'title', {
|
||||
get: function () { return this.getTitle(); },
|
||||
set: function (title) { this.setTitle(title); }
|
||||
});
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'maximizable', {
|
||||
get: function () { return this.isMaximizable(); },
|
||||
set: function (max) { this.setMaximizable(max); }
|
||||
});
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'resizable', {
|
||||
get: function () { return this.isResizable(); },
|
||||
set: function (res) { this.setResizable(res); }
|
||||
});
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'menuBarVisible', {
|
||||
get: function () { return this.isMenuBarVisible(); },
|
||||
set: function (visible) { this.setMenuBarVisibility(visible); }
|
||||
});
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'fullScreenable', {
|
||||
get: function () { return this.isFullScreenable(); },
|
||||
set: function (full) { this.setFullScreenable(full); }
|
||||
});
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'closable', {
|
||||
get: function () { return this.isClosable(); },
|
||||
set: function (close) { this.setClosable(close); }
|
||||
});
|
||||
|
||||
Object.defineProperty(TopLevelWindow.prototype, 'movable', {
|
||||
get: function () { return this.isMovable(); },
|
||||
set: function (move) { this.setMovable(move); }
|
||||
});
|
||||
|
||||
TopLevelWindow.getFocusedWindow = () => {
|
||||
return TopLevelWindow.getAllWindows().find((win) => win.isFocused())
|
||||
}
|
||||
return TopLevelWindow.getAllWindows().find((win) => win.isFocused());
|
||||
};
|
||||
|
||||
module.exports = TopLevelWindow
|
||||
module.exports = TopLevelWindow;
|
||||
|
||||
@@ -1,337 +1,349 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const { EventEmitter } = require('events')
|
||||
const { EventEmitter } = require('events');
|
||||
|
||||
let nextItemID = 1
|
||||
let nextItemID = 1;
|
||||
|
||||
class TouchBar extends EventEmitter {
|
||||
// Bind a touch bar to a window
|
||||
static _setOnWindow (touchBar, window) {
|
||||
if (window._touchBar != null) {
|
||||
window._touchBar._removeFromWindow(window)
|
||||
window._touchBar._removeFromWindow(window);
|
||||
}
|
||||
|
||||
if (touchBar == null) {
|
||||
window._setTouchBarItems([])
|
||||
return
|
||||
window._setTouchBarItems([]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Array.isArray(touchBar)) {
|
||||
touchBar = new TouchBar(touchBar)
|
||||
touchBar = new TouchBar(touchBar);
|
||||
}
|
||||
touchBar._addToWindow(window)
|
||||
touchBar._addToWindow(window);
|
||||
}
|
||||
|
||||
constructor (options) {
|
||||
super()
|
||||
super();
|
||||
|
||||
if (options == null) {
|
||||
throw new Error('Must specify options object as first argument')
|
||||
throw new Error('Must specify options object as first argument');
|
||||
}
|
||||
|
||||
let { items, escapeItem } = options
|
||||
let { items, escapeItem } = options;
|
||||
|
||||
if (!Array.isArray(items)) {
|
||||
items = []
|
||||
items = [];
|
||||
}
|
||||
|
||||
this.changeListener = (item) => {
|
||||
this.emit('change', item.id, item.type)
|
||||
}
|
||||
this.emit('change', item.id, item.type);
|
||||
};
|
||||
|
||||
this.windowListeners = {}
|
||||
this.items = {}
|
||||
this.ordereredItems = []
|
||||
this.escapeItem = escapeItem
|
||||
this.windowListeners = {};
|
||||
this.items = {};
|
||||
this.ordereredItems = [];
|
||||
this.escapeItem = escapeItem;
|
||||
|
||||
const registerItem = (item) => {
|
||||
this.items[item.id] = item
|
||||
item.on('change', this.changeListener)
|
||||
this.items[item.id] = item;
|
||||
item.on('change', this.changeListener);
|
||||
if (item.child instanceof TouchBar) {
|
||||
item.child.ordereredItems.forEach(registerItem)
|
||||
item.child.ordereredItems.forEach(registerItem);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const idSet = new Set();
|
||||
items.forEach((item) => {
|
||||
if (!(item instanceof TouchBarItem)) {
|
||||
throw new Error('Each item must be an instance of TouchBarItem')
|
||||
throw new Error('Each item must be an instance of TouchBarItem');
|
||||
}
|
||||
this.ordereredItems.push(item)
|
||||
registerItem(item)
|
||||
})
|
||||
|
||||
if (!idSet.has(item.id)) {
|
||||
idSet.add(item.id);
|
||||
} else {
|
||||
throw new Error('Cannot add a single instance of TouchBarItem multiple times in a TouchBar');
|
||||
}
|
||||
});
|
||||
|
||||
// register in separate loop after all items are validated
|
||||
for (const item of items) {
|
||||
this.ordereredItems.push(item);
|
||||
registerItem(item);
|
||||
}
|
||||
}
|
||||
|
||||
set escapeItem (item) {
|
||||
if (item != null && !(item instanceof TouchBarItem)) {
|
||||
throw new Error('Escape item must be an instance of TouchBarItem')
|
||||
throw new Error('Escape item must be an instance of TouchBarItem');
|
||||
}
|
||||
if (this.escapeItem != null) {
|
||||
this.escapeItem.removeListener('change', this.changeListener)
|
||||
this.escapeItem.removeListener('change', this.changeListener);
|
||||
}
|
||||
this._escapeItem = item
|
||||
this._escapeItem = item;
|
||||
if (this.escapeItem != null) {
|
||||
this.escapeItem.on('change', this.changeListener)
|
||||
this.escapeItem.on('change', this.changeListener);
|
||||
}
|
||||
this.emit('escape-item-change', item)
|
||||
this.emit('escape-item-change', item);
|
||||
}
|
||||
|
||||
get escapeItem () {
|
||||
return this._escapeItem
|
||||
return this._escapeItem;
|
||||
}
|
||||
|
||||
_addToWindow (window) {
|
||||
const { id } = window
|
||||
const { id } = window;
|
||||
|
||||
// Already added to window
|
||||
if (this.windowListeners.hasOwnProperty(id)) return
|
||||
if (this.windowListeners.hasOwnProperty(id)) return;
|
||||
|
||||
window._touchBar = this
|
||||
window._touchBar = this;
|
||||
|
||||
const changeListener = (itemID) => {
|
||||
window._refreshTouchBarItem(itemID)
|
||||
}
|
||||
this.on('change', changeListener)
|
||||
window._refreshTouchBarItem(itemID);
|
||||
};
|
||||
this.on('change', changeListener);
|
||||
|
||||
const escapeItemListener = (item) => {
|
||||
window._setEscapeTouchBarItem(item != null ? item : {})
|
||||
}
|
||||
this.on('escape-item-change', escapeItemListener)
|
||||
window._setEscapeTouchBarItem(item != null ? item : {});
|
||||
};
|
||||
this.on('escape-item-change', escapeItemListener);
|
||||
|
||||
const interactionListener = (event, itemID, details) => {
|
||||
let item = this.items[itemID]
|
||||
let item = this.items[itemID];
|
||||
if (item == null && this.escapeItem != null && this.escapeItem.id === itemID) {
|
||||
item = this.escapeItem
|
||||
item = this.escapeItem;
|
||||
}
|
||||
if (item != null && item.onInteraction != null) {
|
||||
item.onInteraction(details)
|
||||
item.onInteraction(details);
|
||||
}
|
||||
}
|
||||
window.on('-touch-bar-interaction', interactionListener)
|
||||
};
|
||||
window.on('-touch-bar-interaction', interactionListener);
|
||||
|
||||
const removeListeners = () => {
|
||||
this.removeListener('change', changeListener)
|
||||
this.removeListener('escape-item-change', escapeItemListener)
|
||||
window.removeListener('-touch-bar-interaction', interactionListener)
|
||||
window.removeListener('closed', removeListeners)
|
||||
window._touchBar = null
|
||||
delete this.windowListeners[id]
|
||||
this.removeListener('change', changeListener);
|
||||
this.removeListener('escape-item-change', escapeItemListener);
|
||||
window.removeListener('-touch-bar-interaction', interactionListener);
|
||||
window.removeListener('closed', removeListeners);
|
||||
window._touchBar = null;
|
||||
delete this.windowListeners[id];
|
||||
const unregisterItems = (items) => {
|
||||
for (const item of items) {
|
||||
item.removeListener('change', this.changeListener)
|
||||
item.removeListener('change', this.changeListener);
|
||||
if (item.child instanceof TouchBar) {
|
||||
unregisterItems(item.child.ordereredItems)
|
||||
unregisterItems(item.child.ordereredItems);
|
||||
}
|
||||
}
|
||||
}
|
||||
unregisterItems(this.ordereredItems)
|
||||
};
|
||||
unregisterItems(this.ordereredItems);
|
||||
if (this.escapeItem) {
|
||||
this.escapeItem.removeListener('change', this.changeListener)
|
||||
this.escapeItem.removeListener('change', this.changeListener);
|
||||
}
|
||||
}
|
||||
window.once('closed', removeListeners)
|
||||
this.windowListeners[id] = removeListeners
|
||||
};
|
||||
window.once('closed', removeListeners);
|
||||
this.windowListeners[id] = removeListeners;
|
||||
|
||||
window._setTouchBarItems(this.ordereredItems)
|
||||
escapeItemListener(this.escapeItem)
|
||||
window._setTouchBarItems(this.ordereredItems);
|
||||
escapeItemListener(this.escapeItem);
|
||||
}
|
||||
|
||||
_removeFromWindow (window) {
|
||||
const removeListeners = this.windowListeners[window.id]
|
||||
if (removeListeners != null) removeListeners()
|
||||
const removeListeners = this.windowListeners[window.id];
|
||||
if (removeListeners != null) removeListeners();
|
||||
}
|
||||
}
|
||||
|
||||
class TouchBarItem extends EventEmitter {
|
||||
constructor () {
|
||||
super()
|
||||
this._addImmutableProperty('id', `${nextItemID++}`)
|
||||
this._parents = []
|
||||
super();
|
||||
this._addImmutableProperty('id', `${nextItemID++}`);
|
||||
this._parents = [];
|
||||
}
|
||||
|
||||
_addImmutableProperty (name, value) {
|
||||
Object.defineProperty(this, name, {
|
||||
get: function () {
|
||||
return value
|
||||
return value;
|
||||
},
|
||||
set: function () {
|
||||
throw new Error(`Cannot override property ${name}`)
|
||||
throw new Error(`Cannot override property ${name}`);
|
||||
},
|
||||
enumerable: true,
|
||||
configurable: false
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
_addLiveProperty (name, initialValue) {
|
||||
const privateName = `_${name}`
|
||||
this[privateName] = initialValue
|
||||
const privateName = `_${name}`;
|
||||
this[privateName] = initialValue;
|
||||
Object.defineProperty(this, name, {
|
||||
get: function () {
|
||||
return this[privateName]
|
||||
return this[privateName];
|
||||
},
|
||||
set: function (value) {
|
||||
this[privateName] = value
|
||||
this.emit('change', this)
|
||||
this[privateName] = value;
|
||||
this.emit('change', this);
|
||||
},
|
||||
enumerable: true
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
_addParent (item) {
|
||||
const existing = this._parents.some(test => test.id === item.id)
|
||||
const existing = this._parents.some(test => test.id === item.id);
|
||||
if (!existing) {
|
||||
this._parents.push({
|
||||
id: item.id,
|
||||
type: item.type
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TouchBar.TouchBarButton = class TouchBarButton extends TouchBarItem {
|
||||
constructor (config) {
|
||||
super()
|
||||
if (config == null) config = {}
|
||||
this._addImmutableProperty('type', 'button')
|
||||
this._addLiveProperty('label', config.label)
|
||||
this._addLiveProperty('accessibilityLabel', config.accessibilityLabel)
|
||||
this._addLiveProperty('backgroundColor', config.backgroundColor)
|
||||
this._addLiveProperty('icon', config.icon)
|
||||
this._addLiveProperty('iconPosition', config.iconPosition)
|
||||
this._addLiveProperty('enabled', typeof config.enabled !== 'boolean' ? true : config.enabled)
|
||||
super();
|
||||
if (config == null) config = {};
|
||||
this._addImmutableProperty('type', 'button');
|
||||
this._addLiveProperty('label', config.label);
|
||||
this._addLiveProperty('accessibilityLabel', config.accessibilityLabel);
|
||||
this._addLiveProperty('backgroundColor', config.backgroundColor);
|
||||
this._addLiveProperty('icon', config.icon);
|
||||
this._addLiveProperty('iconPosition', config.iconPosition);
|
||||
this._addLiveProperty('enabled', typeof config.enabled !== 'boolean' ? true : config.enabled);
|
||||
if (typeof config.click === 'function') {
|
||||
this._addImmutableProperty('onInteraction', () => {
|
||||
config.click()
|
||||
})
|
||||
config.click();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TouchBar.TouchBarColorPicker = class TouchBarColorPicker extends TouchBarItem {
|
||||
constructor (config) {
|
||||
super()
|
||||
if (config == null) config = {}
|
||||
this._addImmutableProperty('type', 'colorpicker')
|
||||
this._addLiveProperty('availableColors', config.availableColors)
|
||||
this._addLiveProperty('selectedColor', config.selectedColor)
|
||||
super();
|
||||
if (config == null) config = {};
|
||||
this._addImmutableProperty('type', 'colorpicker');
|
||||
this._addLiveProperty('availableColors', config.availableColors);
|
||||
this._addLiveProperty('selectedColor', config.selectedColor);
|
||||
|
||||
if (typeof config.change === 'function') {
|
||||
this._addImmutableProperty('onInteraction', (details) => {
|
||||
this._selectedColor = details.color
|
||||
config.change(details.color)
|
||||
})
|
||||
this._selectedColor = details.color;
|
||||
config.change(details.color);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TouchBar.TouchBarGroup = class TouchBarGroup extends TouchBarItem {
|
||||
constructor (config) {
|
||||
super()
|
||||
if (config == null) config = {}
|
||||
this._addImmutableProperty('type', 'group')
|
||||
const defaultChild = (config.items instanceof TouchBar) ? config.items : new TouchBar(config.items)
|
||||
this._addLiveProperty('child', defaultChild)
|
||||
this.child.ordereredItems.forEach((item) => item._addParent(this))
|
||||
super();
|
||||
if (config == null) config = {};
|
||||
this._addImmutableProperty('type', 'group');
|
||||
const defaultChild = (config.items instanceof TouchBar) ? config.items : new TouchBar(config.items);
|
||||
this._addLiveProperty('child', defaultChild);
|
||||
this.child.ordereredItems.forEach((item) => item._addParent(this));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TouchBar.TouchBarLabel = class TouchBarLabel extends TouchBarItem {
|
||||
constructor (config) {
|
||||
super()
|
||||
if (config == null) config = {}
|
||||
this._addImmutableProperty('type', 'label')
|
||||
this._addLiveProperty('label', config.label)
|
||||
this._addLiveProperty('accessibilityLabel', config.accessibilityLabel)
|
||||
this._addLiveProperty('textColor', config.textColor)
|
||||
super();
|
||||
if (config == null) config = {};
|
||||
this._addImmutableProperty('type', 'label');
|
||||
this._addLiveProperty('label', config.label);
|
||||
this._addLiveProperty('accessibilityLabel', config.accessibilityLabel);
|
||||
this._addLiveProperty('textColor', config.textColor);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TouchBar.TouchBarPopover = class TouchBarPopover extends TouchBarItem {
|
||||
constructor (config) {
|
||||
super()
|
||||
if (config == null) config = {}
|
||||
this._addImmutableProperty('type', 'popover')
|
||||
this._addLiveProperty('label', config.label)
|
||||
this._addLiveProperty('icon', config.icon)
|
||||
this._addLiveProperty('showCloseButton', config.showCloseButton)
|
||||
const defaultChild = (config.items instanceof TouchBar) ? config.items : new TouchBar(config.items)
|
||||
this._addLiveProperty('child', defaultChild)
|
||||
this.child.ordereredItems.forEach((item) => item._addParent(this))
|
||||
super();
|
||||
if (config == null) config = {};
|
||||
this._addImmutableProperty('type', 'popover');
|
||||
this._addLiveProperty('label', config.label);
|
||||
this._addLiveProperty('icon', config.icon);
|
||||
this._addLiveProperty('showCloseButton', config.showCloseButton);
|
||||
const defaultChild = (config.items instanceof TouchBar) ? config.items : new TouchBar(config.items);
|
||||
this._addLiveProperty('child', defaultChild);
|
||||
this.child.ordereredItems.forEach((item) => item._addParent(this));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TouchBar.TouchBarSlider = class TouchBarSlider extends TouchBarItem {
|
||||
constructor (config) {
|
||||
super()
|
||||
if (config == null) config = {}
|
||||
this._addImmutableProperty('type', 'slider')
|
||||
this._addLiveProperty('label', config.label)
|
||||
this._addLiveProperty('minValue', config.minValue)
|
||||
this._addLiveProperty('maxValue', config.maxValue)
|
||||
this._addLiveProperty('value', config.value)
|
||||
super();
|
||||
if (config == null) config = {};
|
||||
this._addImmutableProperty('type', 'slider');
|
||||
this._addLiveProperty('label', config.label);
|
||||
this._addLiveProperty('minValue', config.minValue);
|
||||
this._addLiveProperty('maxValue', config.maxValue);
|
||||
this._addLiveProperty('value', config.value);
|
||||
|
||||
if (typeof config.change === 'function') {
|
||||
this._addImmutableProperty('onInteraction', (details) => {
|
||||
this._value = details.value
|
||||
config.change(details.value)
|
||||
})
|
||||
this._value = details.value;
|
||||
config.change(details.value);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TouchBar.TouchBarSpacer = class TouchBarSpacer extends TouchBarItem {
|
||||
constructor (config) {
|
||||
super()
|
||||
if (config == null) config = {}
|
||||
this._addImmutableProperty('type', 'spacer')
|
||||
this._addImmutableProperty('size', config.size)
|
||||
super();
|
||||
if (config == null) config = {};
|
||||
this._addImmutableProperty('type', 'spacer');
|
||||
this._addImmutableProperty('size', config.size);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TouchBar.TouchBarSegmentedControl = class TouchBarSegmentedControl extends TouchBarItem {
|
||||
constructor (config) {
|
||||
super()
|
||||
if (config == null) config = {}
|
||||
this._addImmutableProperty('type', 'segmented_control')
|
||||
this._addLiveProperty('segmentStyle', config.segmentStyle)
|
||||
this._addLiveProperty('segments', config.segments || [])
|
||||
this._addLiveProperty('selectedIndex', config.selectedIndex)
|
||||
this._addLiveProperty('mode', config.mode)
|
||||
super();
|
||||
if (config == null) config = {};
|
||||
this._addImmutableProperty('type', 'segmented_control');
|
||||
this._addLiveProperty('segmentStyle', config.segmentStyle);
|
||||
this._addLiveProperty('segments', config.segments || []);
|
||||
this._addLiveProperty('selectedIndex', config.selectedIndex);
|
||||
this._addLiveProperty('mode', config.mode);
|
||||
|
||||
if (typeof config.change === 'function') {
|
||||
this._addImmutableProperty('onInteraction', (details) => {
|
||||
this._selectedIndex = details.selectedIndex
|
||||
config.change(details.selectedIndex, details.isSelected)
|
||||
})
|
||||
this._selectedIndex = details.selectedIndex;
|
||||
config.change(details.selectedIndex, details.isSelected);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TouchBar.TouchBarScrubber = class TouchBarScrubber extends TouchBarItem {
|
||||
constructor (config) {
|
||||
super()
|
||||
if (config == null) config = {}
|
||||
let { select, highlight } = config
|
||||
this._addImmutableProperty('type', 'scrubber')
|
||||
this._addLiveProperty('items', config.items)
|
||||
this._addLiveProperty('selectedStyle', config.selectedStyle || null)
|
||||
this._addLiveProperty('overlayStyle', config.overlayStyle || null)
|
||||
this._addLiveProperty('showArrowButtons', config.showArrowButtons || false)
|
||||
this._addLiveProperty('mode', config.mode || 'free')
|
||||
super();
|
||||
if (config == null) config = {};
|
||||
let { select, highlight } = config;
|
||||
this._addImmutableProperty('type', 'scrubber');
|
||||
this._addLiveProperty('items', config.items);
|
||||
this._addLiveProperty('selectedStyle', config.selectedStyle || null);
|
||||
this._addLiveProperty('overlayStyle', config.overlayStyle || null);
|
||||
this._addLiveProperty('showArrowButtons', config.showArrowButtons || false);
|
||||
this._addLiveProperty('mode', config.mode || 'free');
|
||||
|
||||
const cont = typeof config.continuous === 'undefined' ? true : config.continuous
|
||||
this._addLiveProperty('continuous', cont)
|
||||
const cont = typeof config.continuous === 'undefined' ? true : config.continuous;
|
||||
this._addLiveProperty('continuous', cont);
|
||||
|
||||
if (typeof select === 'function' || typeof highlight === 'function') {
|
||||
if (select == null) select = () => {}
|
||||
if (highlight == null) highlight = () => {}
|
||||
if (select == null) select = () => {};
|
||||
if (highlight == null) highlight = () => {};
|
||||
this._addImmutableProperty('onInteraction', (details) => {
|
||||
if (details.type === 'select' && typeof select === 'function') {
|
||||
select(details.selectedIndex)
|
||||
select(details.selectedIndex);
|
||||
} else if (details.type === 'highlight' && typeof highlight === 'function') {
|
||||
highlight(details.highlightedIndex)
|
||||
highlight(details.highlightedIndex);
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = TouchBar
|
||||
module.exports = TouchBar;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const { EventEmitter } = require('events')
|
||||
const { deprecate } = require('electron')
|
||||
const { Tray } = process.electronBinding('tray')
|
||||
const { EventEmitter } = require('events');
|
||||
const { deprecate } = require('electron');
|
||||
const { Tray } = process.electronBinding('tray');
|
||||
|
||||
Object.setPrototypeOf(Tray.prototype, EventEmitter.prototype)
|
||||
Object.setPrototypeOf(Tray.prototype, EventEmitter.prototype);
|
||||
|
||||
module.exports = Tray
|
||||
module.exports = Tray;
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const { EventEmitter } = require('events')
|
||||
const { View } = process.electronBinding('view')
|
||||
const { EventEmitter } = require('events');
|
||||
const { View } = process.electronBinding('view');
|
||||
|
||||
Object.setPrototypeOf(View.prototype, EventEmitter.prototype)
|
||||
Object.setPrototypeOf(View.prototype, EventEmitter.prototype);
|
||||
|
||||
View.prototype._init = function () {
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = View
|
||||
module.exports = View;
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const electron = require('electron')
|
||||
const electron = require('electron');
|
||||
|
||||
const { LayoutManager } = electron
|
||||
const { BoxLayout } = process.electronBinding('box_layout')
|
||||
const { LayoutManager } = electron;
|
||||
const { BoxLayout } = process.electronBinding('box_layout');
|
||||
|
||||
Object.setPrototypeOf(BoxLayout.prototype, LayoutManager.prototype)
|
||||
Object.setPrototypeOf(BoxLayout.prototype, LayoutManager.prototype);
|
||||
|
||||
BoxLayout.prototype._init = function () {
|
||||
// Call parent class's _init.
|
||||
LayoutManager.prototype._init.call(this)
|
||||
}
|
||||
LayoutManager.prototype._init.call(this);
|
||||
};
|
||||
|
||||
module.exports = BoxLayout
|
||||
module.exports = BoxLayout;
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const electron = require('electron')
|
||||
const electron = require('electron');
|
||||
|
||||
const { View } = electron
|
||||
const { Button } = process.electronBinding('button')
|
||||
const { View } = electron;
|
||||
const { Button } = process.electronBinding('button');
|
||||
|
||||
Object.setPrototypeOf(Button.prototype, View.prototype)
|
||||
Object.setPrototypeOf(Button.prototype, View.prototype);
|
||||
|
||||
Button.prototype._init = function () {
|
||||
// Call parent class's _init.
|
||||
View.prototype._init.call(this)
|
||||
}
|
||||
View.prototype._init.call(this);
|
||||
};
|
||||
|
||||
module.exports = Button
|
||||
module.exports = Button;
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const electron = require('electron')
|
||||
const electron = require('electron');
|
||||
|
||||
const { Button } = electron
|
||||
const { LabelButton } = process.electronBinding('label_button')
|
||||
const { Button } = electron;
|
||||
const { LabelButton } = process.electronBinding('label_button');
|
||||
|
||||
Object.setPrototypeOf(LabelButton.prototype, Button.prototype)
|
||||
Object.setPrototypeOf(LabelButton.prototype, Button.prototype);
|
||||
|
||||
LabelButton.prototype._init = function () {
|
||||
// Call parent class's _init.
|
||||
Button.prototype._init.call(this)
|
||||
}
|
||||
Button.prototype._init.call(this);
|
||||
};
|
||||
|
||||
module.exports = LabelButton
|
||||
module.exports = LabelButton;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
const { LayoutManager } = process.electronBinding('layout_manager')
|
||||
const { LayoutManager } = process.electronBinding('layout_manager');
|
||||
|
||||
LayoutManager.prototype._init = function () {
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = LayoutManager
|
||||
module.exports = LayoutManager;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user