Compare commits

..

58 Commits

Author SHA1 Message Date
John Kleinschmidt
924e372def v1.7.12 2018-01-31 14:46:48 -07:00
John Kleinschmidt
a27b7d1f10 Merge pull request #11785 from electron/case-insensitive-comparison-1-7-x
Do case insensitive comparisons
2018-01-31 12:58:06 -05:00
John Kleinschmidt
d3d8c1626a Merge pull request #11775 from electron/parallel-releases-1-7-x
Parallel releases for 1-7-x
2018-01-31 12:39:14 -05:00
Samuel Attard
8b6aa225ae Do case insensitive comparisons 2018-01-31 10:38:21 -07:00
John Kleinschmidt
e02440e0d8 Allow multiple releases to run at once
Find draft release by draft flag and tag name
2018-01-30 17:52:58 -07:00
John Kleinschmidt
a69a5de12f v1.7.11 2018-01-22 17:24:59 -05:00
Charles Kerr
d2a9ea4684 fix 'npm lint' errors 2018-01-22 15:21:39 -06:00
Aleš Pergl
e7074c5cdb Disallow launching unknown apps via browser client.
CVE-2018-1000006
2018-01-22 14:53:17 -06:00
Cheng Zhao
97349eb30a Merge pull request #11576 from dengyaolong/bugfix/1-7-x/ime-crash
fix mac ime crack
2018-01-18 16:05:23 +09:00
allenliu
f6c915bbb5 fix mac ime crack 2018-01-05 22:06:00 +08:00
John Kleinschmidt
378666668f v1.7.10 2017-12-18 15:23:57 -05:00
John Kleinschmidt
9623329cbd Merge pull request #11427 from electron/prepare-for-release
Preparation for 1.7.10 release
2017-12-18 13:20:31 -05:00
John Kleinschmidt
34b75e5e73 Update to use new release scripts 2017-12-13 11:54:23 -05:00
John Kleinschmidt
c339e576a8 Update libcc 2017-12-13 10:44:20 -05:00
Charles Kerr
c12d88fc30 Merge pull request #11327 from electron/cherry/1-7-x/10540
Cherry #10540
2017-12-04 10:43:49 -06:00
Benjamin Pasero
8f2064d9b7 set iconPosition as optional 2017-12-04 10:04:29 -06:00
Charles Kerr
75ff5d2a45 Merge pull request #11141 from electron/backport-scrubber-width-fix
Backport scrubber width fix to 1-7-x
2017-11-17 14:31:54 -06:00
John Kleinschmidt
87565e25eb Add Jenkinsfile for macOS CI 2017-11-17 10:58:26 -05:00
Samuel Attard
d0c9c4028e Forward declare the scrubber layout 2017-11-17 06:21:36 +11:00
Armagan Amcalar
37f23f6d4e Make ScrubberItem width dynamic
Depending on whether a ScrubberItem has text or an icon, this changeset
calculates the actual width and sizes the TouchBar items accordingly.
Previously, all ScrubberItems, regardless of their content, had a static
width of 50px.

This commit also fixes #10539.
2017-11-17 06:19:19 +11:00
Charles Kerr
4b8f3276b5 Merge pull request #11020 from pfrazee/fix-protocol-crash-error-17x
Fix crash in custom protocols caused by bad callback exec
2017-11-16 09:36:38 -06:00
Charles Kerr
b15c418c54 Merge pull request #10898 from electron/nvidia-high-sierra-17x-fix
Fix rendering issues with Nvidia GPU on High Sierra for 1.7.x
2017-11-13 17:49:30 -06:00
Paul Frazee
d964560990 Fix crash in custom protocols caused by bad callback exec 2017-11-05 12:20:46 -06:00
John Kleinschmidt
66e0e8fdcd Fix rendering issues with Nvidia GPU on High Sierra 2017-10-24 13:48:39 -04:00
John Kleinschmidt
c16498c274 Bump v1.7.9 2017-10-10 15:33:41 -04:00
John Kleinschmidt
62bd339b0d Merge pull request #10743 from electron/crankshaft-fix
Crankshaft RCE fix
2017-10-10 15:04:29 -04:00
John Kleinschmidt
0368460d74 Crankshaft RCE fix 2017-10-10 13:23:31 -04:00
John Kleinschmidt
9386de415a Merge pull request #10687 from electron/circleci-report-testing-results
CircleCI report testing results
2017-10-04 10:41:10 -04:00
John Kleinschmidt
4d3d7aa5fd Improve CircleCI test results 2017-10-04 10:01:09 -04:00
John Kleinschmidt
1d0dfd590b Release process updates for 1-7-x (#10643)
* Add prerelease script

* Update CircleCI for releases

* Rerun builds
2017-09-28 10:48:02 -04:00
Birunthan Mohanathas
5b679cb1eb Merge pull request #10630 from electron/squirrel-avoid-double-update-1-7
Use Squirrel.Windows --checkForUpdate (1.7.x)
2017-09-27 21:20:22 +03:00
J.M
8c28e3b6f1 Use Squirrel.Windows --checkForUpdate
This cherry-picks #10483 to fix #5057.
2017-09-27 20:32:58 +03:00
Birunthan Mohanathas
f786199d2c Merge pull request #10628 from electron/squirrel-mac-bump
Bump external binaries to 1.2.2
2017-09-27 16:06:03 +03:00
Josh Abernathy
acfc24e45e Bump external binaries to 1.2.2 2017-09-27 16:04:05 +03:00
John Kleinschmidt
01ca2252cd Bump v1.7.8 2017-09-24 10:34:18 +09:00
John Kleinschmidt
53db3862c0 Merge pull request #10591 from electron/disable-app-importcertificate-tests
disable flaky app.importCertificate and select-client-certificate tests
2017-09-24 10:25:57 +09:00
John Kleinschmidt
6099ab222e Change GitHub upload to use JS GitHub lib 2017-09-24 10:17:15 +09:00
Zeke Sikelianos
830cc7ecd1 disable select-client-certificate spec 2017-09-24 10:00:34 +09:00
Zeke Sikelianos
eef8ff09e2 disable flaky app.importCertificate tests 2017-09-24 09:49:48 +09:00
Samuel Attard
b15392e1c1 Backporting changes for 1.7.8 (#10586)
* Fix app.makeSingleInstance hanging on posix systems

Wait for the IO thread to be a thing before attempting to listen on the socket

Fixes #9880

* Move OnBrowserReady call to PreMainMessageLoopRun to account for timing issues on macOS

* Woops, how did that happen ;)

* Refactor as per @zcbenz comments

Also fix issue where we run the single instance callback *not* on the UI thread,
this apparently results in a hung process.

* Appease the linting gods

* Create watcher when message loop is ready

* spec: Add test case for app.makeSingleInstance

* Fix missing extension when saving a file without filters

Previously, when triggering the save dialog through e.g. `<a download>`
links (e.g. http://jsfiddle.net/koldev/cW7W5/), the extension was only
saved if Finder was set to show all extensions by default. We now always
display the extension to make sure that it is saved.

If we want to keep the extension hidden, we could also populate the
allowed file types array with the extension from the default filename,
but that would have interfered with how we set the filters.

* Try to make test less flaky

* Try simpler test

* Fix stdout detection

* Try longer timeout on test
2017-09-24 07:27:08 +09:00
John Kleinschmidt
fd1bb3f95d Merge pull request #10585 from electron/turbofan-fix
Apply turbofan-fix
2017-09-23 16:06:34 +09:00
John Kleinschmidt
53eb4d68c5 Apply turbofan-fix 2017-09-23 15:05:15 +09:00
John Kleinschmidt
331a1759d2 Fix CircleCI test step 2017-09-13 11:22:33 -04:00
John Kleinschmidt
b69d76258a Remove arm64 build
Arm64 builds are not built for 1.7.x
2017-09-13 10:50:53 -04:00
John Kleinschmidt
680bf0076b Bump v1.7.7 2017-08-30 13:06:59 -04:00
John Kleinschmidt
d42d856b9a Rerun builds 2017-08-30 09:42:23 -04:00
John Kleinschmidt
e6f6862ae8 Merge pull request #10390 from electron/render_widget_compositor_patch
Backport fix for flickering web contents on large monitors
2017-08-29 21:52:35 -04:00
John Kleinschmidt
44b4cc374b Update to latest build 2017-08-29 21:27:59 -04:00
John Kleinschmidt
9824c88d2d Backport fix for flickering web contents on large monitors 2017-08-29 13:43:02 -04:00
John Kleinschmidt
96bc46c255 Merge pull request #10365 from electron/fix_exit_crash
Fixed crash on process exit on Windows
2017-08-29 11:55:12 -04:00
John Kleinschmidt
873a8902af Merge pull request #10375 from electron/backport-notification-sounds
Backport #10293 (notification-sounds)
2017-08-29 10:52:26 -04:00
John Kleinschmidt
7dac300305 Merge pull request #10377 from electron/backfort-libuv-1419
Backport libuv/libuv#1419
2017-08-29 10:50:32 -04:00
John Kleinschmidt
2a536d2aa2 Merge pull request #10374 from electron/backport-drag-browser-view
Backport #10232 (drag-browser-view)
2017-08-29 09:34:58 -04:00
Cheng Zhao
ccd03c6675 Backport https://github.com/libuv/libuv/pull/1419
win, fs: support unusual reparse points

Allow for running uv_fs_stat and uv_fs_lstat on all reparse points. One
of such points is new OneDrive drive with "files on demand" feature
enabled.
2017-08-29 10:25:45 +09:00
Charlie Hess
5515092944 Merge pull request #10293 from electron/notification-sounds
Add support for soundName in main process notifications
2017-08-28 13:23:27 -07:00
Samuel Attard
fb7661d2d2 Merge pull request #10232 from electron/drag-browser-view
Add -webkit-app-region support to BrowserView
2017-08-28 13:19:09 -07:00
John Kleinschmidt
75b31f0bb6 Add CircleCI 2017-08-28 11:35:30 -04:00
Ales Pergl
cfee5ba8c8 Fixed crash on process exit on Windows 2017-08-28 16:28:07 +02:00
1069 changed files with 56027 additions and 25563 deletions

View File

@@ -3,7 +3,7 @@ version: 2
jobs:
electron-linux-arm:
docker:
- image: electronbuilds/electron:0.0.7
- image: electronbuilds/electron:0.0.4
environment:
TARGET_ARCH: arm
resource_class: 2xlarge
@@ -58,293 +58,11 @@ jobs:
else
echo 'Skipping upload distribution because build is not for release'
fi
- run:
name: Optionally finish release
shell: /bin/sh
command: |
if [ "$ELECTRON_RELEASE" == "1" ] && [ "$AUTO_RELEASE" == "true" ]; then
echo 'Trying to finish release'
node script/release.js --validateRelease --automaticRelease
releaseExitCode=$?
if [ $releaseExitCode -eq 0 ]; then
echo 'Release is ready to go; releasing'
node script/release.js--automaticRelease
if [ $releaseExitCode -eq 0 ]; then
echo 'Release successful, now publishing to npm'
echo "//registry.npmjs.org/:_authToken=$ELECTRON_NPM_TOKEN" >> ~/.npmrc
npm run publish-to-npm
echo 'Release has been published to npm'
fi
else
echo 'Release is not complete, skipping publish for now'
fi
else
echo 'Skipping finishing release because build is not for release'
fi
- run:
name: Zip out directory
command: |
if [ "$ELECTRON_RELEASE" != "1" ]; then
zip -r electron.zip out/D
fi
- persist_to_workspace:
root: /home/builduser
paths:
- project/out
- store_artifacts:
path: electron.zip
electron-linux-arm-test:
machine: true
steps:
- attach_workspace:
at: /tmp/workspace
- checkout
- run:
name: Test in ARM docker container
command: |
if [ "$ELECTRON_RELEASE" != "1" ]; then
docker run --rm --privileged multiarch/qemu-user-static:register --reset
docker run -it \
--mount type=bind,source=/tmp/workspace,target=/tmp/workspace \
--rm electronbuilds/electronarm7:0.0.5 > version.txt
cat version.txt
if grep -q `script/get-version.py` version.txt; then
echo "Versions match"
else
echo "Versions do not match"
exit 1
fi
else
echo "Skipping test for release build"
fi
electron-linux-arm64:
docker:
- image: electronbuilds/electron:0.0.7
environment:
TARGET_ARCH: arm64
resource_class: 2xlarge
steps:
- checkout
- run:
name: Check for release
command: |
if [ -n "${RUN_RELEASE_BUILD}" ]; then
echo 'release build triggered from api'
echo 'export ELECTRON_RELEASE=1 TRIGGERED_BY_API=1' >> $BASH_ENV
fi
- run:
name: Bootstrap
command: |
if [ "$ELECTRON_RELEASE" == "1" ]; then
echo 'Bootstrapping Electron for release build'
script/bootstrap.py --target_arch=$TARGET_ARCH
else
echo 'Bootstrapping Electron for debug build'
script/bootstrap.py --target_arch=$TARGET_ARCH --dev
fi
- run: npm run lint
- run:
name: Build
command: |
if [ "$ELECTRON_RELEASE" == "1" ]; then
echo 'Building Electron for release'
script/build.py -c R
else
echo 'Building Electron for debug'
script/build.py -c D
fi
- run:
name: Create distribution
command: |
if [ "$ELECTRON_RELEASE" == "1" ]; then
echo 'Creating Electron release distribution'
script/create-dist.py
else
echo 'Skipping create distribution because build is not for release'
fi
- run:
name: Upload distribution
command: |
if [ "$ELECTRON_RELEASE" == "1" ] && [ "$TRIGGERED_BY_API" != "1" ]; then
echo 'Uploading Electron release distribution to github releases'
script/upload.py
elif [ "$ELECTRON_RELEASE" == "1" ] && [ "$TRIGGERED_BY_API" == "1" ]; then
echo 'Uploading Electron release distribution to s3'
script/upload.py --upload_to_s3
else
echo 'Skipping upload distribution because build is not for release'
fi
- run:
name: Optionally finish release
shell: /bin/sh
command: |
if [ "$ELECTRON_RELEASE" == "1" ] && [ "$AUTO_RELEASE" == "true" ]; then
echo 'Trying to finish release'
node script/release.js --validateRelease --automaticRelease
releaseExitCode=$?
if [ $releaseExitCode -eq 0 ]; then
echo 'Release is ready to go; releasing'
node script/release.js--automaticRelease
if [ $releaseExitCode -eq 0 ]; then
echo 'Release successful, now publishing to npm'
echo "//registry.npmjs.org/:_authToken=$ELECTRON_NPM_TOKEN" >> ~/.npmrc
npm run publish-to-npm
echo 'Release has been published to npm'
fi
else
echo 'Release is not complete, skipping publish for now'
fi
else
echo 'Skipping finishing release because build is not for release'
fi
- run:
name: Zip out directory
command: |
if [ "$ELECTRON_RELEASE" != "1" ]; then
zip -r electron.zip out/D
fi
- persist_to_workspace:
root: /home/builduser
paths:
- project/out
- store_artifacts:
path: electron.zip
electron-linux-arm64-test:
machine: true
steps:
- attach_workspace:
at: /tmp/workspace
- checkout
- run:
name: Test in ARM64 docker container
command: |
if [ "$ELECTRON_RELEASE" != "1" ]; then
docker run --rm --privileged multiarch/qemu-user-static:register --reset
docker run -it \
--mount type=bind,source=/tmp/workspace,target=/tmp/workspace \
--rm electronbuilds/electronarm64:0.0.6 > version.txt
cat version.txt
if grep -q `script/get-version.py` version.txt; then
echo "Versions match"
else
echo "Versions do not match"
exit 1
fi
else
echo "Skipping test for release build"
fi
electron-linux-ia32:
docker:
- image: electronbuilds/electron:0.0.7
- image: electronbuilds/electron:0.0.4
environment:
TARGET_ARCH: ia32
DISPLAY: ':99.0'
resource_class: xlarge
steps:
- checkout
- run:
name: Setup for headless testing
command: sh -e /etc/init.d/xvfb start
- run:
name: Check for release
command: |
if [ -n "${RUN_RELEASE_BUILD}" ]; then
echo 'release build triggered from api'
echo 'export ELECTRON_RELEASE=1 TRIGGERED_BY_API=1' >> $BASH_ENV
fi
- run:
name: Bootstrap
command: |
if [ "$ELECTRON_RELEASE" == "1" ]; then
echo 'Bootstrapping Electron for release build'
script/bootstrap.py --target_arch=$TARGET_ARCH
else
echo 'Bootstrapping Electron for debug build'
script/bootstrap.py --target_arch=$TARGET_ARCH --dev
fi
- run: npm run lint
- run:
name: Build
command: |
if [ "$ELECTRON_RELEASE" == "1" ]; then
echo 'Building Electron for release'
script/build.py -c R
else
echo 'Building Electron for debug'
script/build.py -c D
fi
- run:
name: Create distribution
command: |
if [ "$ELECTRON_RELEASE" == "1" ]; then
echo 'Creating Electron release distribution'
script/create-dist.py
else
echo 'Skipping create distribution because build is not for release'
fi
- run:
name: Upload distribution
command: |
if [ "$ELECTRON_RELEASE" == "1" ] && [ "$TRIGGERED_BY_API" != "1" ]; then
echo 'Uploading Electron release distribution to github releases'
script/upload.py
elif [ "$ELECTRON_RELEASE" == "1" ] && [ "$TRIGGERED_BY_API" == "1" ]; then
echo 'Uploading Electron release distribution to s3'
script/upload.py --upload_to_s3
else
echo 'Skipping upload distribution because build is not for release'
fi
- run:
name: Optionally finish release
shell: /bin/sh
command: |
if [ "$ELECTRON_RELEASE" == "1" ] && [ "$AUTO_RELEASE" == "true" ]; then
echo 'Trying to finish release'
node script/release.js --validateRelease --automaticRelease
releaseExitCode=$?
if [ $releaseExitCode -eq 0 ]; then
echo 'Release is ready to go; releasing'
node script/release.js--automaticRelease
if [ $releaseExitCode -eq 0 ]; then
echo 'Release successful, now publishing to npm'
echo "//registry.npmjs.org/:_authToken=$ELECTRON_NPM_TOKEN" >> ~/.npmrc
npm run publish-to-npm
echo 'Release has been published to npm'
fi
else
echo 'Release is not complete, skipping publish for now'
fi
else
echo 'Skipping finishing release because build is not for release'
fi
- run:
name: Test
environment:
MOCHA_FILE: junit/test-results.xml
MOCHA_REPORTER: mocha-junit-reporter
command: |
if [ "$ELECTRON_RELEASE" != "1" ]; then
echo 'Testing Electron debug build'
out/D/electron --version
mkdir junit
script/test.py --ci --rebuild_native_modules
else
echo 'Skipping testing on release build'
fi
- run:
name: Verify FFmpeg
command: |
if [ "$ELECTRON_RELEASE" != "1" ]; then
echo 'Verifying ffmpeg on debug build'
script/verify-ffmpeg.py
else
echo 'Skipping verify ffmpeg on release build'
fi
electron-linux-mips64el:
docker:
- image: electronbuilds/electron:0.0.7
environment:
TARGET_ARCH: mips64el
resource_class: xlarge
steps:
- checkout
@@ -397,33 +115,9 @@ jobs:
else
echo 'Skipping upload distribution because build is not for release'
fi
- run:
name: Optionally finish release
shell: /bin/sh
command: |
if [ "$ELECTRON_RELEASE" == "1" ] && [ "$AUTO_RELEASE" == "true" ]; then
echo 'Trying to finish release'
node script/release.js --validateRelease --automaticRelease
releaseExitCode=$?
if [ $releaseExitCode -eq 0 ]; then
echo 'Release is ready to go; releasing'
node script/release.js--automaticRelease
if [ $releaseExitCode -eq 0 ]; then
echo 'Release successful, now publishing to npm'
echo "//registry.npmjs.org/:_authToken=$ELECTRON_NPM_TOKEN" >> ~/.npmrc
npm run publish-to-npm
echo 'Release has been published to npm'
fi
else
echo 'Release is not complete, skipping publish for now'
fi
else
echo 'Skipping finishing release because build is not for release'
fi
electron-linux-x64:
docker:
- image: electronbuilds/electron:0.0.7
- image: electronbuilds/electron:0.0.4
environment:
TARGET_ARCH: x64
DISPLAY: ':99.0'
@@ -451,224 +145,6 @@ jobs:
script/bootstrap.py --target_arch=$TARGET_ARCH --dev
fi
- run: npm run lint
- run:
name: Build
command: |
if [ "$ELECTRON_RELEASE" == "1" ]; then
echo 'Building Electron for release'
script/build.py -c R
else
echo 'Building Electron for debug'
script/build.py -c D
fi
- run:
name: Create distribution
command: |
if [ "$ELECTRON_RELEASE" == "1" ]; then
echo 'Creating Electron release distribution'
script/create-dist.py
else
echo 'Skipping create distribution because build is not for release'
fi
- run:
name: Upload distribution
command: |
if [ "$ELECTRON_RELEASE" == "1" ] && [ "$TRIGGERED_BY_API" != "1" ]; then
echo 'Uploading Electron release distribution to github releases'
script/upload.py
elif [ "$ELECTRON_RELEASE" == "1" ] && [ "$TRIGGERED_BY_API" == "1" ]; then
echo 'Uploading Electron release distribution to s3'
script/upload.py --upload_to_s3
else
echo 'Skipping upload distribution because build is not for release'
fi
- run:
name: Optionally finish release
shell: /bin/sh
command: |
if [ "$ELECTRON_RELEASE" == "1" ] && [ "$AUTO_RELEASE" == "true" ]; then
echo 'Trying to finish release'
node script/release.js --validateRelease --automaticRelease
releaseExitCode=$?
if [ $releaseExitCode -eq 0 ]; then
echo 'Release is ready to go; releasing'
node script/release.js--automaticRelease
if [ $releaseExitCode -eq 0 ]; then
echo 'Release successful, now publishing to npm'
echo "//registry.npmjs.org/:_authToken=$ELECTRON_NPM_TOKEN" >> ~/.npmrc
npm run publish-to-npm
echo 'Release has been published to npm'
fi
else
echo 'Release is not complete, skipping publish for now'
fi
else
echo 'Skipping finishing release because build is not for release'
fi
- run:
name: Test
environment:
MOCHA_FILE: junit/test-results.xml
MOCHA_REPORTER: mocha-junit-reporter
command: |
if [ "$ELECTRON_RELEASE" != "1" ]; then
echo 'Testing Electron debug build'
mkdir junit
script/test.py --ci --rebuild_native_modules
else
echo 'Skipping testing on release build'
fi
- run:
name: Verify FFmpeg
command: |
if [ "$ELECTRON_RELEASE" != "1" ]; then
echo 'Verifying ffmpeg on debug build'
script/verify-ffmpeg.py
else
echo 'Skipping verify ffmpeg on release build'
fi
- run:
name: Generate Typescript Definitions
command: npm run create-typescript-definitions
- store_test_results:
path: junit
- store_artifacts:
path: junit
- store_artifacts:
path: out/electron.d.ts
- store_artifacts:
path: out/electron-api.json
electron-osx-x64:
environment:
TARGET_ARCH: x64
macos:
xcode: "9.0"
steps:
- checkout
- run:
name: Reclaim disk space
command: |
df -h
sudo rm -rf /Library/Developer/CoreSimulator
df -h
sysctl -n hw.ncpu
- run:
name: Check for release
command: |
if [ -n "${RUN_RELEASE_BUILD}" ]; then
echo 'release build triggered from api'
echo 'export ELECTRON_RELEASE=1 TRIGGERED_BY_API=1' >> $BASH_ENV
fi
- run:
name: Bootstrap
command: |
if [ "$ELECTRON_RELEASE" == "1" ]; then
echo 'Bootstrapping Electron for release build'
script/bootstrap.py --target_arch=$TARGET_ARCH
else
echo 'Bootstrapping Electron for debug build'
script/bootstrap.py --target_arch=$TARGET_ARCH --dev
fi
- run: npm run lint
- run:
name: Build
command: |
if [ "$ELECTRON_RELEASE" == "1" ]; then
echo 'Building Electron for release'
script/build.py -c R
else
echo 'Building Electron for debug'
script/build.py -c D
fi
- run:
name: Create distribution
command: |
if [ "$ELECTRON_RELEASE" == "1" ]; then
echo 'Creating Electron release distribution'
script/create-dist.py
else
echo 'Skipping create distribution because build is not for release'
fi
- run:
name: Upload distribution
command: |
if [ "$ELECTRON_RELEASE" == "1" ] && [ "$TRIGGERED_BY_API" != "1" ]; then
echo 'Uploading Electron release distribution to github releases'
script/upload.py
elif [ "$ELECTRON_RELEASE" == "1" ] && [ "$TRIGGERED_BY_API" == "1" ]; then
echo 'Uploading Electron release distribution to s3'
script/upload.py --upload_to_s3
else
echo 'Skipping upload distribution because build is not for release'
fi
- run:
name: Test
environment:
MOCHA_FILE: junit/test-results.xml
MOCHA_REPORTER: mocha-junit-reporter
command: |
if [ "$ELECTRON_RELEASE" != "1" ]; then
echo 'Testing Electron debug build'
mkdir junit
script/test.py --ci --rebuild_native_modules
else
echo 'Skipping testing on release build'
fi
- run:
name: Verify FFmpeg
command: |
if [ "$ELECTRON_RELEASE" != "1" ]; then
echo 'Verifying ffmpeg on debug build'
script/verify-ffmpeg.py
else
echo 'Skipping verify ffmpeg on release build'
fi
- run:
name: Generate Typescript Definitions
command: npm run create-typescript-definitions
- store_test_results:
path: junit
- store_artifacts:
path: junit
- store_artifacts:
path: out/electron.d.ts
- store_artifacts:
path: out/electron-api.json
electron-mas-x64:
environment:
TARGET_ARCH: x64
MAS_BUILD: 1
macos:
xcode: "9.0"
steps:
- checkout
- run:
name: Reclaim disk space
command: |
df -h
sudo rm -rf /Library/Developer/CoreSimulator
df -h
sysctl -n hw.ncpu
- run:
name: Check for release
command: |
if [ -n "${RUN_RELEASE_BUILD}" ]; then
echo 'release build triggered from api'
echo 'export ELECTRON_RELEASE=1 TRIGGERED_BY_API=1' >> $BASH_ENV
fi
- run:
name: Bootstrap
command: |
if [ "$ELECTRON_RELEASE" == "1" ]; then
echo 'Bootstrapping Electron for release build'
script/bootstrap.py --target_arch=$TARGET_ARCH
else
echo 'Bootstrapping Electron for debug build'
script/bootstrap.py --target_arch=$TARGET_ARCH --dev
fi
- run: npm run lint
- run:
name: Build
command: |
@@ -739,24 +215,9 @@ workflows:
build-arm:
jobs:
- electron-linux-arm
- electron-linux-arm-test:
requires:
- electron-linux-arm
build-arm64:
jobs:
- electron-linux-arm64
- electron-linux-arm64-test:
requires:
- electron-linux-arm64
build-ia32:
jobs:
- electron-linux-ia32
build-x64:
jobs:
- electron-linux-x64
build-osx-x64:
jobs:
- electron-osx-x64
build-mas-x64:
jobs:
- electron-mas-x64

View File

@@ -1,3 +0,0 @@
*
!tools/xvfb-init.sh
!tools/run-electron.sh

21
.github/CODEOWNERS vendored
View File

@@ -1,21 +0,0 @@
# Order is important. The LAST matching pattern has the MOST precedence.
# gitignore style patterns are used, not globs.
# https://help.github.com/articles/about-codeowners
# https://git-scm.com/docs/gitignore
# Everything that falls through the cracks:
* @electron/reviewers
# filename patterns
*browser_view* @electron/browserview
*notification* @electron/notifications
*pdf* @electron/printing
*printing* @electron/printing
*updater* @electron/updater
# directories
/.github/ @electron/hubbers
/default_app/ @electron/docs
/docs/ @electron/docs
/docs-translations/ @electron/i18n
/npm/ @electron/hubbers

View File

@@ -1,8 +0,0 @@
<!--
Thank you for your Pull Request. Please provide a description above and review
the requirements below.
Bug fixes and new features should include tests and possibly benchmarks.
Contributors guide: https://github.com/electron/electron/blob/master/CONTRIBUTING.md
-->

31
.github/config.yml vendored
View File

@@ -1,31 +0,0 @@
# Configuration for new-issue-welcome - https://github.com/behaviorbot/new-issue-welcome
# Comment to be posted to on first time issues
newIssueWelcomeComment: |
👋 Thanks for opening your first issue here! If you're reporting a 🐞 bug, please make sure you include steps to reproduce it. We get a lot of issues on this repo, so please be patient and we will get back to you as soon as we can.
To help make it easier for us to investigate your issue, please follow the [contributing guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md#submitting-issues).
# Configuration for new-pr-welcome - https://github.com/behaviorbot/new-pr-welcome
# Comment to be posted to on PRs from first time contributors in your repository
newPRWelcomeComment: |
💖 Thanks for opening this pull request! 💖
![typing cat](https://user-images.githubusercontent.com/2289/36400158-2c7c589e-1584-11e8-81c7-bd34fd3c392b.gif)
Here is a list of things that will help get it across the finish line:
- Follow the JavaScript, C++, and Python [coding style](https://github.com/electron/electron/blob/master/docs/development/coding-style.md).
- Run `npm run lint` locally to catch formatting errors earlier.
- Document any user-facing changes you've made following the [documentation styleguide](https://github.com/electron/electron/blob/master/docs/styleguide.md).
- Include tests when adding/changing behavior.
- Include screenshots and animated GIFs whenever possible.
We get a lot of pull requests on this repo, so please be patient and we will get back to you as soon as we can.
# Configuration for first-pr-merge - https://github.com/behaviorbot/first-pr-merge
# Comment to be posted to on pull requests merged by a first time user
firstPRMergeComment: >
Congrats on merging your first pull request! 🎉🎉🎉
# It is recommend to include as many gifs and emojis as possible

25
.github/stale.yml vendored
View File

@@ -1,25 +0,0 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 45
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale
exemptLabels:
- fixme/bug
- fixme/crash
- fixme/regression
- fixme/security
- blocked
- blocking-stable
- needs-review
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity and is not currently prioritized. It will be closed
in a week if no further activity occurs :)
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: >
If you still think this issue is relevant, please ping a maintainer or
leave a comment!

13
.gitignore vendored
View File

@@ -1,7 +1,6 @@
.DS_Store
.env
.gclient_done
**/.npmrc
.npmrc
.tags*
.vs/
.vscode/
@@ -15,6 +14,7 @@
*.vcxproj.filters
*.vcxproj.user
*.xcodeproj
node_modules/
/.idea/
/brightray/brightray.opensdf
/brightray/brightray.sdf
@@ -32,19 +32,12 @@
/vendor/debian_jessie_arm-sysroot/
/vendor/debian_jessie_arm64-sysroot/
/vendor/debian_jessie_i386-sysroot/
/vendor/debian_jessie_mips64-sysroot/
/vendor/debian_wheezy_amd64-sysroot/
/vendor/debian_wheezy_arm-sysroot/
/vendor/debian_wheezy_i386-sysroot/
/vendor/gcc-4.8.3-d197-n64-loongson/
/vendor/readme-gcc483-loongson.txt
/vendor/download/
/vendor/llvm-build/
/vendor/llvm/
/vendor/node/deps/node-inspect/.npmrc
/vendor/npm/
/vendor/python_26/
/vendor/native_mksnapshot
/vendor/LICENSES.chromium.html
node_modules/
SHASUMS256.txt
**/package-lock.json

View File

@@ -1 +1 @@
v8.2.1
v7.9.0

View File

@@ -1,6 +0,0 @@
{
"plugins": [
["remark-lint-code-block-style", "fenced"],
["remark-lint-fenced-code-flag"]
]
}

View File

@@ -5,7 +5,7 @@ notifications:
before_install:
- export BOTO_CONFIG=/dev/null
language: node_js
node_js:
- "4"
@@ -22,8 +22,6 @@ matrix:
env: TARGET_ARCH=arm
- os: linux
env: TARGET_ARCH=ia32
- os: linux
env: TARGET_ARCH=arm64
allow_failures:
- os: osx

View File

@@ -1,4 +1,4 @@
# Contributor Covenant Code of Conduct:
# Contributor Covenant Code of Conduct
## Our Pledge
@@ -34,13 +34,13 @@ This Code of Conduct applies both within project spaces and in public spaces whe
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [coc@electronjs.org](mailto:coc@electronjs.org). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [electron@github.com](mailto:electron@github.com). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor-Covenant][homepage], version 1.4, available at [https://contributor-covenant.org/version/1/4][version]
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: https://contributor-covenant.org
[version]: https://contributor-covenant.org/version/1/4/
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@@ -1,56 +1,79 @@
# Contributing to Electron
:memo: Available Translations: [Korean](https://github.com/electron/electron/tree/master/docs-translations/ko-KR/project/CONTRIBUTING.md) | [Simplified Chinese](https://github.com/electron/electron/tree/master/docs-translations/zh-CN/project/CONTRIBUTING.md) | [Brazilian Portuguese](https://github.com/electron/electron/tree/master/docs-translations/pt-BR/project/CONTRIBUTING.md) | [Dutch](https://github.com/electron/electron/tree/master/docs-translations/nl/project/CONTRIBUTING.md)
:+1::tada: First off, thanks for taking the time to contribute! :tada::+1:
This project adheres to the Contributor Covenant [code of conduct](CODE_OF_CONDUCT.md).
By participating, you are expected to uphold this code. Please report unacceptable
behavior to coc@electronjs.org.
behavior to electron@github.com.
The following is a set of guidelines for contributing to Electron.
These are just guidelines, not rules, use your best judgment and feel free to
propose changes to this document in a pull request.
## [Issues](https://electronjs.org/docs/development/issues)
## Submitting Issues
Issues are created [here](https://github.com/electron/electron/issues/new).
* You can create an issue [here](https://github.com/electron/electron/issues/new),
but before doing that please read the notes below and include as many details as
possible with your report. If you can, please include:
* The version of Electron you are using
* The operating system you are using
* If applicable, what you were doing when the issue arose and what you
expected to happen
* Other things that will help resolve your issue:
* Screenshots and animated GIFs
* Error output that appears in your terminal, dev tools or as an alert
* Perform a [cursory search](https://github.com/electron/electron/issues?utf8=✓&q=is%3Aissue+)
to see if a similar issue has already been submitted
* [How to Contribute in Issues](https://electronjs.org/docs/development/issues#how-to-contribute-in-issues)
* [Asking for General Help](https://electronjs.org/docs/development/issues#asking-for-general-help)
* [Submitting a Bug Report](https://electronjs.org/docs/development/issues#submitting-a-bug-report)
* [Triaging a Bug Report](https://electronjs.org/docs/development/issues#triaging-a-bug-report)
* [Resolving a Bug Report](https://electronjs.org/docs/development/issues#resolving-a-bug-report)
## Submitting Pull Requests
### Issue Maintenance and Closure
* If an issue is inactive for 45 days (no activity of any kind), it will be
marked for closure with `stale`.
* If after this label is applied, no further activity occurs in the next 7 days,
the issue will be closed.
* If an issue has been closed and you still feel it's relevant, feel free to
ping a maintainer or add a comment!
* Include screenshots and animated GIFs in your pull request whenever possible.
* Follow the JavaScript, C++, and Python [coding style defined in docs](/docs/development/coding-style.md).
* Write documentation in [Markdown](https://daringfireball.net/projects/markdown).
See the [Documentation Styleguide](/docs/styleguide.md).
* Use short, present tense commit messages. See [Commit Message Styleguide](#git-commit-messages).
## [Pull Requests](https://electronjs.org/docs/development/pull-requests)
## Styleguides
Pull Requests are the way concrete changes are made to the code, documentation,
dependencies, and tools contained in the `electron/electron` repository.
### General Code
* [Setting up your local environment](https://electronjs.org/docs/development/pull-requests#setting-up-your-local-environment)
* [Step 1: Fork](https://electronjs.org/docs/development/pull-requests#step-1-fork)
* [Step 2: Build](https://electronjs.org/docs/development/pull-requests#step-2-build)
* [Step 3: Branch](https://electronjs.org/docs/development/pull-requests#step-3-branch)
* [The Process of Making Changes](https://electronjs.org/docs/development/pull-requests#the-process-of-making-changes)
* [Step 4: Code](https://electronjs.org/docs/development/pull-requests#step-4-code)
* [Step 5: Commit](https://electronjs.org/docs/development/pull-requests#step-5-commit)
* [Commit message guidelines](https://electronjs.org/docs/development/pull-requests#commit-message-guidelines)
* [Step 6: Rebase](https://electronjs.org/docs/development/pull-requests#step-6-rebase)
* [Step 7: Test](https://electronjs.org/docs/development/pull-requests#step-7-test)
* [Step 8: Push](https://electronjs.org/docs/development/pull-requests#step-8-push)
* [Step 8: Opening the Pull Request](https://electronjs.org/docs/development/pull-requests#step-8-opening-the-pull-request)
* [Step 9: Discuss and Update](#step-9-discuss-and-update)
* [Approval and Request Changes Workflow](https://electronjs.org/docs/development/pull-requests#approval-and-request-changes-workflow)
* [Step 10: Landing](https://electronjs.org/docs/development/pull-requests#step-10-landing)
* [Continuous Integration Testing](https://electronjs.org/docs/development/pull-requests#continuous-integration-testing)
* End files with a newline.
* Place requires in the following order:
* Built in Node Modules (such as `path`)
* Built in Electron Modules (such as `ipc`, `app`)
* Local Modules (using relative paths)
* Place class properties in the following order:
* Class methods and properties (methods starting with a `@`)
* Instance methods and properties
* Avoid platform-dependent code:
* Use `path.join()` to concatenate filenames.
* Use `os.tmpdir()` rather than `/tmp` when you need to reference the
temporary directory.
* Using a plain `return` when returning explicitly at the end of a function.
* Not `return null`, `return undefined`, `null`, or `undefined`
## Style Guides
See [Coding Style](https://electronjs.org/docs/development/coding-style) for information about which standards Electron adheres to in different parts of its codebase.
### Git Commit Messages
* Use the present tense ("Add feature" not "Added feature")
* Use the imperative mood ("Move cursor to..." not "Moves cursor to...")
* Limit the first line to 72 characters or less
* Reference issues and pull requests liberally
* When only changing documentation, include `[ci skip]` in the commit description
* Consider starting the commit message with an applicable emoji:
* :art: `:art:` when improving the format/structure of the code
* :racehorse: `:racehorse:` when improving performance
* :non-potable_water: `:non-potable_water:` when plugging memory leaks
* :memo: `:memo:` when writing docs
* :penguin: `:penguin:` when fixing something on Linux
* :apple: `:apple:` when fixing something on macOS
* :checkered_flag: `:checkered_flag:` when fixing something on Windows
* :bug: `:bug:` when fixing a bug
* :fire: `:fire:` when removing code or files
* :green_heart: `:green_heart:` when fixing the CI build
* :white_check_mark: `:white_check_mark:` when adding tests
* :lock: `:lock:` when dealing with security
* :arrow_up: `:arrow_up:` when upgrading dependencies
* :arrow_down: `:arrow_down:` when downgrading dependencies
* :shirt: `:shirt:` when removing linter warnings

View File

@@ -1,24 +0,0 @@
FROM electronbuilds/libchromiumcontent:0.0.4
USER root
# Set up HOME directory
ENV HOME=/home
RUN chmod a+rwx /home
# Install node.js
RUN curl -sL https://deb.nodesource.com/setup_8.x | bash -
RUN apt-get update && apt-get install -y nodejs
# Install wget used by crash reporter
RUN apt-get install -y wget
# Install python-dbusmock
RUN apt-get install -y python-dbusmock
# Install libnotify
RUN apt-get install -y libnotify-bin
# Add xvfb init script
ADD tools/xvfb-init.sh /etc/init.d/xvfb
RUN chmod a+x /etc/init.d/xvfb

View File

@@ -1,35 +0,0 @@
FROM multiarch/debian-debootstrap:arm64-jessie
RUN apt-get update && apt-get install -y\
bison \
build-essential \
clang \
curl \
gperf \
libasound2 \
libasound2-dev \
libcap-dev \
libcups2-dev \
libdbus-1-dev \
libgconf-2-4 \
libgconf2-dev \
libgnome-keyring-dev \
libgtk-3-0 \
libgtk-3-dev \
libnotify-bin \
libnotify-dev \
libnss3 \
libnss3-dev \
libx11-xcb-dev \
libxss1 \
libxtst-dev \
libxtst6 \
python-dbusmock \
wget \
xvfb
ADD tools/xvfb-init.sh /etc/init.d/xvfb
RUN chmod a+x /etc/init.d/xvfb
ADD tools/run-electron.sh /run-electron.sh
RUN chmod a+x /run-electron.sh
CMD sh /run-electron.sh

View File

@@ -1,63 +0,0 @@
FROM arm64v8/ubuntu:16.04
RUN groupadd --gid 1000 builduser \
&& useradd --uid 1000 --gid builduser --shell /bin/bash --create-home builduser
RUN groupadd --gid 114 jenkins \
&& useradd --uid 110 --gid jenkins --shell /bin/bash --create-home jenkins
# Set up TEMP directory
ENV TEMP=/tmp
RUN chmod a+rwx /tmp
RUN apt-get update && apt-get install -y\
bison \
build-essential \
clang \
curl \
gperf \
git \
libasound2 \
libasound2-dev \
libcap-dev \
libcups2-dev \
libdbus-1-dev \
libgconf-2-4 \
libgconf2-dev \
libgnome-keyring-dev \
libgtk2.0-0 \
libgtk2.0-dev \
libgtk-3-0 \
libgtk-3-dev \
libnotify-dev \
libnss3 \
libnss3-dev \
libx11-xcb-dev \
libxss1 \
libxtst-dev \
libxtst6 \
lsb-release \
locales \
ninja \
python-setuptools \
python-pip \
python-dbusmock \
wget \
xvfb
# Install node.js
RUN curl -sL https://deb.nodesource.com/setup_8.x | bash -
RUN apt-get update && apt-get install -y nodejs
# Install crcmod
RUN pip install -U crcmod
ADD tools/xvfb-init.sh /etc/init.d/xvfb
RUN chmod a+x /etc/init.d/xvfb
# Install ninja in /usr/local
RUN cd /usr/local && git clone https://github.com/martine/ninja.git -b v1.5.3
RUN cd /usr/local/ninja && ./configure.py --bootstrap
USER builduser
WORKDIR /home/builduser

View File

@@ -1,36 +0,0 @@
FROM multiarch/debian-debootstrap:armhf-jessie
RUN apt-get update && apt-get install -y\
bison \
build-essential \
clang \
curl \
gperf \
libasound2 \
libasound2-dev \
libcap-dev \
libcups2-dev \
libdbus-1-dev \
libgconf-2-4 \
libgconf2-dev \
libgnome-keyring-dev \
libgtk-3-0 \
libgtk-3-dev \
libnotify-bin \
libnotify-dev \
libnss3 \
libnss3-dev \
libx11-xcb-dev \
libxss1 \
libxtst-dev \
libxtst6 \
python-dbusmock \
git \
wget \
xvfb
ADD tools/xvfb-init.sh /etc/init.d/xvfb
RUN chmod a+x /etc/init.d/xvfb
ADD tools/run-electron.sh /run-electron.sh
RUN chmod a+x /run-electron.sh
CMD sh /run-electron.sh

View File

@@ -1,23 +0,0 @@
FROM electronbuilds/libchromiumcontent:0.0.4
USER root
# Install node.js
RUN curl -sL https://deb.nodesource.com/setup_8.x | bash -
RUN apt-get update && apt-get install -y nodejs
# Install wget used by crash reporter
RUN apt-get install -y wget
# Install python-dbusmock
RUN apt-get install -y python-dbusmock
# Install libnotify
RUN apt-get install -y libnotify-bin
# Add xvfb init script
ADD tools/xvfb-init.sh /etc/init.d/xvfb
RUN chmod a+x /etc/init.d/xvfb
USER builduser
WORKDIR /home/builduser

20
Jenkinsfile vendored
View File

@@ -8,12 +8,10 @@ pipeline {
label 'osx'
}
steps {
timeout(60) {
sh 'script/bootstrap.py --target_arch=x64 --dev'
sh 'npm run lint'
sh 'script/build.py -c D'
sh 'script/test.py --ci --rebuild_native_modules'
}
sh 'script/bootstrap.py --target_arch=x64 --dev'
sh 'npm run lint'
sh 'script/build.py -c D'
sh 'script/test.py --ci --rebuild_native_modules'
}
post {
always {
@@ -29,12 +27,10 @@ pipeline {
MAS_BUILD = '1'
}
steps {
timeout(60) {
sh 'script/bootstrap.py --target_arch=x64 --dev'
sh 'npm run lint'
sh 'script/build.py -c D'
sh 'script/test.py --ci --rebuild_native_modules'
}
sh 'script/bootstrap.py --target_arch=x64 --dev'
sh 'npm run lint'
sh 'script/build.py -c D'
sh 'script/test.py --ci --rebuild_native_modules'
}
post {
always {

View File

@@ -1,36 +0,0 @@
pipeline {
agent {
docker {
image 'electronbuilds/arm64v8:0.0.2'
args '--privileged'
}
}
environment {
TARGET_ARCH='arm64'
DISPLAY=':99.0'
MOCHA_TIMEOUT='60000'
}
stages {
stage('Bootstrap') {
steps {
sh 'script/bootstrap.py -v --dev --target_arch=$TARGET_ARCH'
}
}
stage('Build') {
steps {
sh 'script/build.py -c D --ninja-path /usr/local/ninja/ninja'
}
}
stage('Test') {
steps {
sh '/etc/init.d/xvfb start'
sh 'script/test.py --ci'
}
}
}
post {
always {
cleanWs()
}
}
}

View File

@@ -1,4 +1,4 @@
Copyright (c) 2013-2018 GitHub Inc.
Copyright (c) 2013-2017 GitHub Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

View File

@@ -1,27 +1,24 @@
[![Electron Logo](https://electronjs.org/images/electron-logo.svg)](https://electronjs.org)
[![Electron Logo](https://electron.atom.io/images/electron-logo.svg)](https://electron.atom.io/)
[![CircleCI Build Status](https://circleci.com/gh/electron/electron/tree/master.svg?style=shield)](https://circleci.com/gh/electron/electron/tree/master)
[![AppVeyor Build Status](https://windows-ci.electronjs.org/api/projects/status/nilyf07hcef14dvj/branch/master?svg=true)](https://windows-ci.electronjs.org/project/AppVeyor/electron/branch/master)
[![Jenkins Build Status](https://mac-ci.electronjs.org/buildStatus/icon?job=Electron%20org/electron/master)](https://mac-ci.electronjs.org/blue/organizations/jenkins/Electron%20org%2Felectron/activity?branch=master)
[![Travis Build Status](https://travis-ci.org/electron/electron.svg?branch=master)](https://travis-ci.org/electron/electron)
[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/bc56v83355fi3369/branch/master?svg=true)](https://ci.appveyor.com/project/electron-bot/electron/branch/master)
[![devDependency Status](https://david-dm.org/electron/electron/dev-status.svg)](https://david-dm.org/electron/electron?type=dev)
[![Join the Electron Community on Slack](https://atom-slack.herokuapp.com/badge.svg)](https://atom-slack.herokuapp.com/)
[![Join the Electron Community on Slack](http://atom-slack.herokuapp.com/badge.svg)](http://atom-slack.herokuapp.com/)
:memo: Available Translations: 🇨🇳 🇹🇼 🇧🇷 🇪🇸 🇰🇷 🇯🇵 🇷🇺 🇫🇷 🇹🇭 🇳🇱 🇹🇷 🇮🇩 🇺🇦 🇨🇿 🇮🇹.
View these docs in other languages at [electron/electron-i18n](https://github.com/electron/electron-i18n/tree/master/content/).
:memo: Available Translations: [Korean](https://github.com/electron/electron/tree/master/docs-translations/ko-KR/project/README.md) | [Simplified Chinese](https://github.com/electron/electron/tree/master/docs-translations/zh-CN/project/README.md) | [Brazilian Portuguese](https://github.com/electron/electron/tree/master/docs-translations/pt-BR/project/README.md) | [Traditional Chinese](https://github.com/electron/electron/tree/master/docs-translations/zh-TW/project/README.md) | [Spanish](https://github.com/electron/electron/tree/master/docs-translations/es/project/README.md) | [Turkish](https://github.com/electron/electron/tree/master/docs-translations/tr-TR/project/README.md) | [German](https://github.com/electron/electron/tree/master/docs-translations/de-DE/project/README.md)
The Electron framework lets you write cross-platform desktop applications
using JavaScript, HTML and CSS. It is based on [Node.js](https://nodejs.org/) and
[Chromium](https://www.chromium.org) and is used by the [Atom
editor](https://github.com/atom/atom) and many other [apps](https://electronjs.org/apps).
[Chromium](http://www.chromium.org) and is used by the [Atom
editor](https://github.com/atom/atom) and many other [apps](https://electron.atom.io/apps).
Follow [@ElectronJS](https://twitter.com/electronjs) on Twitter for important
announcements.
This project adheres to the Contributor Covenant
This project adheres to the Contributor Covenant
[code of conduct](https://github.com/electron/electron/tree/master/CODE_OF_CONDUCT.md).
By participating, you are expected to uphold this code. Please report unacceptable
behavior to [coc@electronjs.org](mailto:coc@electronjs.org).
behavior to [electron@github.com](mailto:electron@github.com).
## Installation
@@ -35,29 +32,29 @@ npm install electron --save-dev --save-exact
The `--save-exact` flag is recommended as Electron does not follow semantic
versioning. For info on how to manage Electron versions in your apps, see
[Electron versioning](docs/tutorial/electron-versioning.md).
[Electron versioning](https://electron.atom.io/docs/tutorial/electron-versioning/).
For more installation options and troubleshooting tips, see
[installation](docs/tutorial/installation.md).
[installation](https://electron.atom.io/docs/tutorial/installation/).
## Quick start
## Quick Start
Clone and run the
Clone and run the
[electron/electron-quick-start](https://github.com/electron/electron-quick-start)
repository to see a minimal Electron app in action:
```sh
```
git clone https://github.com/electron/electron-quick-start
cd electron-quick-start
npm install
npm start
```
## Resources for learning Electron
## Resources for Learning Electron
- [electronjs.org/docs](https://electronjs.org/docs) - all of Electron's documentation
- [electron.atom.io/docs](http://electron.atom.io/docs) - all of Electron's documentation
- [electron/electron-quick-start](https://github.com/electron/electron-quick-start) - a very basic starter Electron app
- [electronjs.org/community#boilerplates](https://electronjs.org/community#boilerplates) - sample starter apps created by the community
- [electron.atom.io/community/#boilerplates](http://electron.atom.io/community/#boilerplates) - sample starter apps created by the community
- [electron/simple-samples](https://github.com/electron/simple-samples) - small applications with ideas for taking them further
- [electron/electron-api-demos](https://github.com/electron/electron-api-demos) - an Electron app that teaches you how to use Electron
- [hokein/electron-sample-apps](https://github.com/hokein/electron-sample-apps) - small demo apps for the various Electron APIs
@@ -85,12 +82,36 @@ const child = proc.spawn(electron)
## Documentation Translations
Find documentation translations in [electron/electron-i18n](https://github.com/electron/electron-i18n).
- [Brazilian Portuguese](https://github.com/electron/electron/tree/master/docs-translations/pt-BR)
- [Korean](https://github.com/electron/electron/tree/master/docs-translations/ko-KR)
- [Japanese](https://github.com/electron/electron/tree/master/docs-translations/jp)
- [Spanish](https://github.com/electron/electron/tree/master/docs-translations/es)
- [Simplified Chinese](https://github.com/electron/electron/tree/master/docs-translations/zh-CN)
- [Traditional Chinese](https://github.com/electron/electron/tree/master/docs-translations/zh-TW)
- [Turkish](https://github.com/electron/electron/tree/master/docs-translations/tr-TR)
- [Thai](https://github.com/electron/electron/tree/master/docs-translations/th-TH)
- [Ukrainian](https://github.com/electron/electron/tree/master/docs-translations/uk-UA)
- [Russian](https://github.com/electron/electron/tree/master/docs-translations/ru-RU)
- [French](https://github.com/electron/electron/tree/master/docs-translations/fr-FR)
- [Indonesian](https://github.com/electron/electron/tree/master/docs-translations/id)
## Community
Info on reporting bugs, getting help, finding third-party tools and sample apps,
and more can be found in the [support document](docs/tutorial/support.md#finding-support).
You can ask questions and interact with the community in the following
locations:
- [`electron`](http://discuss.atom.io/c/electron) category on the Atom
forums
- `#atom-shell` channel on Freenode
- [`Atom`](http://atom-slack.herokuapp.com/) channel on Slack
- [`electron-ru`](https://telegram.me/electron_ru) *(Russian)*
- [`electron-br`](https://electron-br.slack.com) *(Brazilian Portuguese)*
- [`electron-kr`](http://www.meetup.com/electron-kr/) *(Korean)*
- [`electron-jp`](https://electron-jp.slack.com) *(Japanese)*
- [`electron-tr`](http://electron-tr.herokuapp.com) *(Turkish)*
- [`electron-id`](https://electron-id.slack.com) *(Indonesia)*
Check out [awesome-electron](https://github.com/sindresorhus/awesome-electron)
for a community maintained list of useful example apps, tools and resources.
## License

View File

@@ -2,11 +2,8 @@
The Electron team and community take security bugs in Electron seriously. We appreciate your efforts to responsibly disclose your findings, and will make every effort to acknowledge your contributions.
To report a security issue, email [security@electronjs.org](mailto:security@electronjs.org) and include the word "SECURITY" in the subject line.
To report a security issue, email [electron@github.com](mailto:electron@github.com) and include the word "SECURITY" in the subject line.
The Electron team will send a response indicating the next steps in handling your report. After the initial reply to your report, the security team will keep you informed of the progress towards a fix and full announcement, and may ask for additional information or guidance.
Report security bugs in third-party modules to the person or team maintaining the module. You can also report a vulnerability through the [Node Security Project](https://nodesecurity.io/report).
## Learning More About Security
To learn more about securing an Electron application, please see the [security tutorial](docs/tutorial/security.md).

View File

@@ -1,58 +0,0 @@
build_cloud: electron-16
image: electron-16-vs2015
build_script:
- ps: >-
if(($env:APPVEYOR_PULL_REQUEST_HEAD_REPO_NAME -split "/")[0] -eq ($env:APPVEYOR_REPO_NAME -split "/")[0]) {
Write-warning "Skipping PR build for branch"; Exit-AppveyorBuild
} else {
Add-Path "$env:ProgramFiles (x86)\Windows Kits\10\Debuggers\x64"
$env:path = "$env:ProgramFiles (x86)\Windows Kits\10\Debuggers\x64;$env:path"
if($env:APPVEYOR_SCHEDULED_BUILD -eq 'True') {
$env:RUN_RELEASE_BUILD = "1"
}
$Message = (git log --format=%B -n 1 HEAD) | Out-String
if ((Test-Path Env:\RUN_RELEASE_BUILD)) {
$env:ELECTRON_RELEASE = '1'
Write-Output "release build triggered from api"
}
if ((Test-Path Env:\ELECTRON_RELEASE)) {
Write-Output "Running release build"
python script\bootstrap.py --target_arch=$env:TARGET_ARCH
python script\build.py -c R
python script\create-dist.py
} else {
Write-Output "Running debug build"
python script\bootstrap.py --target_arch=$env:TARGET_ARCH --dev
python script\build.py -c D
}
if ($? -ne 'True') {
throw "Build failed with exit code $?"
} else {
"Build succeeded."
}
Push-AppveyorArtifact out
}
test_script:
- ps: >-
if (Test-Path Env:\ELECTRON_RELEASE) {
Write-Output "Skipping tests for release build"
} else {
Write-Output "Running tests for debug build"
python script\test.py --ci --rebuild_native_modules
if ($LASTEXITCODE -ne '0') {
throw "Tests failed with exit code $LASTEXITCODE"
} else {
Write-Output "Tests succeeded."
}
python script\verify-ffmpeg.py
if ($LASTEXITCODE -ne '0') {
throw "Verify ffmpeg failed with exit code $LASTEXITCODE"
} else {
"Verify ffmpeg succeeded."
}
}
artifacts:
- path: test-results.xml
name: test-results.xml
deploy_script:
- ps: "if (Test-Path Env:\\ELECTRON_RELEASE) {\n if (Test-Path Env:\\RUN_RELEASE_BUILD) {\n Write-Output \"Uploading Electron release distribution to s3\"\n & python script\\upload.py --upload_to_s3\n } else {\n Write-Output \"Uploading Electron release distribution to github releases\"\n & python script\\upload.py\n if (Test-Path Env:\\AUTO_RELEASE) {\n node script\\release.js --validateRelease --automaticRelease\n if ($? -eq 'True') {\n echo 'Release is ready to go; now running release'\n node script\\release.js --automaticRelease\n if ($? -eq 'True') { \n echo 'Release successful, now publishing to npm' \n $npmfile = \"$HOME\\.npmrc\"\n \"//registry.npmjs.org/:_authToken=$env:ELECTRON_NPM_TOKEN\" > $npmfile\n npm run publish-to-npm\n }\n } else {\n echo 'Release is not complete, skipping publish for now.'\n }\n }\n }\n} else {\n Write-Output \"Skipping upload distribution because build is not for release\"\n}"

25
appveyor.yml Normal file
View File

@@ -0,0 +1,25 @@
# appveyor file
# http://www.appveyor.com/docs/appveyor-yml
version: "{build}"
os: Visual Studio 2015
init:
- git config --global core.autocrlf input
platform:
- x86
- x64
install:
- cmd: SET PATH=C:\Program Files (x86)\MSBuild\14.0\bin\;%PATH%
- cmd: SET PATH=C:\python27;%PATH%
- cmd: python script/cibuild
branches:
only:
- master
# disable build and test phases
build: off
test: off

View File

@@ -1,11 +0,0 @@
#import <Cocoa/Cocoa.h>
int main(int argc, char* argv[]) {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSArray* pathComponents = [[[NSBundle mainBundle] bundlePath] pathComponents];
pathComponents = [pathComponents subarrayWithRange:NSMakeRange(0, [pathComponents count] - 4)];
NSString* path = [NSString pathWithComponents:pathComponents];
[[NSWorkspace sharedWorkspace] launchApplication:path];
[pool drain];
return 0;
}

View File

@@ -10,7 +10,6 @@
#if defined(OS_WIN)
#include <windows.h> // windows.h must be included first
#include <atlbase.h> // ensures that ATL statics like `_AtlWinModule` are initialized (it's an issue in static debug build)
#include <shellapi.h>
#include <shellscalingapi.h>
#include <tchar.h>
@@ -38,9 +37,7 @@
namespace {
#ifdef ENABLE_RUN_AS_NODE
const auto kRunAsNode = "ELECTRON_RUN_AS_NODE";
#endif
const char* kRunAsNode = "ELECTRON_RUN_AS_NODE";
bool IsEnvSet(const char* name) {
#if defined(OS_WIN)
@@ -91,11 +88,7 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
}
#endif
#ifdef ENABLE_RUN_AS_NODE
bool run_as_node = IsEnvSet(kRunAsNode);
#else
bool run_as_node = false;
#endif
// Make sure the output is printed to console.
if (run_as_node || !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE"))
@@ -120,7 +113,6 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
});
#endif
#ifdef ENABLE_RUN_AS_NODE
if (run_as_node) {
std::vector<char*> argv(arguments.argc);
std::transform(
@@ -132,10 +124,7 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
auto ret = atom::NodeMain(argv.size(), argv.data());
std::for_each(argv.begin(), argv.end(), free);
return ret;
}
#endif
if (IsEnvSet("ELECTRON_INTERNAL_CRASH_SERVICE")) {
} else if (IsEnvSet("ELECTRON_INTERNAL_CRASH_SERVICE")) {
return crash_service::Main(cmd);
}
@@ -156,13 +145,11 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
#elif defined(OS_LINUX) // defined(OS_WIN)
int main(int argc, char* argv[]) {
#ifdef ENABLE_RUN_AS_NODE
if (IsEnvSet(kRunAsNode)) {
base::i18n::InitializeICU();
base::AtExitManager atexit_manager;
return atom::NodeMain(argc, argv);
}
#endif
atom::AtomMainDelegate delegate;
content::ContentMainParams params(&delegate);
@@ -175,11 +162,9 @@ int main(int argc, char* argv[]) {
#else // defined(OS_LINUX)
int main(int argc, char* argv[]) {
#ifdef ENABLE_RUN_AS_NODE
if (IsEnvSet(kRunAsNode)) {
return AtomInitializeICUandStartNode(argc, argv);
}
#endif
return AtomMain(argc, argv);
}

View File

@@ -21,18 +21,9 @@
#include "base/logging.h"
#include "chrome/common/chrome_paths.h"
#include "content/public/common/content_switches.h"
#include "ipc/ipc_features.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#if BUILDFLAG(IPC_MESSAGE_LOG_ENABLED)
#define IPC_MESSAGE_MACROS_LOG_ENABLED
#include "content/public/common/content_ipc_logging.h"
#define IPC_LOG_TABLE_ADD_ENTRY(msg_id, logger) \
content::RegisterIPCLogger(msg_id, logger)
#include "atom/common/common_message_generator.h"
#endif
namespace atom {
namespace {
@@ -95,10 +86,9 @@ bool AtomMainDelegate::BasicStartupComplete(int* exit_code) {
logging::SetLogItems(true, false, true, false);
// Enable convient stack printing.
#if defined(DEBUG) && defined(OS_LINUX)
bool enable_stack_dumping = true;
#else
bool enable_stack_dumping = env->HasVar("ELECTRON_ENABLE_STACK_DUMPING");
#if defined(DEBUG) && defined(OS_LINUX)
enable_stack_dumping = true;
#endif
if (enable_stack_dumping)
base::debug::EnableInProcessStackDumping();

View File

@@ -44,6 +44,7 @@ class AtomMainDelegate : public brightray::MainDelegate {
void SetUpBundleOverrides();
#endif
brightray::ContentClient content_client_;
std::unique_ptr<content::ContentBrowserClient> browser_client_;
std::unique_ptr<content::ContentRendererClient> renderer_client_;
std::unique_ptr<content::ContentUtilityClient> utility_client_;

View File

@@ -2,11 +2,10 @@
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/app/command_line_args.h"
#include <algorithm>
#include <string>
#include "atom/app/command_line_args.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/common/content_switches.h"
@@ -38,35 +37,18 @@ bool IsUrlArg(const base::CommandLine::CharType* arg) {
return false;
}
/*
* The blacklist of command line switches, must be sorted.
* Update the list by pasting the following command into bash
* in libchromiumcontent/src/:
const char* blacklist[] = {
// node
"inspect",
"inspect-brk",
(find ./ \( -name "*switches.cc" -o -name "*switch_list.h" \) | \
xargs grep -P --no-filename '"\S+"[);]$' | \
perl -pe 's|^.*?"(\S+)"[);]$| "$1",|'; \
echo ' "inspect",'; \
echo ' "inspect-brk",') | \
LANG="C" sort | \
uniq > blacklist-switches.txt
*/
const char* kBlacklist[] = {
"/prefetch:1",
"/prefetch:2",
"/prefetch:3",
"/prefetch:4",
"/prefetch:5",
"/prefetch:6",
"/prefetch:8",
"0",
// chromium switches:
// find ./ -name "*switches.cc" \
// | xargs grep -P --no-filename "\"\S+\";" \
// | perl -pe 's|^.*?"(\S+)";| "$1",|' \
// | sort | uniq
"?",
"BlacklistOnly",
"ChromeOSMemoryPressureHandling",
"Disabled",
"OnlineCheckOnly",
"SafeSites",
"0",
"accept-resource-provider",
"account-consistency",
"adaboost",
@@ -75,7 +57,7 @@ const char* kBlacklist[] = {
"aggressive",
"aggressive-cache-discard",
"aggressive-tab-discard",
"all-toolchains",
"all",
"allarticles",
"allow-cross-origin-auth-prompt",
"allow-external-pages",
@@ -96,6 +78,7 @@ const char* kBlacklist[] = {
"allow-running-insecure-content",
"allow-sandbox-debugging",
"allow-silent-push",
"all-toolchains",
"alsa-check-close-timeout",
"alsa-enable-upsampling",
"alsa-fixed-output-sample-rate",
@@ -113,8 +96,9 @@ const char* kBlacklist[] = {
"alternative",
"always-authorize-plugins",
"always-on",
"always-use-complex-text",
"alwaystrue",
"always-use-complex-text",
"amd-switchable",
"android-fonts-path",
"android-stderr-port",
"android-stdin-port",
@@ -123,18 +107,18 @@ const char* kBlacklist[] = {
"app",
"app-auto-launched",
"app-id",
"apple",
"app-mode-auth-code",
"app-mode-oauth-token",
"app-mode-oem-manifest",
"apps-gallery-download-url",
"apps-gallery-update-url",
"apps-gallery-url",
"app-shell-allow-roaming",
"app-shell-host-window-size",
"app-shell-preferred-network",
"app-shell-refresh-token",
"app-shell-user",
"apple",
"apps-gallery-download-url",
"apps-gallery-update-url",
"apps-gallery-url",
"apps-keep-chrome-alive-in-tests",
"arc-availability",
"arc-available",
@@ -142,12 +126,11 @@ const char* kBlacklist[] = {
"arc-transition-migration-required",
"args",
"artifacts-dir",
"ash-animate-from-boot-splash-screen",
"ash-constrain-pointer-to-root",
"ash-copy-host-background-at-boot",
"ash-debug-shortcuts",
"ash-dev-shortcuts",
"ash-disable-smooth-screen-rotation",
"ash-disable-tablet-autohide-titlebars",
"ash-disable-touch-exploration-mode",
"ash-enable-magnifier-key-scroller",
"ash-enable-mirrored-screen",
@@ -172,10 +155,12 @@ const char* kBlacklist[] = {
"auth-spnego-account-type",
"auto",
"auto-open-devtools-for-tabs",
"auto-select-desktop-capture-source",
"autoplay-policy",
"auto-select-desktop-capture-source",
"blink-settings",
"bootstrap",
"browser",
"browser-startup-dialog",
"browser-subprocess-path",
"browser-test",
"bwsi",
@@ -193,6 +178,7 @@ const char* kBlacklist[] = {
"child-wallpaper-large",
"child-wallpaper-small",
"chrome-home-swipe-logic",
"ChromeOSMemoryPressureHandling",
"cipher-suite-blacklist",
"clamshell",
"class",
@@ -216,21 +202,21 @@ const char* kBlacklist[] = {
"crash-dumps-dir",
"crash-on-failure",
"crash-on-hang-threads",
"crashpad-handler",
"crash-server-url",
"crash-test",
"crashpad-handler",
"create-browser-on-startup-for-tests",
"create-default-gl-context",
"cros-gaia-api-v1",
"crosh-command",
"cros-region",
"cros-regions-mode",
"crosh-command",
"cryptauth-http-host",
"custom-devtools-frontend",
"custom-launcher-page",
"custom_summary",
"d3d11",
"d3d9",
"d3d-support",
"daemon",
"dark_muted",
"dark_vibrant",
@@ -254,7 +240,6 @@ const char* kBlacklist[] = {
"default-wallpaper-is-oem",
"default-wallpaper-large",
"default-wallpaper-small",
"delay-reload-stop-button-change",
"demo",
"derelict-detection-timeout",
"derelict-idle-timeout",
@@ -268,6 +253,7 @@ const char* kBlacklist[] = {
"diagnostics-format",
"diagnostics-recovery",
"dice",
"dice_fix_auth_errors",
"disable",
"disable-2d-canvas-clip-aa",
"disable-2d-canvas-image-chromium",
@@ -276,20 +262,19 @@ const char* kBlacklist[] = {
"disable-accelerated-jpeg-decoding",
"disable-accelerated-mjpeg-decode",
"disable-accelerated-video-decode",
"disable-appcontainer",
"disable-app-info-dialog-mac",
"disable-app-list-dismiss-on-blur",
"disable-app-window-cycling",
"disable-appcontainer",
"disable-arc-data-wipe",
"disable-arc-opt-in-verification",
"disable-audio-support-for-desktop-share",
"disable-avfoundation-overlays",
"disable-backgrounding-occluded-windows",
"disable-background-networking",
"disable-background-timer-throttling",
"disable-backgrounding-occluded-windows",
"disable-backing-store-limit",
"disable-blink-features",
"disable-bookmark-reordering",
"disable-boot-animation",
"disable-breakpad",
"disable-browser-task-scheduler",
@@ -306,6 +291,7 @@ const char* kBlacklist[] = {
"disable-component-update",
"disable-composited-antialiasing",
"disable-contextual-search",
"disabled",
"disable-d3d11",
"disable-databases",
"disable-datasaver-prompt",
@@ -317,9 +303,9 @@ const char* kBlacklist[] = {
"disable-direct-composition",
"disable-direct-composition-layers",
"disable-directwrite-for-ui",
"disable-display-color-calibration",
"disable-display-list-2d-canvas",
"disable-distance-field-text",
"disabled-new-style-notification",
"disable-domain-blocking-for-3d-apis",
"disable-domain-reliability",
"disable-drive-search-in-app-launcher",
@@ -332,7 +318,6 @@ const char* kBlacklist[] = {
"disable-extensions-except",
"disable-extensions-file-access-check",
"disable-extensions-http-throttling",
"disable-fast-web-scroll-view-insets",
"disable-features",
"disable-field-trial-config",
"disable-file-manager-touch-mode",
@@ -367,14 +352,11 @@ const char* kBlacklist[] = {
"disable-histogram-customizer",
"disable-hosted-app-shim-creation",
"disable-hosted-apps-in-windows",
"disable-http2",
"disable-in-process-stack-traces",
"disable-infobars",
"disable-in-process-stack-traces",
"disable-input-ime-api",
"disable-input-view",
"disable-ios-password-generation",
"disable-ios-password-suggestions",
"disable-ios-physical-web",
"disable-javascript-harmony-shipping",
"disable-kill-after-bad-ipc",
"disable-lcd-text",
@@ -388,10 +370,9 @@ const char* kBlacklist[] = {
"disable-low-end-device-mode",
"disable-low-latency-dxva",
"disable-low-res-tiling",
"disable-lru-snapshot-cache",
"disable-machine-cert-request",
"disable-mac-overlays",
"disable-mac-views-native-app-windows",
"disable-machine-cert-request",
"disable-main-frame-before-activation",
"disable-md-error-screen",
"disable-md-oobe",
@@ -405,7 +386,6 @@ const char* kBlacklist[] = {
"disable-namespace-sandbox",
"disable-native-gpu-memory-buffers",
"disable-network-portal-notification",
"disable-new-channel-switcher-ui",
"disable-new-korean-ime",
"disable-new-virtual-keyboard-behavior",
"disable-new-zip-unpacker",
@@ -427,6 +407,7 @@ const char* kBlacklist[] = {
"disable-pepper-3d-image-chromium",
"disable-permission-action-reporting",
"disable-permissions-api",
"disable-per-user-timezone",
"disable-physical-keyboard-autocorrect",
"disable-pinch",
"disable-pnacl-crash-throttling",
@@ -438,15 +419,12 @@ const char* kBlacklist[] = {
"disable-proximity-auth-bluetooth-low-energy-discovery",
"disable-pull-to-refresh-effect",
"disable-push-api-background-mode",
"disable-quic",
"disable-reading-from-canvas",
"disable-remote-core-animation",
"disable-remote-fonts",
"disable-remote-playback-api",
"disable-renderer-accessibility",
"disable-renderer-backgrounding",
"disable-renderer-priority-management",
"disable-request-mobile-site",
"disable-resize-lock",
"disable-rgba-4444-textures",
"disable-rollback-option",
@@ -454,7 +432,6 @@ const char* kBlacklist[] = {
"disable-screen-orientation-lock",
"disable-search-geolocation-disclosure",
"disable-seccomp-filter-sandbox",
"disable-settings-window",
"disable-setuid-sandbox",
"disable-shader-name-hashing",
"disable-shared-workers",
@@ -462,22 +439,23 @@ const char* kBlacklist[] = {
"disable-signin-scoped-device-id",
"disable-single-click-autofill",
"disable-skia-runtime-opts",
"disable-slim-navigation-manager",
"disable-slimming-paint-invalidation",
"disable-slim-navigation-manager",
"disable-smooth-scrolling",
"disable-software-rasterizer",
"disable-speech-api",
"disable-suggestions-ui",
"disable-surface-references",
"disable-sync",
"disable-sync-app-list",
"disable-sync-types",
"disable-system-timezone-automatic-detection",
"disable-tab-for-desktop-share",
"disable-tab-strip-autoscroll-new-tabs",
"disable-third-party-keyboard-workaround",
"disable-threaded-animation",
"disable-threaded-compositing",
"disable-threaded-scrolling",
"disable-timeouts-for-profiling",
"disable-touch-adjustment",
"disable-touch-drag-drop",
"disable-translate-new-ux",
@@ -488,20 +466,18 @@ const char* kBlacklist[] = {
"disable-voice-input",
"disable-volume-adjust-sound",
"disable-wake-on-wifi",
"disable-web-notification-custom-layouts",
"disable-web-security",
"disable-webgl",
"disable-webgl-image-chromium",
"disable-web-notification-custom-layouts",
"disable-webrtc-encryption",
"disable-webrtc-hw-decoding",
"disable-webrtc-hw-encoding",
"disable-web-security",
"disable-win32k-lockdown",
"disable-xss-auditor",
"disable-zero-browsers-open-for-tests",
"disable-zero-copy",
"disable-zero-copy-dxgi-video",
"disabled",
"disabled-new-style-notification",
"disallow-non-exact-resource-reuse",
"disk-cache-dir",
"disk-cache-size",
@@ -532,22 +508,24 @@ const char* kBlacklist[] = {
"enable-adaptive-selection-handle-orientation",
"enable-aggressive-domstorage-flushing",
"enable-android-wallpapers-app",
"enable-appcontainer",
"enable-app-info-dialog-mac",
"enable-app-list",
"enable-app-window-cycling",
"enable-appcontainer",
"enable-arc",
"enable-arc-oobe-optin",
"enable-async-event-targeting",
"enable-audio-debug-recordings-from-extension",
"enable-audio-focus",
"enable-automation",
"enable-background-fetch-persistence",
"enable-benchmarking",
"enable-ble-advertising-in-apps",
"enable-blink-features",
"enable-bookmark-reordering",
"enable-bookmark-undo",
"enable-browser-side-navigation",
"enable-browser-task-scheduler",
"enable-cast-receiver",
"enable-checker-imaging",
"enable-chromevox-arc-support",
"enable-clear-browsing-data-counters",
@@ -558,6 +536,9 @@ const char* kBlacklist[] = {
"enable-crash-reporter",
"enable-crash-reporter-for-testing",
"enable-crx-hash-check",
"enabled",
"enabled-2g",
"enabled-3g",
"enable-data-reduction-proxy-bypass-warning",
"enable-data-reduction-proxy-force-pingback",
"enable-data-reduction-proxy-lite-page",
@@ -569,10 +550,12 @@ const char* kBlacklist[] = {
"enable-display-list-2d-canvas",
"enable-distance-field-text",
"enable-distillability-service",
"enable-dom-distiller",
"enabled-new-style-notification",
"enable-domain-reliability",
"enable-dom-distiller",
"enable-drive-search-in-app-launcher",
"enable-drm-atomic",
"enabled-slow2g",
"enable-embedded-extension-options",
"enable-encryption-migration",
"enable-encryption-selection",
@@ -584,11 +567,11 @@ const char* kBlacklist[] = {
"enable-experimental-fullscreen-exit-ui",
"enable-experimental-input-view-features",
"enable-experimental-web-platform-features",
"enable-extension-activity-log-testing",
"enable-extension-activity-logging",
"enable-extension-activity-log-testing",
"enable-extension-assets-sharing",
"enable-external-drive-rename",
"enable-fast-unload",
"enable-fast-web-scroll-view-insets",
"enable-features",
"enable-file-manager-touch-mode",
"enable-first-run-ui-transitions",
@@ -611,7 +594,6 @@ const char* kBlacklist[] = {
"enable-gpu-service-tracing",
"enable-hardware-overlays",
"enable-harfbuzz-rendertext",
"enable-hdr",
"enable-heap-profiling",
"enable-hosted-app-quit-notification",
"enable-hosted-apps-in-windows",
@@ -619,10 +601,9 @@ const char* kBlacklist[] = {
"enable-hung-renderer-infobar",
"enable-inband-text-tracks",
"enable-input-ime-api",
"enable-instant-tethering",
"enable-internal-media-session",
"enable-ios-handoff-to-other-devices",
"enable-ios-password-generation",
"enable-ios-physical-web",
"enable-layer-lists",
"enable-lcd-text",
"enable-leak-detection",
@@ -632,11 +613,9 @@ const char* kBlacklist[] = {
"enable-longpress-drag-selection",
"enable-low-end-device-mode",
"enable-low-res-tiling",
"enable-lru-snapshot-cache",
"enable-mac-views-native-app-windows",
"enable-main-frame-before-activation",
"enable-md-feedback",
"enable-md-policy-page",
"enable-media-suspend",
"enable-merge-key-char-events",
"enable-message-center-always-scroll-up-upon-notification-removal",
@@ -657,6 +636,7 @@ const char* kBlacklist[] = {
"enable-offer-upload-credit-cards",
"enable-offline-auto-reload",
"enable-offline-auto-reload-visible-only",
"enable-oop-rasterization",
"enable-osk-overscroll",
"enable-override-bookmarks-ui",
"enable-partial-raster",
@@ -666,6 +646,7 @@ const char* kBlacklist[] = {
"enable-physical-keyboard-autocorrect",
"enable-picture-in-picture",
"enable-pinch",
"enable-pixel-canvas-recording",
"enable-pixel-output-in-tests",
"enable-plugin-placeholder-testing",
"enable-potentially-annoying-security-features",
@@ -677,8 +658,6 @@ const char* kBlacklist[] = {
"enable-profile-shortcut-manager",
"enable-profiling",
"enable-push-api-background-mode",
"enable-quic",
"enable-reader-mode-toolbar-icon",
"enable-refresh-token-annotation-request",
"enable-request-tablet-site",
"enable-rgba-4444-textures",
@@ -688,15 +667,14 @@ const char* kBlacklist[] = {
"enable-scripts-require-action",
"enable-scroll-prediction",
"enable-service-manager-tracing",
"enable-settings-window",
"enable-sgi-video-sync",
"enable-signin-promo",
"enable-single-click-autofill",
"enable-site-settings",
"enable-skia-benchmarking",
"enable-slim-navigation-manager",
"enable-slimming-paint-invalidation",
"enable-slimming-paint-v2",
"enable-slim-navigation-manager",
"enable-smooth-scrolling",
"enable-spatial-navigation",
"enable-spdy-proxy-auth",
@@ -730,10 +708,9 @@ const char* kBlacklist[] = {
"enable-tracing-output",
"enable-translate-new-ux",
"enable-ui-devtools",
"enable-use-zoom-for-dsf",
"enable-user-controlled-alternate-protocol-ports",
"enable-user-metrics",
"enable-usermedia-screen-capturing",
"enable-user-metrics",
"enable-use-zoom-for-dsf",
"enable-video-player-chromecast-support",
"enable-viewport",
"enable-virtual-keyboard",
@@ -741,30 +718,26 @@ const char* kBlacklist[] = {
"enable-vtune-support",
"enable-vulkan",
"enable-wayland-server",
"enable-web-notification-custom-layouts",
"enable-webfonts-intervention-trigger",
"enable-webfonts-intervention-v2",
"enable-webgl-draft-extensions",
"enable-webgl-image-chromium",
"enable-web-notification-custom-layouts",
"enable-webrtc-event-logging-from-extension",
"enable-webrtc-srtp-aes-gcm",
"enable-webrtc-srtp-encrypted-headers",
"enable-webrtc-stun-origin",
"enable-webview-finch",
"enable-webview-variations",
"enable-webvr",
"enable-wifi-credential-sync",
"enable-win7-webrtc-hw-h264-decoding",
"enable-zero-copy",
"enable-zip-archiver-on-file-manager",
"enabled",
"enabled-2g",
"enabled-3g",
"enabled-new-style-notification",
"enabled-slow2g",
"encode-binary",
"enforce",
"enforce-gl-minimums",
"enforce-webrtc-ip-permission-check",
"enforce_strict",
"enforce-webrtc-ip-permission-check",
"enterprise-disable-arc",
"enterprise-enable-forced-re-enrollment",
"enterprise-enable-license-type-selection",
@@ -772,6 +745,8 @@ const char* kBlacklist[] = {
"enterprise-enrollment-initial-modulus",
"enterprise-enrollment-modulus-limit",
"error-console",
"evaluate_capability",
"evaluate-type",
"experiment",
"explicitly-allowed-ports",
"expose-internals-for-testing",
@@ -799,8 +774,8 @@ const char* kBlacklist[] = {
"force-clamshell-power-button",
"force-color-profile",
"force-desktop-ios-promotion",
"force-dev-mode-highlighting",
"force-device-scale-factor",
"force-dev-mode-highlighting",
"force-display-list-2d-canvas",
"force-effective-connection-type",
"force-enable-metrics-reporting",
@@ -819,6 +794,7 @@ const char* kBlacklist[] = {
"force-overlay-fullscreen-video",
"force-password-reauth",
"force-pnacl-subzero",
"force-presentation-receiver-for-testing",
"force-renderer-accessibility",
"force-show-update-menu-badge",
"force-show-update-menu-item",
@@ -838,8 +814,8 @@ const char* kBlacklist[] = {
"generate-accessibility-test-expectations",
"gl",
"gl-composited-overlay-candidate-quad-border",
"gl-shader-interm-output",
"gles",
"gl-shader-interm-output",
"golden-screenshots-dir",
"google-apis-url",
"google-base-url",
@@ -848,7 +824,6 @@ const char* kBlacklist[] = {
"gpu-active-device-id",
"gpu-active-vendor-id",
"gpu-device-id",
"gpu-driver-bug-workarounds",
"gpu-driver-date",
"gpu-driver-vendor",
"gpu-driver-version",
@@ -874,6 +849,7 @@ const char* kBlacklist[] = {
"gpu-testing-secondary-vendor-ids",
"gpu-testing-vendor-id",
"gpu-vendor-id",
"graphics-buffer-count",
"guest-wallpaper-large",
"guest-wallpaper-small",
"h",
@@ -891,7 +867,6 @@ const char* kBlacklist[] = {
"host",
"host-pairing-oobe",
"host-resolver-rules",
"host-rules",
"icu-data-dir",
"ignore-autocomplete-off-autofill",
"ignore-autoplay-restrictions",
@@ -900,11 +875,9 @@ const char* kBlacklist[] = {
"ignore-gpu-blacklist",
"ignore-urlfetcher-cert-requests",
"ignore-user-profile-mapping-for-tests",
"in-process-gpu",
"incognito",
"in-process-gpu",
"input",
"inspect",
"inspect-brk",
"install-chrome-app",
"install-supervised-user-whitelists",
"instant-process",
@@ -912,9 +885,9 @@ const char* kBlacklist[] = {
"ipc-connection-timeout",
"ipc-dump-directory",
"ipc-fuzzer-testcase",
"is-running-in-mash",
"isolate-origins",
"isolate-sites-for-testing",
"is-running-in-mash",
"javascript-harmony",
"js-flags",
"keep-alive-for-test",
@@ -934,11 +907,15 @@ const char* kBlacklist[] = {
"local-ntp-reload",
"local-sync-backend-dir",
"log-gpu-control-list-decisions",
"log-level",
"log-net-log",
"login-manager",
"login-profile",
"login-user",
"log-level",
"log-net-log",
"loopback-i2s-bits",
"loopback-i2s-bus-name",
"loopback-i2s-channels",
"loopback-i2s-rate-hz",
"lso-url",
"ltr",
"main-frame-resizes-are-orientation-changes",
@@ -946,9 +923,9 @@ const char* kBlacklist[] = {
"make-default-browser",
"managed-user-id",
"managed-user-sync-token",
"mark-non-secure-as",
"markdown",
"market-url-for-testing",
"mark-non-secure-as",
"mash",
"material",
"material-design-ink-drop-animation-speed",
@@ -958,13 +935,13 @@ const char* kBlacklist[] = {
"max-untiled-layer-height",
"max-untiled-layer-width",
"media-cache-size",
"mem-pressure-system-reserved-kb",
"memlog",
"memlog-pipe",
"memory-pressure-off",
"memory-pressure-thresholds",
"memory-pressure-thresholds-mb",
"mem-pressure-system-reserved-kb",
"message-center-changes-while-open",
"method",
"metrics-client-id",
"metrics-recording-only",
"mhtml-generator-option",
@@ -988,39 +965,38 @@ const char* kBlacklist[] = {
"native",
"native-crx-bindings",
"need-arc-migration-policy-check",
"net-log-capture-mode",
"netifs-to-ignore",
"net-log-capture-mode",
"network-country-iso",
"network-settings-config",
"new-window",
"nocolor",
"no-default-browser-check",
"noerrdialogs",
"no-experiments",
"no-first-run",
"no-managed-user-acknowledgment-check",
"none",
"no-network-profile-warning",
"no-pings",
"no-proxy-server",
"no-referrers",
"no-sandbox",
"no-service-autorun",
"no-session-id",
"no-startup-window",
"no-user-gesture-required",
"no-wifi",
"no-zygote",
"nocolor",
"noerrdialogs",
"non-material",
"non-secure",
"non-secure-after-editing",
"non-secure-while-incognito",
"non-secure-while-incognito-or-editing",
"none",
"no-pings",
"no-proxy-server",
"no-referrers",
"normal_muted",
"normal_vibrant",
"no-sandbox",
"no-service-autorun",
"no-session-id",
"no-startup-window",
"note-taking-app-ids",
"no-user-gesture-required",
"no-wifi",
"no-zygote",
"ntp-snippets-add-incomplete",
"ntp-switch-to-existing-tab",
"null",
"num-raster-threads",
"oauth2-client-id",
@@ -1034,11 +1010,10 @@ const char* kBlacklist[] = {
"oobe-timer-interval",
"open-ash",
"opengraph",
"origin-to-force-quic-on",
"original-process-start-time",
"origin-trial-disabled-features",
"origin-trial-disabled-tokens",
"origin-trial-public-key",
"original-process-start-time",
"osmesa",
"output",
"override",
@@ -1067,7 +1042,13 @@ const char* kBlacklist[] = {
"ppapi-plugin-launcher",
"ppapi-startup-dialog",
"ppapi-subpixel-rendering-setting",
"prerender-from-omnibox",
"/prefetch:1",
"/prefetch:2",
"/prefetch:3",
"/prefetch:4",
"/prefetch:5",
"/prefetch:6",
"/prefetch:8",
"previous-app",
"primary",
"print-to-pdf",
@@ -1077,7 +1058,6 @@ const char* kBlacklist[] = {
"product-version",
"profile-directory",
"profiler-timing",
"profiling",
"profiling-at-start",
"profiling-file",
"profiling-flush",
@@ -1088,17 +1068,15 @@ const char* kBlacklist[] = {
"proxy-bypass-list",
"proxy-pac-url",
"proxy-server",
"pull-to-refresh",
"q",
"quic-connection-options",
"quic-max-packet-length",
"quic-version",
"rdp_desktop_session",
"reader-mode-feedback",
"reader-mode-heuristics",
"rebaseline-pixel-tests",
"record-type",
"reduce-security-for-testing",
"reduced-referrer-granularity",
"reduce-security-for-testing",
"register-font-files",
"register-pepper-plugins",
"relauncher",
@@ -1123,19 +1101,20 @@ const char* kBlacklist[] = {
"root",
"root-layer-scrolls",
"rtl",
"run-all-compositor-stages-before-draw",
"run-layout-test",
"runtime-deps-list-file",
"safebrowsing-disable-auto-update",
"safebrowsing-disable-download-protection",
"safebrowsing-disable-extension-blacklist",
"safebrowsing-manual-download-blacklist",
"SafeSites",
"sandbox-ipc",
"save-page-as-mhtml",
"screen-config",
"screenshot",
"script-executable",
"scripts-require-action",
"scroll-end-effect",
"search-provider-logo-url",
"secondary",
"secondary-display-layout",
@@ -1182,6 +1161,7 @@ const char* kBlacklist[] = {
"skip-reencoding-on-skp-capture",
"slow",
"slow-connections-only",
"slow-down-compositing-scale-factor",
"slow-down-raster-scale-factor",
"sms-test-messages",
"spdy-proxy-auth-fallback",
@@ -1198,13 +1178,12 @@ const char* kBlacklist[] = {
"ssl-version-max",
"ssl-version-min",
"stable-release-mode",
"started",
"start-fullscreen",
"start-maximized",
"start-stack-profiler",
"started",
"stub",
"stub-cros-settings",
"supports-dual-gpus",
"surface",
"swiftshader",
"swiftshader-webgl",
@@ -1221,6 +1200,7 @@ const char* kBlacklist[] = {
"system-log-upload-frequency",
"tab-management-experiment-type-disabled",
"tab-management-experiment-type-elderberry",
"task-manager-show-extra-renderers",
"task-profiler",
"team-drives",
"test-auto-update-ui",
@@ -1229,6 +1209,8 @@ const char* kBlacklist[] = {
"test-do-not-initialize-icu",
"test-encryption-migration-ui",
"test-gl-lib",
"testing-fixed-http-port",
"testing-fixed-https-port",
"test-launcher-batch-limit",
"test-launcher-bot-mode",
"test-launcher-debug-launcher",
@@ -1249,9 +1231,8 @@ const char* kBlacklist[] = {
"test-name",
"test-tiny-timeout",
"test-type",
"testing-fixed-http-port",
"testing-fixed-https-port",
"tether-stub",
"third-party-doodle-url",
"threads",
"time",
"timeout",
@@ -1271,6 +1252,7 @@ const char* kBlacklist[] = {
"touch_view",
"trace-config-file",
"trace-export-events-to-etw",
"tracelog",
"trace-shutdown",
"trace-shutdown-file",
"trace-startup",
@@ -1280,7 +1262,6 @@ const char* kBlacklist[] = {
"trace-to-file",
"trace-to-file-name",
"trace-upload-url",
"tracelog",
"translate-ranker-model-url",
"translate-script-url",
"translate-security-origin",
@@ -1306,12 +1287,11 @@ const char* kBlacklist[] = {
"ui-test-action-timeout",
"uninstall",
"unlimited-storage",
"unsafe-pac-url",
"unsafely-allow-protected-media-identifier-for-domain",
"unsafely-treat-insecure-origin-as-secure",
"unsafe-pac-url",
"use-angle",
"use-cras",
"use-double-buffering",
"use-fake-device-for-media-stream",
"use-fake-jpeg-decode-accelerator",
"use-fake-ui-for-media-stream",
@@ -1324,18 +1304,21 @@ const char* kBlacklist[] = {
"use-mobile-user-agent",
"use-mock-keychain",
"use-passthrough-cmd-decoder",
"use-simple-cache-backend",
"use-system-default-printer",
"use-test-config",
"user-agent",
"user-always-affiliated",
"user-data-dir",
"user-gesture-required",
"user-gesture-required-for-cross-origin",
"use-skia-renderer",
"use-system-default-printer",
"use-test-config",
"use-viz-hit-test",
"utility",
"utility-allowed-dir",
"utility-cmd-prefix",
"utility-run-elevated",
"utility-sandbox-type",
"utility-startup-dialog",
"v",
"v2-sandbox",
"v2-sandbox-enabled",
@@ -1359,21 +1342,20 @@ const char* kBlacklist[] = {
"watcher",
"waveout-buffers",
"webapk-server-url",
"webrtc-max-cpu-consumption-percentage",
"webrtc-stun-probe-trial",
"webview-enable-safebrowsing-support",
"webview-sandboxed-renderer",
"whitelisted-extension-id",
"win-jumplist-action",
"window-position",
"windows10-custom-titlebar",
"window-size",
"window-workspace",
"windows10-custom-titlebar",
"winhttp-proxy-resolver",
"win-jumplist-action",
"wm-window-animations-disabled",
"yield-between-content-script-runs",
"zygote",
"zygote-cmd-prefix",
"zygote-cmd-prefix"
};
bool IsBlacklistedArg(const base::CommandLine::CharType* arg) {
@@ -1398,8 +1380,10 @@ bool IsBlacklistedArg(const base::CommandLine::CharType* arg) {
a += prefix_length;
std::string switch_name =
base::ToLowerASCII(base::StringPiece(a, strcspn(a, "=")));
return std::binary_search(std::begin(kBlacklist), std::end(kBlacklist),
switch_name);
for (auto& item : blacklist) {
if (switch_name == item)
return true;
}
}
return false;
@@ -1410,15 +1394,6 @@ bool IsBlacklistedArg(const base::CommandLine::CharType* arg) {
namespace atom {
bool CheckCommandLineArguments(int argc, base::CommandLine::CharType** argv) {
DCHECK(std::is_sorted(std::begin(kBlacklist), std::end(kBlacklist),
[](const char* a, const char* b) {
return base::StringPiece(a) < base::StringPiece(b);
}))
<< "The kBlacklist must be in sorted order";
DCHECK(std::binary_search(std::begin(kBlacklist), std::end(kBlacklist),
base::StringPiece("inspect")))
<< "Remember to add Node command line flags to kBlacklist";
const base::CommandLine::StringType dashdash(2, '-');
bool block_blacklisted_args = false;
for (int i = 0; i < argc; ++i) {

View File

@@ -2,8 +2,6 @@
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifdef ENABLE_RUN_AS_NODE
#include "atom/app/node_main.h"
#include "atom/app/uv_task_runner.h"
@@ -14,7 +12,6 @@
#include "atom/common/native_mate_converters/string16_converter.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/task_scheduler/task_scheduler.h"
#include "base/threading/thread_task_runner_handle.h"
#include "gin/array_buffer.h"
#include "gin/public/isolate_holder.h"
@@ -43,11 +40,6 @@ int NodeMain(int argc, char *argv[]) {
gin::V8Initializer::LoadV8Snapshot();
gin::V8Initializer::LoadV8Natives();
// V8 requires a task scheduler apparently
base::TaskScheduler::CreateAndStartWithDefaultParams("Electron");
// Initialize gin::IsolateHolder.
JavascriptEnvironment gin_env;
int exec_argc;
@@ -61,7 +53,7 @@ int NodeMain(int argc, char *argv[]) {
// Enable support for v8 inspector.
NodeDebugger node_debugger(env);
node_debugger.Start(gin_env.platform());
node_debugger.Start();
mate::Dictionary process(gin_env.isolate(), env->process_object());
#if defined(OS_WIN)
@@ -96,18 +88,9 @@ int NodeMain(int argc, char *argv[]) {
node::FreeEnvironment(env);
}
// According to "src/gin/shell/gin_main.cc":
//
// gin::IsolateHolder waits for tasks running in TaskScheduler in its
// destructor and thus must be destroyed before TaskScheduler starts skipping
// CONTINUE_ON_SHUTDOWN tasks.
base::TaskScheduler::GetInstance()->Shutdown();
v8::V8::Dispose();
return exit_code;
}
} // namespace atom
#endif // ENABLE_RUN_AS_NODE

View File

@@ -5,14 +5,10 @@
#ifndef ATOM_APP_NODE_MAIN_H_
#define ATOM_APP_NODE_MAIN_H_
#ifdef ENABLE_RUN_AS_NODE
namespace atom {
int NodeMain(int argc, char *argv[]);
} // namespace atom
#endif // ENABLE_RUN_AS_NODE
#endif // ATOM_APP_NODE_MAIN_H_

View File

@@ -1,16 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>${ATOM_BUNDLE_ID}</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundleExecutable</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>LSBackgroundOnly</key>
<true/>
</dict>
</plist>

View File

@@ -2,8 +2,6 @@
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <utility>
#include "atom/app/uv_task_runner.h"
#include "base/stl_util.h"
@@ -21,25 +19,25 @@ UvTaskRunner::~UvTaskRunner() {
}
bool UvTaskRunner::PostDelayedTask(const tracked_objects::Location& from_here,
base::OnceClosure task,
const base::Closure& task,
base::TimeDelta delay) {
auto* timer = new uv_timer_t;
timer->data = this;
uv_timer_init(loop_, timer);
uv_timer_start(timer, UvTaskRunner::OnTimeout, delay.InMilliseconds(), 0);
tasks_[timer] = std::move(task);
tasks_[timer] = task;
return true;
}
bool UvTaskRunner::RunsTasksInCurrentSequence() const {
bool UvTaskRunner::RunsTasksOnCurrentThread() const {
return true;
}
bool UvTaskRunner::PostNonNestableDelayedTask(
const tracked_objects::Location& from_here,
base::OnceClosure task,
const base::Closure& task,
base::TimeDelta delay) {
return PostDelayedTask(from_here, std::move(task), delay);
return PostDelayedTask(from_here, task, delay);
}
// static
@@ -48,7 +46,7 @@ void UvTaskRunner::OnTimeout(uv_timer_t* timer) {
if (!ContainsKey(self->tasks_, timer))
return;
std::move(self->tasks_[timer]).Run();
self->tasks_[timer].Run();
self->tasks_.erase(timer);
uv_timer_stop(timer);
uv_close(reinterpret_cast<uv_handle_t*>(timer), UvTaskRunner::OnClose);

View File

@@ -21,12 +21,12 @@ class UvTaskRunner : public base::SingleThreadTaskRunner {
// base::SingleThreadTaskRunner:
bool PostDelayedTask(const tracked_objects::Location& from_here,
base::OnceClosure task,
const base::Closure& task,
base::TimeDelta delay) override;
bool RunsTasksInCurrentSequence() const override;
bool RunsTasksOnCurrentThread() const override;
bool PostNonNestableDelayedTask(
const tracked_objects::Location& from_here,
base::OnceClosure task,
const base::Closure& task,
base::TimeDelta delay) override;
private:
@@ -35,7 +35,7 @@ class UvTaskRunner : public base::SingleThreadTaskRunner {
uv_loop_t* loop_;
std::map<uv_timer_t*, base::OnceClosure> tasks_;
std::map<uv_timer_t*, base::Closure> tasks_;
DISALLOW_COPY_AND_ASSIGN(UvTaskRunner);
};

View File

@@ -45,7 +45,6 @@
#include "content/public/common/content_switches.h"
#include "media/audio/audio_manager.h"
#include "native_mate/object_template_builder.h"
#include "net/ssl/client_cert_identity.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/image/image.h"
@@ -55,10 +54,6 @@
#include "base/strings/utf_string_conversions.h"
#endif
#if defined(OS_MACOSX)
#include "atom/browser/ui/cocoa/atom_bundle_mover.h"
#endif
using atom::Browser;
namespace mate {
@@ -376,8 +371,6 @@ int GetPathConstant(const std::string& name) {
return brightray::DIR_CACHE;
else if (name == "userCache")
return brightray::DIR_USER_CACHE;
else if (name == "logs")
return brightray::DIR_APP_LOGS;
else if (name == "home")
return base::DIR_HOME;
else if (name == "temp")
@@ -421,26 +414,19 @@ bool NotificationCallbackWrapper(
return !Browser::Get()->is_shutting_down();
}
void GotPrivateKey(std::shared_ptr<content::ClientCertificateDelegate> delegate,
scoped_refptr<net::X509Certificate> cert,
scoped_refptr<net::SSLPrivateKey> private_key) {
delegate->ContinueWithCertificate(cert, private_key);
}
void OnClientCertificateSelected(
v8::Isolate* isolate,
std::shared_ptr<content::ClientCertificateDelegate> delegate,
std::shared_ptr<net::ClientCertIdentityList> identities,
mate::Arguments* args) {
if (args->Length() == 2) {
delegate->ContinueWithCertificate(nullptr, nullptr);
delegate->ContinueWithCertificate(nullptr);
return;
}
v8::Local<v8::Value> val;
args->GetNext(&val);
if (val->IsNull()) {
delegate->ContinueWithCertificate(nullptr, nullptr);
delegate->ContinueWithCertificate(nullptr);
return;
}
@@ -456,17 +442,8 @@ void OnClientCertificateSelected(
auto certs = net::X509Certificate::CreateCertificateListFromBytes(
data.c_str(), data.length(), net::X509Certificate::FORMAT_AUTO);
if (!certs.empty()) {
scoped_refptr<net::X509Certificate> cert(certs[0].get());
for (size_t i = 0; i < identities->size(); ++i) {
if (cert->Equals((*identities)[i]->certificate())) {
net::ClientCertIdentity::SelfOwningAcquirePrivateKey(
std::move((*identities)[i]),
base::Bind(&GotPrivateKey, delegate, std::move(cert)));
break;
}
}
}
if (!certs.empty())
delegate->ContinueWithCertificate(certs[0].get());
}
void PassLoginInformation(scoped_refptr<LoginHandler> login_handler,
@@ -532,6 +509,7 @@ App::App(v8::Isolate* isolate) {
static_cast<AtomBrowserClient*>(AtomBrowserClient::Get())->set_delegate(this);
Browser::Get()->AddObserver(this);
content::GpuDataManager::GetInstance()->AddObserver(this);
content::BrowserChildProcessObserver::Add(this);
base::ProcessId pid = base::GetCurrentProcId();
std::unique_ptr<atom::ProcessMetric> process_metric(
new atom::ProcessMetric(
@@ -598,7 +576,6 @@ void App::OnFinishLaunching(const base::DictionaryValue& launch_info) {
}
void App::OnPreMainMessageLoopRun() {
content::BrowserChildProcessObserver::Add(this);
if (process_singleton_) {
process_singleton_->OnBrowserReady();
}
@@ -609,18 +586,6 @@ void App::OnAccessibilitySupportChanged() {
}
#if defined(OS_MACOSX)
void App::OnWillContinueUserActivity(
bool* prevent_default,
const std::string& type) {
*prevent_default = Emit("will-continue-activity", type);
}
void App::OnDidFailToContinueUserActivity(
const std::string& type,
const std::string& error) {
Emit("continue-activity-error", type, error);
}
void App::OnContinueUserActivity(
bool* prevent_default,
const std::string& type,
@@ -628,72 +593,50 @@ void App::OnContinueUserActivity(
*prevent_default = Emit("continue-activity", type, user_info);
}
void App::OnUserActivityWasContinued(
const std::string& type,
const base::DictionaryValue& user_info) {
Emit("activity-was-continued", type, user_info);
}
void App::OnUpdateUserActivityState(
bool* prevent_default,
const std::string& type,
const base::DictionaryValue& user_info) {
*prevent_default = Emit("update-activity-state", type, user_info);
}
void App::OnNewWindowForTab() {
Emit("new-window-for-tab");
}
#endif
void App::OnLogin(LoginHandler* login_handler,
const base::DictionaryValue& request_details) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
bool prevent_default = false;
content::WebContents* web_contents = login_handler->GetWebContents();
if (web_contents) {
prevent_default =
Emit("login",
WebContents::CreateFrom(isolate(), web_contents),
request_details,
login_handler->auth_info(),
base::Bind(&PassLoginInformation,
make_scoped_refptr(login_handler)));
}
bool prevent_default = Emit(
"login",
WebContents::CreateFrom(isolate(), login_handler->GetWebContents()),
request_details,
login_handler->auth_info(),
base::Bind(&PassLoginInformation, make_scoped_refptr(login_handler)));
// Default behavior is to always cancel the auth.
if (!prevent_default)
login_handler->CancelAuth();
}
bool App::CanCreateWindow(
content::RenderFrameHost* opener,
const GURL& opener_url,
const GURL& opener_top_level_frame_url,
const GURL& source_origin,
content::mojom::WindowContainerType container_type,
void App::OnCreateWindow(
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& features,
const std::vector<std::string>& additional_features,
const scoped_refptr<content::ResourceRequestBody>& body,
bool user_gesture,
bool opener_suppressed,
bool* no_javascript_access) {
const std::vector<std::string>& features,
const scoped_refptr<content::ResourceRequestBodyImpl>& body,
int render_process_id,
int render_frame_id) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
content::RenderFrameHost* rfh =
content::RenderFrameHost::FromID(render_process_id, render_frame_id);
content::WebContents* web_contents =
content::WebContents::FromRenderFrameHost(opener);
content::WebContents::FromRenderFrameHost(rfh);
if (web_contents) {
auto api_web_contents = WebContents::CreateFrom(isolate(), web_contents);
api_web_contents->OnCreateWindow(target_url, frame_name, disposition,
additional_features, body);
api_web_contents->OnCreateWindow(target_url,
frame_name,
disposition,
features,
body);
}
return false;
}
void App::AllowCertificateError(
@@ -724,35 +667,22 @@ void App::AllowCertificateError(
void App::SelectClientCertificate(
content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info,
net::ClientCertIdentityList identities,
std::unique_ptr<content::ClientCertificateDelegate> delegate) {
std::shared_ptr<content::ClientCertificateDelegate>
shared_delegate(delegate.release());
// Convert the ClientCertIdentityList to a CertificateList
// to avoid changes in the API.
auto client_certs = net::CertificateList();
for (const std::unique_ptr<net::ClientCertIdentity>& identity : identities)
client_certs.push_back(identity->certificate());
auto shared_identities =
std::make_shared<net::ClientCertIdentityList>(std::move(identities));
bool prevent_default =
Emit("select-client-certificate",
WebContents::CreateFrom(isolate(), web_contents),
cert_request_info->host_and_port.ToString(), std::move(client_certs),
base::Bind(&OnClientCertificateSelected, isolate(), shared_delegate,
shared_identities));
cert_request_info->host_and_port.ToString(),
cert_request_info->client_certs,
base::Bind(&OnClientCertificateSelected,
isolate(),
shared_delegate));
// Default to first certificate from the platform store.
if (!prevent_default) {
scoped_refptr<net::X509Certificate> cert =
(*shared_identities)[0]->certificate();
net::ClientCertIdentity::SelfOwningAcquirePrivateKey(
std::move((*shared_identities)[0]),
base::Bind(&GotPrivateKey, shared_delegate, std::move(cert)));
}
if (!prevent_default)
shared_delegate->ContinueWithCertificate(
cert_request_info->client_certs[0].get());
}
void App::OnGpuProcessCrashed(base::TerminationStatus status) {
@@ -851,7 +781,7 @@ void App::SetDesktopName(const std::string& desktop_name) {
}
std::string App::GetLocale() {
return g_browser_process->GetApplicationLocale();
return l10n_util::GetApplicationLocale("");
}
bool App::MakeSingleInstance(
@@ -867,10 +797,9 @@ bool App::MakeSingleInstance(
switch (process_singleton_->NotifyOtherProcessOrCreate()) {
case ProcessSingleton::NotifyResult::LOCK_ERROR:
case ProcessSingleton::NotifyResult::PROFILE_IN_USE:
case ProcessSingleton::NotifyResult::PROCESS_NOTIFIED: {
case ProcessSingleton::NotifyResult::PROCESS_NOTIFIED:
process_singleton_.reset();
return true;
}
case ProcessSingleton::NotifyResult::PROCESS_NONE:
default: // Shouldn't be needed, but VS warns if it is not there.
return false;
@@ -942,16 +871,6 @@ bool App::IsAccessibilitySupportEnabled() {
return ax_state->IsAccessibleBrowser();
}
void App::SetAccessibilitySupportEnabled(bool enabled) {
auto ax_state = content::BrowserAccessibilityState::GetInstance();
if (enabled) {
ax_state->OnScreenReaderDetected();
} else {
ax_state->DisableAccessibility();
}
Browser::Get()->OnAccessibilitySupportChanged();
}
Browser::LoginItemSettings App::GetLoginItemSettings(mate::Arguments* args) {
Browser::LoginItemSettings options;
args->GetNext(&options);
@@ -1110,17 +1029,8 @@ std::vector<mate::Dictionary> App::GetAppMetrics(v8::Isolate* isolate) {
cpu_dict.Set("percentCPUUsage",
process_metric.second->metrics->GetPlatformIndependentCPUUsage()
/ processor_count);
#if !defined(OS_WIN)
cpu_dict.Set("idleWakeupsPerSecond",
process_metric.second->metrics->GetIdleWakeupsPerSecond());
#else
// Chrome's underlying process_metrics.cc will throw a non-fatal warning
// that this method isn't implemented on Windows, so set it to 0 instead
// of calling it
cpu_dict.Set("idleWakeupsPerSecond", 0);
#endif
pid_dict.Set("cpu", cpu_dict);
pid_dict.Set("pid", process_metric.second->pid);
pid_dict.Set("type",
@@ -1164,16 +1074,6 @@ void App::EnableMixedSandbox(mate::Arguments* args) {
command_line->AppendSwitch(switches::kEnableMixedSandbox);
}
#if defined(OS_MACOSX)
bool App::MoveToApplicationsFolder(mate::Arguments* args) {
return ui::cocoa::AtomBundleMover::Move(args);
}
bool App::IsInApplicationsFolder() {
return ui::cocoa::AtomBundleMover::IsCurrentAppInApplicationsFolder();
}
#endif
// static
mate::Handle<App> App::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new App(isolate));
@@ -1217,10 +1117,6 @@ void App::BuildPrototype(
base::Bind(&Browser::SetUserActivity, browser))
.SetMethod("getCurrentActivityType",
base::Bind(&Browser::GetCurrentActivityType, browser))
.SetMethod("invalidateCurrentActivity",
base::Bind(&Browser::InvalidateCurrentActivity, browser))
.SetMethod("updateCurrentActivity",
base::Bind(&Browser::UpdateCurrentActivity, browser))
.SetMethod("setAboutPanelOptions",
base::Bind(&Browser::SetAboutPanelOptions, browser))
#endif
@@ -1247,8 +1143,6 @@ void App::BuildPrototype(
.SetMethod("relaunch", &App::Relaunch)
.SetMethod("isAccessibilitySupportEnabled",
&App::IsAccessibilitySupportEnabled)
.SetMethod("setAccessibilitySupportEnabled",
&App::SetAccessibilitySupportEnabled)
.SetMethod("disableHardwareAcceleration",
&App::DisableHardwareAcceleration)
.SetMethod("disableDomainBlockingFor3DAPIs",
@@ -1256,16 +1150,9 @@ void App::BuildPrototype(
.SetMethod("getFileIcon", &App::GetFileIcon)
.SetMethod("getAppMetrics", &App::GetAppMetrics)
.SetMethod("getGPUFeatureStatus", &App::GetGPUFeatureStatus)
.SetMethod("enableMixedSandbox", &App::EnableMixedSandbox)
// TODO(juturu): Remove in 2.0, deprecate before then with warnings
#if defined(OS_MACOSX)
.SetMethod("moveToApplicationsFolder", &App::MoveToApplicationsFolder)
.SetMethod("isInApplicationsFolder", &App::IsInApplicationsFolder)
#endif
#if defined(MAS_BUILD)
.SetMethod("startAccessingSecurityScopedResource",
&App::StartAccessingSecurityScopedResource)
#endif
.SetMethod("enableMixedSandbox", &App::EnableMixedSandbox);
.SetMethod("getAppMemoryInfo", &App::GetAppMetrics);
}
} // namespace api

View File

@@ -25,7 +25,6 @@
#include "native_mate/dictionary.h"
#include "native_mate/handle.h"
#include "net/base/completion_callback.h"
#include "net/ssl/client_cert_identity.h"
#if defined(USE_NSS_CERTS)
#include "chrome/browser/certificate_manager_model.h"
@@ -75,6 +74,16 @@ class App : public AtomBrowserClient::Delegate,
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
// Called when window with disposition needs to be created.
void OnCreateWindow(
const GURL& target_url,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::vector<std::string>& features,
const scoped_refptr<content::ResourceRequestBodyImpl>& body,
int render_process_id,
int render_frame_id);
#if defined(USE_NSS_CERTS)
void OnCertificateManagerModelCreated(
std::unique_ptr<base::DictionaryValue> options,
@@ -106,23 +115,11 @@ class App : public AtomBrowserClient::Delegate,
void OnAccessibilitySupportChanged() override;
void OnPreMainMessageLoopRun() override;
#if defined(OS_MACOSX)
void OnWillContinueUserActivity(
bool* prevent_default,
const std::string& type) override;
void OnDidFailToContinueUserActivity(
const std::string& type,
const std::string& error) override;
void OnContinueUserActivity(
bool* prevent_default,
const std::string& type,
const base::DictionaryValue& user_info) override;
void OnUserActivityWasContinued(
const std::string& type,
const base::DictionaryValue& user_info) override;
void OnUpdateUserActivityState(
bool* prevent_default,
const std::string& type,
const base::DictionaryValue& user_info) override;
void OnNewWindowForTab() override;
#endif
@@ -141,23 +138,7 @@ class App : public AtomBrowserClient::Delegate,
void SelectClientCertificate(
content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info,
net::ClientCertIdentityList client_certs,
std::unique_ptr<content::ClientCertificateDelegate> delegate) override;
bool CanCreateWindow(content::RenderFrameHost* opener,
const GURL& opener_url,
const GURL& opener_top_level_frame_url,
const GURL& source_origin,
content::mojom::WindowContainerType container_type,
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& features,
const std::vector<std::string>& additional_features,
const scoped_refptr<content::ResourceRequestBody>& body,
bool user_gesture,
bool opener_suppressed,
bool* no_javascript_access) override;
// content::GpuDataManagerObserver:
void OnGpuProcessCrashed(base::TerminationStatus status) override;
@@ -192,7 +173,6 @@ class App : public AtomBrowserClient::Delegate,
void DisableHardwareAcceleration(mate::Arguments* args);
void DisableDomainBlockingFor3DAPIs(mate::Arguments* args);
bool IsAccessibilitySupportEnabled();
void SetAccessibilitySupportEnabled(bool enabled);
Browser::LoginItemSettings GetLoginItemSettings(mate::Arguments* args);
#if defined(USE_NSS_CERTS)
void ImportCertificate(const base::DictionaryValue& options,
@@ -205,15 +185,6 @@ class App : public AtomBrowserClient::Delegate,
v8::Local<v8::Value> GetGPUFeatureStatus(v8::Isolate* isolate);
void EnableMixedSandbox(mate::Arguments* args);
#if defined(OS_MACOSX)
bool MoveToApplicationsFolder(mate::Arguments* args);
bool IsInApplicationsFolder();
#endif
#if defined(MAS_BUILD)
base::Callback<void()> StartAccessingSecurityScopedResource(
mate::Arguments* args);
#endif
#if defined(OS_WIN)
// Get the current Jump List settings.
v8::Local<v8::Value> GetJumpListSettings();

View File

@@ -1,59 +0,0 @@
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_app.h"
#import <Cocoa/Cocoa.h>
#include "base/strings/sys_string_conversions.h"
namespace atom {
namespace api {
// Callback passed to js which will stop accessing the given bookmark.
void OnStopAccessingSecurityScopedResource(NSURL* bookmarkUrl) {
[bookmarkUrl stopAccessingSecurityScopedResource];
[bookmarkUrl release];
}
// Get base64 encoded NSData, create a bookmark for it and start accessing it.
base::Callback<void ()> App::StartAccessingSecurityScopedResource(mate::Arguments* args) {
std::string data;
args->GetNext(&data);
NSString *base64str = base::SysUTF8ToNSString(data);
NSData *bookmarkData = [[NSData alloc] initWithBase64EncodedString: base64str options: 0];
// Create bookmarkUrl from NSData.
BOOL isStale = false;
NSError *error = nil;
NSURL *bookmarkUrl = [NSURL URLByResolvingBookmarkData: bookmarkData
options: NSURLBookmarkResolutionWithSecurityScope
relativeToURL: nil
bookmarkDataIsStale: &isStale
error: &error];
if (error != nil) {
NSString *err = [NSString stringWithFormat: @"NSError: %@ %@", error, [error userInfo]];
args->ThrowError(base::SysNSStringToUTF8(err));
}
if (isStale) {
args->ThrowError("bookmarkDataIsStale - try recreating the bookmark");
}
if (error == nil && isStale == false) {
[bookmarkUrl startAccessingSecurityScopedResource];
}
// Stop the NSURL from being GC'd.
[bookmarkUrl retain];
// Return a js callback which will close the bookmark.
return base::Bind(&OnStopAccessingSecurityScopedResource, bookmarkUrl);
}
} // namespace atom
} // namespace api

View File

@@ -99,8 +99,10 @@ void AutoUpdater::OnWindowAllClosed() {
QuitAndInstall();
}
void AutoUpdater::SetFeedURL(mate::Arguments* args) {
auto_updater::AutoUpdater::SetFeedURL(args);
void AutoUpdater::SetFeedURL(const std::string& url, mate::Arguments* args) {
auto_updater::AutoUpdater::HeaderMap headers;
args->GetNext(&headers);
auto_updater::AutoUpdater::SetFeedURL(url, headers);
}
void AutoUpdater::QuitAndInstall() {

View File

@@ -47,7 +47,7 @@ class AutoUpdater : public mate::EventEmitter<AutoUpdater>,
private:
std::string GetFeedURL();
void SetFeedURL(mate::Arguments* args);
void SetFeedURL(const std::string& url, mate::Arguments* args);
void QuitAndInstall();
DISALLOW_COPY_AND_ASSIGN(AutoUpdater);

View File

@@ -68,8 +68,8 @@ void BrowserView::Init(v8::Isolate* isolate,
web_contents_.Reset(isolate, web_contents.ToV8());
api_web_contents_ = web_contents.get();
view_.reset(
NativeBrowserView::Create(api_web_contents_->managed_web_contents()));
view_.reset(NativeBrowserView::Create(
api_web_contents_->managed_web_contents()->GetView()));
InitWith(isolate, wrapper);
}
@@ -114,7 +114,7 @@ void BrowserView::SetBackgroundColor(const std::string& color_name) {
view_->SetBackgroundColor(ParseHexColor(color_name));
}
v8::Local<v8::Value> BrowserView::GetWebContents() {
v8::Local<v8::Value> BrowserView::WebContents() {
if (web_contents_.IsEmpty()) {
return v8::Null(isolate());
}
@@ -131,7 +131,7 @@ void BrowserView::BuildPrototype(v8::Isolate* isolate,
.SetMethod("setAutoResize", &BrowserView::SetAutoResize)
.SetMethod("setBounds", &BrowserView::SetBounds)
.SetMethod("setBackgroundColor", &BrowserView::SetBackgroundColor)
.SetProperty("webContents", &BrowserView::GetWebContents)
.SetProperty("webContents", &BrowserView::WebContents)
.SetProperty("id", &BrowserView::ID);
}
@@ -154,8 +154,6 @@ void Initialize(v8::Local<v8::Object> exports,
isolate, BrowserView::GetConstructor(isolate)->GetFunction());
browser_view.SetMethod("fromId",
&mate::TrackableObject<BrowserView>::FromWeakMapID);
browser_view.SetMethod("getAllViews",
&mate::TrackableObject<BrowserView>::GetAll);
mate::Dictionary dict(isolate, exports);
dict.Set("BrowserView", browser_view);
}

View File

@@ -56,7 +56,7 @@ class BrowserView : public mate::TrackableObject<BrowserView> {
void SetBounds(const gfx::Rect& bounds);
void SetBackgroundColor(const std::string& color_name);
v8::Local<v8::Value> GetWebContents();
v8::Local<v8::Value> WebContents();
v8::Global<v8::Value> web_contents_;
class WebContents* api_web_contents_;

View File

@@ -9,9 +9,7 @@
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/memory/ptr_util.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/web_contents.h"
#include "native_mate/dictionary.h"
@@ -49,11 +47,20 @@ void Debugger::DispatchProtocolMessage(DevToolsAgentHost* agent_host,
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
std::unique_ptr<base::Value> parsed_message = base::JSONReader::Read(message);
if (!parsed_message || !parsed_message->is_dict())
v8::Local<v8::String> local_message =
v8::String::NewFromUtf8(isolate(), message.data());
v8::MaybeLocal<v8::Value> parsed_message = v8::JSON::Parse(
isolate()->GetCurrentContext(), local_message);
if (parsed_message.IsEmpty()) {
return;
base::DictionaryValue* dict =
static_cast<base::DictionaryValue*>(parsed_message.get());
}
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
if (!mate::ConvertFromV8(isolate(), parsed_message.ToLocalChecked(),
dict.get())) {
return;
}
int id;
if (!dict->GetInteger("id", &id)) {
std::string method;
@@ -136,7 +143,7 @@ void Debugger::SendCommand(mate::Arguments* args) {
request.SetInteger("id", request_id);
request.SetString("method", method);
if (!command_params.empty())
request.Set("params", base::WrapUnique(command_params.DeepCopy()));
request.Set("params", command_params.DeepCopy());
std::string json_args;
base::JSONWriter::Write(request, &json_args);

View File

@@ -10,7 +10,6 @@ using base::PlatformThreadRef;
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/media/desktop_media_list.h"
#include "content/public/browser/desktop_capture.h"
#include "native_mate/dictionary.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
@@ -51,7 +50,17 @@ void DesktopCapturer::StartHandling(bool capture_window,
bool capture_screen,
const gfx::Size& thumbnail_size) {
webrtc::DesktopCaptureOptions options =
content::CreateDesktopCaptureOptions();
webrtc::DesktopCaptureOptions::CreateDefault();
#if defined(OS_WIN)
// On windows, desktop effects (e.g. Aero) will be disabled when the Desktop
// capture API is active by default.
// We keep the desktop effects in most times. Howerver, the screen still
// fickers when the API is capturing the window due to limitation of current
// implemetation. This is a known and wontFix issue in webrtc (see:
// http://code.google.com/p/webrtc/issues/detail?id=3373)
options.set_disable_effects(false);
#endif
std::unique_ptr<webrtc::DesktopCapturer> screen_capturer(
capture_screen ? webrtc::DesktopCapturer::CreateScreenCapturer(options)

View File

@@ -54,9 +54,6 @@ struct Converter<file_dialog::DialogSettings> {
dict.Get("filters", &(out->filters));
dict.Get("properties", &(out->properties));
dict.Get("showsTagField", &(out->shows_tag_field));
#if defined(MAS_BUILD)
dict.Get("securityScopedBookmarks", &(out->security_scoped_bookmarks));
#endif
return true;
}
};

View File

@@ -1,115 +0,0 @@
// Copyright (c) 2017 Amaplex Software, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_in_app_purchase.h"
#include <string>
#include <utility>
#include <vector>
#include "atom/common/native_mate_converters/callback.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
namespace mate {
template <>
struct Converter<in_app_purchase::Payment> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const in_app_purchase::Payment& payment) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("productIdentifier", payment.productIdentifier);
dict.Set("quantity", payment.quantity);
return dict.GetHandle();
}
};
template <>
struct Converter<in_app_purchase::Transaction> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const in_app_purchase::Transaction& val) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("transactionIdentifier", val.transactionIdentifier);
dict.Set("transactionDate", val.transactionDate);
dict.Set("originalTransactionIdentifier",
val.originalTransactionIdentifier);
dict.Set("transactionState", val.transactionState);
dict.Set("errorCode", val.errorCode);
dict.Set("errorMessage", val.errorMessage);
dict.Set("payment", val.payment);
return dict.GetHandle();
}
};
} // namespace mate
namespace atom {
namespace api {
#if defined(OS_MACOSX)
// static
mate::Handle<InAppPurchase> InAppPurchase::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new InAppPurchase(isolate));
}
// static
void InAppPurchase::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "InAppPurchase"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("canMakePayments", &in_app_purchase::CanMakePayments)
.SetMethod("getReceiptURL", &in_app_purchase::GetReceiptURL)
.SetMethod("purchaseProduct", &InAppPurchase::PurchaseProduct);
}
InAppPurchase::InAppPurchase(v8::Isolate* isolate) {
Init(isolate);
}
InAppPurchase::~InAppPurchase() {
}
void InAppPurchase::PurchaseProduct(const std::string& product_id,
mate::Arguments* args) {
int quantity = 1;
in_app_purchase::InAppPurchaseCallback callback;
args->GetNext(&quantity);
args->GetNext(&callback);
in_app_purchase::PurchaseProduct(product_id, quantity, callback);
}
void InAppPurchase::OnTransactionsUpdated(
const std::vector<in_app_purchase::Transaction>& transactions) {
Emit("transactions-updated", transactions);
}
#endif
} // namespace api
} // namespace atom
namespace {
using atom::api::InAppPurchase;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
#if defined(OS_MACOSX)
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("inAppPurchase", InAppPurchase::Create(isolate));
dict.Set("InAppPurchase",
InAppPurchase::GetConstructor(isolate)->GetFunction());
#endif
}
} // namespace
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_in_app_purchase, Initialize)

View File

@@ -1,46 +0,0 @@
// Copyright (c) 2017 Amaplex Software, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_ATOM_API_IN_APP_PURCHASE_H_
#define ATOM_BROWSER_API_ATOM_API_IN_APP_PURCHASE_H_
#include <string>
#include <vector>
#include "atom/browser/api/event_emitter.h"
#include "atom/browser/mac/in_app_purchase.h"
#include "atom/browser/mac/in_app_purchase_observer.h"
#include "native_mate/handle.h"
namespace atom {
namespace api {
class InAppPurchase: public mate::EventEmitter<InAppPurchase>,
public in_app_purchase::TransactionObserver {
public:
static mate::Handle<InAppPurchase> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
protected:
explicit InAppPurchase(v8::Isolate* isolate);
~InAppPurchase() override;
void PurchaseProduct(const std::string& product_id, mate::Arguments* args);
// TransactionObserver:
void OnTransactionsUpdated(
const std::vector<in_app_purchase::Transaction>& transactions) override;
private:
DISALLOW_COPY_AND_ASSIGN(InAppPurchase);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_IN_APP_PURCHASE_H_

View File

@@ -23,13 +23,9 @@ Menu::Menu(v8::Isolate* isolate, v8::Local<v8::Object> wrapper)
: model_(new AtomMenuModel(this)),
parent_(nullptr) {
InitWith(isolate, wrapper);
model_->AddObserver(this);
}
Menu::~Menu() {
if (model_) {
model_->RemoveObserver(this);
}
}
void Menu::AfterInit(v8::Isolate* isolate) {
@@ -47,21 +43,15 @@ void Menu::AfterInit(v8::Isolate* isolate) {
}
bool Menu::IsCommandIdChecked(int command_id) const {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
return is_checked_.Run(GetWrapper(), command_id);
return is_checked_.Run(command_id);
}
bool Menu::IsCommandIdEnabled(int command_id) const {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
return is_enabled_.Run(GetWrapper(), command_id);
return is_enabled_.Run(command_id);
}
bool Menu::IsCommandIdVisible(int command_id) const {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
return is_visible_.Run(GetWrapper(), command_id);
return is_visible_.Run(command_id);
}
bool Menu::GetAcceleratorForCommandIdWithParams(
@@ -71,23 +61,18 @@ bool Menu::GetAcceleratorForCommandIdWithParams(
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
v8::Local<v8::Value> val = get_accelerator_.Run(
GetWrapper(), command_id, use_default_accelerator);
command_id, use_default_accelerator);
return mate::ConvertFromV8(isolate(), val, accelerator);
}
void Menu::ExecuteCommand(int command_id, int flags) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
execute_command_.Run(
GetWrapper(),
mate::internal::CreateEventFromFlags(isolate(), flags),
command_id);
}
void Menu::MenuWillShow(ui::SimpleMenuModel* source) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
menu_will_show_.Run(GetWrapper());
menu_will_show_.Run();
}
void Menu::InsertItemAt(
@@ -168,14 +153,6 @@ bool Menu::IsVisibleAt(int index) const {
return model_->IsVisibleAt(index);
}
void Menu::OnMenuWillClose() {
Emit("menu-will-close");
}
void Menu::OnMenuWillShow() {
Emit("menu-will-show");
}
// static
void Menu::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {

View File

@@ -18,8 +18,7 @@ namespace atom {
namespace api {
class Menu : public mate::TrackableObject<Menu>,
public AtomMenuModel::Delegate,
public AtomMenuModel::Observer {
public AtomMenuModel::Delegate {
public:
static mate::WrappableBase* New(mate::Arguments* args);
@@ -54,17 +53,13 @@ class Menu : public mate::TrackableObject<Menu>,
void ExecuteCommand(int command_id, int event_flags) override;
void MenuWillShow(ui::SimpleMenuModel* source) override;
virtual void PopupAt(Window* window, int x, int y, int positioning_item,
const base::Closure& callback) = 0;
virtual void PopupAt(
Window* window, int x, int y, int positioning_item, bool async) = 0;
virtual void ClosePopupAt(int32_t window_id) = 0;
std::unique_ptr<AtomMenuModel> model_;
Menu* parent_;
// Observable:
void OnMenuWillClose() override;
void OnMenuWillShow() override;
private:
void InsertItemAt(int index, int command_id, const base::string16& label);
void InsertSeparatorAt(int index);
@@ -93,14 +88,12 @@ class Menu : public mate::TrackableObject<Menu>,
bool IsVisibleAt(int index) const;
// Stored delegate methods.
base::Callback<bool(v8::Local<v8::Value>, int)> is_checked_;
base::Callback<bool(v8::Local<v8::Value>, int)> is_enabled_;
base::Callback<bool(v8::Local<v8::Value>, int)> is_visible_;
base::Callback<v8::Local<v8::Value>(v8::Local<v8::Value>, int, bool)>
get_accelerator_;
base::Callback<void(v8::Local<v8::Value>, v8::Local<v8::Value>, int)>
execute_command_;
base::Callback<void(v8::Local<v8::Value>)> menu_will_show_;
base::Callback<bool(int)> is_checked_;
base::Callback<bool(int)> is_enabled_;
base::Callback<bool(int)> is_visible_;
base::Callback<v8::Local<v8::Value>(int, bool)> get_accelerator_;
base::Callback<void(v8::Local<v8::Value>, int)> execute_command_;
base::Callback<void()> menu_will_show_;
DISALLOW_COPY_AND_ASSIGN(Menu);
};

View File

@@ -22,20 +22,17 @@ class MenuMac : public Menu {
protected:
MenuMac(v8::Isolate* isolate, v8::Local<v8::Object> wrapper);
void PopupAt(Window* window, int x, int y, int positioning_item,
const base::Closure& callback) override;
void PopupAt(
Window* window, int x, int y, int positioning_item, bool async) override;
void PopupOnUI(const base::WeakPtr<NativeWindow>& native_window,
int32_t window_id,
int x,
int y,
int positioning_item,
base::Closure callback);
int32_t window_id, int x, int y, int positioning_item,
bool async);
void ClosePopupAt(int32_t window_id) override;
private:
friend class Menu;
void OnClosed(int32_t window_id, base::Closure callback);
static void SendActionToFirstResponder(const std::string& action);
scoped_nsobject<AtomMenuController> menu_controller_;

View File

@@ -18,12 +18,6 @@
using content::BrowserThread;
namespace {
static scoped_nsobject<NSMenu> applicationMenu_;
} // namespace
namespace atom {
namespace api {
@@ -33,24 +27,24 @@ MenuMac::MenuMac(v8::Isolate* isolate, v8::Local<v8::Object> wrapper)
weak_factory_(this) {
}
void MenuMac::PopupAt(Window* window, int x, int y, int positioning_item,
const base::Closure& callback) {
void MenuMac::PopupAt(
Window* window, int x, int y, int positioning_item, bool async) {
NativeWindow* native_window = window->window();
if (!native_window)
return;
auto popup = base::Bind(&MenuMac::PopupOnUI, weak_factory_.GetWeakPtr(),
native_window->GetWeakPtr(), window->ID(), x, y,
positioning_item, callback);
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, popup);
positioning_item, async);
if (async)
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, popup);
else
popup.Run();
}
void MenuMac::PopupOnUI(const base::WeakPtr<NativeWindow>& native_window,
int32_t window_id,
int x,
int y,
int positioning_item,
base::Closure callback) {
int32_t window_id, int x, int y, int positioning_item,
bool async) {
if (!native_window)
return;
brightray::InspectableWebContents* web_contents =
@@ -58,8 +52,8 @@ void MenuMac::PopupOnUI(const base::WeakPtr<NativeWindow>& native_window,
if (!web_contents)
return;
auto close_callback = base::Bind(
&MenuMac::OnClosed, weak_factory_.GetWeakPtr(), window_id, callback);
auto close_callback = base::Bind(&MenuMac::ClosePopupAt,
weak_factory_.GetWeakPtr(), window_id);
popup_controllers_[window_id] = base::scoped_nsobject<AtomMenuController>(
[[AtomMenuController alloc] initWithModel:model()
useDefaultAccelerator:NO]);
@@ -98,41 +92,33 @@ void MenuMac::PopupOnUI(const base::WeakPtr<NativeWindow>& native_window,
if (rightmostMenuPoint > screenRight)
position.x = position.x - [menu size].width;
[popup_controllers_[window_id] setCloseCallback:close_callback];
// Make sure events can be pumped while the menu is up.
base::MessageLoop::ScopedNestableTaskAllower allow(
base::MessageLoop::current());
// One of the events that could be pumped is |window.close()|.
// User-initiated event-tracking loops protect against this by
// setting flags in -[CrApplication sendEvent:], but since
// web-content menus are initiated by IPC message the setup has to
// be done manually.
base::mac::ScopedSendingEvent sendingEventScoper;
if (async) {
[popup_controllers_[window_id] setCloseCallback:close_callback];
// Make sure events can be pumped while the menu is up.
base::MessageLoop::ScopedNestableTaskAllower allow(
base::MessageLoop::current());
// Don't emit unresponsive event when showing menu.
atom::UnresponsiveSuppressor suppressor;
[menu popUpMenuPositioningItem:item atLocation:position inView:view];
}
// One of the events that could be pumped is |window.close()|.
// User-initiated event-tracking loops protect against this by
// setting flags in -[CrApplication sendEvent:], but since
// web-content menus are initiated by IPC message the setup has to
// be done manually.
base::mac::ScopedSendingEvent sendingEventScoper;
void MenuMac::ClosePopupAt(int32_t window_id) {
auto controller = popup_controllers_.find(window_id);
if (controller != popup_controllers_.end()) {
// Close the controller for the window.
[controller->second cancel];
} else if (window_id == -1) {
// Or just close all opened controllers.
for (auto it = popup_controllers_.begin();
it != popup_controllers_.end();) {
// The iterator is invalidated after the call.
[(it++)->second cancel];
}
// Don't emit unresponsive event when showing menu.
atom::UnresponsiveSuppressor suppressor;
[menu popUpMenuPositioningItem:item atLocation:position inView:view];
} else {
// Don't emit unresponsive event when showing menu.
atom::UnresponsiveSuppressor suppressor;
[menu popUpMenuPositioningItem:item atLocation:position inView:view];
close_callback.Run();
}
}
void MenuMac::OnClosed(int32_t window_id, base::Closure callback) {
void MenuMac::ClosePopupAt(int32_t window_id) {
popup_controllers_.erase(window_id);
callback.Run();
}
// static
@@ -141,18 +127,7 @@ void Menu::SetApplicationMenu(Menu* base_menu) {
base::scoped_nsobject<AtomMenuController> menu_controller(
[[AtomMenuController alloc] initWithModel:menu->model_.get()
useDefaultAccelerator:YES]);
NSRunLoop* currentRunLoop = [NSRunLoop currentRunLoop];
[currentRunLoop cancelPerformSelector:@selector(setMainMenu:)
target:NSApp
argument:applicationMenu_];
applicationMenu_.reset([[menu_controller menu] retain]);
[[NSRunLoop currentRunLoop]
performSelector:@selector(setMainMenu:)
target:NSApp
argument:applicationMenu_
order:0
modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];
[NSApp setMainMenu:[menu_controller menu]];
// Ensure the menu_controller_ is destroyed after main menu is set.
menu_controller.swap(menu->menu_controller_);

View File

@@ -6,8 +6,7 @@
#include "atom/browser/native_window_views.h"
#include "atom/browser/unresponsive_suppressor.h"
#include "brightray/browser/inspectable_web_contents.h"
#include "brightray/browser/inspectable_web_contents_view.h"
#include "content/public/browser/render_widget_host_view.h"
#include "ui/display/screen.h"
using views::MenuRunner;
@@ -21,22 +20,30 @@ MenuViews::MenuViews(v8::Isolate* isolate, v8::Local<v8::Object> wrapper)
weak_factory_(this) {
}
void MenuViews::PopupAt(Window* window, int x, int y, int positioning_item,
const base::Closure& callback) {
auto* native_window = static_cast<NativeWindowViews*>(window->window());
void MenuViews::PopupAt(
Window* window, int x, int y, int positioning_item, bool async) {
NativeWindow* native_window = static_cast<NativeWindow*>(window->window());
if (!native_window)
return;
content::WebContents* web_contents = native_window->web_contents();
if (!web_contents)
return;
content::RenderWidgetHostView* view = web_contents->GetRenderWidgetHostView();
if (!view)
return;
// (-1, -1) means showing on mouse location.
gfx::Point location;
if (x == -1 || y == -1) {
location = display::Screen::GetScreen()->GetCursorScreenPoint();
} else {
gfx::Point origin = native_window->GetContentBounds().origin();
gfx::Point origin = view->GetViewBounds().origin();
location = gfx::Point(origin.x() + x, origin.y() + y);
}
int flags = MenuRunner::CONTEXT_MENU | MenuRunner::HAS_MNEMONICS;
if (async)
flags |= MenuRunner::ASYNC;
// Don't emit unresponsive event when showing menu.
atom::UnresponsiveSuppressor suppressor;
@@ -44,34 +51,19 @@ void MenuViews::PopupAt(Window* window, int x, int y, int positioning_item,
// Show the menu.
int32_t window_id = window->ID();
auto close_callback = base::Bind(
&MenuViews::OnClosed, weak_factory_.GetWeakPtr(), window_id, callback);
&MenuViews::ClosePopupAt, weak_factory_.GetWeakPtr(), window_id);
menu_runners_[window_id] = std::unique_ptr<MenuRunner>(new MenuRunner(
model(), flags, close_callback));
menu_runners_[window_id]->RunMenuAt(
native_window->widget(),
ignore_result(menu_runners_[window_id]->RunMenuAt(
static_cast<NativeWindowViews*>(window->window())->widget(),
NULL,
gfx::Rect(location, gfx::Size()),
views::MENU_ANCHOR_TOPLEFT,
ui::MENU_SOURCE_MOUSE);
ui::MENU_SOURCE_MOUSE));
}
void MenuViews::ClosePopupAt(int32_t window_id) {
auto runner = menu_runners_.find(window_id);
if (runner != menu_runners_.end()) {
// Close the runner for the window.
runner->second->Cancel();
} else if (window_id == -1) {
// Or just close all opened runners.
for (auto it = menu_runners_.begin(); it != menu_runners_.end();) {
// The iterator is invalidated after the call.
(it++)->second->Cancel();
}
}
}
void MenuViews::OnClosed(int32_t window_id, base::Closure callback) {
menu_runners_.erase(window_id);
callback.Run();
}
// static

View File

@@ -21,13 +21,11 @@ class MenuViews : public Menu {
MenuViews(v8::Isolate* isolate, v8::Local<v8::Object> wrapper);
protected:
void PopupAt(Window* window, int x, int y, int positioning_item,
const base::Closure& callback) override;
void PopupAt(
Window* window, int x, int y, int positioning_item, bool async) override;
void ClosePopupAt(int32_t window_id) override;
private:
void OnClosed(int32_t window_id, base::Closure callback);
// window ID -> open context menu
std::map<int32_t, std::unique_ptr<views::MenuRunner>> menu_runners_;

View File

@@ -9,15 +9,13 @@
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/node_includes.h"
#include "base/strings/utf_string_conversions.h"
#include "brightray/browser/browser_client.h"
#include "native_mate/constructor.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
#include "url/gurl.h"
// Must be the last in the includes list.
// See https://github.com/electron/electron/issues/10363
#include "atom/common/node_includes.h"
namespace mate {
template<>
@@ -70,7 +68,6 @@ Notification::Notification(v8::Isolate* isolate,
opts.Get("hasReply", &has_reply_);
opts.Get("actions", &actions_);
opts.Get("sound", &sound_);
opts.Get("closeButtonText", &close_button_text_);
}
}
@@ -105,24 +102,20 @@ bool Notification::GetSilent() const {
return silent_;
}
bool Notification::GetHasReply() const {
return has_reply_;
}
base::string16 Notification::GetReplyPlaceholder() const {
return reply_placeholder_;
}
base::string16 Notification::GetSound() const {
return sound_;
bool Notification::GetHasReply() const {
return has_reply_;
}
std::vector<brightray::NotificationAction> Notification::GetActions() const {
return actions_;
}
base::string16 Notification::GetCloseButtonText() const {
return close_button_text_;
base::string16 Notification::GetSound() const {
return sound_;
}
// Setters
@@ -142,16 +135,12 @@ void Notification::SetSilent(bool new_silent) {
silent_ = new_silent;
}
void Notification::SetHasReply(bool new_has_reply) {
has_reply_ = new_has_reply;
}
void Notification::SetReplyPlaceholder(const base::string16& new_placeholder) {
reply_placeholder_ = new_placeholder;
}
void Notification::SetSound(const base::string16& new_sound) {
sound_ = new_sound;
void Notification::SetHasReply(bool new_has_reply) {
has_reply_ = new_has_reply;
}
void Notification::SetActions(
@@ -159,8 +148,8 @@ void Notification::SetActions(
actions_ = actions;
}
void Notification::SetCloseButtonText(const base::string16& text) {
close_button_text_ = text;
void Notification::SetSound(const base::string16& new_sound) {
sound_ = new_sound;
}
void Notification::NotificationAction(int index) {
@@ -180,22 +169,14 @@ void Notification::NotificationDisplayed() {
}
void Notification::NotificationDestroyed() {
}
void Notification::NotificationClosed() {
Emit("close");
}
void Notification::Close() {
if (notification_) {
notification_->Dismiss();
notification_.reset();
}
void Notification::NotificationClosed() {
}
// Showing notifications
void Notification::Show() {
Close();
if (presenter_) {
notification_ = presenter_->CreateNotification(this);
if (notification_) {
@@ -210,7 +191,6 @@ void Notification::Show() {
options.reply_placeholder = reply_placeholder_;
options.actions = actions_;
options.sound = sound_;
options.close_button_text = close_button_text_;
notification_->Show(options);
}
}
@@ -227,23 +207,19 @@ void Notification::BuildPrototype(v8::Isolate* isolate,
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.MakeDestroyable()
.SetMethod("show", &Notification::Show)
.SetMethod("close", &Notification::Close)
.SetProperty("title", &Notification::GetTitle, &Notification::SetTitle)
.SetProperty("subtitle", &Notification::GetSubtitle,
&Notification::SetSubtitle)
.SetProperty("body", &Notification::GetBody, &Notification::SetBody)
.SetProperty("silent", &Notification::GetSilent,
&Notification::SetSilent)
.SetProperty("hasReply", &Notification::GetHasReply,
&Notification::SetHasReply)
.SetProperty("silent", &Notification::GetSilent, &Notification::SetSilent)
.SetProperty("replyPlaceholder", &Notification::GetReplyPlaceholder,
&Notification::SetReplyPlaceholder)
.SetProperty("sound", &Notification::GetSound,
&Notification::SetSound)
.SetProperty("hasReply", &Notification::GetHasReply,
&Notification::SetHasReply)
.SetProperty("actions", &Notification::GetActions,
&Notification::SetActions)
.SetProperty("closeButtonText", &Notification::GetCloseButtonText,
&Notification::SetCloseButtonText);
.SetProperty("sound", &Notification::GetSound,
&Notification::SetSound);
}
} // namespace api

View File

@@ -45,29 +45,26 @@ class Notification : public mate::TrackableObject<Notification>,
~Notification() override;
void Show();
void Close();
// Prop Getters
base::string16 GetTitle() const;
base::string16 GetSubtitle() const;
base::string16 GetBody() const;
bool GetSilent() const;
bool GetHasReply() const;
base::string16 GetReplyPlaceholder() const;
base::string16 GetSound() const;
bool GetHasReply() const;
std::vector<brightray::NotificationAction> GetActions() const;
base::string16 GetCloseButtonText() const;
base::string16 GetSound() const;
// Prop Setters
void SetTitle(const base::string16& new_title);
void SetSubtitle(const base::string16& new_subtitle);
void SetBody(const base::string16& new_body);
void SetSilent(bool new_silent);
void SetHasReply(bool new_has_reply);
void SetReplyPlaceholder(const base::string16& new_reply_placeholder);
void SetSound(const base::string16& sound);
void SetHasReply(bool new_has_reply);
void SetActions(const std::vector<brightray::NotificationAction>& actions);
void SetCloseButtonText(const base::string16& text);
void SetSound(const base::string16& sound);
private:
base::string16 title_;
@@ -77,11 +74,10 @@ class Notification : public mate::TrackableObject<Notification>,
base::string16 icon_path_;
bool has_icon_ = false;
bool silent_ = false;
bool has_reply_ = false;
base::string16 reply_placeholder_;
base::string16 sound_;
bool has_reply_ = false;
std::vector<brightray::NotificationAction> actions_;
base::string16 close_button_text_;
base::string16 sound_;
brightray::NotificationPresenter* presenter_;

View File

@@ -16,13 +16,6 @@ namespace atom {
namespace api {
PowerMonitor::PowerMonitor(v8::Isolate* isolate) {
#if defined(OS_LINUX)
SetShutdownHandler(base::Bind(&PowerMonitor::ShouldShutdown,
base::Unretained(this)));
#elif defined(OS_MACOSX)
Browser::Get()->SetShutdownHandler(base::Bind(&PowerMonitor::ShouldShutdown,
base::Unretained(this)));
#endif
base::PowerMonitor::Get()->AddObserver(this);
Init(isolate);
}
@@ -31,20 +24,6 @@ PowerMonitor::~PowerMonitor() {
base::PowerMonitor::Get()->RemoveObserver(this);
}
bool PowerMonitor::ShouldShutdown() {
return !Emit("shutdown");
}
#if defined(OS_LINUX)
void PowerMonitor::BlockShutdown() {
PowerObserverLinux::BlockShutdown();
}
void PowerMonitor::UnblockShutdown() {
PowerObserverLinux::UnblockShutdown();
}
#endif
void PowerMonitor::OnPowerStateChange(bool on_battery_power) {
if (on_battery_power)
Emit("on-battery");
@@ -76,11 +55,6 @@ v8::Local<v8::Value> PowerMonitor::Create(v8::Isolate* isolate) {
void PowerMonitor::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "PowerMonitor"));
#if defined(OS_LINUX)
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("blockShutdown", &PowerMonitor::BlockShutdown)
.SetMethod("unblockShutdown", &PowerMonitor::UnblockShutdown);
#endif
}
} // namespace api
@@ -94,6 +68,10 @@ using atom::api::PowerMonitor;
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
#if defined(OS_MACOSX)
base::PowerMonitorDeviceSource::AllocateSystemIOPorts();
#endif
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("powerMonitor", PowerMonitor::Create(isolate));

View File

@@ -6,8 +6,8 @@
#define ATOM_BROWSER_API_ATOM_API_POWER_MONITOR_H_
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/lib/power_observer.h"
#include "base/compiler_specific.h"
#include "base/power_monitor/power_observer.h"
#include "native_mate/handle.h"
namespace atom {
@@ -15,7 +15,7 @@ namespace atom {
namespace api {
class PowerMonitor : public mate::TrackableObject<PowerMonitor>,
public PowerObserver {
public base::PowerObserver {
public:
static v8::Local<v8::Value> Create(v8::Isolate* isolate);
@@ -26,15 +26,6 @@ class PowerMonitor : public mate::TrackableObject<PowerMonitor>,
explicit PowerMonitor(v8::Isolate* isolate);
~PowerMonitor() override;
// Called by native calles.
bool ShouldShutdown();
#if defined(OS_LINUX)
// Private JS APIs.
void BlockShutdown();
void UnblockShutdown();
#endif
// base::PowerObserver implementations:
void OnPowerStateChange(bool on_battery_power) override;
void OnSuspend() override;

View File

@@ -9,8 +9,8 @@
#include <memory>
#include "atom/browser/api/trackable_object.h"
#include "device/power_save_blocker/power_save_blocker.h"
#include "native_mate/handle.h"
#include "services/device/wake_lock/power_save_blocker/power_save_blocker.h"
namespace mate {
class Dictionary;

View File

@@ -10,7 +10,6 @@
#include "atom/browser/net/url_request_async_asar_job.h"
#include "atom/browser/net/url_request_buffer_job.h"
#include "atom/browser/net/url_request_fetch_job.h"
#include "atom/browser/net/url_request_stream_job.h"
#include "atom/browser/net/url_request_string_job.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/value_converter.h"
@@ -209,8 +208,6 @@ void Protocol::BuildPrototype(
&Protocol::RegisterProtocol<URLRequestAsyncAsarJob>)
.SetMethod("registerHttpProtocol",
&Protocol::RegisterProtocol<URLRequestFetchJob>)
.SetMethod("registerStreamProtocol",
&Protocol::RegisterProtocol<URLRequestStreamJob>)
.SetMethod("unregisterProtocol", &Protocol::UnregisterProtocol)
.SetMethod("isProtocolHandled", &Protocol::IsProtocolHandled)
.SetMethod("interceptStringProtocol",
@@ -221,8 +218,6 @@ void Protocol::BuildPrototype(
&Protocol::InterceptProtocol<URLRequestAsyncAsarJob>)
.SetMethod("interceptHttpProtocol",
&Protocol::InterceptProtocol<URLRequestFetchJob>)
.SetMethod("interceptStreamProtocol",
&Protocol::InterceptProtocol<URLRequestStreamJob>)
.SetMethod("uninterceptProtocol", &Protocol::UninterceptProtocol);
}

View File

@@ -9,7 +9,6 @@ namespace atom {
namespace api {
//TODO(codebytere): deprecated; remove in 3.0
int Screen::getMenuBarHeight() {
return [[NSApp mainMenu] menuBarHeight];
}

View File

@@ -17,7 +17,6 @@
#include "atom/browser/atom_permission_manager.h"
#include "atom/browser/browser.h"
#include "atom/browser/net/atom_cert_verifier.h"
#include "atom/browser/session_preferences.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/content_converter.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
@@ -29,10 +28,10 @@
#include "base/guid.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "brightray/browser/media/media_device_id_salt.h"
#include "brightray/browser/net/devtools_network_conditions.h"
#include "brightray/browser/net/devtools_network_controller_handle.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_thread.h"
@@ -46,6 +45,7 @@
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_auth_preferences.h"
#include "net/proxy/proxy_config_service_fixed.h"
#include "net/proxy/proxy_service.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
@@ -212,7 +212,6 @@ struct Converter<atom::VerifyRequestParams> {
dict.Set("hostname", val.hostname);
dict.Set("certificate", val.certificate);
dict.Set("verificationResult", val.default_result);
dict.Set("errorCode", val.error_code);
return dict.GetHandle();
}
};
@@ -230,6 +229,59 @@ const char kPersistPrefix[] = "persist:";
// Referenced session objects.
std::map<uint32_t, v8::Global<v8::Object>> g_sessions;
class ResolveProxyHelper {
public:
ResolveProxyHelper(AtomBrowserContext* browser_context,
const GURL& url,
const Session::ResolveProxyCallback& callback)
: callback_(callback),
original_thread_(base::ThreadTaskRunnerHandle::Get()) {
scoped_refptr<net::URLRequestContextGetter> context_getter =
browser_context->url_request_context_getter();
context_getter->GetNetworkTaskRunner()->PostTask(
FROM_HERE,
base::Bind(&ResolveProxyHelper::ResolveProxy,
base::Unretained(this), context_getter, url));
}
void OnResolveProxyCompleted(int result) {
std::string proxy;
if (result == net::OK)
proxy = proxy_info_.ToPacString();
original_thread_->PostTask(FROM_HERE,
base::Bind(callback_, proxy));
delete this;
}
private:
void ResolveProxy(scoped_refptr<net::URLRequestContextGetter> context_getter,
const GURL& url) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
net::ProxyService* proxy_service =
context_getter->GetURLRequestContext()->proxy_service();
net::CompletionCallback completion_callback =
base::Bind(&ResolveProxyHelper::OnResolveProxyCompleted,
base::Unretained(this));
// Start the request.
int result = proxy_service->ResolveProxy(
url, "GET", &proxy_info_, completion_callback, &pac_req_, nullptr,
net::NetLogWithSource());
// Completed synchronously.
if (result != net::ERR_IO_PENDING)
completion_callback.Run(result);
}
Session::ResolveProxyCallback callback_;
net::ProxyInfo proxy_info_;
net::ProxyService::PacRequest* pac_req_;
scoped_refptr<base::SingleThreadTaskRunner> original_thread_;
DISALLOW_COPY_AND_ASSIGN(ResolveProxyHelper);
};
// Runs the callback in UI thread.
void RunCallbackInUI(const base::Callback<void()>& callback) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback);
@@ -381,22 +433,9 @@ void DownloadIdCallback(content::DownloadManager* download_manager,
content::DownloadItem::INTERRUPTED,
content::DownloadDangerType::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
content::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT, false,
base::Time(), false,
std::vector<content::DownloadItem::ReceivedSlice>());
}
void SetDevToolsNetworkEmulationClientIdInIO(
brightray::URLRequestContextGetter* url_request_context_getter,
const std::string& client_id) {
if (!url_request_context_getter)
return;
net::URLRequestContext* context =
url_request_context_getter->GetURLRequestContext();
AtomNetworkDelegate* network_delegate =
static_cast<AtomNetworkDelegate*>(context->network_delegate());
network_delegate->SetDevToolsNetworkEmulationClientId(client_id);
}
} // namespace
Session::Session(v8::Isolate* isolate, AtomBrowserContext* browser_context)
@@ -406,8 +445,6 @@ Session::Session(v8::Isolate* isolate, AtomBrowserContext* browser_context)
content::BrowserContext::GetDownloadManager(browser_context)->
AddObserver(this);
new SessionPreferences(browser_context);
Init(isolate);
AttachAsUserData(browser_context);
}
@@ -435,10 +472,8 @@ void Session::OnDownloadCreated(content::DownloadManager* manager,
}
}
void Session::ResolveProxy(
const GURL& url,
const ResolveProxyHelper::ResolveProxyCallback& callback) {
browser_context_->GetResolveProxyHelper()->ResolveProxy(url, callback);
void Session::ResolveProxy(const GURL& url, ResolveProxyCallback callback) {
new ResolveProxyHelper(browser_context(), url, callback);
}
template<Session::CacheAction action>
@@ -508,24 +543,16 @@ void Session::EnableNetworkEmulation(const mate::Dictionary& options) {
browser_context_->network_controller_handle()->SetNetworkState(
devtools_network_emulation_client_id_, std::move(conditions));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(
&SetDevToolsNetworkEmulationClientIdInIO,
base::RetainedRef(browser_context_->url_request_context_getter()),
devtools_network_emulation_client_id_));
browser_context_->network_delegate()->SetDevToolsNetworkEmulationClientId(
devtools_network_emulation_client_id_);
}
void Session::DisableNetworkEmulation() {
std::unique_ptr<brightray::DevToolsNetworkConditions> conditions;
browser_context_->network_controller_handle()->SetNetworkState(
devtools_network_emulation_client_id_, std::move(conditions));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(
&SetDevToolsNetworkEmulationClientIdInIO,
base::RetainedRef(browser_context_->url_request_context_getter()),
std::string()));
browser_context_->network_delegate()->SetDevToolsNetworkEmulationClientId(
std::string());
}
void Session::SetCertVerifyProc(v8::Local<v8::Value> val,
@@ -591,11 +618,10 @@ void Session::SetUserAgent(const std::string& user_agent,
mate::Arguments* args) {
browser_context_->SetUserAgent(user_agent);
std::string accept_lang = g_browser_process->GetApplicationLocale();
std::string accept_lang = l10n_util::GetApplicationLocale("");
args->GetNext(&accept_lang);
scoped_refptr<brightray::URLRequestContextGetter> getter(
browser_context_->GetRequestContext());
auto getter = browser_context_->GetRequestContext();
getter->GetNetworkTaskRunner()->PostTask(
FROM_HERE,
base::Bind(&SetUserAgentInIO, getter, accept_lang, user_agent));
@@ -651,19 +677,6 @@ void Session::CreateInterruptedDownload(const mate::Dictionary& options) {
length, last_modified, etag, base::Time::FromDoubleT(start_time)));
}
void Session::SetPreloads(
const std::vector<base::FilePath::StringType>& preloads) {
auto* prefs = SessionPreferences::FromBrowserContext(browser_context());
DCHECK(prefs);
prefs->set_preloads(preloads);
}
std::vector<base::FilePath::StringType> Session::GetPreloads() const {
auto* prefs = SessionPreferences::FromBrowserContext(browser_context());
DCHECK(prefs);
return prefs->preloads();
}
v8::Local<v8::Value> Session::Cookies(v8::Isolate* isolate) {
if (cookies_.IsEmpty()) {
auto handle = Cookies::Create(isolate, browser_context());
@@ -750,8 +763,6 @@ void Session::BuildPrototype(v8::Isolate* isolate,
.SetMethod("getBlobData", &Session::GetBlobData)
.SetMethod("createInterruptedDownload",
&Session::CreateInterruptedDownload)
.SetMethod("setPreloads", &Session::SetPreloads)
.SetMethod("getPreloads", &Session::GetPreloads)
.SetProperty("cookies", &Session::Cookies)
.SetProperty("protocol", &Session::Protocol)
.SetProperty("webRequest", &Session::WebRequest);

View File

@@ -6,11 +6,9 @@
#define ATOM_BROWSER_API_ATOM_API_SESSION_H_
#include <string>
#include <vector>
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/atom_blob_reader.h"
#include "atom/browser/net/resolve_proxy_helper.h"
#include "base/values.h"
#include "content/public/browser/download_manager.h"
#include "native_mate/handle.h"
@@ -40,6 +38,8 @@ namespace api {
class Session: public mate::TrackableObject<Session>,
public content::DownloadManager::Observer {
public:
using ResolveProxyCallback = base::Callback<void(std::string)>;
enum class CacheAction {
CLEAR,
STATS,
@@ -61,8 +61,7 @@ class Session: public mate::TrackableObject<Session>,
v8::Local<v8::FunctionTemplate> prototype);
// Methods.
void ResolveProxy(const GURL& url,
const ResolveProxyHelper::ResolveProxyCallback& callback);
void ResolveProxy(const GURL& url, ResolveProxyCallback callback);
template<CacheAction action>
void DoCacheAction(const net::CompletionCallback& callback);
void ClearStorageData(mate::Arguments* args);
@@ -82,8 +81,6 @@ class Session: public mate::TrackableObject<Session>,
void GetBlobData(const std::string& uuid,
const AtomBlobReader::CompletionCallback& callback);
void CreateInterruptedDownload(const mate::Dictionary& options);
void SetPreloads(const std::vector<base::FilePath::StringType>& preloads);
std::vector<base::FilePath::StringType> GetPreloads() const;
v8::Local<v8::Value> Cookies(v8::Isolate* isolate);
v8::Local<v8::Value> Protocol(v8::Isolate* isolate);
v8::Local<v8::Value> WebRequest(v8::Isolate* isolate);

View File

@@ -65,10 +65,8 @@ void SystemPreferences::BuildPrototype(
&SystemPreferences::SubscribeLocalNotification)
.SetMethod("unsubscribeLocalNotification",
&SystemPreferences::UnsubscribeLocalNotification)
.SetMethod("registerDefaults", &SystemPreferences::RegisterDefaults)
.SetMethod("getUserDefault", &SystemPreferences::GetUserDefault)
.SetMethod("setUserDefault", &SystemPreferences::SetUserDefault)
.SetMethod("removeUserDefault", &SystemPreferences::RemoveUserDefault)
.SetMethod("isSwipeTrackingFromScrollEventsEnabled",
&SystemPreferences::IsSwipeTrackingFromScrollEventsEnabled)
#endif

View File

@@ -73,11 +73,9 @@ class SystemPreferences : public mate::EventEmitter<SystemPreferences>
void UnsubscribeLocalNotification(int request_id);
v8::Local<v8::Value> GetUserDefault(const std::string& name,
const std::string& type);
void RegisterDefaults(mate::Arguments* args);
void SetUserDefault(const std::string& name,
const std::string& type,
mate::Arguments* args);
void RemoveUserDefault(const std::string& name);
bool IsSwipeTrackingFromScrollEventsEnabled();
#endif
bool IsDarkMode();

View File

@@ -144,28 +144,6 @@ v8::Local<v8::Value> SystemPreferences::GetUserDefault(
}
}
void SystemPreferences::RegisterDefaults(mate::Arguments* args) {
base::DictionaryValue value;
if(!args->GetNext(&value)) {
args->ThrowError("Invalid userDefault data provided");
} else {
@try {
NSDictionary* dict = DictionaryValueToNSDictionary(value);
for (id key in dict) {
id value = [dict objectForKey:key];
if ([value isKindOfClass:[NSNull class]] || value == nil) {
args->ThrowError("Invalid userDefault data provided");
return;
}
}
[[NSUserDefaults standardUserDefaults] registerDefaults:dict];
} @catch (NSException* exception) {
args->ThrowError("Invalid userDefault data provided");
}
}
}
void SystemPreferences::SetUserDefault(const std::string& name,
const std::string& type,
mate::Arguments* args) {
@@ -251,11 +229,6 @@ void SystemPreferences::SetUserDefault(const std::string& name,
}
}
void SystemPreferences::RemoveUserDefault(const std::string& name) {
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:base::SysUTF8ToNSString(name)];
}
bool SystemPreferences::IsDarkMode() {
NSString* mode = [[NSUserDefaults standardUserDefaults]
stringForKey:@"AppleInterfaceStyle"];

View File

@@ -2,8 +2,6 @@
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <iomanip>
#include "atom/browser/api/atom_api_system_preferences.h"
#include "atom/common/color_util.h"
@@ -28,10 +26,10 @@ bool SystemPreferences::IsAeroGlassEnabled() {
}
std::string hexColorDWORDToRGBA(DWORD color) {
DWORD rgba = color << 8 | color >> 24;
std::ostringstream stream;
stream << std::hex << std::setw(8) << std::setfill('0') << rgba;
return stream.str();
stream << std::hex << color;
std::string hexColor = stream.str();
return hexColor.substr(2) + hexColor.substr(0, 2);
}
std::string SystemPreferences::GetAccentColor() {

View File

@@ -40,6 +40,8 @@ struct Converter<atom::TrayIcon::HighlightMode> {
}
}
// Support old boolean parameter
// TODO(kevinsawicki): Remove in 2.0, deprecate before then with warnings
bool highlight;
if (ConvertFromV8(isolate, val, &highlight)) {
if (highlight)
@@ -84,10 +86,8 @@ mate::WrappableBase* Tray::New(mate::Handle<NativeImage> image,
return new Tray(args->isolate(), args->GetThis(), image);
}
void Tray::OnClicked(const gfx::Rect& bounds,
const gfx::Point& location,
int modifiers) {
EmitWithFlags("click", modifiers, bounds, location);
void Tray::OnClicked(const gfx::Rect& bounds, int modifiers) {
EmitWithFlags("click", modifiers, bounds);
}
void Tray::OnDoubleClicked(const gfx::Rect& bounds, int modifiers) {
@@ -130,10 +130,6 @@ void Tray::OnMouseExited(const gfx::Point& location, int modifiers) {
EmitWithFlags("mouse-leave", modifiers, location);
}
void Tray::OnMouseMoved(const gfx::Point& location, int modifiers) {
EmitWithFlags("mouse-move", modifiers, location);
}
void Tray::OnDragEntered() {
Emit("drag-enter");
}

View File

@@ -47,9 +47,7 @@ class Tray : public mate::TrackableObject<Tray>,
~Tray() override;
// TrayIconObserver:
void OnClicked(const gfx::Rect& bounds,
const gfx::Point& location,
int modifiers) override;
void OnClicked(const gfx::Rect& bounds, int modifiers) override;
void OnDoubleClicked(const gfx::Rect& bounds, int modifiers) override;
void OnRightClicked(const gfx::Rect& bounds, int modifiers) override;
void OnBalloonShow() override;
@@ -63,7 +61,6 @@ class Tray : public mate::TrackableObject<Tray>,
void OnDragEnded() override;
void OnMouseEntered(const gfx::Point& location, int modifiers) override;
void OnMouseExited(const gfx::Point& location, int modifiers) override;
void OnMouseMoved(const gfx::Point& location, int modifiers) override;
void SetImage(v8::Isolate* isolate, mate::Handle<NativeImage> image);
void SetPressedImage(v8::Isolate* isolate, mate::Handle<NativeImage> image);

View File

@@ -43,7 +43,6 @@
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/options_switches.h"
#include "base/message_loop/message_loop.h"
#include "base/process/process_handle.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
@@ -57,7 +56,6 @@
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/view_messages.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/navigation_details.h"
@@ -83,7 +81,6 @@
#include "third_party/WebKit/public/web/WebFindOptions.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#include "ui/latency/latency_info.h"
#if !defined(OS_MACOSX)
#include "ui/aura/window.h"
@@ -113,7 +110,7 @@ struct Converter<atom::SetSizeParams> {
return false;
bool autosize;
if (params.Get("enableAutoSize", &autosize))
out->enable_auto_size.reset(new bool(autosize));
out->enable_auto_size.reset(new bool(true));
gfx::Size size;
if (params.Get("min", &size))
out->min_size.reset(new gfx::Size(size));
@@ -272,35 +269,11 @@ content::ServiceWorkerContext* GetServiceWorkerContext(
void OnCapturePageDone(const base::Callback<void(const gfx::Image&)>& callback,
const SkBitmap& bitmap,
content::ReadbackResponse response) {
// Hack to enable transparency in captured image
// TODO(nitsakh) Remove hack once fixed in chromium
const_cast<SkBitmap&>(bitmap).setAlphaType(kPremul_SkAlphaType);
callback.Run(gfx::Image::CreateFrom1xBitmap(bitmap));
}
} // namespace
struct WebContents::FrameDispatchHelper {
WebContents* api_web_contents;
content::RenderFrameHost* rfh;
bool Send(IPC::Message* msg) { return rfh->Send(msg); }
void OnSetTemporaryZoomLevel(double level, IPC::Message* reply_msg) {
api_web_contents->OnSetTemporaryZoomLevel(rfh, level, reply_msg);
}
void OnGetZoomLevel(IPC::Message* reply_msg) {
api_web_contents->OnGetZoomLevel(rfh, reply_msg);
}
void OnRendererMessageSync(const base::string16& channel,
const base::ListValue& args,
IPC::Message* message) {
api_web_contents->OnRendererMessageSync(rfh, channel, args, message);
}
};
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents,
Type type)
@@ -311,13 +284,12 @@ WebContents::WebContents(v8::Isolate* isolate,
request_id_(0),
background_throttling_(true),
enable_devtools_(true) {
const mate::Dictionary options = mate::Dictionary::CreateEmpty(isolate);
if (type == REMOTE) {
web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
Init(isolate);
AttachAsUserData(web_contents);
InitZoomController(web_contents, options);
} else {
const mate::Dictionary options = mate::Dictionary::CreateEmpty(isolate);
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, web_contents, session, options);
@@ -331,10 +303,6 @@ WebContents::WebContents(v8::Isolate* isolate, const mate::Dictionary& options)
request_id_(0),
background_throttling_(true),
enable_devtools_(true) {
// WebContents may need to emit events when it is garbage collected, so it
// has to be deleted in the first gc callback.
MarkHighMemoryUsage();
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
@@ -364,7 +332,7 @@ WebContents::WebContents(v8::Isolate* isolate, const mate::Dictionary& options)
// Obtain the session.
std::string partition;
mate::Handle<api::Session> session;
if (options.Get("session", &session) && !session.IsEmpty()) {
if (options.Get("session", &session)) {
} else if (options.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
@@ -402,8 +370,8 @@ WebContents::WebContents(v8::Isolate* isolate, const mate::Dictionary& options)
options.Get("transparent", &transparent);
content::WebContents::CreateParams params(session->browser_context());
auto* view = new OffScreenWebContentsView(transparent,
base::Bind(&WebContents::OnPaint, base::Unretained(this)));
auto* view = new OffScreenWebContentsView(
transparent, base::Bind(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
@@ -418,15 +386,6 @@ WebContents::WebContents(v8::Isolate* isolate, const mate::Dictionary& options)
InitWithSessionAndOptions(isolate, web_contents, session, options);
}
void WebContents::InitZoomController(content::WebContents* web_contents,
const mate::Dictionary& options) {
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
}
void WebContents::InitWithSessionAndOptions(v8::Isolate* isolate,
content::WebContents *web_contents,
mate::Handle<api::Session> session,
@@ -444,7 +403,11 @@ void WebContents::InitWithSessionAndOptions(v8::Isolate* isolate,
// Initialize security state client.
SecurityStateTabHelper::CreateForWebContents(web_contents);
// Initialize zoom controller.
InitZoomController(web_contents, options);
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
@@ -505,7 +468,12 @@ bool WebContents::DidAddMessageToConsole(content::WebContents* source,
const base::string16& message,
int32_t line_no,
const base::string16& source_id) {
return Emit("console-message", level, message, line_no, source_id);
if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) {
return false;
} else {
Emit("console-message", level, message, line_no, source_id);
return true;
}
}
void WebContents::OnCreateWindow(
@@ -513,20 +481,19 @@ void WebContents::OnCreateWindow(
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::vector<std::string>& features,
const scoped_refptr<content::ResourceRequestBody>& body) {
const scoped_refptr<content::ResourceRequestBodyImpl>& body) {
if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
Emit("-new-window", target_url, frame_name, disposition, features, body);
else
Emit("new-window", target_url, frame_name, disposition, features);
}
void WebContents::WebContentsCreated(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const std::string& frame_name,
const GURL& target_url,
content::WebContents* new_contents) {
void WebContents::WebContentsCreated(content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const std::string& frame_name,
const GURL& target_url,
content::WebContents* new_contents) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
auto api_web_contents = CreateFrom(isolate(), new_contents, BROWSER_WINDOW);
@@ -619,18 +586,16 @@ void WebContents::HandleKeyboardEvent(
}
}
content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent(
bool WebContents::PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown ||
event.GetType() == blink::WebInputEvent::Type::kKeyUp) {
bool prevent_default = Emit("before-input-event", event);
if (prevent_default) {
return content::KeyboardEventProcessingResult::HANDLED;
}
const content::NativeWebKeyboardEvent& event,
bool* is_keyboard_shortcut) {
if (event.type() == blink::WebInputEvent::Type::RawKeyDown ||
event.type() == blink::WebInputEvent::Type::KeyUp) {
return Emit("before-input-event", event);
} else {
return false;
}
return content::KeyboardEventProcessingResult::NOT_HANDLED;
}
void WebContents::EnterFullscreenModeForTab(content::WebContents* source,
@@ -672,10 +637,8 @@ void WebContents::RendererResponsive(content::WebContents* source) {
bool WebContents::HandleContextMenu(const content::ContextMenuParams& params) {
if (params.custom_context.is_pepper_menu) {
Emit("pepper-context-menu",
std::make_pair(params, web_contents()),
base::Bind(&content::WebContents::NotifyContextMenuClosed,
base::Unretained(web_contents()), params.custom_context));
Emit("pepper-context-menu", std::make_pair(params, web_contents()));
web_contents()->NotifyContextMenuClosed(params.custom_context);
} else {
Emit("context-menu", std::make_pair(params, web_contents()));
}
@@ -790,11 +753,7 @@ void WebContents::MediaStoppedPlaying(const MediaPlayerInfo& video_type,
}
void WebContents::DidChangeThemeColor(SkColor theme_color) {
if (theme_color != SK_ColorTRANSPARENT) {
Emit("did-change-theme-color", atom::ToRGBHex(theme_color));
} else {
Emit("did-change-theme-color", nullptr);
}
Emit("did-change-theme-color", atom::ToRGBHex(theme_color));
}
void WebContents::DocumentLoadedInFrame(
@@ -859,10 +818,10 @@ void WebContents::DidFinishNavigation(
bool is_main_frame = navigation_handle->IsInMainFrame();
if (navigation_handle->HasCommitted() && !navigation_handle->IsErrorPage()) {
auto url = navigation_handle->GetURL();
bool is_same_document = navigation_handle->IsSameDocument();
if (is_main_frame && !is_same_document) {
bool is_in_page = navigation_handle->IsSamePage();
if (is_main_frame && !is_in_page) {
Emit("did-navigate", url);
} else if (is_same_document) {
} else if (is_in_page) {
Emit("did-navigate-in-page", url, is_main_frame);
}
} else {
@@ -887,7 +846,7 @@ void WebContents::DidUpdateFaviconURL(
const std::vector<content::FaviconURL>& urls) {
std::set<GURL> unique_urls;
for (const auto& iter : urls) {
if (iter.icon_type != content::FaviconURL::IconType::kFavicon)
if (iter.icon_type != content::FaviconURL::FAVICON)
continue;
const GURL& url = iter.icon_url;
if (url.is_valid())
@@ -916,11 +875,10 @@ void WebContents::DevToolsOpened() {
managed_web_contents()->CallClientFunction(
"DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr);
// Inherit owner window in devtools when it doesn't have one.
auto* devtools = managed_web_contents()->GetDevToolsWebContents();
bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey());
if (owner_window() && !has_window)
handle->SetOwnerWindow(devtools, owner_window());
// Inherit owner window in devtools.
if (owner_window())
handle->SetOwnerWindow(managed_web_contents()->GetDevToolsWebContents(),
owner_window());
Emit("devtools-opened");
}
@@ -933,20 +891,16 @@ void WebContents::DevToolsClosed() {
Emit("devtools-closed");
}
void WebContents::ShowAutofillPopup(content::RenderFrameHost* frame_host,
const gfx::RectF& bounds,
const std::vector<base::string16>& values,
const std::vector<base::string16>& labels) {
auto relay = NativeWindowRelay::FromWebContents(web_contents());
if (relay) {
relay->window->ShowAutofillPopup(
frame_host, web_contents(), bounds, values, labels);
}
}
bool WebContents::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(WebContents, message)
IPC_MESSAGE_HANDLER(AtomViewHostMsg_Message, OnRendererMessage)
IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_Message_Sync,
OnRendererMessageSync)
IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_SetTemporaryZoomLevel,
OnSetTemporaryZoomLevel)
IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_GetZoomLevel,
OnGetZoomLevel)
IPC_MESSAGE_HANDLER_CODE(ViewHostMsg_SetCursor, OnCursorChange,
handled = false)
IPC_MESSAGE_UNHANDLED(handled = false)
@@ -956,28 +910,16 @@ bool WebContents::OnMessageReceived(const IPC::Message& message) {
}
bool WebContents::OnMessageReceived(const IPC::Message& message,
content::RenderFrameHost* frame_host) {
content::RenderFrameHost* frame_host) {
bool handled = true;
FrameDispatchHelper helper = {this, frame_host};
auto relay = NativeWindowRelay::FromWebContents(web_contents());
if (relay) {
IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(NativeWindow, message, frame_host)
IPC_MESSAGE_FORWARD(AtomAutofillFrameHostMsg_HidePopup,
relay->window.get(), NativeWindow::HideAutofillPopup)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
}
IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContents, message, frame_host)
IPC_MESSAGE_HANDLER(AtomFrameHostMsg_Message, OnRendererMessage)
IPC_MESSAGE_FORWARD_DELAY_REPLY(AtomFrameHostMsg_Message_Sync, &helper,
FrameDispatchHelper::OnRendererMessageSync)
IPC_MESSAGE_FORWARD_DELAY_REPLY(
AtomFrameHostMsg_SetTemporaryZoomLevel, &helper,
FrameDispatchHelper::OnSetTemporaryZoomLevel)
IPC_MESSAGE_FORWARD_DELAY_REPLY(AtomFrameHostMsg_GetZoomLevel, &helper,
FrameDispatchHelper::OnGetZoomLevel)
IPC_MESSAGE_HANDLER(AtomAutofillFrameHostMsg_ShowPopup, ShowAutofillPopup)
if (!relay)
return false;
IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(NativeWindow, message, frame_host)
IPC_MESSAGE_FORWARD(AtomAutofillFrameHostMsg_ShowPopup,
relay->window.get(), NativeWindow::ShowAutofillPopup)
IPC_MESSAGE_FORWARD(AtomAutofillFrameHostMsg_HidePopup,
relay->window.get(), NativeWindow::HideAutofillPopup)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
@@ -1014,18 +956,14 @@ void WebContents::WebContentsDestroyed() {
void WebContents::NavigationEntryCommitted(
const content::LoadCommittedDetails& details) {
Emit("navigation-entry-commited", details.entry->GetURL(),
details.is_same_document, details.did_replace_entry);
}
int64_t WebContents::GetIDForContents(content::WebContents* web_contents) {
int64_t process_id = web_contents->GetRenderProcessHost()->GetID();
int64_t routing_id = web_contents->GetMainFrame()->GetRoutingID();
int64_t rv = (process_id << 32) + routing_id;
return rv;
details.is_in_page, details.did_replace_entry);
}
int64_t WebContents::GetID() const {
return WebContents::GetIDForContents(web_contents());
int64_t process_id = web_contents()->GetRenderProcessHost()->GetID();
int64_t routing_id = web_contents()->GetRenderViewHost()->GetRoutingID();
int64_t rv = (process_id << 32) + routing_id;
return rv;
}
int WebContents::GetProcessID() const {
@@ -1064,7 +1002,7 @@ void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) {
GURL http_referrer;
if (options.Get("httpReferrer", &http_referrer))
params.referrer = content::Referrer(http_referrer.GetAsReferrer(),
blink::kWebReferrerPolicyDefault);
blink::WebReferrerPolicyDefault);
std::string user_agent;
if (options.Get("userAgent", &user_agent))
@@ -1074,7 +1012,7 @@ void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) {
if (options.Get("extraHeaders", &extra_headers))
params.extra_headers = extra_headers;
scoped_refptr<content::ResourceRequestBody> body;
scoped_refptr<content::ResourceRequestBodyImpl> body;
if (options.Get("postData", &body)) {
params.post_data = body;
params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
@@ -1115,7 +1053,7 @@ void WebContents::DownloadURL(const GURL& url) {
download_manager->DownloadUrl(
content::DownloadUrlParameters::CreateForWebContentsMainFrame(
web_contents(), url, NO_TRAFFIC_ANNOTATION_YET));
web_contents(), url));
}
GURL WebContents::GetURL() const {
@@ -1208,8 +1146,7 @@ void WebContents::OpenDevTools(mate::Arguments* args) {
std::string state;
if (type_ == WEB_VIEW || !owner_window()) {
state = "detach";
}
if (args && args->Length() == 1) {
} else if (args && args->Length() == 1) {
bool detach = false;
mate::Dictionary options;
if (args->GetNext(&options)) {
@@ -1303,22 +1240,9 @@ void WebContents::HasServiceWorker(
if (!context)
return;
struct WrappedCallback {
base::Callback<void(bool)> callback_;
explicit WrappedCallback(const base::Callback<void(bool)>& callback)
: callback_(callback) {}
void Run(content::ServiceWorkerCapability capability) {
callback_.Run(capability !=
content::ServiceWorkerCapability::NO_SERVICE_WORKER);
delete this;
}
};
auto wrapped_callback = new WrappedCallback(callback);
context->CheckHasServiceWorker(
web_contents()->GetLastCommittedURL(), GURL::EmptyGURL(),
base::Bind(&WrappedCallback::Run, base::Unretained(wrapped_callback)));
context->CheckHasServiceWorker(web_contents()->GetLastCommittedURL(),
GURL::EmptyGURL(),
callback);
}
void WebContents::UnregisterServiceWorker(
@@ -1345,21 +1269,13 @@ bool WebContents::IsAudioMuted() {
void WebContents::Print(mate::Arguments* args) {
PrintSettings settings = { false, false, base::string16() };
if (args->Length() >= 1 && !args->GetNext(&settings)) {
if (args->Length() == 1 && !args->GetNext(&settings)) {
args->ThrowError();
return;
}
auto print_view_manager_basic_ptr =
printing::PrintViewManagerBasic::FromWebContents(web_contents());
if (args->Length() == 2) {
base::Callback<void(bool)> callback;
if (!args->GetNext(&callback)) {
args->ThrowError();
return;
}
print_view_manager_basic_ptr->SetCallback(callback);
}
print_view_manager_basic_ptr->PrintNow(web_contents()->GetMainFrame(),
printing::PrintViewManagerBasic::FromWebContents(web_contents())->
PrintNow(web_contents()->GetMainFrame(),
settings.silent,
settings.print_background,
settings.device_name);
@@ -1368,7 +1284,6 @@ void WebContents::Print(mate::Arguments* args) {
std::vector<printing::PrinterBasicInfo> WebContents::GetPrinterList() {
std::vector<printing::PrinterBasicInfo> printers;
auto print_backend = printing::PrintBackend::CreateInstance(nullptr);
base::ThreadRestrictions::ScopedAllowIO allow_io;
print_backend->EnumeratePrinters(&printers);
return printers;
}
@@ -1500,12 +1415,7 @@ void WebContents::TabTraverse(bool reverse) {
bool WebContents::SendIPCMessage(bool all_frames,
const base::string16& channel,
const base::ListValue& args) {
auto frame_host = web_contents()->GetMainFrame();
if (frame_host) {
return frame_host->Send(new AtomFrameMsg_Message(
frame_host->GetRoutingID(), all_frames, channel, args));
}
return false;
return Send(new AtomViewMsg_Message(routing_id(), all_frames, channel, args));
}
void WebContents::SendInputEvent(v8::Isolate* isolate,
@@ -1515,24 +1425,23 @@ void WebContents::SendInputEvent(v8::Isolate* isolate,
if (!view)
return;
blink::WebInputEvent::Type type = mate::GetWebInputEventType(isolate,
input_event);
if (blink::WebInputEvent::IsMouseEventType(type)) {
int type = mate::GetWebInputEventType(isolate, input_event);
if (blink::WebInputEvent::isMouseEventType(type)) {
blink::WebMouseEvent mouse_event;
if (mate::ConvertFromV8(isolate, input_event, &mouse_event)) {
view->ProcessMouseEvent(mouse_event, ui::LatencyInfo());
return;
}
} else if (blink::WebInputEvent::IsKeyboardEventType(type)) {
} else if (blink::WebInputEvent::isKeyboardEventType(type)) {
content::NativeWebKeyboardEvent keyboard_event(
blink::WebKeyboardEvent::kRawKeyDown,
blink::WebInputEvent::kNoModifiers,
blink::WebKeyboardEvent::RawKeyDown,
blink::WebInputEvent::NoModifiers,
ui::EventTimeForNow());
if (mate::ConvertFromV8(isolate, input_event, &keyboard_event)) {
view->ProcessKeyboardEvent(keyboard_event, ui::LatencyInfo());
view->ProcessKeyboardEvent(keyboard_event);
return;
}
} else if (type == blink::WebInputEvent::kMouseWheel) {
} else if (type == blink::WebInputEvent::MouseWheel) {
blink::WebMouseWheelEvent mouse_wheel_event;
if (mate::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
view->ProcessMouseWheelEvent(mouse_wheel_event, ui::LatencyInfo());
@@ -1632,7 +1541,7 @@ void WebContents::CapturePage(mate::Arguments* args) {
gfx::Size bitmap_size = view_size;
const gfx::NativeView native_view = view->GetNativeView();
const float scale =
display::Screen::GetScreen()->GetDisplayNearestView(native_view)
display::Screen::GetScreen()->GetDisplayNearestWindow(native_view)
.device_scale_factor();
if (scale > 1.0f)
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
@@ -1644,7 +1553,7 @@ void WebContents::CapturePage(mate::Arguments* args) {
}
void WebContents::OnCursorChange(const content::WebCursor& cursor) {
content::CursorInfo info;
content::WebCursor::CursorInfo info;
cursor.GetCursorInfo(&info);
if (cursor.IsCustom()) {
@@ -1675,6 +1584,10 @@ bool WebContents::IsOffScreen() const {
#endif
}
bool WebContents::IsOffScreenOrEmbedderOffscreen() const {
return IsOffScreen() || (embedder_ && embedder_->IsOffScreen());
}
void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap));
}
@@ -1684,10 +1597,10 @@ void WebContents::StartPainting() {
return;
#if defined(ENABLE_OSR)
const auto* wc_impl = static_cast<content::WebContentsImpl*>(web_contents());
auto* osr_wcv = static_cast<OffScreenWebContentsView*>(wc_impl->GetView());
if (osr_wcv)
osr_wcv->SetPainting(true);
auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
web_contents()->GetRenderWidgetHostView());
if (osr_rwhv)
osr_rwhv->SetPainting(true);
#endif
}
@@ -1696,10 +1609,10 @@ void WebContents::StopPainting() {
return;
#if defined(ENABLE_OSR)
const auto* wc_impl = static_cast<content::WebContentsImpl*>(web_contents());
auto* osr_wcv = static_cast<OffScreenWebContentsView*>(wc_impl->GetView());
if (osr_wcv)
osr_wcv->SetPainting(false);
auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
web_contents()->GetRenderWidgetHostView());
if (osr_rwhv)
osr_rwhv->SetPainting(false);
#endif
}
@@ -1708,10 +1621,9 @@ bool WebContents::IsPainting() const {
return false;
#if defined(ENABLE_OSR)
const auto* wc_impl = static_cast<content::WebContentsImpl*>(web_contents());
auto* osr_wcv = static_cast<OffScreenWebContentsView*>(wc_impl->GetView());
return osr_wcv && osr_wcv->IsPainting();
const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
web_contents()->GetRenderWidgetHostView());
return osr_rwhv && osr_rwhv->IsPainting();
#else
return false;
#endif
@@ -1722,11 +1634,10 @@ void WebContents::SetFrameRate(int frame_rate) {
return;
#if defined(ENABLE_OSR)
const auto* wc_impl = static_cast<content::WebContentsImpl*>(web_contents());
auto* osr_wcv = static_cast<OffScreenWebContentsView*>(wc_impl->GetView());
if (osr_wcv)
osr_wcv->SetFrameRate(frame_rate);
auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
web_contents()->GetRenderWidgetHostView());
if (osr_rwhv)
osr_rwhv->SetFrameRate(frame_rate);
#endif
}
@@ -1735,10 +1646,9 @@ int WebContents::GetFrameRate() const {
return 0;
#if defined(ENABLE_OSR)
const auto* wc_impl = static_cast<content::WebContentsImpl*>(web_contents());
auto* osr_wcv = static_cast<OffScreenWebContentsView*>(wc_impl->GetView());
return osr_wcv ? osr_wcv->GetFrameRate() : 0;
const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
web_contents()->GetRenderWidgetHostView());
return osr_rwhv ? osr_rwhv->GetFrameRate() : 0;
#else
return 0;
#endif
@@ -1789,38 +1699,25 @@ double WebContents::GetZoomFactor() {
return content::ZoomLevelToZoomFactor(level);
}
void WebContents::OnSetTemporaryZoomLevel(content::RenderFrameHost* rfh,
double level,
void WebContents::OnSetTemporaryZoomLevel(double level,
IPC::Message* reply_msg) {
zoom_controller_->SetTemporaryZoomLevel(level);
double new_level = zoom_controller_->GetZoomLevel();
AtomFrameHostMsg_SetTemporaryZoomLevel::WriteReplyParams(reply_msg,
new_level);
rfh->Send(reply_msg);
AtomViewHostMsg_SetTemporaryZoomLevel::WriteReplyParams(reply_msg, new_level);
Send(reply_msg);
}
void WebContents::OnGetZoomLevel(content::RenderFrameHost* rfh,
IPC::Message* reply_msg) {
AtomFrameHostMsg_GetZoomLevel::WriteReplyParams(reply_msg, GetZoomLevel());
rfh->Send(reply_msg);
void WebContents::OnGetZoomLevel(IPC::Message* reply_msg) {
AtomViewHostMsg_GetZoomLevel::WriteReplyParams(reply_msg, GetZoomLevel());
Send(reply_msg);
}
v8::Local<v8::Value> WebContents::GetWebPreferences(v8::Isolate* isolate) {
WebContentsPreferences* web_preferences =
WebContentsPreferences::FromWebContents(web_contents());
if (!web_preferences)
return v8::Null(isolate);
return mate::ConvertToV8(isolate, *web_preferences->web_preferences());
}
v8::Local<v8::Value> WebContents::GetLastWebPreferences(v8::Isolate* isolate) {
WebContentsPreferences* web_preferences =
WebContentsPreferences::FromWebContents(web_contents());
if (!web_preferences)
return v8::Null(isolate);
return mate::ConvertToV8(isolate, *web_preferences->last_web_preferences());
}
v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow() {
if (owner_window())
return Window::From(isolate(), owner_window());
@@ -1861,21 +1758,6 @@ void WebContents::SetEmbedder(const WebContents* embedder) {
}
}
void WebContents::SetDevToolsWebContents(const WebContents* devtools) {
if (managed_web_contents())
managed_web_contents()->SetDevToolsWebContents(devtools->web_contents());
}
v8::Local<v8::Value> WebContents::GetNativeView() const {
gfx::NativeView ptr = web_contents()->GetNativeView();
auto buffer = node::Buffer::Copy(
isolate(), reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView));
if (buffer.IsEmpty())
return v8::Null(isolate());
else
return buffer.ToLocalChecked();
}
v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
if (devtools_web_contents_.IsEmpty())
return v8::Null(isolate);
@@ -1891,12 +1773,6 @@ v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
return v8::Local<v8::Value>::New(isolate, debugger_);
}
void WebContents::GrantOriginAccess(const GURL& url) {
content::ChildProcessSecurityPolicy::GetInstance()->GrantOrigin(
web_contents()->GetMainFrame()->GetProcess()->GetID(),
url::Origin(url));
}
// static
void WebContents::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
@@ -1957,7 +1833,9 @@ void WebContents::BuildPrototype(v8::Isolate* isolate,
.SetMethod("startDrag", &WebContents::StartDrag)
.SetMethod("setSize", &WebContents::SetSize)
.SetMethod("isGuest", &WebContents::IsGuest)
#if defined(ENABLE_OSR)
.SetMethod("isOffscreen", &WebContents::IsOffScreen)
#endif
.SetMethod("startPainting", &WebContents::StartPainting)
.SetMethod("stopPainting", &WebContents::StopPainting)
.SetMethod("isPainting", &WebContents::IsPainting)
@@ -1970,7 +1848,6 @@ void WebContents::BuildPrototype(v8::Isolate* isolate,
.SetMethod("_getZoomFactor", &WebContents::GetZoomFactor)
.SetMethod("getType", &WebContents::GetType)
.SetMethod("getWebPreferences", &WebContents::GetWebPreferences)
.SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
.SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
.SetMethod("hasServiceWorker", &WebContents::HasServiceWorker)
.SetMethod("unregisterServiceWorker",
@@ -1986,13 +1863,10 @@ void WebContents::BuildPrototype(v8::Isolate* isolate,
.SetMethod("copyImageAt", &WebContents::CopyImageAt)
.SetMethod("capturePage", &WebContents::CapturePage)
.SetMethod("setEmbedder", &WebContents::SetEmbedder)
.SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents)
.SetMethod("getNativeView", &WebContents::GetNativeView)
.SetMethod("setWebRTCIPHandlingPolicy",
&WebContents::SetWebRTCIPHandlingPolicy)
.SetMethod("getWebRTCIPHandlingPolicy",
&WebContents::GetWebRTCIPHandlingPolicy)
.SetMethod("_grantOriginAccess", &WebContents::GrantOriginAccess)
.SetProperty("id", &WebContents::ID)
.SetProperty("session", &WebContents::Session)
.SetProperty("hostWebContents", &WebContents::HostWebContents)
@@ -2004,19 +1878,17 @@ AtomBrowserContext* WebContents::GetBrowserContext() const {
return static_cast<AtomBrowserContext*>(web_contents()->GetBrowserContext());
}
void WebContents::OnRendererMessage(content::RenderFrameHost* frame_host,
const base::string16& channel,
void WebContents::OnRendererMessage(const base::string16& channel,
const base::ListValue& args) {
// webContents.emit(channel, new Event(), args...);
Emit(base::UTF16ToUTF8(channel), args);
}
void WebContents::OnRendererMessageSync(content::RenderFrameHost* frame_host,
const base::string16& channel,
void WebContents::OnRendererMessageSync(const base::string16& channel,
const base::ListValue& args,
IPC::Message* message) {
// webContents.emit(channel, new Event(sender, message), args...);
EmitWithSender(base::UTF16ToUTF8(channel), frame_host, message, args);
EmitWithSender(base::UTF16ToUTF8(channel), web_contents(), message, args);
}
// static

View File

@@ -14,8 +14,6 @@
#include "atom/browser/common_web_contents_delegate.h"
#include "atom/browser/ui/autofill_popup.h"
#include "content/common/cursors/webcursor.h"
#include "content/public/browser/keyboard_event_processing_result.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/favicon_url.h"
#include "native_mate/handle.h"
@@ -31,7 +29,7 @@ class InspectableWebContents;
}
namespace content {
class ResourceRequestBody;
class ResourceRequestBodyImpl;
}
namespace mate {
@@ -79,8 +77,6 @@ class WebContents : public mate::TrackableObject<WebContents>,
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
static int64_t GetIDForContents(content::WebContents* web_contents);
// Notifies to destroy any guest web contents before destroying self.
void DestroyWebContents(bool async);
@@ -119,8 +115,7 @@ class WebContents : public mate::TrackableObject<WebContents>,
void DisableDeviceEmulation();
void InspectElement(int x, int y);
void InspectServiceWorker();
void HasServiceWorker(
const base::Callback<void(bool)>&);
void HasServiceWorker(const base::Callback<void(bool)>&);
void UnregisterServiceWorker(const base::Callback<void(bool)>&);
void SetIgnoreMenuShortcuts(bool ignore);
void SetAudioMuted(bool muted);
@@ -128,8 +123,6 @@ class WebContents : public mate::TrackableObject<WebContents>,
void Print(mate::Arguments* args);
std::vector<printing::PrinterBasicInfo> GetPrinterList();
void SetEmbedder(const WebContents* embedder);
void SetDevToolsWebContents(const WebContents* devtools);
v8::Local<v8::Value> GetNativeView() const;
// Print current page as PDF.
void PrintToPDF(const base::DictionaryValue& setting,
@@ -186,6 +179,7 @@ class WebContents : public mate::TrackableObject<WebContents>,
// Methods for offscreen rendering
bool IsOffScreen() const;
bool IsOffScreenOrEmbedderOffscreen() const;
void OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap);
void StartPainting();
void StopPainting();
@@ -212,19 +206,14 @@ class WebContents : public mate::TrackableObject<WebContents>,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::vector<std::string>& features,
const scoped_refptr<content::ResourceRequestBody>& body);
const scoped_refptr<content::ResourceRequestBodyImpl>& body);
// Returns the web preferences of current WebContents.
v8::Local<v8::Value> GetWebPreferences(v8::Isolate* isolate);
v8::Local<v8::Value> GetLastWebPreferences(v8::Isolate* isolate);
// Returns the owner window.
v8::Local<v8::Value> GetOwnerBrowserWindow();
// Grants the child process the capability to access URLs with the origin of
// the specified URL.
void GrantOriginAccess(const GURL& url);
// Properties.
int32_t ID() const;
v8::Local<v8::Value> Session(v8::Isolate* isolate);
@@ -252,14 +241,12 @@ class WebContents : public mate::TrackableObject<WebContents>,
const base::string16& message,
int32_t line_no,
const base::string16& source_id) override;
void WebContentsCreated(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const std::string& frame_name,
const GURL& target_url,
content::WebContents* new_contents)
override;
void WebContentsCreated(content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const std::string& frame_name,
const GURL& target_url,
content::WebContents* new_contents) override;
void AddNewContents(content::WebContents* source,
content::WebContents* new_contents,
WindowOpenDisposition disposition,
@@ -281,9 +268,9 @@ class WebContents : public mate::TrackableObject<WebContents>,
void HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) override;
content::KeyboardEventProcessingResult PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) override;
bool PreHandleKeyboardEvent(content::WebContents* source,
const content::NativeWebKeyboardEvent& event,
bool* is_keyboard_shortcut) override;
void EnterFullscreenModeForTab(content::WebContents* source,
const GURL& origin) override;
void ExitFullscreenModeForTab(content::WebContents* source) override;
@@ -364,13 +351,7 @@ class WebContents : public mate::TrackableObject<WebContents>,
void DevToolsOpened() override;
void DevToolsClosed() override;
void ShowAutofillPopup(content::RenderFrameHost* frame_host,
const gfx::RectF& bounds,
const std::vector<base::string16>& values,
const std::vector<base::string16>& labels);
private:
struct FrameDispatchHelper;
AtomBrowserContext* GetBrowserContext() const;
uint32_t GetNextRequestId() {
@@ -381,29 +362,21 @@ class WebContents : public mate::TrackableObject<WebContents>,
void OnCursorChange(const content::WebCursor& cursor);
// Called when received a message from renderer.
void OnRendererMessage(content::RenderFrameHost* frame_host,
const base::string16& channel,
void OnRendererMessage(const base::string16& channel,
const base::ListValue& args);
// Called when received a synchronous message from renderer.
void OnRendererMessageSync(content::RenderFrameHost* frame_host,
const base::string16& channel,
void OnRendererMessageSync(const base::string16& channel,
const base::ListValue& args,
IPC::Message* message);
// Called when received a synchronous message from renderer to
// set temporary zoom level.
void OnSetTemporaryZoomLevel(content::RenderFrameHost* frame_host,
double level,
IPC::Message* reply_msg);
void OnSetTemporaryZoomLevel(double level, IPC::Message* reply_msg);
// Called when received a synchronous message from renderer to
// get the zoom level.
void OnGetZoomLevel(content::RenderFrameHost* frame_host,
IPC::Message* reply_msg);
void InitZoomController(content::WebContents* web_contents,
const mate::Dictionary& options);
void OnGetZoomLevel(IPC::Message* reply_msg);
v8::Global<v8::Value> session_;
v8::Global<v8::Value> devtools_web_contents_;

View File

@@ -37,26 +37,6 @@ namespace atom {
namespace api {
namespace {
template<typename Method, typename Event, typename Listener>
void CallNetworkDelegateMethod(
brightray::URLRequestContextGetter* url_request_context_getter,
Method method,
Event type,
URLPatterns patterns,
Listener listener) {
// Force creating network delegate.
net::URLRequestContext* context =
url_request_context_getter->GetURLRequestContext();
// Then call the method.
AtomNetworkDelegate* network_delegate =
static_cast<AtomNetworkDelegate*>(context->network_delegate());
(network_delegate->*method)(type, std::move(patterns), std::move(listener));
}
} // namespace
WebRequest::WebRequest(v8::Isolate* isolate,
AtomBrowserContext* browser_context)
: browser_context_(browser_context) {
@@ -94,15 +74,10 @@ void WebRequest::SetListener(Method method, Event type, mate::Arguments* args) {
return;
}
brightray::URLRequestContextGetter* url_request_context_getter =
browser_context_->url_request_context_getter();
if (!url_request_context_getter)
return;
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&CallNetworkDelegateMethod<Method, Event, Listener>,
base::RetainedRef(url_request_context_getter),
method, type, std::move(patterns), std::move(listener)));
auto delegate = browser_context_->network_delegate();
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(method, base::Unretained(delegate), type,
patterns, listener));
}
// static

View File

@@ -7,12 +7,10 @@
#include "atom/browser/web_view_manager.h"
#include "atom/common/native_mate_converters/content_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "content/public/browser/browser_context.h"
#include "native_mate/dictionary.h"
// Must be the last in the includes list.
// See https://github.com/electron/electron/issues/10363
#include "atom/common/node_includes.h"
using atom::WebContentsPreferences;

View File

@@ -3,6 +3,7 @@
// found in the LICENSE file.
#include "atom/browser/api/atom_api_window.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/browser/api/atom_api_browser_view.h"
#include "atom/browser/api/atom_api_menu.h"
@@ -16,7 +17,6 @@
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/threading/thread_task_runner_handle.h"
@@ -101,7 +101,7 @@ Window::Window(v8::Isolate* isolate, v8::Local<v8::Object> wrapper,
}
#endif
if (options.Get("webContents", &web_contents) && !web_contents.IsEmpty()) {
if (options.Get("webContents", &web_contents)) {
// Set webPreferences from options if using an existing webContents.
// These preferences will be used when the webContent launches new
// render processes.
@@ -135,7 +135,7 @@ void Window::Init(v8::Isolate* isolate,
// The parent window.
mate::Handle<Window> parent;
if (options.Get("parent", &parent) && !parent.IsEmpty())
if (options.Get("parent", &parent))
parent_window_.Reset(isolate, parent.ToV8());
// Creates BrowserWindow.
@@ -144,12 +144,11 @@ void Window::Init(v8::Isolate* isolate,
options,
parent.IsEmpty() ? nullptr : parent->window_.get()));
web_contents->SetOwnerWindow(window_.get());
window_->set_is_offscreen_dummy(api_web_contents_->IsOffScreen());
#if defined(TOOLKIT_VIEWS)
// Sets the window icon.
mate::Handle<NativeImage> icon;
if (options.Get(options::kIcon, &icon) && !icon.IsEmpty())
if (options.Get(options::kIcon, &icon))
SetIcon(icon);
#endif
@@ -184,7 +183,7 @@ void Window::WillDestroyNativeObject() {
v8::HandleScope handle_scope(isolate());
for (v8::Local<v8::Value> value : child_windows_.Values(isolate())) {
mate::Handle<Window> child;
if (mate::ConvertFromV8(isolate(), value, &child) && !child.IsEmpty())
if (mate::ConvertFromV8(isolate(), value, &child))
child->window_->CloseImmediately();
}
}
@@ -393,10 +392,6 @@ bool Window::IsEnabled() {
return window_->IsEnabled();
}
void Window::SetEnabled(bool enable) {
window_->SetEnabled(enable);
}
void Window::Maximize() {
window_->Maximize();
}
@@ -608,14 +603,6 @@ void Window::SetSkipTaskbar(bool skip) {
window_->SetSkipTaskbar(skip);
}
void Window::SetSimpleFullScreen(bool simple_fullscreen) {
window_->SetSimpleFullScreen(simple_fullscreen);
}
bool Window::IsSimpleFullScreen() {
return window_->IsSimpleFullScreen();
}
void Window::SetKiosk(bool kiosk) {
window_->SetKiosk(kiosk);
}
@@ -636,14 +623,6 @@ bool Window::HasShadow() {
return window_->HasShadow();
}
void Window::SetOpacity(const double opacity) {
window_->SetOpacity(opacity);
}
double Window::GetOpacity() {
return window_->GetOpacity();
}
void Window::FocusOnWebView() {
window_->FocusOnWebView();
}
@@ -672,11 +651,8 @@ bool Window::IsDocumentEdited() {
return window_->IsDocumentEdited();
}
void Window::SetIgnoreMouseEvents(bool ignore, mate::Arguments* args) {
mate::Dictionary options;
bool forward = false;
args->GetNext(&options) && options.Get("forward", &forward);
return window_->SetIgnoreMouseEvents(ignore, forward);
void Window::SetIgnoreMouseEvents(bool ignore) {
return window_->SetIgnoreMouseEvents(ignore);
}
void Window::SetContentProtection(bool enable) {
@@ -731,7 +707,7 @@ void Window::SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> value) {
mate::Handle<Menu> menu;
if (value->IsObject() &&
mate::V8ToString(value->ToObject()->GetConstructorName()) == "Menu" &&
mate::ConvertFromV8(isolate, value, &menu) && !menu.IsEmpty()) {
mate::ConvertFromV8(isolate, value, &menu)) {
menu_.Reset(isolate, menu.ToV8());
window_->SetMenu(menu->model());
} else if (value->IsNull()) {
@@ -851,7 +827,7 @@ void Window::SetParentWindow(v8::Local<v8::Value> value,
}
mate::Handle<Window> parent;
if (value->IsNull() || value->IsUndefined()) {
if (value->IsNull()) {
RemoveFromParentChildWindows();
parent_window_.Reset();
window_->SetParentWindow(nullptr);
@@ -887,14 +863,12 @@ void Window::SetBrowserView(v8::Local<v8::Value> value) {
ResetBrowserView();
mate::Handle<BrowserView> browser_view;
if (value->IsNull() || value->IsUndefined()) {
if (value->IsNull()) {
window_->SetBrowserView(nullptr);
} else if (mate::ConvertFromV8(isolate(), value, &browser_view)) {
window_->SetBrowserView(browser_view->view());
browser_view->web_contents()->SetOwnerWindow(window_.get());
browser_view_.Reset(isolate(), value);
window_->UpdateDraggableRegionViews();
}
}
@@ -904,8 +878,7 @@ void Window::ResetBrowserView() {
}
mate::Handle<BrowserView> browser_view;
if (mate::ConvertFromV8(isolate(), GetBrowserView(), &browser_view)
&& !browser_view.IsEmpty()) {
if (mate::ConvertFromV8(isolate(), GetBrowserView(), &browser_view)) {
browser_view->web_contents()->SetOwnerWindow(nullptr);
}
@@ -934,33 +907,6 @@ void Window::SetAutoHideCursor(bool auto_hide) {
window_->SetAutoHideCursor(auto_hide);
}
void Window::SelectPreviousTab() {
window_->SelectPreviousTab();
}
void Window::SelectNextTab() {
window_->SelectNextTab();
}
void Window::MergeAllWindows() {
window_->MergeAllWindows();
}
void Window::MoveTabToNewWindow() {
window_->MoveTabToNewWindow();
}
void Window::ToggleTabBar() {
window_->ToggleTabBar();
}
void Window::AddTabbedWindow(NativeWindow* window,
mate::Arguments* args) {
const bool windowAdded = window_->AddTabbedWindow(window);
if (!windowAdded)
args->ThrowError("AddTabbedWindow cannot be called by a window on itself.");
}
void Window::SetVibrancy(mate::Arguments* args) {
std::string type;
@@ -997,10 +943,8 @@ void Window::RemoveFromParentChildWindows() {
return;
mate::Handle<Window> parent;
if (!mate::ConvertFromV8(isolate(), GetParentWindow(), &parent)
|| parent.IsEmpty()) {
if (!mate::ConvertFromV8(isolate(), GetParentWindow(), &parent))
return;
}
parent->child_windows_.Remove(ID());
}
@@ -1020,7 +964,6 @@ void Window::BuildPrototype(v8::Isolate* isolate,
.SetMethod("hide", &Window::Hide)
.SetMethod("isVisible", &Window::IsVisible)
.SetMethod("isEnabled", &Window::IsEnabled)
.SetMethod("setEnabled", & Window::SetEnabled)
.SetMethod("maximize", &Window::Maximize)
.SetMethod("unmaximize", &Window::Unmaximize)
.SetMethod("isMaximized", &Window::IsMaximized)
@@ -1075,15 +1018,11 @@ void Window::BuildPrototype(v8::Isolate* isolate,
.SetMethod("getTitle", &Window::GetTitle)
.SetMethod("flashFrame", &Window::FlashFrame)
.SetMethod("setSkipTaskbar", &Window::SetSkipTaskbar)
.SetMethod("setSimpleFullScreen", &Window::SetSimpleFullScreen)
.SetMethod("isSimpleFullScreen", &Window::IsSimpleFullScreen)
.SetMethod("setKiosk", &Window::SetKiosk)
.SetMethod("isKiosk", &Window::IsKiosk)
.SetMethod("setBackgroundColor", &Window::SetBackgroundColor)
.SetMethod("setHasShadow", &Window::SetHasShadow)
.SetMethod("hasShadow", &Window::HasShadow)
.SetMethod("setOpacity", &Window::SetOpacity)
.SetMethod("getOpacity", &Window::GetOpacity)
.SetMethod("setRepresentedFilename", &Window::SetRepresentedFilename)
.SetMethod("getRepresentedFilename", &Window::GetRepresentedFilename)
.SetMethod("setDocumentEdited", &Window::SetDocumentEdited)
@@ -1108,12 +1047,6 @@ void Window::BuildPrototype(v8::Isolate* isolate,
&Window::IsVisibleOnAllWorkspaces)
#if defined(OS_MACOSX)
.SetMethod("setAutoHideCursor", &Window::SetAutoHideCursor)
.SetMethod("mergeAllWindows", &Window::MergeAllWindows)
.SetMethod("selectPreviousTab", &Window::SelectPreviousTab)
.SetMethod("selectNextTab", &Window::SelectNextTab)
.SetMethod("moveTabToNewWindow", &Window::MoveTabToNewWindow)
.SetMethod("toggleTabBar", &Window::ToggleTabBar)
.SetMethod("addTabbedWindow", &Window::AddTabbedWindow)
#endif
.SetMethod("setVibrancy", &Window::SetVibrancy)
.SetMethod("_setTouchBarItems", &Window::SetTouchBar)

View File

@@ -112,7 +112,6 @@ class Window : public mate::TrackableObject<Window>,
void Hide();
bool IsVisible();
bool IsEnabled();
void SetEnabled(bool enable);
void Maximize();
void Unmaximize();
bool IsMaximized();
@@ -155,15 +154,11 @@ class Window : public mate::TrackableObject<Window>,
std::string GetTitle();
void FlashFrame(bool flash);
void SetSkipTaskbar(bool skip);
void SetSimpleFullScreen(bool simple_fullscreen);
bool IsSimpleFullScreen();
void SetKiosk(bool kiosk);
bool IsKiosk();
void SetBackgroundColor(const std::string& color_name);
void SetHasShadow(bool has_shadow);
bool HasShadow();
void SetOpacity(const double opacity);
double GetOpacity();
void FocusOnWebView();
void BlurWebView();
bool IsWebViewFocused();
@@ -171,7 +166,7 @@ class Window : public mate::TrackableObject<Window>,
std::string GetRepresentedFilename();
void SetDocumentEdited(bool edited);
bool IsDocumentEdited();
void SetIgnoreMouseEvents(bool ignore, mate::Arguments* args);
void SetIgnoreMouseEvents(bool ignore);
void SetContentProtection(bool enable);
void SetFocusable(bool focusable);
void SetProgressBar(double progress, mate::Arguments* args);
@@ -217,13 +212,6 @@ class Window : public mate::TrackableObject<Window>,
void SetAutoHideCursor(bool auto_hide);
void SelectPreviousTab();
void SelectNextTab();
void MergeAllWindows();
void MoveTabToNewWindow();
void ToggleTabBar();
void AddTabbedWindow(NativeWindow* window, mate::Arguments* args);
void SetVibrancy(mate::Arguments* args);
void SetTouchBar(const std::vector<mate::PersistentDictionary>& items);
void RefreshTouchBarItem(const std::string& item_id);

View File

@@ -6,7 +6,6 @@
#include "atom/common/api/api_messages.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "native_mate/object_template_builder.h"
@@ -21,32 +20,17 @@ Event::Event(v8::Isolate* isolate)
Event::~Event() {
}
void Event::SetSenderAndMessage(content::RenderFrameHost* sender,
void Event::SetSenderAndMessage(content::WebContents* sender,
IPC::Message* message) {
DCHECK(!sender_);
DCHECK(!message_);
sender_ = sender;
message_ = message;
Observe(content::WebContents::FromRenderFrameHost(sender));
Observe(sender);
}
void Event::RenderFrameDeleted(content::RenderFrameHost* rfh) {
if (sender_ != rfh)
return;
sender_ = nullptr;
message_ = nullptr;
}
void Event::RenderFrameHostChanged(content::RenderFrameHost* old_rfh,
content::RenderFrameHost* new_rfh) {
if (sender_ && sender_ == old_rfh)
sender_ = new_rfh;
}
void Event::FrameDeleted(content::RenderFrameHost* rfh) {
if (sender_ != rfh)
return;
void Event::WebContentsDestroyed() {
sender_ = nullptr;
message_ = nullptr;
}
@@ -60,7 +44,7 @@ bool Event::SendReply(const base::string16& json) {
if (message_ == nullptr || sender_ == nullptr)
return false;
AtomFrameHostMsg_Message_Sync::WriteReplyParams(message_, json);
AtomViewHostMsg_Message_Sync::WriteReplyParams(message_, json);
bool success = sender_->Send(message_);
message_ = nullptr;
sender_ = nullptr;

View File

@@ -24,8 +24,7 @@ class Event : public Wrappable<Event>,
v8::Local<v8::FunctionTemplate> prototype);
// Pass the sender and message to be replied.
void SetSenderAndMessage(content::RenderFrameHost* sender,
IPC::Message* message);
void SetSenderAndMessage(content::WebContents* sender, IPC::Message* message);
// event.PreventDefault().
void PreventDefault(v8::Isolate* isolate);
@@ -38,14 +37,11 @@ class Event : public Wrappable<Event>,
~Event() override;
// content::WebContentsObserver implementations:
void RenderFrameDeleted(content::RenderFrameHost* rfh) override;
void RenderFrameHostChanged(content::RenderFrameHost* old_rfh,
content::RenderFrameHost* new_rfh) override;
void FrameDeleted(content::RenderFrameHost* rfh) override;
void WebContentsDestroyed() override;
private:
// Replyer for the synchronous messages.
content::RenderFrameHost* sender_;
content::WebContents* sender_;
IPC::Message* message_;
DISALLOW_COPY_AND_ASSIGN(Event);

View File

@@ -39,10 +39,11 @@ v8::Local<v8::Object> CreateEventObject(v8::Isolate* isolate) {
namespace internal {
v8::Local<v8::Object> CreateJSEvent(v8::Isolate* isolate,
v8::Local<v8::Object> object,
content::RenderFrameHost* sender,
IPC::Message* message) {
v8::Local<v8::Object> CreateJSEvent(
v8::Isolate* isolate,
v8::Local<v8::Object> object,
content::WebContents* sender,
IPC::Message* message) {
v8::Local<v8::Object> event;
bool use_native_event = sender && message;

View File

@@ -11,7 +11,7 @@
#include "native_mate/wrappable.h"
namespace content {
class RenderFrameHost;
class WebContents;
}
namespace IPC {
@@ -24,7 +24,7 @@ namespace internal {
v8::Local<v8::Object> CreateJSEvent(v8::Isolate* isolate,
v8::Local<v8::Object> object,
content::RenderFrameHost* sender,
content::WebContents* sender,
IPC::Message* message);
v8::Local<v8::Object> CreateCustomEvent(
v8::Isolate* isolate,
@@ -42,10 +42,8 @@ class EventEmitter : public Wrappable<T> {
// Make the convinient methods visible:
// https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-members
v8::Local<v8::Object> GetWrapper() { return Wrappable<T>::GetWrapper(); }
v8::Isolate* isolate() const { return Wrappable<T>::isolate(); }
v8::Local<v8::Object> GetWrapper() const {
return Wrappable<T>::GetWrapper();
}
// this.emit(name, event, args...);
template<typename... Args>
@@ -74,19 +72,15 @@ class EventEmitter : public Wrappable<T> {
}
// this.emit(name, new Event(sender, message), args...);
template <typename... Args>
template<typename... Args>
bool EmitWithSender(const base::StringPiece& name,
content::RenderFrameHost* sender,
content::WebContents* sender,
IPC::Message* message,
const Args&... args) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
v8::Local<v8::Object> wrapper = GetWrapper();
if (wrapper.IsEmpty()) {
return false;
}
v8::Local<v8::Object> event = internal::CreateJSEvent(
isolate(), wrapper, sender, message);
isolate(), GetWrapper(), sender, message);
return EmitWithEvent(name, event, args...);
}

View File

@@ -1,121 +0,0 @@
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <string>
#include "atom/browser/api/event_subscriber.h"
#include "atom/common/native_mate_converters/callback.h"
namespace {
// A FunctionTemplate lifetime is bound to the v8 context, so it can be safely
// stored as a global here since there's only one for the main process.
v8::Global<v8::FunctionTemplate> g_cached_template;
struct JSHandlerData {
JSHandlerData(v8::Isolate* isolate,
mate::internal::EventSubscriberBase* subscriber)
: handle_(isolate, v8::External::New(isolate, this)),
subscriber_(subscriber) {
handle_.SetWeak(this, GC, v8::WeakCallbackType::kFinalizer);
}
static void GC(const v8::WeakCallbackInfo<JSHandlerData>& data) {
delete data.GetParameter();
}
v8::Global<v8::External> handle_;
mate::internal::EventSubscriberBase* subscriber_;
};
void InvokeCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Locker locker(info.GetIsolate());
v8::HandleScope handle_scope(info.GetIsolate());
v8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext();
v8::Context::Scope context_scope(context);
mate::Arguments args(info);
v8::Local<v8::Value> handler, event;
args.GetNext(&handler);
args.GetNext(&event);
DCHECK(handler->IsExternal());
DCHECK(event->IsString());
JSHandlerData* handler_data = static_cast<JSHandlerData*>(
v8::Local<v8::External>::Cast(handler)->Value());
handler_data->subscriber_->EventEmitted(mate::V8ToString(event), &args);
}
} // namespace
namespace mate {
namespace internal {
EventSubscriberBase::EventSubscriberBase(v8::Isolate* isolate,
v8::Local<v8::Object> emitter)
: isolate_(isolate), emitter_(isolate, emitter) {
if (g_cached_template.IsEmpty()) {
g_cached_template = v8::Global<v8::FunctionTemplate>(
isolate_, v8::FunctionTemplate::New(isolate_, InvokeCallback));
}
}
EventSubscriberBase::~EventSubscriberBase() {
if (!isolate_) {
return;
}
RemoveAllListeners();
emitter_.Reset();
DCHECK_EQ(js_handlers_.size(), 0u);
}
void EventSubscriberBase::On(const std::string& event_name) {
DCHECK(js_handlers_.find(event_name) == js_handlers_.end());
v8::Locker locker(isolate_);
v8::Isolate::Scope isolate_scope(isolate_);
v8::HandleScope handle_scope(isolate_);
auto fn_template = g_cached_template.Get(isolate_);
auto event = mate::StringToV8(isolate_, event_name);
auto js_handler_data = new JSHandlerData(isolate_, this);
v8::Local<v8::Value> fn = internal::BindFunctionWith(
isolate_, isolate_->GetCurrentContext(), fn_template->GetFunction(),
js_handler_data->handle_.Get(isolate_), event);
js_handlers_.insert(
std::make_pair(event_name, v8::Global<v8::Value>(isolate_, fn)));
internal::ValueVector converted_args = {event, fn};
internal::CallMethodWithArgs(isolate_, emitter_.Get(isolate_), "on",
&converted_args);
}
void EventSubscriberBase::Off(const std::string& event_name) {
v8::Locker locker(isolate_);
v8::Isolate::Scope isolate_scope(isolate_);
v8::HandleScope handle_scope(isolate_);
auto js_handler = js_handlers_.find(event_name);
DCHECK(js_handler != js_handlers_.end());
RemoveListener(js_handler);
}
void EventSubscriberBase::RemoveAllListeners() {
v8::Locker locker(isolate_);
v8::Isolate::Scope isolate_scope(isolate_);
v8::HandleScope handle_scope(isolate_);
while (!js_handlers_.empty()) {
RemoveListener(js_handlers_.begin());
}
}
std::map<std::string, v8::Global<v8::Value>>::iterator
EventSubscriberBase::RemoveListener(
std::map<std::string, v8::Global<v8::Value>>::iterator it) {
internal::ValueVector args = {StringToV8(isolate_, it->first),
it->second.Get(isolate_)};
internal::CallMethodWithArgs(
isolate_, v8::Local<v8::Object>::Cast(emitter_.Get(isolate_)),
"removeListener", &args);
it->second.Reset();
return js_handlers_.erase(it);
}
} // namespace internal
} // namespace mate

View File

@@ -1,139 +0,0 @@
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_EVENT_SUBSCRIBER_H_
#define ATOM_BROWSER_API_EVENT_SUBSCRIBER_H_
#include <map>
#include <string>
#include "atom/common/api/event_emitter_caller.h"
#include "base/synchronization/lock.h"
#include "content/public/browser/browser_thread.h"
#include "native_mate/native_mate/arguments.h"
namespace mate {
namespace internal {
class EventSubscriberBase {
public:
EventSubscriberBase(v8::Isolate* isolate, v8::Local<v8::Object> emitter);
virtual ~EventSubscriberBase();
virtual void EventEmitted(const std::string& event_name,
mate::Arguments* args) = 0;
protected:
void On(const std::string& event_name);
void Off(const std::string& event_name);
void RemoveAllListeners();
private:
std::map<std::string, v8::Global<v8::Value>>::iterator RemoveListener(
std::map<std::string, v8::Global<v8::Value>>::iterator it);
v8::Isolate* isolate_;
v8::Global<v8::Object> emitter_;
std::map<std::string, v8::Global<v8::Value>> js_handlers_;
DISALLOW_COPY_AND_ASSIGN(EventSubscriberBase);
};
} // namespace internal
template <typename HandlerType>
class EventSubscriber : internal::EventSubscriberBase {
public:
using EventCallback = void (HandlerType::*)(mate::Arguments* args);
// Alias to unique_ptr with deleter.
using unique_ptr = std::unique_ptr<EventSubscriber<HandlerType>,
void (*)(EventSubscriber<HandlerType>*)>;
// EventSubscriber should only be created/deleted in the main thread since it
// communicates with the V8 engine. This smart pointer makes it simpler to
// bind the lifetime of EventSubscriber with a class whose lifetime is managed
// by a non-UI thread.
class SafePtr : public unique_ptr {
public:
SafePtr() : SafePtr(nullptr) {}
explicit SafePtr(EventSubscriber<HandlerType>* ptr)
: unique_ptr(ptr, Deleter) {}
private:
// Custom deleter that schedules destructor invocation to the main thread.
static void Deleter(EventSubscriber<HandlerType>* ptr) {
DCHECK(
!::content::BrowserThread::CurrentlyOn(::content::BrowserThread::UI));
DCHECK(ptr);
// Acquire handler lock and reset handler_ to ensure that any new events
// emitted will be ignored after this function returns
base::AutoLock auto_lock(ptr->handler_lock_);
ptr->handler_ = nullptr;
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(
[](EventSubscriber<HandlerType>* subscriber) {
{
// It is possible that this function will execute in the UI
// thread before the outer function has returned and destroyed
// its auto_lock. We need to acquire the lock before deleting
// or risk a crash.
base::AutoLock auto_lock(subscriber->handler_lock_);
}
delete subscriber;
},
ptr));
}
};
EventSubscriber(HandlerType* handler,
v8::Isolate* isolate,
v8::Local<v8::Object> emitter)
: EventSubscriberBase(isolate, emitter), handler_(handler) {
DCHECK_CURRENTLY_ON(::content::BrowserThread::UI);
}
void On(const std::string& event, EventCallback callback) {
DCHECK_CURRENTLY_ON(::content::BrowserThread::UI);
EventSubscriberBase::On(event);
callbacks_.insert(std::make_pair(event, callback));
}
void Off(const std::string& event) {
DCHECK_CURRENTLY_ON(::content::BrowserThread::UI);
EventSubscriberBase::Off(event);
DCHECK(callbacks_.find(event) != callbacks_.end());
callbacks_.erase(callbacks_.find(event));
}
void RemoveAllListeners() {
DCHECK_CURRENTLY_ON(::content::BrowserThread::UI);
EventSubscriberBase::RemoveAllListeners();
callbacks_.clear();
}
private:
void EventEmitted(const std::string& event_name,
mate::Arguments* args) override {
DCHECK_CURRENTLY_ON(::content::BrowserThread::UI);
base::AutoLock auto_lock(handler_lock_);
if (!handler_) {
// handler_ was probably destroyed by another thread and we should not
// access it.
return;
}
auto it = callbacks_.find(event_name);
if (it != callbacks_.end()) {
auto method = it->second;
(handler_->*method)(args);
}
}
HandlerType* handler_;
base::Lock handler_lock_;
std::map<std::string, EventCallback> callbacks_;
};
} // namespace mate
#endif // ATOM_BROWSER_API_EVENT_SUBSCRIBER_H_

View File

@@ -45,9 +45,9 @@ bool FrameSubscriber::ShouldCaptureFrame(
gfx::Size view_size = rect.size();
gfx::Size bitmap_size = view_size;
gfx::NativeView native_view = view_->GetNativeView();
const gfx::NativeView native_view = view_->GetNativeView();
const float scale =
display::Screen::GetScreen()->GetDisplayNearestView(native_view)
display::Screen::GetScreen()->GetDisplayNearestWindow(native_view)
.device_scale_factor();
if (scale > 1.0f)
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
@@ -78,31 +78,20 @@ void FrameSubscriber::OnFrameDelivered(const FrameCaptureCallback& callback,
v8::Locker locker(isolate_);
v8::HandleScope handle_scope(isolate_);
size_t rgb_row_size = bitmap.width() * bitmap.bytesPerPixel();
v8::MaybeLocal<v8::Object> buffer =
node::Buffer::New(isolate_, rgb_row_size * bitmap.height());
size_t rgb_arr_size = bitmap.width() * bitmap.height() *
bitmap.bytesPerPixel();
v8::MaybeLocal<v8::Object> buffer = node::Buffer::New(isolate_, rgb_arr_size);
if (buffer.IsEmpty())
return;
auto local_buffer = buffer.ToLocalChecked();
{
auto source = static_cast<const unsigned char*>(bitmap.getPixels());
auto target = node::Buffer::Data(local_buffer);
for (int y = 0; y < bitmap.height(); ++y) {
memcpy(target, source, rgb_row_size);
source += bitmap.rowBytes();
target += rgb_row_size;
}
}
bitmap.copyPixelsTo(
reinterpret_cast<uint8_t*>(node::Buffer::Data(buffer.ToLocalChecked())),
rgb_arr_size);
v8::Local<v8::Value> damage =
mate::Converter<gfx::Rect>::ToV8(isolate_, damage_rect);
callback_.Run(local_buffer, damage);
callback_.Run(buffer.ToLocalChecked(), damage);
}
} // namespace api

View File

@@ -6,7 +6,6 @@
#include "atom/browser/atom_browser_main_parts.h"
#include "base/bind.h"
#include "base/memory/ptr_util.h"
#include "base/supports_user_data.h"
namespace mate {
@@ -47,19 +46,16 @@ void TrackableObjectBase::Destroy() {
}
void TrackableObjectBase::AttachAsUserData(base::SupportsUserData* wrapped) {
wrapped->SetUserData(kTrackedObjectKey,
base::MakeUnique<IDUserData>(weak_map_id_));
wrapped->SetUserData(kTrackedObjectKey, new IDUserData(weak_map_id_));
}
// static
int32_t TrackableObjectBase::GetIDFromWrappedClass(
base::SupportsUserData* wrapped) {
if (wrapped) {
auto id = static_cast<IDUserData*>(wrapped->GetUserData(kTrackedObjectKey));
if (id)
return *id;
}
return 0;
int32_t TrackableObjectBase::GetIDFromWrappedClass(base::SupportsUserData* w) {
auto id = static_cast<IDUserData*>(w->GetUserData(kTrackedObjectKey));
if (id)
return *id;
else
return 0;
}
// static

View File

@@ -30,15 +30,15 @@ class TrackableObjectBase {
// Wrap TrackableObject into a class that SupportsUserData.
void AttachAsUserData(base::SupportsUserData* wrapped);
// Get the weak_map_id from SupportsUserData.
static int32_t GetIDFromWrappedClass(base::SupportsUserData* wrapped);
protected:
virtual ~TrackableObjectBase();
// Returns a closure that can destroy the native class.
base::Closure GetDestroyClosure();
// Get the weak_map_id from SupportsUserData.
static int32_t GetIDFromWrappedClass(base::SupportsUserData* wrapped);
// Register a callback that should be destroyed before JavaScript environment
// gets destroyed.
static base::Closure RegisterDestructionCallback(const base::Closure& c);
@@ -62,10 +62,7 @@ class TrackableObject : public TrackableObjectBase,
public:
// Mark the JS object as destroyed.
void MarkDestroyed() {
v8::Local<v8::Object> wrapper = Wrappable<T>::GetWrapper();
if (!wrapper.IsEmpty()) {
wrapper->SetAlignedPointerInInternalField(0, nullptr);
}
Wrappable<T>::GetWrapper()->SetAlignedPointerInInternalField(0, nullptr);
}
bool IsDestroyed() {

View File

@@ -29,7 +29,8 @@ class GeoURLRequestContextGetter : public net::URLRequestContextGetter {
net::URLRequestContextBuilder builder;
builder.set_proxy_config_service(
net::ProxyService::CreateSystemProxyConfigService(
BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)));
BrowserThread::GetTaskRunnerForThread(BrowserThread::IO),
BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE)));
url_request_context_ = builder.Build();
}
return url_request_context_.get();
@@ -54,6 +55,7 @@ class GeoURLRequestContextGetter : public net::URLRequestContextGetter {
AtomAccessTokenStore::AtomAccessTokenStore()
: request_context_getter_(new internal::GeoURLRequestContextGetter) {
device::GeolocationProvider::GetInstance()->UserDidOptIntoLocationServices();
}
AtomAccessTokenStore::~AtomAccessTokenStore() {

View File

@@ -72,7 +72,8 @@ void AtomBlobReader::StartReading(
}
auto blob_reader = blob_data_handle->CreateReader(
file_system_context_.get());
file_system_context_.get(),
BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE).get());
BlobReadHelper* blob_read_helper =
new BlobReadHelper(std::move(blob_reader), callback);
blob_read_helper->Read();

View File

@@ -10,7 +10,6 @@
#include "atom/browser/api/atom_api_app.h"
#include "atom/browser/api/atom_api_protocol.h"
#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/atom_quota_permission_context.h"
@@ -18,13 +17,13 @@
#include "atom/browser/atom_speech_recognition_manager_delegate.h"
#include "atom/browser/child_web_contents_tracker.h"
#include "atom/browser/native_window.h"
#include "atom/browser/session_preferences.h"
#include "atom/browser/web_contents_permission_helper.h"
#include "atom/browser/web_contents_preferences.h"
#include "atom/browser/window_list.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/path_service.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
@@ -32,6 +31,7 @@
#include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
#include "chrome/browser/renderer_host/pepper/widevine_cdm_message_filter.h"
#include "chrome/browser/speech/tts_message_filter.h"
#include "content/common/resource_request_body_impl.h"
#include "content/public/browser/browser_ppapi_host.h"
#include "content/public/browser/client_certificate_delegate.h"
#include "content/public/browser/render_process_host.h"
@@ -41,7 +41,6 @@
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/resource_request_body.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/web_preferences.h"
#include "net/ssl/ssl_cert_request_info.h"
@@ -168,14 +167,11 @@ void AtomBrowserClient::RenderProcessWillLaunch(
content::WebContents* web_contents = GetWebContentsFromProcessID(process_id);
ProcessPreferences process_prefs;
process_prefs.sandbox =
WebContentsPreferences::IsPreferenceEnabled("sandbox", web_contents);
process_prefs.native_window_open =
WebContentsPreferences::IsPreferenceEnabled("nativeWindowOpen",
web_contents);
process_prefs.disable_popups =
WebContentsPreferences::IsPreferenceEnabled("disablePopups",
web_contents);
process_prefs.sandbox = WebContentsPreferences::IsSandboxed(web_contents);
process_prefs.native_window_open
= WebContentsPreferences::UsesNativeWindowOpen(web_contents);
process_prefs.disable_popups
= WebContentsPreferences::DisablePopups(web_contents);
AddProcessPreferences(host->GetID(), process_prefs);
// ensure the ProcessPreferences is removed later
host->AddObserver(this);
@@ -190,6 +186,7 @@ void AtomBrowserClient::OverrideWebkitPrefs(
content::RenderViewHost* host, content::WebPreferences* prefs) {
prefs->javascript_enabled = true;
prefs->web_security_enabled = true;
prefs->javascript_can_open_windows_automatically = true;
prefs->plugins_enabled = true;
prefs->dom_paste_enabled = true;
prefs->allow_scripts_to_close_windows = true;
@@ -207,8 +204,12 @@ void AtomBrowserClient::OverrideWebkitPrefs(
WebContentsPreferences::OverrideWebkitPrefs(web_contents, prefs);
}
std::string AtomBrowserClient::GetApplicationLocale() {
return l10n_util::GetApplicationLocale("");
}
void AtomBrowserClient::OverrideSiteInstanceForNavigation(
content::RenderFrameHost* rfh,
content::RenderFrameHost* render_frame_host,
content::BrowserContext* browser_context,
content::SiteInstance* current_instance,
const GURL& url,
@@ -218,66 +219,36 @@ void AtomBrowserClient::OverrideSiteInstanceForNavigation(
return;
}
if (!ShouldCreateNewSiteInstance(rfh, browser_context, current_instance, url))
if (!ShouldCreateNewSiteInstance(render_frame_host, browser_context,
current_instance, url))
return;
bool is_new_instance = true;
scoped_refptr<content::SiteInstance> site_instance;
// Do we have an affinity site to manage ?
std::string affinity;
auto* web_contents = content::WebContents::FromRenderFrameHost(rfh);
auto* web_preferences = web_contents ?
WebContentsPreferences::FromWebContents(web_contents) : nullptr;
if (web_preferences &&
web_preferences->web_preferences()->GetString("affinity", &affinity) &&
!affinity.empty()) {
affinity = base::ToLowerASCII(affinity);
auto iter = site_per_affinities.find(affinity);
if (iter != site_per_affinities.end()) {
site_instance = iter->second;
is_new_instance = false;
} else {
// We must not provide the url.
// This site is "isolated" and must not be taken into account
// when Chromium looking at a candidate for an url.
site_instance = content::SiteInstance::Create(
browser_context);
site_per_affinities[affinity] = site_instance.get();
}
} else {
site_instance = content::SiteInstance::CreateForURL(
browser_context,
url);
}
scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(browser_context, url);
*new_instance = site_instance.get();
if (is_new_instance) {
// Make sure the |site_instance| is not freed
// when this function returns.
// FIXME(zcbenz): We should adjust
// OverrideSiteInstanceForNavigation's interface to solve this.
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(&Noop, base::RetainedRef(site_instance)));
// Make sure the |site_instance| is not freed when this function returns.
// FIXME(zcbenz): We should adjust OverrideSiteInstanceForNavigation's
// interface to solve this.
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(&Noop, base::RetainedRef(site_instance)));
// Remember the original web contents for the pending renderer process.
auto pending_process = site_instance->GetProcess();
pending_processes_[pending_process->GetID()] = web_contents;
}
// Remember the original web contents for the pending renderer process.
auto pending_process = (*new_instance)->GetProcess();
pending_processes_[pending_process->GetID()] =
content::WebContents::FromRenderFrameHost(render_frame_host);;
// Clear the entry in map when process ends.
pending_process->AddObserver(this);
}
void AtomBrowserClient::AppendExtraCommandLineSwitches(
base::CommandLine* command_line,
int process_id) {
// Make sure we're about to launch a known executable
{
base::FilePath child_path;
PathService::Get(content::CHILD_PROCESS_EXE, &child_path);
base::ThreadRestrictions::ScopedAllowIO allow_io;
CHECK(base::MakeAbsoluteFilePath(command_line->GetProgram()) == child_path);
}
base::FilePath child_path;
PathService::Get(content::CHILD_PROCESS_EXE, &child_path);
CHECK(base::MakeAbsoluteFilePath(command_line->GetProgram()) == child_path);
std::string process_type =
command_line->GetSwitchValueASCII(::switches::kProcessType);
@@ -314,17 +285,9 @@ void AtomBrowserClient::AppendExtraCommandLineSwitches(
}
content::WebContents* web_contents = GetWebContentsFromProcessID(process_id);
if (web_contents) {
if (web_contents)
WebContentsPreferences::AppendExtraCommandLineSwitches(
web_contents, command_line);
SessionPreferences::AppendExtraCommandLineSwitches(
web_contents->GetBrowserContext(), command_line);
auto context_id = atom::api::WebContents::GetIDForContents(
web_contents);
command_line->AppendSwitchASCII(switches::kContextId,
base::IntToString(context_id));
}
}
void AtomBrowserClient::DidCreatePpapiPlugin(
@@ -360,12 +323,10 @@ void AtomBrowserClient::AllowCertificateError(
void AtomBrowserClient::SelectClientCertificate(
content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info,
net::ClientCertIdentityList client_certs,
std::unique_ptr<content::ClientCertificateDelegate> delegate) {
if (!client_certs.empty() && delegate_) {
delegate_->SelectClientCertificate(web_contents, cert_request_info,
std::move(client_certs),
std::move(delegate));
if (!cert_request_info->client_certs.empty() && delegate_) {
delegate_->SelectClientCertificate(
web_contents, cert_request_info, std::move(delegate));
}
}
@@ -377,7 +338,8 @@ void AtomBrowserClient::ResourceDispatcherHostCreated() {
}
bool AtomBrowserClient::CanCreateWindow(
content::RenderFrameHost* opener,
int opener_render_process_id,
int opener_render_frame_id,
const GURL& opener_url,
const GURL& opener_top_level_frame_url,
const GURL& source_origin,
@@ -388,13 +350,12 @@ bool AtomBrowserClient::CanCreateWindow(
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& features,
const std::vector<std::string>& additional_features,
const scoped_refptr<content::ResourceRequestBody>& body,
const scoped_refptr<content::ResourceRequestBodyImpl>& body,
bool user_gesture,
bool opener_suppressed,
content::ResourceContext* context,
bool* no_javascript_access) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
int opener_render_process_id = opener->GetProcess()->GetID();
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (IsRendererSandboxed(opener_render_process_id)) {
*no_javascript_access = false;
@@ -413,11 +374,16 @@ bool AtomBrowserClient::CanCreateWindow(
}
if (delegate_) {
return delegate_->CanCreateWindow(
opener, opener_url, opener_top_level_frame_url, source_origin,
container_type, target_url, referrer, frame_name, disposition, features,
additional_features, body, user_gesture, opener_suppressed,
no_javascript_access);
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(&api::App::OnCreateWindow,
base::Unretained(static_cast<api::App*>(delegate_)),
target_url,
frame_name,
disposition,
additional_features,
body,
opener_render_process_id,
opener_render_frame_id));
}
return false;
@@ -433,21 +399,9 @@ void AtomBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
additional_schemes->push_back(content::kChromeDevToolsScheme);
}
void AtomBrowserClient::SiteInstanceDeleting(
content::SiteInstance* site_instance) {
// We are storing weak_ptr, is it fundamental to maintain the map up-to-date
// when an instance is destroyed.
for (auto iter = site_per_affinities.begin();
iter != site_per_affinities.end(); ++iter) {
if (iter->second == site_instance) {
site_per_affinities.erase(iter);
break;
}
}
}
brightray::BrowserMainParts* AtomBrowserClient::OverrideCreateBrowserMainParts(
const content::MainFunctionParams&) {
v8::V8::Initialize(); // Init V8 before creating main parts.
return new AtomBrowserMainParts;
}

View File

@@ -12,7 +12,6 @@
#include "brightray/browser/browser_client.h"
#include "content/public/browser/render_process_host_observer.h"
#include "net/ssl/client_cert_identity.h"
namespace content {
class QuotaPermissionContext;
@@ -53,6 +52,7 @@ class AtomBrowserClient : public brightray::BrowserClient,
CreateSpeechRecognitionManagerDelegate() override;
void OverrideWebkitPrefs(content::RenderViewHost* render_view_host,
content::WebPreferences* prefs) override;
std::string GetApplicationLocale() override;
void OverrideSiteInstanceForNavigation(
content::RenderFrameHost* render_frame_host,
content::BrowserContext* browser_context,
@@ -77,11 +77,11 @@ class AtomBrowserClient : public brightray::BrowserClient,
void SelectClientCertificate(
content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info,
net::ClientCertIdentityList client_certs,
std::unique_ptr<content::ClientCertificateDelegate> delegate) override;
void ResourceDispatcherHostCreated() override;
bool CanCreateWindow(
content::RenderFrameHost* opener,
int opener_render_process_id,
int opener_render_frame_id,
const GURL& opener_url,
const GURL& opener_top_level_frame_url,
const GURL& source_origin,
@@ -92,13 +92,13 @@ class AtomBrowserClient : public brightray::BrowserClient,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& features,
const std::vector<std::string>& additional_features,
const scoped_refptr<content::ResourceRequestBody>& body,
const scoped_refptr<content::ResourceRequestBodyImpl>& body,
bool user_gesture,
bool opener_suppressed,
content::ResourceContext* context,
bool* no_javascript_access) override;
void GetAdditionalAllowedSchemesForFileSystem(
std::vector<std::string>* schemes) override;
void SiteInstanceDeleting(content::SiteInstance* site_instance) override;
// brightray::BrowserClient:
brightray::BrowserMainParts* OverrideCreateBrowserMainParts(
@@ -120,9 +120,9 @@ class AtomBrowserClient : public brightray::BrowserClient,
content::SiteInstance* current_instance,
const GURL& dest_url);
struct ProcessPreferences {
bool sandbox = false;
bool native_window_open = false;
bool disable_popups = false;
bool sandbox;
bool native_window_open;
bool disable_popups;
};
void AddProcessPreferences(int process_id, ProcessPreferences prefs);
void RemoveProcessPreferences(int process_id);
@@ -135,10 +135,6 @@ class AtomBrowserClient : public brightray::BrowserClient,
std::map<int, ProcessPreferences> process_preferences_;
std::map<int, base::ProcessId> render_process_host_pids_;
// list of site per affinity. weak_ptr to prevent instance locking
std::map<std::string, content::SiteInstance*> site_per_affinities;
base::Lock process_preferences_lock_;
std::unique_ptr<AtomResourceDispatcherHostDelegate>

View File

@@ -13,10 +13,10 @@
#include "atom/browser/net/about_protocol_handler.h"
#include "atom/browser/net/asar/asar_protocol_handler.h"
#include "atom/browser/net/atom_cert_verifier.h"
#include "atom/browser/net/atom_ct_delegate.h"
#include "atom/browser/net/atom_network_delegate.h"
#include "atom/browser/net/atom_url_request_job_factory.h"
#include "atom/browser/net/http_protocol_handler.h"
#include "atom/browser/net/resolve_proxy_helper.h"
#include "atom/browser/web_view_manager.h"
#include "atom/common/atom_version.h"
#include "atom/common/chrome_version.h"
@@ -72,6 +72,8 @@ AtomBrowserContext::AtomBrowserContext(const std::string& partition,
bool in_memory,
const base::DictionaryValue& options)
: brightray::BrowserContext(partition, in_memory),
ct_delegate_(new AtomCTDelegate),
network_delegate_(new AtomNetworkDelegate),
cookie_delegate_(new AtomCookieDelegate) {
// Construct user agent string.
Browser* browser = Browser::Get();
@@ -104,9 +106,8 @@ void AtomBrowserContext::SetUserAgent(const std::string& user_agent) {
user_agent_ = user_agent;
}
std::unique_ptr<net::NetworkDelegate>
AtomBrowserContext::CreateNetworkDelegate() {
return base::MakeUnique<AtomNetworkDelegate>();
net::NetworkDelegate* AtomBrowserContext::CreateNetworkDelegate() {
return network_delegate_;
}
net::CookieMonsterDelegate* AtomBrowserContext::CreateCookieDelegate() {
@@ -191,9 +192,8 @@ content::PermissionManager* AtomBrowserContext::GetPermissionManager() {
return permission_manager_.get();
}
std::unique_ptr<net::CertVerifier> AtomBrowserContext::CreateCertVerifier(
brightray::RequireCTDelegate* ct_delegate) {
return base::WrapUnique(new AtomCertVerifier(ct_delegate));
std::unique_ptr<net::CertVerifier> AtomBrowserContext::CreateCertVerifier() {
return base::WrapUnique(new AtomCertVerifier(ct_delegate_.get()));
}
std::vector<std::string> AtomBrowserContext::GetCookieableSchemes() {
@@ -204,6 +204,11 @@ std::vector<std::string> AtomBrowserContext::GetCookieableSchemes() {
return default_schemes;
}
net::TransportSecurityState::RequireCTDelegate*
AtomBrowserContext::GetRequireCTDelegate() {
return ct_delegate_.get();
}
void AtomBrowserContext::RegisterPrefs(PrefRegistrySimple* pref_registry) {
pref_registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory,
base::FilePath());
@@ -227,14 +232,6 @@ AtomBlobReader* AtomBrowserContext::GetBlobReader() {
return blob_reader_.get();
}
ResolveProxyHelper* AtomBrowserContext::GetResolveProxyHelper() {
if (!resolve_proxy_helper_.get()) {
resolve_proxy_helper_ =
base::MakeRefCounted<ResolveProxyHelper>(url_request_context_getter());
}
return resolve_proxy_helper_.get();
}
// static
scoped_refptr<AtomBrowserContext> AtomBrowserContext::From(
const std::string& partition, bool in_memory,

View File

@@ -15,10 +15,10 @@
namespace atom {
class AtomBlobReader;
class AtomCTDelegate;
class AtomDownloadManagerDelegate;
class AtomNetworkDelegate;
class AtomPermissionManager;
class ResolveProxyHelper;
class WebViewManager;
class AtomBrowserContext : public brightray::BrowserContext {
@@ -33,16 +33,17 @@ class AtomBrowserContext : public brightray::BrowserContext {
void SetUserAgent(const std::string& user_agent);
// brightray::URLRequestContextGetter::Delegate:
std::unique_ptr<net::NetworkDelegate> CreateNetworkDelegate() override;
net::NetworkDelegate* CreateNetworkDelegate() override;
net::CookieMonsterDelegate* CreateCookieDelegate() override;
std::string GetUserAgent() override;
std::unique_ptr<net::URLRequestJobFactory> CreateURLRequestJobFactory(
content::ProtocolHandlerMap* protocol_handlers) override;
net::HttpCache::BackendFactory* CreateHttpCacheBackendFactory(
const base::FilePath& base_path) override;
std::unique_ptr<net::CertVerifier> CreateCertVerifier(
brightray::RequireCTDelegate* ct_delegate) override;
std::unique_ptr<net::CertVerifier> CreateCertVerifier() override;
std::vector<std::string> GetCookieableSchemes() override;
net::TransportSecurityState::RequireCTDelegate* GetRequireCTDelegate()
override;
// content::BrowserContext:
content::DownloadManagerDelegate* GetDownloadManagerDelegate() override;
@@ -52,9 +53,8 @@ class AtomBrowserContext : public brightray::BrowserContext {
// brightray::BrowserContext:
void RegisterPrefs(PrefRegistrySimple* pref_registry) override;
ResolveProxyHelper* GetResolveProxyHelper();
AtomBlobReader* GetBlobReader();
AtomNetworkDelegate* network_delegate() const { return network_delegate_; }
AtomCookieDelegate* cookie_delegate() const {
return cookie_delegate_.get();
}
@@ -65,14 +65,16 @@ class AtomBrowserContext : public brightray::BrowserContext {
~AtomBrowserContext() override;
private:
scoped_refptr<ResolveProxyHelper> resolve_proxy_helper_;
std::unique_ptr<AtomDownloadManagerDelegate> download_manager_delegate_;
std::unique_ptr<WebViewManager> guest_manager_;
std::unique_ptr<AtomPermissionManager> permission_manager_;
std::unique_ptr<AtomBlobReader> blob_reader_;
std::unique_ptr<AtomCTDelegate> ct_delegate_;
std::string user_agent_;
bool use_cache_;
// Managed by brightray::BrowserContext.
AtomNetworkDelegate* network_delegate_;
scoped_refptr<AtomCookieDelegate> cookie_delegate_;
DISALLOW_COPY_AND_ASSIGN(AtomBrowserContext);

View File

@@ -24,7 +24,6 @@
#include "content/public/browser/child_process_security_policy.h"
#include "device/geolocation/geolocation_delegate.h"
#include "device/geolocation/geolocation_provider.h"
#include "ui/base/l10n/l10n_util.h"
#include "v8/include/v8-debug.h"
#if defined(USE_X11)
@@ -39,10 +38,7 @@ namespace {
// A provider of Geolocation services to override AccessTokenStore.
class AtomGeolocationDelegate : public device::GeolocationDelegate {
public:
AtomGeolocationDelegate() {
device::GeolocationProvider::GetInstance()
->UserDidOptIntoLocationServices();
}
AtomGeolocationDelegate() = default;
scoped_refptr<device::AccessTokenStore> CreateAccessTokenStore() final {
return new AtomAccessTokenStore();
@@ -141,7 +137,7 @@ void AtomBrowserMainParts::PostEarlyInitialization() {
// Enable support for v8 inspector
node_debugger_.reset(new NodeDebugger(env));
node_debugger_->Start(js_env_->platform());
node_debugger_->Start();
// Add Electron extended APIs.
atom_bindings_->BindTo(js_env_->isolate(), env->process_object());
@@ -151,23 +147,6 @@ void AtomBrowserMainParts::PostEarlyInitialization() {
// Wrap the uv loop with global env.
node_bindings_->set_uv_env(env);
// We already initialized the feature list in
// brightray::BrowserMainParts::PreEarlyInitialization(), but
// the user JS script would not have had a chance to alter the command-line
// switches at that point. Lets reinitialize it here to pick up the
// command-line changes.
base::FeatureList::ClearInstanceForTesting();
brightray::BrowserMainParts::InitializeFeatureList();
}
int AtomBrowserMainParts::PreCreateThreads() {
const int result = brightray::BrowserMainParts::PreCreateThreads();
if (!result) {
fake_browser_process_->SetApplicationLocale(
brightray::BrowserClient::Get()->GetApplicationLocale());
}
return result;
}
void AtomBrowserMainParts::PreMainMessageLoopRun() {
@@ -206,7 +185,6 @@ void AtomBrowserMainParts::PreMainMessageLoopRun() {
Browser::Get()->DidFinishLaunching(*empty_info);
#endif
// Notify observers that main thread message loop was initialized.
Browser::Get()->PreMainMessageLoopRun();
}

View File

@@ -49,7 +49,6 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts {
// content::BrowserMainParts:
void PreEarlyInitialization() override;
void PostEarlyInitialization() override;
int PreCreateThreads() override;
void PreMainMessageLoopRun() override;
bool MainMessageLoopRun(int* result_code) override;
void PostMainMessageLoopStart() override;

View File

@@ -119,8 +119,9 @@ void ShutdownDetector::ThreadMain() {
int signal;
size_t bytes_read = 0;
ssize_t ret;
do {
ssize_t ret = HANDLE_EINTR(
ret = HANDLE_EINTR(
read(shutdown_fd_,
reinterpret_cast<char*>(&signal) + bytes_read,
sizeof(signal) - bytes_read));

View File

@@ -21,32 +21,6 @@
namespace atom {
namespace {
// Generate default file path to save the download.
void CreateDownloadPath(
const GURL& url,
const std::string& content_disposition,
const std::string& suggested_filename,
const std::string& mime_type,
const base::FilePath& default_download_path,
const AtomDownloadManagerDelegate::CreateDownloadPathCallback& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
auto generated_name =
net::GenerateFileName(url, content_disposition, std::string(),
suggested_filename, mime_type, "download");
if (!base::PathExists(default_download_path))
base::CreateDirectory(default_download_path);
base::FilePath path(default_download_path.Append(generated_name));
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(callback, path));
}
} // namespace
AtomDownloadManagerDelegate::AtomDownloadManagerDelegate(
content::DownloadManager* manager)
: download_manager_(manager),
@@ -72,6 +46,30 @@ void AtomDownloadManagerDelegate::GetItemSavePath(content::DownloadItem* item,
*path = download->GetSavePath();
}
void AtomDownloadManagerDelegate::CreateDownloadPath(
const GURL& url,
const std::string& content_disposition,
const std::string& suggested_filename,
const std::string& mime_type,
const base::FilePath& default_download_path,
const CreateDownloadPathCallback& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
auto generated_name = net::GenerateFileName(url,
content_disposition,
std::string(),
suggested_filename,
mime_type,
"download");
if (!base::PathExists(default_download_path))
base::CreateDirectory(default_download_path);
base::FilePath path(default_download_path.Append(generated_name));
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(callback, path));
}
void AtomDownloadManagerDelegate::OnDownloadPathGenerated(
uint32_t download_id,
const content::DownloadTargetCallback& callback,
@@ -94,7 +92,6 @@ void AtomDownloadManagerDelegate::OnDownloadPathGenerated(
// Show save dialog if save path was not set already on item
file_dialog::DialogSettings settings;
settings.parent_window = window;
settings.force_detached = window->is_offscreen_dummy();
settings.title = item->GetURL().spec();
settings.default_path = default_path;
if (path.empty() && file_dialog::ShowSaveDialog(settings, &path)) {
@@ -118,10 +115,7 @@ void AtomDownloadManagerDelegate::OnDownloadPathGenerated(
// If user cancels the file save dialog, run the callback with empty FilePath.
callback.Run(path,
content::DownloadItem::TARGET_DISPOSITION_PROMPT,
content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, path,
path.empty() ?
content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED :
content::DOWNLOAD_INTERRUPT_REASON_NONE);
content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, path);
}
void AtomDownloadManagerDelegate::Shutdown() {
@@ -138,8 +132,7 @@ bool AtomDownloadManagerDelegate::DetermineDownloadTarget(
callback.Run(download->GetForcedFilePath(),
content::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download->GetForcedFilePath(),
content::DOWNLOAD_INTERRUPT_REASON_NONE);
download->GetForcedFilePath());
return true;
}
@@ -150,7 +143,7 @@ bool AtomDownloadManagerDelegate::DetermineDownloadTarget(
callback.Run(save_path,
content::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
save_path, content::DOWNLOAD_INTERRUPT_REASON_NONE);
save_path);
return true;
}
@@ -166,10 +159,14 @@ bool AtomDownloadManagerDelegate::DetermineDownloadTarget(
content::BrowserThread::PostTask(
content::BrowserThread::FILE, FROM_HERE,
base::Bind(&CreateDownloadPath, download->GetURL(),
base::Bind(&AtomDownloadManagerDelegate::CreateDownloadPath,
weak_ptr_factory_.GetWeakPtr(),
download->GetURL(),
download->GetContentDisposition(),
download->GetSuggestedFilename(), download->GetMimeType(),
default_download_path, download_path_callback));
download->GetSuggestedFilename(),
download->GetMimeType(),
default_download_path,
download_path_callback));
return true;
}

View File

@@ -24,6 +24,13 @@ class AtomDownloadManagerDelegate : public content::DownloadManagerDelegate {
explicit AtomDownloadManagerDelegate(content::DownloadManager* manager);
virtual ~AtomDownloadManagerDelegate();
// Generate default file path to save the download.
void CreateDownloadPath(const GURL& url,
const std::string& suggested_filename,
const std::string& content_disposition,
const std::string& mime_type,
const base::FilePath& path,
const CreateDownloadPathCallback& callback);
void OnDownloadPathGenerated(uint32_t download_id,
const content::DownloadTargetCallback& callback,
const base::FilePath& default_path);

View File

@@ -97,28 +97,11 @@ int AtomPermissionManager::RequestPermission(
const GURL& requesting_origin,
bool user_gesture,
const StatusCallback& response_callback) {
return RequestPermissionWithDetails(
permission,
render_frame_host,
requesting_origin,
user_gesture,
nullptr,
response_callback);
}
int AtomPermissionManager::RequestPermissionWithDetails(
content::PermissionType permission,
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
bool user_gesture,
const base::DictionaryValue* details,
const StatusCallback& response_callback) {
return RequestPermissionsWithDetails(
return RequestPermissions(
std::vector<content::PermissionType>(1, permission),
render_frame_host,
requesting_origin,
user_gesture,
details,
base::Bind(&PermissionRequestResponseCallbackWrapper, response_callback));
}
@@ -128,18 +111,6 @@ int AtomPermissionManager::RequestPermissions(
const GURL& requesting_origin,
bool user_gesture,
const StatusesCallback& response_callback) {
return RequestPermissionsWithDetails(
permissions, render_frame_host, requesting_origin,
user_gesture, nullptr, response_callback);
}
int AtomPermissionManager::RequestPermissionsWithDetails(
const std::vector<content::PermissionType>& permissions,
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
bool user_gesture,
const base::DictionaryValue* details,
const StatusesCallback& response_callback) {
if (permissions.empty()) {
response_callback.Run(std::vector<blink::mojom::PermissionStatus>());
return kNoPendingOperation;
@@ -172,12 +143,7 @@ int AtomPermissionManager::RequestPermissionsWithDetails(
const auto callback =
base::Bind(&AtomPermissionManager::OnPermissionResponse,
base::Unretained(this), request_id, i);
if (details == nullptr) {
request_handler_.Run(web_contents, permission, callback,
base::DictionaryValue());
} else {
request_handler_.Run(web_contents, permission, callback, *details);
}
request_handler_.Run(web_contents, permission, callback);
}
return request_id;

View File

@@ -10,7 +10,6 @@
#include "base/callback.h"
#include "base/id_map.h"
#include "base/values.h"
#include "content/public/browser/permission_manager.h"
namespace content {
@@ -31,8 +30,7 @@ class AtomPermissionManager : public content::PermissionManager {
using RequestHandler =
base::Callback<void(content::WebContents*,
content::PermissionType,
const StatusCallback&,
const base::DictionaryValue&)>;
const StatusCallback&)>;
// Handler to dispatch permission requests in JS.
void SetPermissionRequestHandler(const RequestHandler& handler);
@@ -45,13 +43,6 @@ class AtomPermissionManager : public content::PermissionManager {
bool user_gesture,
const base::Callback<void(blink::mojom::PermissionStatus)>& callback)
override;
int RequestPermissionWithDetails(
content::PermissionType permission,
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
bool user_gesture,
const base::DictionaryValue* details,
const base::Callback<void(blink::mojom::PermissionStatus)>& callback);
int RequestPermissions(
const std::vector<content::PermissionType>& permissions,
content::RenderFrameHost* render_frame_host,
@@ -60,14 +51,6 @@ class AtomPermissionManager : public content::PermissionManager {
const base::Callback<void(
const std::vector<blink::mojom::PermissionStatus>&)>& callback)
override;
int RequestPermissionsWithDetails(
const std::vector<content::PermissionType>& permissions,
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
bool user_gesture,
const base::DictionaryValue* details,
const base::Callback<void(
const std::vector<blink::mojom::PermissionStatus>&)>& callback);
protected:
void OnPermissionResponse(int request_id,

View File

@@ -14,7 +14,6 @@
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/stream_info.h"
#include "net/base/escape.h"
#include "net/ssl/client_cert_store.h"
@@ -35,7 +34,8 @@ namespace atom {
namespace {
void OnOpenExternal(const GURL& escaped_url, bool allowed) {
void OnOpenExternal(const GURL& escaped_url,
bool allowed) {
if (allowed)
platform_util::OpenExternal(
#if defined(OS_WIN)
@@ -61,57 +61,51 @@ void HandleExternalProtocolInUI(
GURL escaped_url(net::EscapeExternalHandlerValue(url.spec()));
auto callback = base::Bind(&OnOpenExternal, escaped_url);
permission_helper->RequestOpenExternalPermission(callback, has_user_gesture,
url);
permission_helper->RequestOpenExternalPermission(callback, has_user_gesture);
}
void OnPdfResourceIntercepted(
const GURL& original_url,
int render_process_host_id,
int render_frame_id,
const content::ResourceRequestInfo::WebContentsGetter&
web_contents_getter) {
content::WebContents* web_contents = web_contents_getter.Run();
if (!web_contents)
return;
if (!WebContentsPreferences::IsPreferenceEnabled("plugins", web_contents)) {
if (!WebContentsPreferences::IsPluginsEnabled(web_contents)) {
auto browser_context = web_contents->GetBrowserContext();
auto download_manager =
content::BrowserContext::GetDownloadManager(browser_context);
content::BrowserContext::GetDownloadManager(browser_context);
download_manager->DownloadUrl(
content::DownloadUrlParameters::CreateForWebContentsMainFrame(
web_contents, original_url, NO_TRAFFIC_ANNOTATION_YET));
web_contents, original_url));
return;
}
// The URL passes the original pdf resource url, that will be requested
// by the webui page.
// chrome://pdf-viewer/index.html?src=https://somepage/123.pdf
content::NavigationController::LoadURLParams params(GURL(base::StringPrintf(
"%sindex.html?%s=%s", kPdfViewerUIOrigin, kPdfPluginSrc,
net::EscapeUrlEncodedData(original_url.spec(), false).c_str())));
content::RenderFrameHost* frame_host =
content::RenderFrameHost::FromID(render_process_host_id, render_frame_id);
if (!frame_host) {
return;
}
params.frame_tree_node_id = frame_host->GetFrameTreeNodeId();
content::NavigationController::LoadURLParams params(
GURL(base::StringPrintf(
"%sindex.html?%s=%s",
kPdfViewerUIOrigin,
kPdfPluginSrc,
net::EscapeUrlEncodedData(original_url.spec(), false).c_str())));
web_contents->GetController().LoadURLWithParams(params);
}
} // namespace
AtomResourceDispatcherHostDelegate::AtomResourceDispatcherHostDelegate() {}
AtomResourceDispatcherHostDelegate::AtomResourceDispatcherHostDelegate() {
}
bool AtomResourceDispatcherHostDelegate::HandleExternalProtocol(
const GURL& url,
content::ResourceRequestInfo* info) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(&HandleExternalProtocolInUI, url,
base::Bind(&HandleExternalProtocolInUI,
url,
info->GetWebContentsGetterForRequest(),
info->HasUserGesture()));
return true;
@@ -127,16 +121,16 @@ AtomResourceDispatcherHostDelegate::CreateLoginDelegate(
std::unique_ptr<net::ClientCertStore>
AtomResourceDispatcherHostDelegate::CreateClientCertStore(
content::ResourceContext* resource_context) {
#if defined(USE_NSS_CERTS)
return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(
net::ClientCertStoreNSS::PasswordDelegateFactory()));
#elif defined(OS_WIN)
return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreWin());
#elif defined(OS_MACOSX)
return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreMac());
#elif defined(USE_OPENSSL)
return std::unique_ptr<net::ClientCertStore>();
#endif
#if defined(USE_NSS_CERTS)
return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(
net::ClientCertStoreNSS::PasswordDelegateFactory()));
#elif defined(OS_WIN)
return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreWin());
#elif defined(OS_MACOSX)
return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreMac());
#elif defined(USE_OPENSSL)
return std::unique_ptr<net::ClientCertStore>();
#endif
}
bool AtomResourceDispatcherHostDelegate::ShouldInterceptResourceAsStream(
@@ -147,20 +141,11 @@ bool AtomResourceDispatcherHostDelegate::ShouldInterceptResourceAsStream(
std::string* payload) {
const content::ResourceRequestInfo* info =
content::ResourceRequestInfo::ForRequest(request);
int render_process_host_id;
int render_frame_id;
if (!info->GetAssociatedRenderFrame(&render_process_host_id,
&render_frame_id)) {
return false;
}
if (mime_type == "application/pdf") {
if (mime_type == "application/pdf" && info->IsMainFrame()) {
*origin = GURL(kPdfViewerUIOrigin);
content::BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&OnPdfResourceIntercepted, request->url(),
render_process_host_id, render_frame_id,
info->GetWebContentsGetterForRequest()));
return true;
}

View File

@@ -52,8 +52,8 @@ void AtomSpeechRecognitionManagerDelegate::OnAudioLevelsChange(
void AtomSpeechRecognitionManagerDelegate::CheckRecognitionIsAllowed(
int session_id,
base::OnceCallback<void(bool ask_user, bool is_allowed)> callback) {
std::move(callback).Run(true, true);
base::Callback<void(bool ask_user, bool is_allowed)> callback) {
callback.Run(true, true);
}
content::SpeechRecognitionEventListener*

View File

@@ -38,8 +38,7 @@ class AtomSpeechRecognitionManagerDelegate
// content::SpeechRecognitionManagerDelegate:
void CheckRecognitionIsAllowed(
int session_id,
base::OnceCallback<void(bool ask_user, bool is_allowed)> callback)
override;
base::Callback<void(bool ask_user, bool is_allowed)> callback) override;
content::SpeechRecognitionEventListener* GetEventListener() override;
bool FilterProfanities(int render_process_id) override;

View File

@@ -52,7 +52,7 @@ AtomWebUIControllerFactory::CreateWebUIControllerForURL(content::WebUI* web_ui,
if (url.host() == kPdfViewerUIHost) {
base::StringPairs toplevel_params;
base::SplitStringIntoKeyValuePairs(url.query(), '=', '&', &toplevel_params);
std::string src;
std::string stream_id, src;
const net::UnescapeRule::Type unescape_rules =
net::UnescapeRule::SPACES | net::UnescapeRule::PATH_SEPARATORS |

Some files were not shown because too many files have changed in this diff Show More