Compare commits

...

88 Commits

Author SHA1 Message Date
Electron Bot
7da7dd85e3 Bump v3.0.0-beta.8 2018-08-28 23:04:31 -07:00
trop[bot]
ccf8a797dc fix: use OS process handle to clear object registry (#14364)
RenderProcessHost switch can happen between ipc calls when
speculative process are invvolved, which will lead to deletion
of entries on current context. Use OS process handles to
uniquely associate a destruction handler for a render process.
2018-08-28 22:55:42 -07:00
Milan Burda
3301e05f33 fix: don't expose desktopCapturer in sandboxed renderers if the feature is disabled (#14345) 2018-08-28 19:51:07 -05:00
trop[bot]
b1c22ba531 fix: emit focus/blur events for webview (backport: 3-0-x) (#14359)
* fix: emit focus/blur events for webview

* test: webview can emit focus event
2018-08-28 13:38:11 -05:00
trop[bot]
873f39b159 fix: crash when tray is destroyed (#14357)
Release the view of status item before destroying it,
gives chance to perform cleanup on the view.
2018-08-28 13:37:38 -05:00
trop[bot]
11864e9e08 fix: create persistent channel ID store when cookie store is persistent (#14358) 2018-08-28 13:37:09 -05:00
trop[bot]
c8a21dbb92 fix: don't crash on tray.setContextMenu(null) (#14331) 2018-08-27 13:27:41 -07:00
trop[bot]
97058837e7 fix: dont parse arguments after a -- in the inspector (#14333) 2018-08-27 14:44:53 -05:00
trop[bot]
ff539c1d61 fix: don't expose view APIs when not enabled (#14321) 2018-08-27 13:00:19 +09:00
trop[bot]
9237d40e09 fix: issue 10962, crash when open devtool (backport: 3-0-x) (#14303)
* fix: crash when opening devtool (#10962)

* fix: fixed linting issues
2018-08-25 12:23:06 -07:00
Shelley Vohr
4721dc0856 fix: opt into location services once device service has been started (backport: 3-0-x) (#14289)
* fix: opt into location services once device service has been started (#14253)

* fix: opt into location services once device service has been started

* refactor: provide fake location provider to mock geolocation reponses

* chore: add spec for navigator.geolocation api using fake location provider

* fix conflict
2018-08-24 08:23:15 -07:00
Electron Bot
1f7fd985dd Bump v3.0.0-nightly.20180823 2018-08-23 21:23:48 -07:00
Roller Bot
d432e420ae chore: bump libcc (3-0-x) (#14280)
* chore: bump libcc submodule to 7165af0ca9863529f28e493568ae3d105eddcdef

* chore: bump libcc in DEPS to 7165af0ca9863529f28e493568ae3d105eddcdef
2018-08-23 21:12:09 -07:00
trop[bot]
635c3f53d8 fix: add method and referrer properties to app login event (backport: 3-0-x) (#14277)
* refactor: remove brightray/network_delegate.{cc|h}

* refactor: respond to http requests through network delegate
2018-08-23 20:47:16 +09:00
trop[bot]
ba703deee2 Print error when removed webview attribute is used (backport: 3-0-x) (#14274)
* chore: print error when removed webview attribute is used

* docs: document removed webview features
2018-08-23 15:42:08 +09:00
Electron Bot
b03178105d Bump v3.0.0-beta.7 2018-08-22 11:13:36 -07:00
Samuel Attard
ef0a6d9a1c fix: inheritance of webPreferences sub properties 2018-08-22 12:19:11 -05:00
trop[bot]
4c7af6a429 fix: notify request context shutdown on IO before cleanup (#14092) 2018-08-22 08:24:56 -07:00
trop[bot]
d1886c5d22 ci: add better logging around request failures for releasing (#14245) 2018-08-21 13:31:44 -07:00
trop[bot]
c558dc2d7d chore: retry for the meta dumper a few times (#14243) 2018-08-21 13:31:13 -07:00
Electron Bot
be68cfd4ea Bump v3.0.0-nightly.20180821 2018-08-21 12:07:19 -07:00
Samuel Attard
115a15c356 Revert "Bump v3.0.0-nightly.20180821"
This reverts commit d4fb904450.
2018-08-21 11:45:21 -07:00
Electron Bot
d4fb904450 Bump v3.0.0-nightly.20180821 2018-08-21 11:16:44 -07:00
Electron Bot
c7f7bdab8a Bump v3.0.0-beta.6 2018-08-20 11:01:41 -07:00
trop[bot]
de7cb9524a chore: remove autorelease check logic (#14222) 2018-08-20 10:57:01 -07:00
trop[bot]
5d17e48490 fix: enable osr (backport: 3-0-x) (#14219)
* fix: re-enable osr

* fix: add changes from CEF to add MouseWheelPhaseHandler

* fix: re-enable surface synchronization by applying fix from cef

* update method call and enable AsyncWheelEvents var

* fix: make BrowserCompositorMacGetGutterColor behave like chromium

* fix: HANDLE only exists on windows

* fix: pass correct params to mouse_wheel_phase_handler_

* fix variable accessing

* revert: revert the workaround for disableHardwareAcceleration crash

* fix: remove GuestViewCrossProcessFrames from the disabled features list

* revert: remove check from BrowserChildProcessLaunchedAndConnected
2018-08-20 10:45:53 -07:00
trop[bot]
058c03fdab chore: add option to return next version from prepare-release (backport: 3-0-x) (#14217)
* chore: add option to return next version from prepare-release

* shuffle logic
2018-08-20 08:35:34 -07:00
trop[bot]
bd0d6b1a02 chore: match the bump commit exactly, reverts should not count (#14209) 2018-08-19 14:46:17 -07:00
trop[bot]
0783eb9881 fix: #14160 (#14205) 2018-08-19 14:14:05 -07:00
trop[bot]
4e3aa2e061 fix: electron path for postinstall (backport: 3-0-x) (#14197)
* fix #14127 issue caused by #12426

* add ELECTRON_OVERRIDE_DIST_PATH check for install.js
2018-08-19 12:54:39 -07:00
Samuel Attard
92f3d47ab3 Revert "Bump v3.0.0-nightly.20180819"
This reverts commit bf465dc233.
2018-08-18 19:12:01 -07:00
Shelley Vohr
2a7ec7e051 fix: update_electron_gyp regex for nightlies 2018-08-18 19:11:24 -07:00
Electron Bot
bf465dc233 Bump v3.0.0-nightly.20180819 2018-08-19 01:58:59 +00:00
trop[bot]
00cf45609f chore: only prepare release if last commit not a bump (#14193) 2018-08-18 18:37:47 -07:00
Roller Bot
26f4190102 chore: bump libcc (3-0-x) (#14175)
* chore: bump libcc submodule to 92dc0accfae5cd133fa2a6758ae6b3ff4ff7e569

* chore: bump libcc in DEPS to 92dc0accfae5cd133fa2a6758ae6b3ff4ff7e569
2018-08-18 09:36:18 -07:00
Electron Bot
5d6382270a Bump v3.0.0-nightly.20180818 2018-08-18 07:05:22 +00:00
Samuel Attard
2162c996eb Revert "Bump v3.0.0-nightly.20180818"
This reverts commit 2945be4b9b.
2018-08-17 23:54:57 -07:00
Electron Bot
2945be4b9b Bump v3.0.0-nightly.20180818 2018-08-18 06:37:26 +00:00
Samuel Attard
c066a51bfe chore: always target master for nightly release commitish 2018-08-17 23:35:34 -07:00
Samuel Attard
ff7dfe4a11 chore: add logging to prepare-release 2018-08-17 23:25:09 -07:00
Shelley Vohr
6d17663a0b fix: add dist tags for release branches (#14186) (#14187)
* fix: add dist tags for release branches
2018-08-17 19:47:19 -07:00
Samuel Attard
bd4334e2b4 chore: apply patches from master to 3.0 (#14184) 2018-08-17 17:42:46 -07:00
Samuel Attard
0f937c2300 chore: fix beta bumping in 3.0 (#14173) 2018-08-17 13:00:04 -07:00
Shelley Vohr
2ecdf4a0eb chore: update release scripts to support sudowoodo (#14170)
Backports the totality of our release script changes to support sudowoodo. Also backports changes that have been made to a few other release script files in master after 3-0-x was cut with the purpose of keeping them in sync.
2018-08-17 12:01:10 -07:00
Cheng Zhao
44b0245ac4 fix: use OOPIF for webview tag (#13869) (#14156)
* fix: use OOIF for webview tag

* fix: do not call GetNativeView for webview

* fix: OOIPF webview's WebContents is managed by embedder frame

* fix: guest view can not be focused

* fix: clear zoom controller when guest is destroyed

* fix: implement the webview resize event

The webview is no longer a browser plugin with the resize event, use
ResizeObserver instead.

* test: disable failed tests due to OOPIF webview

* fix: embedder can be destroyed earlier than guest

This happens when embedder is manually destroyed.

* fix: don't double attach

* fix: recreate iframe when webview is reattached

* fix: resize event may happen very early

* test: some tests are working after OOPIF webview

* chore: remove unused browser plugin webview code

* fix: get embedder via closure

When the "destroyed" event is emitted, the entry in guestInstances would be
cleared.

* chore: rename browserPluginNode to internalElement

* test: make the visibilityState test more robust

* chore: guestinstance can not work with OOPIF webview

* fix: element could be detached before got response from browser
2018-08-17 08:21:36 -07:00
trop[bot]
c4d6484264 docs: fix electron.d.ts typings (#14138) 2018-08-16 11:11:38 -07:00
Shelley Vohr
ef2ad40bd9 fix: roll node to fix fs.readSync bug (#14118) 2018-08-15 11:42:31 -07:00
trop[bot]
2642e064a2 fix: add a hidden option to disable remote dereferencing (#14113) 2018-08-15 08:44:23 -07:00
trop[bot]
daf23288bc fix: override fs.realpathSync.native and fs.realpath.native (backport: 3-0-x) (#14051)
* fix: override fs.realpathSync.native and fs.realpath.native

* spec: test new native functions
2018-08-13 23:53:34 -07:00
trop[bot]
8eec8e150d Fix flaky sandbox tests (#14056)
Windows apparently has issues running opening two windows at once which is causing flakiness on the mixed sandbox tests.
2018-08-13 15:14:32 -07:00
trop[bot]
2af61cbe95 fix: lint js and docs alongside clang-format (backport: 3-0-x) (#14053)
* fix: lint js and docs alongside clang-format

* chore: change lint scripts to colon format
2018-08-13 14:25:34 -07:00
Shelley Vohr
32ffb0ba17 Bump v3.0.0-beta.5 2018-08-13 08:30:14 -07:00
trop[bot]
69caea38c1 fix: make asarStatsToFsStats nherit from fs.stats (#14041) 2018-08-12 21:13:38 -07:00
Milan Burda
b5bfd9867b Don't pass preloadPath via ELECTRON_BROWSER_SANDBOX_LOAD for security reasons (#13031) (#14026) 2018-08-11 12:53:33 -05:00
John Kleinschmidt
fb2afe8656 Merge pull request #14022 from electron/3-0-x-vs2017-15-4-5
ci: Use vs2017-15.4.5 for 3-0-x on AppVeyor
2018-08-10 17:18:21 -04:00
John Kleinschmidt
c926f3f6dc Use vs2017-15.4.5 for AppVeyor
Update to libcc with VS2017 15.4.5
2018-08-10 14:16:23 -04:00
trop[bot]
5aa247a627 feat: add location url to "Node.js Integration with Remote Content" warning (backport: 3-0-x) (#13976)
* docs: fix typo

* feat: add location url to Node+Remote warning
2018-08-09 20:48:36 -05:00
trop[bot]
67d202eaf6 Fix typos (#14001) 2018-08-09 10:06:10 -05:00
Milan Burda
98033e4f45 Fix process.execPath returning parent process path instead of the helper in sandboxed renderer (#13959) 2018-08-09 09:58:44 -05:00
trop[bot]
3d89185396 fix: ipcRemote.sendSync regression after moving away from JSON for return values (#13997) 2018-08-09 09:24:10 -05:00
John Kleinschmidt
1f430259ce Merge pull request #13975 from electron/roll-libcc-3-0-x
chore: roll libcc
2018-08-08 09:30:46 -04:00
Jeremy Apthorp
ff86cf5f6a chore: roll libcc
Picks up electron/libchromiumcontent#633
2018-08-07 16:21:17 -07:00
John Kleinschmidt
274a53654c Merge pull request #13898 from electron/release-notes-generator
chore: Merge PR #13359 from electron/release-notes-generator
2018-08-06 12:44:39 -04:00
trop[bot]
8f5fafb636 fix: dipToScreenRect / screenToDipRect - window can be null (#13924) 2018-08-03 13:14:52 +10:00
trop[bot]
bfbd4a2540 fix: Improve --enable-features/--disable-features handling (#13923)
As it turns out, we can reinitialize the feature list directly after the
user JS script has been executed instead of much later. This allows
modifications to `--enable-features`/`--disable-features` to work with a
greater set of features.
2018-08-03 13:08:27 +10:00
Charles Kerr
1926eab172 Bump v3.0.0-beta.4 2018-08-01 15:13:06 -05:00
trop[bot]
9818378e2d fix: some APIs modified for ASAR support cannot be util.promisify'ed (#13902) 2018-08-01 16:38:50 +10:00
trop[bot]
ad2d35c7cf memo: Update security docs: will-navigate, new-window (#13887) 2018-08-01 13:25:24 +10:00
trop[bot]
13d3a055fa fix: handle SIGINT and SIGTERM from the Electron CLI helper (#13889)
Fixes #12840
2018-08-01 13:25:04 +10:00
Charles Kerr
07b93d475d simplify package-lock.json diffs from last commit 2018-07-31 17:36:33 -05:00
John Kleinschmidt
c9da2d7669 Merge pull request #13359 from electron/release-notes-generator
build: New release notes generator
2018-07-31 16:07:40 -05:00
trop[bot]
a9a5766804 chore(tests): allow usage of deprecated APIs in tests (#13862) 2018-07-30 15:02:59 +10:00
trop[bot]
a62cb1e84c fix: util.promisify(setTimeout) (#13860) 2018-07-30 15:02:52 +10:00
trop[bot]
2bdb7a5047 fix: window.setVibrancy parameter passing (backport: 3-0-x) (#13863)
* fix: setVibrancy parameter passing

* fix: uses correct parameter types for setVibrancy
2018-07-30 13:02:32 +10:00
trop[bot]
29f70d7e35 memo: First draft: Here be dragons (#13861) 2018-07-30 11:44:43 +10:00
trop[bot]
91af624cb1 docs: fix electron.d.ts typings (#13857) 2018-07-30 11:20:19 +10:00
trop[bot]
b08df88b7c fix: Use --enable-features and --disable-features (#13805)
Unlike Chrome, we were not using the --enable-features and
--disable-features command-line arguments to initialize
`base::FeatureList`.
2018-07-26 08:29:08 -07:00
Birunthan Mohanathas
b659ff2de3 build: Bump libcc to latest (3.0.x) (#13822)
This picks up electron/libchromiumcontent#618.
2018-07-26 08:25:28 -07:00
trop[bot]
3ad6abc5cc fix: check string encoding before creating value (#13818) 2018-07-26 19:35:18 +09:00
Cheng Zhao
a880e0222f fix: pass scrollBounce by command line flag (#13813)
Implement the scrollBounce option by reading the command line flag in
`RenderThreadImpl::IsElasticOverscrollEnabled`, there is no more need
to set NSScrollViewRubberbanding.
2018-07-26 18:38:48 +09:00
Birunthan Mohanathas
95c69e660c build: Bump libcc to latest (3.0.x)
This picks up electron/libchromiumcontent#611 and
electron/libchromiumcontent#599.
2018-07-25 09:54:00 -07:00
trop[bot]
4333020157 fix: create WebContents for webview on request (#13761) 2018-07-21 16:51:31 +09:00
John Kleinschmidt
f4ff97038c Merge pull request #13755 from trop-bot/3-0-x-bp-fix--update-rebuild-test-modules.py-for-node-10-1532100223562
fix: update rebuild-test-modules.py for node 10 (backport: 3-0-x)
2018-07-20 14:45:00 -04:00
John Kleinschmidt
967577c335 fix: update for node 10 2018-07-20 15:23:49 +00:00
John Kleinschmidt
8bd5c1f858 Merge pull request #13734 from electron/backport-13727-3-0-x
fix: use context counter as contextId (backport 3-0-x)
2018-07-20 10:17:18 -04:00
trop[bot]
2955b0168c fix: ensure DirectX capturer is supported. (backport: 3-0-x) (#13738)
* Ensure DirectX capturer is supported.

* Actually try building on Windows.
2018-07-20 14:25:29 +10:00
Cheng Zhao
04b7c77951 fix: use webContentsId with contextId together
After after using `processId-contextCounter` as contextId, it may happen
that contexts in different WebContents sharing the same renderer process
get the same contextId. Using webContentsId as part of key in
ObjectsRegistry can fix this.
2018-07-20 10:53:02 +09:00
Cheng Zhao
136cf389e8 fix: use context counter as contextId (backport 3-0-x)
For sandboxed renderer it may not have a node::Environment in the context,
using a increasing counter as contextId works for all cases.
2018-07-19 11:27:41 -07:00
158 changed files with 5287 additions and 4272 deletions

7
.env.example Normal file
View File

@@ -0,0 +1,7 @@
# These env vars are only necessary for creating Electron releases.
# See docs/development/releasing.md
APPVEYOR_TOKEN=
CIRCLE_TOKEN=
ELECTRON_GITHUB_TOKEN=
VSTS_TOKEN=

View File

@@ -27,6 +27,12 @@ declare_args() {
enable_desktop_capturer = true
enable_run_as_node = true
enable_osr = true
# Provide a fake location provider for mocking
# the geolocation responses. Disable it if you
# need to test with chromium's location provider.
# Should not be enabled for release build.
enable_fake_location_provider = !is_official_build
}
filenames_gypi = exec_script(
@@ -312,6 +318,13 @@ static_library("electron_lib") {
sources = filenames_gypi.lib_sources
set_sources_assignment_filter(sources_assignment_filter)
if (enable_fake_location_provider) {
defines += [
"OVERRIDE_LOCATION_PROVIDER"
]
sources += filenames_gypi.lib_sources_location_provider
}
if (enable_run_as_node) {
sources += [
"atom/app/node_main.cc",

2
DEPS
View File

@@ -2,7 +2,7 @@ vars = {
'chromium_version':
'63.0.3239.150',
'libchromiumcontent_revision':
'1c542968990da951df27c8a0371a4ab5494a5a6c',
'7165af0ca9863529f28e493568ae3d105eddcdef',
'node_version':
'v9.7.0-33-g538a5023af',
'native_mate_revision':

View File

@@ -1,13 +1,11 @@
version: 1.0.{build}
branches:
except:
- /^release$|^release-\d-\d-x$/
build_cloud: electron-16
image: electron-16-vs2017
environment:
DISABLE_CRASH_REPORTER_TESTS: true
image: electron-16-vs2017-15.4.5
build_script:
- ps: >-
echo "Build worker image $env:APPVEYOR_BUILD_WORKER_IMAGE"
&"C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe"
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 {

View File

@@ -667,17 +667,17 @@ void App::OnNewWindowForTab() {
}
#endif
void App::OnLogin(LoginHandler* login_handler,
void App::OnLogin(scoped_refptr<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, WrapRefCounted(login_handler)));
prevent_default = Emit(
"login", WebContents::CreateFrom(isolate(), web_contents),
request_details, login_handler->auth_info(),
base::Bind(&PassLoginInformation, base::RetainedRef(login_handler)));
}
// Default behavior is to always cancel the auth.

View File

@@ -98,7 +98,7 @@ class App : public AtomBrowserClient::Delegate,
void OnActivate(bool has_visible_windows) override;
void OnWillFinishLaunching() override;
void OnFinishLaunching(const base::DictionaryValue& launch_info) override;
void OnLogin(LoginHandler* login_handler,
void OnLogin(scoped_refptr<LoginHandler> login_handler,
const base::DictionaryValue& request_details) override;
void OnAccessibilitySupportChanged() override;
void OnPreMainMessageLoopRun() override;

View File

@@ -311,9 +311,9 @@ void BrowserWindow::SetBrowserView(v8::Local<v8::Value> value) {
#endif
}
void BrowserWindow::SetVibrancy(mate::Arguments* args) {
std::string type;
args->GetNext(&type);
void BrowserWindow::SetVibrancy(v8::Isolate* isolate,
v8::Local<v8::Value> value) {
std::string type = mate::V8ToString(value);
auto* render_view_host = web_contents()->GetRenderViewHost();
if (render_view_host) {
@@ -324,7 +324,7 @@ void BrowserWindow::SetVibrancy(mate::Arguments* args) {
impl->SetBackgroundOpaque(type.empty() ? !window_->transparent() : false);
}
TopLevelWindow::SetVibrancy(args);
TopLevelWindow::SetVibrancy(isolate, value);
}
void BrowserWindow::FocusOnWebView() {

View File

@@ -71,7 +71,7 @@ class BrowserWindow : public TopLevelWindow,
void Blur() override;
void SetBackgroundColor(const std::string& color_name) override;
void SetBrowserView(v8::Local<v8::Value> value) override;
void SetVibrancy(mate::Arguments* args) override;
void SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value) override;
// BrowserWindow APIs.
void FocusOnWebView();

View File

@@ -5,6 +5,7 @@
#include "atom/browser/api/atom_api_cookies.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/request_context_delegate.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
@@ -253,9 +254,10 @@ void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter,
Cookies::Cookies(v8::Isolate* isolate, AtomBrowserContext* browser_context)
: browser_context_(browser_context) {
Init(isolate);
auto subscription = browser_context->RegisterCookieChangeCallback(
base::Bind(&Cookies::OnCookieChanged, base::Unretained(this)));
browser_context->set_cookie_change_subscription(std::move(subscription));
cookie_change_subscription_ =
browser_context->GetRequestContextDelegate()
->RegisterCookieChangeCallback(
base::Bind(&Cookies::OnCookieChanged, base::Unretained(this)));
}
Cookies::~Cookies() {}

View File

@@ -9,7 +9,7 @@
#include "atom/browser/api/trackable_object.h"
#include "atom/browser/net/cookie_details.h"
#include "base/callback.h"
#include "base/callback_list.h"
#include "native_mate/handle.h"
#include "net/cookies/canonical_cookie.h"
@@ -59,6 +59,8 @@ class Cookies : public mate::TrackableObject<Cookies> {
void OnCookieChanged(const CookieDetails*);
private:
std::unique_ptr<base::CallbackList<void(const CookieDetails*)>::Subscription>
cookie_change_subscription_;
scoped_refptr<AtomBrowserContext> browser_context_;
DISALLOW_COPY_AND_ASSIGN(Cookies);

View File

@@ -22,6 +22,7 @@ using base::PlatformThreadRef;
#include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
#if defined(OS_WIN)
#include "third_party/webrtc/modules/desktop_capture/win/dxgi_duplicator_controller.h"
#include "third_party/webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h"
#include "ui/display/win/display_info.h"
#endif // defined(OS_WIN)
@@ -61,9 +62,14 @@ void StartHandlingTask(bool capture_window,
const gfx::Size& thumbnail_size,
atom::api::DesktopCapturer* cap) {
#if defined(OS_WIN)
cap->using_directx_capturer_ =
content::desktop_capture::CreateDesktopCaptureOptions()
.allow_directx_capturer();
if (content::desktop_capture::CreateDesktopCaptureOptions()
.allow_directx_capturer()) {
// DxgiDuplicatorController should be alive in this scope according to
// screen_capturer_win.cc.
auto duplicator = webrtc::DxgiDuplicatorController::Instance();
cap->using_directx_capturer_ =
webrtc::ScreenCapturerWinDirectx::IsSupported();
}
#endif // defined(OS_WIN)
std::unique_ptr<webrtc::DesktopCapturer> screen_capturer(
capture_screen ? content::desktop_capture::CreateScreenCapturer()

View File

@@ -36,7 +36,7 @@ class DesktopCapturer : public mate::EventEmitter<DesktopCapturer>,
std::unique_ptr<DesktopMediaList> media_list_;
#if defined(OS_WIN)
bool using_directx_capturer_;
bool using_directx_capturer_ = false;
#endif // defined(OS_WIN)
protected:

View File

@@ -78,13 +78,13 @@ class Protocol : public mate::TrackableObject<Protocol> {
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const override {
RequestJob* request_job = new RequestJob(request, network_delegate);
request_job->SetHandlerInfo(isolate_, request_context_.get(), handler_);
request_job->SetHandlerInfo(isolate_, request_context_, handler_);
return request_job;
}
private:
v8::Isolate* isolate_;
scoped_refptr<net::URLRequestContextGetter> request_context_;
net::URLRequestContextGetter* request_context_;
Protocol::Handler handler_;
DISALLOW_COPY_AND_ASSIGN(CustomProtocolHandler);

View File

@@ -244,7 +244,7 @@ class ResolveProxyHelper {
: callback_(callback),
original_thread_(base::ThreadTaskRunnerHandle::Get()) {
scoped_refptr<net::URLRequestContextGetter> context_getter =
browser_context->url_request_context_getter();
browser_context->GetRequestContext();
context_getter->GetNetworkTaskRunner()->PostTask(
FROM_HERE, base::BindOnce(&ResolveProxyHelper::ResolveProxy,
base::Unretained(this), context_getter, url));
@@ -453,15 +453,6 @@ void SetDevToolsNetworkEmulationClientIdInIO(
network_delegate->SetDevToolsNetworkEmulationClientId(client_id);
}
// Clear protocol handlers in IO thread.
void ClearJobFactoryInIO(
scoped_refptr<brightray::URLRequestContextGetter> request_context_getter) {
auto* job_factory = static_cast<AtomURLRequestJobFactory*>(
request_context_getter->job_factory());
if (job_factory)
job_factory->Clear();
}
void DestroyGlobalHandle(v8::Isolate* isolate,
const v8::Global<v8::Value>& global_handle) {
v8::Locker locker(isolate);
@@ -495,10 +486,6 @@ Session::Session(v8::Isolate* isolate, AtomBrowserContext* browser_context)
}
Session::~Session() {
auto* getter = browser_context_->GetRequestContext();
content::BrowserThread::PostTask(
content::BrowserThread::IO, FROM_HERE,
base::BindOnce(ClearJobFactoryInIO, base::RetainedRef(getter)));
content::BrowserContext::GetDownloadManager(browser_context())
->RemoveObserver(this);
DestroyGlobalHandle(isolate(), cookies_);
@@ -597,10 +584,9 @@ void Session::EnableNetworkEmulation(const mate::Dictionary& options) {
devtools_network_emulation_client_id_, std::move(conditions));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&SetDevToolsNetworkEmulationClientIdInIO,
base::RetainedRef(browser_context_->url_request_context_getter()),
devtools_network_emulation_client_id_));
base::BindOnce(&SetDevToolsNetworkEmulationClientIdInIO,
base::RetainedRef(browser_context_->GetRequestContext()),
devtools_network_emulation_client_id_));
}
void Session::DisableNetworkEmulation() {
@@ -609,10 +595,9 @@ void Session::DisableNetworkEmulation() {
devtools_network_emulation_client_id_, std::move(conditions));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&SetDevToolsNetworkEmulationClientIdInIO,
base::RetainedRef(browser_context_->url_request_context_getter()),
std::string()));
base::BindOnce(&SetDevToolsNetworkEmulationClientIdInIO,
base::RetainedRef(browser_context_->GetRequestContext()),
std::string()));
}
void Session::SetCertVerifyProc(v8::Local<v8::Value> val,

View File

@@ -692,9 +692,9 @@ void TopLevelWindow::SetAutoHideCursor(bool auto_hide) {
window_->SetAutoHideCursor(auto_hide);
}
void TopLevelWindow::SetVibrancy(mate::Arguments* args) {
std::string type;
args->GetNext(&type);
void TopLevelWindow::SetVibrancy(v8::Isolate* isolate,
v8::Local<v8::Value> value) {
std::string type = mate::V8ToString(value);
window_->SetVibrancy(type);
}

View File

@@ -163,7 +163,7 @@ class TopLevelWindow : public mate::TrackableObject<TopLevelWindow>,
void SetVisibleOnAllWorkspaces(bool visible);
bool IsVisibleOnAllWorkspaces();
void SetAutoHideCursor(bool auto_hide);
virtual void SetVibrancy(mate::Arguments* args);
virtual void SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value);
void SetTouchBar(const std::vector<mate::PersistentDictionary>& items);
void RefreshTouchBarItem(const std::string& item_id);
void SetEscapeTouchBarItem(const mate::PersistentDictionary& item);

View File

@@ -210,7 +210,7 @@ void Tray::PopUpContextMenu(mate::Arguments* args) {
void Tray::SetContextMenu(v8::Isolate* isolate, mate::Handle<Menu> menu) {
menu_.Reset(isolate, menu.ToV8());
tray_icon_->SetContextMenu(menu->model());
tray_icon_->SetContextMenu(menu.IsEmpty() ? nullptr : menu->model());
}
gfx::Rect Tray::GetBounds() {

View File

@@ -120,28 +120,6 @@ struct PrintSettings {
namespace mate {
template <>
struct Converter<atom::SetSizeParams> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
atom::SetSizeParams* out) {
mate::Dictionary params;
if (!ConvertFromV8(isolate, val, &params))
return false;
bool autosize;
if (params.Get("enableAutoSize", &autosize))
out->enable_auto_size.reset(new bool(autosize));
gfx::Size size;
if (params.Get("min", &size))
out->min_size.reset(new gfx::Size(size));
if (params.Get("max", &size))
out->max_size.reset(new gfx::Size(size));
if (params.Get("normal", &size))
out->normal_size.reset(new gfx::Size(size));
return true;
}
};
template <>
struct Converter<PrintSettings> {
static bool FromV8(v8::Isolate* isolate,
@@ -396,7 +374,8 @@ WebContents::WebContents(v8::Isolate* isolate,
GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(session->browser_context(),
site_instance);
guest_delegate_.reset(new WebViewGuestDelegate);
guest_delegate_.reset(
new WebViewGuestDelegate(embedder_->web_contents(), this));
params.guest_delegate = guest_delegate_.get();
#if defined(ENABLE_OSR)
@@ -448,7 +427,7 @@ void WebContents::InitWithSessionAndOptions(v8::Isolate* isolate,
mate::Handle<api::Session> session,
const mate::Dictionary& options) {
Observe(web_contents);
InitWithWebContents(web_contents, session->browser_context());
InitWithWebContents(web_contents, session->browser_context(), IsGuest());
managed_web_contents()->GetView()->SetDelegate(this);
@@ -481,8 +460,6 @@ void WebContents::InitWithSessionAndOptions(v8::Isolate* isolate,
web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
if (IsGuest()) {
guest_delegate_->Initialize(this);
NativeWindow* owner_window = nullptr;
if (embedder_) {
// New WebContents's owner_window is the embedder's owner_window.
@@ -504,27 +481,18 @@ WebContents::~WebContents() {
if (managed_web_contents()) {
managed_web_contents()->GetView()->SetDelegate(nullptr);
// For webview we need to tell content module to do some cleanup work before
// destroying it.
if (type_ == WEB_VIEW)
guest_delegate_->Destroy();
RenderViewDeleted(web_contents()->GetRenderViewHost());
if (type_ == WEB_VIEW) {
DestroyWebContents(false /* async */);
if (type_ == BROWSER_WINDOW && owner_window()) {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnCloseContents();
} else {
if (type_ == BROWSER_WINDOW && owner_window()) {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnCloseContents();
} else {
DestroyWebContents(true /* async */);
}
// The WebContentsDestroyed will not be called automatically because we
// destroy the webContents in the next tick. So we have to manually
// call it here to make sure "destroyed" event is emitted.
WebContentsDestroyed();
DestroyWebContents(!IsGuest() /* async */);
}
// The WebContentsDestroyed will not be called automatically because we
// destroy the webContents in the next tick. So we have to manually
// call it here to make sure "destroyed" event is emitted.
WebContentsDestroyed();
}
}
@@ -784,13 +752,6 @@ content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
return dialog_manager_.get();
}
void WebContents::ResizeDueToAutoResize(content::WebContents* web_contents,
const gfx::Size& new_size) {
if (IsGuest()) {
guest_delegate_->ResizeDueToAutoResize(new_size);
}
}
void WebContents::BeforeUnloadFired(const base::TimeTicks& proceed_time) {
// Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired.
@@ -805,7 +766,8 @@ void WebContents::RenderViewCreated(content::RenderViewHost* render_view_host) {
}
void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
Emit("render-view-deleted", render_view_host->GetProcess()->GetID(),
base::GetProcId(render_view_host->GetProcess()->GetHandle()));
}
void WebContents::RenderProcessGone(base::TerminationStatus status) {
@@ -935,6 +897,8 @@ void WebContents::DidFinishNavigation(
Emit("did-navigate", url, http_response_code, http_status_text);
}
}
if (IsGuest())
Emit("load-commit", url, is_main_frame);
} else {
auto url = navigation_handle->GetURL();
int code = navigation_handle->GetNetErrorCode();
@@ -1075,7 +1039,8 @@ bool WebContents::OnMessageReceived(const IPC::Message& message,
// 1. call webContents.destroy();
// 2. garbage collection;
// 3. user closes the window of webContents;
// For webview only #1 will happen, for BrowserWindow both #1 and #3 may
// 4. the embedder detaches the frame.
// For webview only #4 will happen, for BrowserWindow both #1 and #3 may
// happen. The #2 should never happen for webContents, because webview is
// managed by GuestViewManager, and BrowserWindow's webContents is managed
// by api::BrowserWindow.
@@ -1083,6 +1048,7 @@ bool WebContents::OnMessageReceived(const IPC::Message& message,
// sure "destroyed" event is emitted. For #3, the content::WebContents will
// be destroyed on close, and WebContentsDestroyed would be called for it, so
// we need to make sure the api::WebContents is also deleted.
// For #4, the WebContents will be destroyed by embedder.
void WebContents::WebContentsDestroyed() {
// Cleanup relationships with other parts.
RemoveFromWeakMap();
@@ -1093,6 +1059,13 @@ void WebContents::WebContentsDestroyed() {
Emit("destroyed");
// For guest view based on OOPIF, the WebContents is released by the embedder
// frame, and we need to clear the reference to the memory.
if (IsGuest() && managed_web_contents()) {
managed_web_contents()->ReleaseWebContents();
ResetManagedWebContents(false);
}
// Destroy the native class in next tick.
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, GetDestroyClosure());
}
@@ -1140,10 +1113,6 @@ void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) {
return;
}
if (guest_delegate_ && !guest_delegate_->IsAttached()) {
return;
}
content::NavigationController::LoadURLParams params(url);
if (!options.Get("httpReferrer", &params.referrer)) {
@@ -1754,15 +1723,16 @@ void WebContents::OnCursorChange(const content::WebCursor& cursor) {
}
}
void WebContents::SetSize(const SetSizeParams& params) {
if (guest_delegate_)
guest_delegate_->SetSize(params);
}
bool WebContents::IsGuest() const {
return type_ == WEB_VIEW;
}
void WebContents::AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id) {
if (guest_delegate_)
guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id);
}
bool WebContents::IsOffScreen() const {
#if defined(ENABLE_OSR)
return type_ == OFF_SCREEN;
@@ -1891,6 +1861,16 @@ void WebContents::OnGetZoomLevel(content::RenderFrameHost* rfh,
rfh->Send(reply_msg);
}
v8::Local<v8::Value> WebContents::GetPreloadPath(v8::Isolate* isolate) const {
if (auto* web_preferences = WebContentsPreferences::From(web_contents())) {
base::FilePath::StringType preload;
if (web_preferences->GetPreloadPath(&preload)) {
return mate::ConvertToV8(isolate, preload);
}
}
return v8::Null(isolate);
}
v8::Local<v8::Value> WebContents::GetWebPreferences(v8::Isolate* isolate) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (!web_preferences)
@@ -2039,8 +2019,8 @@ void WebContents::BuildPrototype(v8::Isolate* isolate,
.SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription)
.SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
.SetMethod("startDrag", &WebContents::StartDrag)
.SetMethod("setSize", &WebContents::SetSize)
.SetMethod("isGuest", &WebContents::IsGuest)
.SetMethod("attachToIframe", &WebContents::AttachToIframe)
.SetMethod("isOffscreen", &WebContents::IsOffScreen)
.SetMethod("startPainting", &WebContents::StartPainting)
.SetMethod("stopPainting", &WebContents::StopPainting)
@@ -2053,6 +2033,7 @@ void WebContents::BuildPrototype(v8::Isolate* isolate,
.SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
.SetMethod("_getZoomFactor", &WebContents::GetZoomFactor)
.SetMethod("getType", &WebContents::GetType)
.SetMethod("_getPreloadPath", &WebContents::GetPreloadPath)
.SetMethod("getWebPreferences", &WebContents::GetWebPreferences)
.SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
.SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)

View File

@@ -42,7 +42,6 @@ class ResourceRequestBody;
namespace atom {
struct SetSizeParams;
class AtomBrowserContext;
class AtomJavaScriptDialogManager;
class WebContentsZoomController;
@@ -199,8 +198,9 @@ class WebContents : public mate::TrackableObject<WebContents>,
void CapturePage(mate::Arguments* args);
// Methods for creating <webview>.
void SetSize(const SetSizeParams& params);
bool IsGuest() const;
void AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id);
// Methods for offscreen rendering
bool IsOffScreen() const;
@@ -232,6 +232,9 @@ class WebContents : public mate::TrackableObject<WebContents>,
const std::vector<std::string>& features,
const scoped_refptr<network::ResourceRequestBody>& body);
// Returns the preload script path of current WebContents.
v8::Local<v8::Value> GetPreloadPath(v8::Isolate* isolate) const;
// Returns the web preferences of current WebContents.
v8::Local<v8::Value> GetWebPreferences(v8::Isolate* isolate);
v8::Local<v8::Value> GetLastWebPreferences(v8::Isolate* isolate);
@@ -339,8 +342,6 @@ class WebContents : public mate::TrackableObject<WebContents>,
const content::BluetoothChooser::EventHandler& handler) override;
content::JavaScriptDialogManager* GetJavaScriptDialogManager(
content::WebContents* source) override;
void ResizeDueToAutoResize(content::WebContents* web_contents,
const gfx::Size& new_size) override;
// content::WebContentsObserver:
void BeforeUnloadFired(const base::TimeTicks& proceed_time) override;

View File

@@ -95,7 +95,7 @@ void WebRequest::SetListener(Method method, Event type, mate::Arguments* args) {
}
brightray::URLRequestContextGetter* url_request_context_getter =
browser_context_->url_request_context_getter();
browser_context_->GetRequestContext();
if (!url_request_context_getter)
return;
BrowserThread::PostTask(

View File

@@ -10,6 +10,7 @@
#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"

View File

@@ -17,7 +17,6 @@
#include "atom/browser/atom_resource_dispatcher_host_delegate.h"
#include "atom/browser/atom_speech_recognition_manager_delegate.h"
#include "atom/browser/child_web_contents_tracker.h"
#include "atom/browser/login_handler.h"
#include "atom/browser/native_window.h"
#include "atom/browser/session_preferences.h"
#include "atom/browser/web_contents_permission_helper.h"
@@ -46,6 +45,7 @@
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/web_preferences.h"
#include "device/geolocation/public/cpp/location_provider.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "ppapi/host/ppapi_host.h"
#include "services/network/public/cpp/resource_request_body.h"
@@ -62,6 +62,10 @@
#include "net/ssl/client_cert_store.h"
#endif
#if defined(OVERRIDE_LOCATION_PROVIDER)
#include "atom/browser/fake_location_provider.h"
#endif // defined(OVERRIDE_LOCATION_PROVIDER)
using content::BrowserThread;
namespace atom {
@@ -495,17 +499,13 @@ std::unique_ptr<net::ClientCertStore> AtomBrowserClient::CreateClientCertStore(
#endif
}
content::ResourceDispatcherHostLoginDelegate*
AtomBrowserClient::CreateLoginDelegate(
net::AuthChallengeInfo* auth_info,
content::ResourceRequestInfo::WebContentsGetter web_contents_getter,
bool is_main_frame,
const GURL& url,
bool first_auth_attempt,
const base::Callback<void(const base::Optional<net::AuthCredentials>&)>&
auth_required_callback) {
return new LoginHandler(auth_info, web_contents_getter, url,
auth_required_callback);
std::unique_ptr<device::LocationProvider>
AtomBrowserClient::OverrideSystemLocationProvider() {
#if defined(OVERRIDE_LOCATION_PROVIDER)
return std::make_unique<FakeLocationProvider>();
#else
return nullptr;
#endif
}
brightray::BrowserMainParts* AtomBrowserClient::OverrideCreateBrowserMainParts(

View File

@@ -106,14 +106,8 @@ class AtomBrowserClient : public brightray::BrowserClient,
void SiteInstanceDeleting(content::SiteInstance* site_instance) override;
std::unique_ptr<net::ClientCertStore> CreateClientCertStore(
content::ResourceContext* resource_context) override;
content::ResourceDispatcherHostLoginDelegate* CreateLoginDelegate(
net::AuthChallengeInfo* auth_info,
content::ResourceRequestInfo::WebContentsGetter web_contents_getter,
bool is_main_frame,
const GURL& url,
bool first_auth_attempt,
const base::Callback<void(const base::Optional<net::AuthCredentials>&)>&
auth_required_callback) override;
std::unique_ptr<device::LocationProvider> OverrideSystemLocationProvider()
override;
// brightray::BrowserClient:
brightray::BrowserMainParts* OverrideCreateBrowserMainParts(

View File

@@ -4,59 +4,30 @@
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/api/atom_api_protocol.h"
#include "atom/browser/atom_blob_reader.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/atom_download_manager_delegate.h"
#include "atom/browser/atom_permission_manager.h"
#include "atom/browser/browser.h"
#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_network_delegate.h"
#include "atom/browser/net/atom_url_request_job_factory.h"
#include "atom/browser/net/cookie_details.h"
#include "atom/browser/net/http_protocol_handler.h"
#include "atom/browser/request_context_delegate.h"
#include "atom/browser/web_view_manager.h"
#include "atom/common/atom_version.h"
#include "atom/common/chrome_version.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/memory/ptr_util.h"
#include "base/path_service.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/task_scheduler/post_task.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_registry_simple.h"
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/user_agent.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/url_request/data_protocol_handler.h"
#include "net/url_request/ftp_protocol_handler.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_intercepting_job_factory.h"
#include "url/url_constants.h"
using content::BrowserThread;
namespace atom {
namespace {
class NoCacheBackend : public net::HttpCache::BackendFactory {
int CreateBackend(net::NetLog* net_log,
std::unique_ptr<disk_cache::Backend>* backend,
const net::CompletionCallback& callback) override {
return net::ERR_FAILED;
}
};
std::string RemoveWhitespace(const std::string& str) {
std::string trimmed;
if (base::RemoveChars(str, " ", &trimmed))
@@ -70,7 +41,8 @@ std::string RemoveWhitespace(const std::string& str) {
AtomBrowserContext::AtomBrowserContext(const std::string& partition,
bool in_memory,
const base::DictionaryValue& options)
: brightray::BrowserContext(partition, in_memory) {
: brightray::BrowserContext(partition, in_memory),
url_request_context_getter_(nullptr) {
// Construct user agent string.
Browser* browser = Browser::Get();
std::string name = RemoveWhitespace(browser->GetName());
@@ -86,87 +58,24 @@ AtomBrowserContext::AtomBrowserContext(const std::string& partition,
user_agent_ = content::BuildUserAgentFromProduct(user_agent);
// Read options.
use_cache_ = true;
options.GetBoolean("cache", &use_cache_);
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
bool use_cache = !command_line->HasSwitch(switches::kDisableHttpCache);
options.GetBoolean("cache", &use_cache);
request_context_delegate_.reset(new RequestContextDelegate(use_cache));
// Initialize Pref Registry in brightray.
InitPrefs();
}
AtomBrowserContext::~AtomBrowserContext() {}
AtomBrowserContext::~AtomBrowserContext() {
url_request_context_getter_->set_delegate(nullptr);
}
void AtomBrowserContext::SetUserAgent(const std::string& user_agent) {
user_agent_ = user_agent;
}
std::unique_ptr<base::CallbackList<void(const CookieDetails*)>::Subscription>
AtomBrowserContext::RegisterCookieChangeCallback(
const base::Callback<void(const CookieDetails*)>& cb) {
return cookie_change_sub_list_.Add(cb);
}
std::unique_ptr<net::NetworkDelegate>
AtomBrowserContext::CreateNetworkDelegate() {
return std::make_unique<AtomNetworkDelegate>();
}
std::string AtomBrowserContext::GetUserAgent() {
return user_agent_;
}
std::unique_ptr<net::URLRequestJobFactory>
AtomBrowserContext::CreateURLRequestJobFactory(
content::ProtocolHandlerMap* protocol_handlers) {
std::unique_ptr<AtomURLRequestJobFactory> job_factory(
new AtomURLRequestJobFactory);
for (auto& it : *protocol_handlers) {
job_factory->SetProtocolHandler(it.first,
base::WrapUnique(it.second.release()));
}
protocol_handlers->clear();
job_factory->SetProtocolHandler(url::kAboutScheme,
base::WrapUnique(new AboutProtocolHandler));
job_factory->SetProtocolHandler(
url::kDataScheme, base::WrapUnique(new net::DataProtocolHandler));
job_factory->SetProtocolHandler(
url::kFileScheme,
base::WrapUnique(
new asar::AsarProtocolHandler(base::CreateTaskRunnerWithTraits(
{base::MayBlock(), base::TaskPriority::USER_VISIBLE,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}))));
job_factory->SetProtocolHandler(
url::kHttpScheme,
base::WrapUnique(new HttpProtocolHandler(url::kHttpScheme)));
job_factory->SetProtocolHandler(
url::kHttpsScheme,
base::WrapUnique(new HttpProtocolHandler(url::kHttpsScheme)));
job_factory->SetProtocolHandler(
url::kWsScheme,
base::WrapUnique(new HttpProtocolHandler(url::kWsScheme)));
job_factory->SetProtocolHandler(
url::kWssScheme,
base::WrapUnique(new HttpProtocolHandler(url::kWssScheme)));
auto* host_resolver =
url_request_context_getter()->GetURLRequestContext()->host_resolver();
job_factory->SetProtocolHandler(
url::kFtpScheme, net::FtpProtocolHandler::Create(host_resolver));
return std::move(job_factory);
}
net::HttpCache::BackendFactory*
AtomBrowserContext::CreateHttpCacheBackendFactory(
const base::FilePath& base_path) {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (!use_cache_ || command_line->HasSwitch(switches::kDisableHttpCache))
return new NoCacheBackend;
else
return brightray::BrowserContext::CreateHttpCacheBackendFactory(base_path);
}
content::DownloadManagerDelegate*
AtomBrowserContext::GetDownloadManagerDelegate() {
if (!download_manager_delegate_.get()) {
@@ -189,26 +98,6 @@ 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::vector<std::string> AtomBrowserContext::GetCookieableSchemes() {
auto default_schemes = brightray::BrowserContext::GetCookieableSchemes();
const auto& standard_schemes = atom::api::GetStandardSchemes();
default_schemes.insert(default_schemes.end(), standard_schemes.begin(),
standard_schemes.end());
return default_schemes;
}
void AtomBrowserContext::NotifyCookieChange(const net::CanonicalCookie& cookie,
bool removed,
net::CookieChangeCause cause) {
CookieDetails cookie_details(&cookie, removed, cause);
cookie_change_sub_list_.Notify(&cookie_details);
}
void AtomBrowserContext::RegisterPrefs(PrefRegistrySimple* pref_registry) {
pref_registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory,
base::FilePath());
@@ -219,6 +108,16 @@ void AtomBrowserContext::RegisterPrefs(PrefRegistrySimple* pref_registry) {
pref_registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths);
}
std::string AtomBrowserContext::GetUserAgent() const {
return user_agent_;
}
void AtomBrowserContext::OnMainRequestContextCreated(
brightray::URLRequestContextGetter* getter) {
getter->set_delegate(request_context_delegate_.get());
url_request_context_getter_ = getter;
}
AtomBlobReader* AtomBrowserContext::GetBlobReader() {
if (!blob_reader_.get()) {
content::ChromeBlobStorageContext* blob_context =

View File

@@ -8,17 +8,15 @@
#include <string>
#include <vector>
#include "base/callback_list.h"
#include "brightray/browser/browser_context.h"
namespace atom {
class AtomBlobReader;
class AtomDownloadManagerDelegate;
class AtomNetworkDelegate;
class AtomPermissionManager;
class RequestContextDelegate;
class WebViewManager;
struct CookieDetails;
class AtomBrowserContext : public brightray::BrowserContext {
public:
@@ -31,24 +29,7 @@ class AtomBrowserContext : public brightray::BrowserContext {
const base::DictionaryValue& options = base::DictionaryValue());
void SetUserAgent(const std::string& user_agent);
// Register callbacks that needs to notified on any cookie store changes.
std::unique_ptr<base::CallbackList<void(const CookieDetails*)>::Subscription>
RegisterCookieChangeCallback(
const base::Callback<void(const CookieDetails*)>& cb);
// brightray::URLRequestContextGetter::Delegate:
std::unique_ptr<net::NetworkDelegate> CreateNetworkDelegate() 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::vector<std::string> GetCookieableSchemes() override;
void NotifyCookieChange(const net::CanonicalCookie& cookie,
bool removed,
net::CookieChangeCause cause) override;
AtomBlobReader* GetBlobReader();
// content::BrowserContext:
content::DownloadManagerDelegate* GetDownloadManagerDelegate() override;
@@ -57,14 +38,12 @@ class AtomBrowserContext : public brightray::BrowserContext {
// brightray::BrowserContext:
void RegisterPrefs(PrefRegistrySimple* pref_registry) override;
std::string GetUserAgent() const override;
void OnMainRequestContextCreated(
brightray::URLRequestContextGetter* getter) override;
AtomBlobReader* GetBlobReader();
void set_cookie_change_subscription(
std::unique_ptr<
base::CallbackList<void(const CookieDetails*)>::Subscription>
subscription) {
cookie_change_subscription_.swap(subscription);
RequestContextDelegate* GetRequestContextDelegate() const {
return request_context_delegate_.get();
}
protected:
@@ -74,16 +53,14 @@ class AtomBrowserContext : public brightray::BrowserContext {
~AtomBrowserContext() override;
private:
brightray::URLRequestContextGetter* url_request_context_getter_;
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<RequestContextDelegate> request_context_delegate_;
std::string user_agent_;
bool use_cache_;
base::CallbackList<void(const CookieDetails*)> cookie_change_sub_list_;
std::unique_ptr<base::CallbackList<void(const CookieDetails*)>::Subscription>
cookie_change_subscription_;
DISALLOW_COPY_AND_ASSIGN(AtomBrowserContext);
};

View File

@@ -154,6 +154,14 @@ 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() {
@@ -229,9 +237,6 @@ void AtomBrowserMainParts::PostMainMessageLoopStart() {
#if defined(OS_POSIX)
HandleShutdownSignals();
#endif
// TODO(deepak1556): Enable this optionally based on response
// from AtomPermissionManager.
GetGeolocationControl()->UserDidOptIntoLocationServices();
}
void AtomBrowserMainParts::PostMainMessageLoopRun() {

View File

@@ -54,6 +54,10 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts {
// Returns a closure that can be used to remove |callback| from the list.
void RegisterDestructionCallback(base::OnceClosure callback);
// Returns the connection to GeolocationControl which can be
// used to enable the location services once per client.
device::mojom::GeolocationControl* GetGeolocationControl();
Browser* browser() { return browser_.get(); }
protected:
@@ -87,8 +91,6 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts {
std::unique_ptr<brightray::ViewsDelegate> views_delegate_;
#endif
device::mojom::GeolocationControl* GetGeolocationControl();
// A fake BrowserProcess object that used to feed the source code from chrome.
std::unique_ptr<BrowserProcess> fake_browser_process_;

View File

@@ -7,6 +7,7 @@
#include <vector>
#include "atom/browser/atom_browser_client.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/web_contents_preferences.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/permission_type.h"
@@ -43,6 +44,7 @@ class AtomPermissionManager::PendingRequest {
const StatusesCallback& callback)
: render_process_id_(render_frame_host->GetProcess()->GetID()),
callback_(callback),
permissions_(permissions),
results_(permissions.size(), blink::mojom::PermissionStatus::DENIED),
remaining_results_(permissions.size()) {}
@@ -50,6 +52,18 @@ class AtomPermissionManager::PendingRequest {
blink::mojom::PermissionStatus status) {
DCHECK(!IsComplete());
if (status == blink::mojom::PermissionStatus::GRANTED) {
const auto permission = permissions_[permission_id];
if (permission == content::PermissionType::MIDI_SYSEX) {
content::ChildProcessSecurityPolicy::GetInstance()
->GrantSendMidiSysExMessage(render_process_id_);
} else if (permission == content::PermissionType::GEOLOCATION) {
AtomBrowserMainParts::Get()
->GetGeolocationControl()
->UserDidOptIntoLocationServices();
}
}
results_[permission_id] = status;
--remaining_results_;
}
@@ -63,6 +77,7 @@ class AtomPermissionManager::PendingRequest {
private:
int render_process_id_;
const StatusesCallback callback_;
std::vector<content::PermissionType> permissions_;
std::vector<blink::mojom::PermissionStatus> results_;
size_t remaining_results_;
};
@@ -139,6 +154,10 @@ int AtomPermissionManager::RequestPermissionsWithDetails(
content::ChildProcessSecurityPolicy::GetInstance()
->GrantSendMidiSysExMessage(
render_frame_host->GetProcess()->GetID());
} else if (permission == content::PermissionType::GEOLOCATION) {
AtomBrowserMainParts::Get()
->GetGeolocationControl()
->UserDidOptIntoLocationServices();
}
statuses.push_back(blink::mojom::PermissionStatus::GRANTED);
}
@@ -153,10 +172,6 @@ int AtomPermissionManager::RequestPermissionsWithDetails(
for (size_t i = 0; i < permissions.size(); ++i) {
auto permission = permissions[i];
if (permission == content::PermissionType::MIDI_SYSEX) {
content::ChildProcessSecurityPolicy::GetInstance()
->GrantSendMidiSysExMessage(render_frame_host->GetProcess()->GetID());
}
const auto callback =
base::Bind(&AtomPermissionManager::OnPermissionResponse,
base::Unretained(this), request_id, i);
@@ -186,7 +201,6 @@ void AtomPermissionManager::OnPermissionResponse(
}
}
void AtomPermissionManager::ResetPermission(content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) {}

View File

@@ -8,6 +8,7 @@
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/browser_observer.h"
#include "atom/browser/login_handler.h"
#include "atom/browser/native_window.h"
#include "atom/browser/window_list.h"
#include "base/files/file_util.h"
@@ -164,7 +165,7 @@ void Browser::OnAccessibilitySupportChanged() {
}
void Browser::RequestLogin(
LoginHandler* login_handler,
scoped_refptr<LoginHandler> login_handler,
std::unique_ptr<base::DictionaryValue> request_details) {
for (BrowserObserver& observer : observers_)
observer.OnLogin(login_handler, *(request_details.get()));

View File

@@ -33,7 +33,6 @@ class Image;
namespace atom {
class AtomMenuModel;
class LoginHandler;
// This class is used for control application-wide operations.
class Browser : public WindowListObserver {
@@ -229,7 +228,7 @@ class Browser : public WindowListObserver {
void OnAccessibilitySupportChanged();
// Request basic auth login.
void RequestLogin(LoginHandler* login_handler,
void RequestLogin(scoped_refptr<LoginHandler> login_handler,
std::unique_ptr<base::DictionaryValue> request_details);
void PreMainMessageLoopRun();

View File

@@ -7,6 +7,8 @@
#include <string>
#include "atom/browser/login_handler.h"
#include "base/memory/scoped_refptr.h"
#include "build/build_config.h"
namespace base {
@@ -15,8 +17,6 @@ class DictionaryValue;
namespace atom {
class LoginHandler;
class BrowserObserver {
public:
// The browser is about to close all windows.
@@ -49,7 +49,7 @@ class BrowserObserver {
virtual void OnFinishLaunching(const base::DictionaryValue& launch_info) {}
// The browser requests HTTP login.
virtual void OnLogin(LoginHandler* login_handler,
virtual void OnLogin(scoped_refptr<LoginHandler> login_handler,
const base::DictionaryValue& request_details) {}
// The browser's accessibility suppport has changed.

View File

@@ -152,7 +152,8 @@ CommonWebContentsDelegate::~CommonWebContentsDelegate() {}
void CommonWebContentsDelegate::InitWithWebContents(
content::WebContents* web_contents,
AtomBrowserContext* browser_context) {
AtomBrowserContext* browser_context,
bool is_guest) {
browser_context_ = browser_context;
web_contents->SetDelegate(this);
@@ -165,7 +166,8 @@ void CommonWebContentsDelegate::InitWithWebContents(
!web_preferences || web_preferences->IsEnabled(options::kOffscreen);
// Create InspectableWebContents.
web_contents_.reset(brightray::InspectableWebContents::Create(web_contents));
web_contents_.reset(
brightray::InspectableWebContents::Create(web_contents, is_guest));
web_contents_->SetDelegate(this);
}

View File

@@ -42,7 +42,8 @@ class CommonWebContentsDelegate
// Creates a InspectableWebContents object and takes onwership of
// |web_contents|.
void InitWithWebContents(content::WebContents* web_contents,
AtomBrowserContext* browser_context);
AtomBrowserContext* browser_context,
bool is_guest);
// Set the window as owner window.
void SetOwnerWindow(NativeWindow* owner_window);

View File

@@ -0,0 +1,44 @@
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/fake_location_provider.h"
#include "base/callback.h"
#include "base/time/time.h"
namespace atom {
FakeLocationProvider::FakeLocationProvider() {
position_.latitude = 10;
position_.longitude = -10;
position_.accuracy = 1;
position_.error_code =
device::mojom::Geoposition::ErrorCode::POSITION_UNAVAILABLE;
}
FakeLocationProvider::~FakeLocationProvider() = default;
void FakeLocationProvider::SetUpdateCallback(
const LocationProviderUpdateCallback& callback) {
callback_ = callback;
}
void FakeLocationProvider::StartProvider(bool high_accuracy) {}
void FakeLocationProvider::StopProvider() {}
const device::mojom::Geoposition& FakeLocationProvider::GetPosition() {
return position_;
}
void FakeLocationProvider::OnPermissionGranted() {
if (!callback_.is_null()) {
// Check device::ValidateGeoPosition for range of values.
position_.error_code = device::mojom::Geoposition::ErrorCode::NONE;
position_.timestamp = base::Time::Now();
callback_.Run(this, position_);
}
}
} // namespace atom

View File

@@ -0,0 +1,36 @@
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_FAKE_LOCATION_PROVIDER_H_
#define ATOM_BROWSER_FAKE_LOCATION_PROVIDER_H_
#include "base/macros.h"
#include "device/geolocation/public/cpp/location_provider.h"
#include "services/device/public/mojom/geoposition.mojom.h"
namespace atom {
class FakeLocationProvider : public device::LocationProvider {
public:
FakeLocationProvider();
~FakeLocationProvider() override;
// LocationProvider Implementation:
void SetUpdateCallback(
const LocationProviderUpdateCallback& callback) override;
void StartProvider(bool high_accuracy) override;
void StopProvider() override;
const device::mojom::Geoposition& GetPosition() override;
void OnPermissionGranted() override;
private:
device::mojom::Geoposition position_;
LocationProviderUpdateCallback callback_;
DISALLOW_COPY_AND_ASSIGN(FakeLocationProvider);
};
} // namespace atom
#endif // ATOM_BROWSER_FAKE_LOCATION_PROVIDER_H_

View File

@@ -5,6 +5,7 @@
#include "atom/browser/login_handler.h"
#include "atom/browser/browser.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "base/values.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
@@ -15,78 +16,75 @@ using content::BrowserThread;
namespace atom {
LoginHandler::LoginHandler(
net::AuthChallengeInfo* auth_info,
content::ResourceRequestInfo::WebContentsGetter web_contents_getter,
const GURL& url,
const base::Callback<void(const base::Optional<net::AuthCredentials>&)>&
auth_required_callback)
: auth_info_(auth_info),
web_contents_getter_(web_contents_getter),
auth_required_callback_(auth_required_callback) {
// Fill request details on IO thread.
// TODO(deepak1556): Fill in method and referrer details to
// avoid breaking the app login event.
net::URLRequest* request,
const net::AuthChallengeInfo& auth_info,
const net::NetworkDelegate::AuthCallback& callback,
net::AuthCredentials* credentials,
const content::ResourceRequestInfo* resource_request_info)
: credentials_(credentials),
auth_info_(auth_info),
auth_callback_(std::move(callback)),
weak_factory_(this) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
std::unique_ptr<base::DictionaryValue> request_details(
new base::DictionaryValue);
request_details->SetKey("url", base::Value(url.spec()));
FillRequestDetails(request_details.get(), request);
web_contents_getter_ =
resource_request_info->GetWebContentsGetterForRequest();
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&Browser::RequestLogin, base::Unretained(Browser::Get()),
base::RetainedRef(WrapRefCounted(this)),
std::move(request_details)));
base::RetainedRef(this), std::move(request_details)));
}
LoginHandler::~LoginHandler() {}
void LoginHandler::Login(const base::string16& username,
const base::string16& password) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&LoginHandler::DoLogin, weak_factory_.GetWeakPtr(),
username, password));
}
void LoginHandler::CancelAuth() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&LoginHandler::DoCancelAuth, weak_factory_.GetWeakPtr()));
}
void LoginHandler::NotifyRequestDestroyed() {
auth_callback_.Reset();
credentials_ = nullptr;
weak_factory_.InvalidateWeakPtrs();
}
content::WebContents* LoginHandler::GetWebContents() const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return web_contents_getter_.Run();
}
void LoginHandler::Login(const base::string16& username,
const base::string16& password) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (TestAndSetAuthHandled())
return;
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&LoginHandler::DoLogin, this, username, password));
}
void LoginHandler::CancelAuth() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (TestAndSetAuthHandled())
return;
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::BindOnce(&LoginHandler::DoCancelAuth, this));
}
void LoginHandler::OnRequestCancelled() {
TestAndSetAuthHandled();
auth_required_callback_.Reset();
}
// Marks authentication as handled and returns the previous handled state.
bool LoginHandler::TestAndSetAuthHandled() {
base::AutoLock lock(handled_auth_lock_);
bool was_handled = handled_auth_;
handled_auth_ = true;
return was_handled;
}
void LoginHandler::DoCancelAuth() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!auth_required_callback_.is_null())
std::move(auth_required_callback_).Run(base::nullopt);
if (!auth_callback_.is_null())
std::move(auth_callback_)
.Run(net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
}
void LoginHandler::DoLogin(const base::string16& username,
const base::string16& password) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!auth_required_callback_.is_null()) {
std::move(auth_required_callback_)
.Run(net::AuthCredentials(username, password));
if (!auth_callback_.is_null()) {
credentials_->Set(username, password);
std::move(auth_callback_)
.Run(net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
}
}

View File

@@ -6,72 +6,65 @@
#define ATOM_BROWSER_LOGIN_HANDLER_H_
#include "base/callback.h"
#include "base/optional.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/string16.h"
#include "base/synchronization/lock.h"
#include "content/public/browser/resource_dispatcher_host_login_delegate.h"
#include "content/public/browser/resource_request_info.h"
#include "net/base/network_delegate.h"
namespace content {
class WebContents;
}
namespace net {
class AuthChallengeInfo;
class AuthCredentials;
} // namespace net
namespace atom {
// Handles the HTTP basic auth, must be created on IO thread.
class LoginHandler : public content::ResourceDispatcherHostLoginDelegate {
class LoginHandler : public base::RefCountedThreadSafe<LoginHandler> {
public:
LoginHandler(
net::AuthChallengeInfo* auth_info,
content::ResourceRequestInfo::WebContentsGetter web_contents_getter,
const GURL& url,
const base::Callback<void(const base::Optional<net::AuthCredentials>&)>&
auth_required_callback);
LoginHandler(net::URLRequest* request,
const net::AuthChallengeInfo& auth_info,
const net::NetworkDelegate::AuthCallback& callback,
net::AuthCredentials* credentials,
const content::ResourceRequestInfo* resource_request_info);
// The auth is cancelled, must be called on UI thread.
void CancelAuth();
// The URLRequest associated with the auth is destroyed.
void NotifyRequestDestroyed();
// Login with |username| and |password|, must be called on UI thread.
void Login(const base::string16& username, const base::string16& password);
// Returns the WebContents associated with the request, must be called on UI
// thread.
content::WebContents* GetWebContents() const;
// The auth is cancelled, must be called on UI thread.
void CancelAuth();
// Login with |username| and |password|, must be called on UI thread.
void Login(const base::string16& username, const base::string16& password);
const net::AuthChallengeInfo* auth_info() const { return auth_info_.get(); }
protected:
~LoginHandler() override;
// content::ResourceDispatcherHostLoginDelegate:
void OnRequestCancelled() override;
const net::AuthChallengeInfo* auth_info() const { return &auth_info_; }
private:
friend class base::RefCountedThreadSafe<LoginHandler>;
friend class base::DeleteHelper<LoginHandler>;
~LoginHandler();
// Must be called on IO thread.
void DoCancelAuth();
void DoLogin(const base::string16& username, const base::string16& password);
// Marks authentication as handled and returns the previous handled
// state.
bool TestAndSetAuthHandled();
// True if we've handled auth (Login or CancelAuth has been called).
bool handled_auth_ = false;
mutable base::Lock handled_auth_lock_;
// Credentials to be used for the auth.
net::AuthCredentials* credentials_;
// Who/where/what asked for the authentication.
scoped_refptr<net::AuthChallengeInfo> auth_info_;
const net::AuthChallengeInfo& auth_info_;
// WebContents associated with the login request.
content::ResourceRequestInfo::WebContentsGetter web_contents_getter_;
base::Callback<void(const base::Optional<net::AuthCredentials>&)>
auth_required_callback_;
// Called with preferred value of net::NetworkDelegate::AuthRequiredResponse.
net::NetworkDelegate::AuthCallback auth_callback_;
base::WeakPtrFactory<LoginHandler> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(LoginHandler);
};

View File

@@ -7,11 +7,17 @@
#include <utility>
#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/login_handler.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/resource_request_info.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/url_request/url_request.h"
#include "services/network/throttling/throttling_network_transaction.h"
@@ -231,7 +237,15 @@ AtomNetworkDelegate::ResponseListenerInfo::ResponseListenerInfo(
AtomNetworkDelegate::ResponseListenerInfo::ResponseListenerInfo() = default;
AtomNetworkDelegate::ResponseListenerInfo::~ResponseListenerInfo() = default;
AtomNetworkDelegate::AtomNetworkDelegate() {}
AtomNetworkDelegate::AtomNetworkDelegate() {
auto* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kIgnoreConnectionsLimit)) {
std::string value =
command_line->GetSwitchValueASCII(switches::kIgnoreConnectionsLimit);
ignore_connections_limit_domains_ = base::SplitString(
value, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
}
}
AtomNetworkDelegate::~AtomNetworkDelegate() {}
@@ -262,9 +276,17 @@ int AtomNetworkDelegate::OnBeforeURLRequest(
net::URLRequest* request,
const net::CompletionCallback& callback,
GURL* new_url) {
if (!base::ContainsKey(response_listeners_, kOnBeforeRequest))
return brightray::NetworkDelegate::OnBeforeURLRequest(request, callback,
new_url);
if (!base::ContainsKey(response_listeners_, kOnBeforeRequest)) {
for (const auto& domain : ignore_connections_limit_domains_) {
if (request->url().DomainIs(domain)) {
// Allow unlimited concurrent connections.
request->SetPriority(net::MAXIMUM_PRIORITY);
request->SetLoadFlags(request->load_flags() | net::LOAD_IGNORE_LIMITS);
break;
}
}
return net::OK;
}
return HandleResponseEvent(kOnBeforeRequest, request, callback, new_url);
}
@@ -278,8 +300,7 @@ int AtomNetworkDelegate::OnBeforeStartTransaction(
kDevToolsEmulateNetworkConditionsClientId,
client_id_);
if (!base::ContainsKey(response_listeners_, kOnBeforeSendHeaders))
return brightray::NetworkDelegate::OnBeforeStartTransaction(
request, callback, headers);
return net::OK;
return HandleResponseEvent(kOnBeforeSendHeaders, request, callback, headers,
*headers);
@@ -288,10 +309,8 @@ int AtomNetworkDelegate::OnBeforeStartTransaction(
void AtomNetworkDelegate::OnStartTransaction(
net::URLRequest* request,
const net::HttpRequestHeaders& headers) {
if (!base::ContainsKey(simple_listeners_, kOnSendHeaders)) {
brightray::NetworkDelegate::OnStartTransaction(request, headers);
if (!base::ContainsKey(simple_listeners_, kOnSendHeaders))
return;
}
HandleSimpleEvent(kOnSendHeaders, request, headers);
}
@@ -303,8 +322,7 @@ int AtomNetworkDelegate::OnHeadersReceived(
scoped_refptr<net::HttpResponseHeaders>* override,
GURL* allowed) {
if (!base::ContainsKey(response_listeners_, kOnHeadersReceived))
return brightray::NetworkDelegate::OnHeadersReceived(
request, callback, original, override, allowed);
return net::OK;
return HandleResponseEvent(
kOnHeadersReceived, request, callback,
@@ -313,10 +331,8 @@ int AtomNetworkDelegate::OnHeadersReceived(
void AtomNetworkDelegate::OnBeforeRedirect(net::URLRequest* request,
const GURL& new_location) {
if (!base::ContainsKey(simple_listeners_, kOnBeforeRedirect)) {
brightray::NetworkDelegate::OnBeforeRedirect(request, new_location);
if (!base::ContainsKey(simple_listeners_, kOnBeforeRedirect))
return;
}
HandleSimpleEvent(kOnBeforeRedirect, request, new_location,
request->response_headers(), request->GetSocketAddress(),
@@ -325,10 +341,8 @@ void AtomNetworkDelegate::OnBeforeRedirect(net::URLRequest* request,
void AtomNetworkDelegate::OnResponseStarted(net::URLRequest* request,
int net_error) {
if (!base::ContainsKey(simple_listeners_, kOnResponseStarted)) {
brightray::NetworkDelegate::OnResponseStarted(request, net_error);
if (!base::ContainsKey(simple_listeners_, kOnResponseStarted))
return;
}
if (request->status().status() != net::URLRequestStatus::SUCCESS)
return;
@@ -346,33 +360,109 @@ void AtomNetworkDelegate::OnCompleted(net::URLRequest* request, bool started) {
// Error event.
OnErrorOccurred(request, started);
return;
} else if (request->response_headers() &&
net::HttpResponseHeaders::IsRedirectResponseCode(
request->response_headers()->response_code())) {
}
if (request->response_headers() &&
net::HttpResponseHeaders::IsRedirectResponseCode(
request->response_headers()->response_code())) {
// Redirect event.
brightray::NetworkDelegate::OnCompleted(request, started);
return;
}
if (!base::ContainsKey(simple_listeners_, kOnCompleted)) {
brightray::NetworkDelegate::OnCompleted(request, started);
if (!base::ContainsKey(simple_listeners_, kOnCompleted))
return;
}
HandleSimpleEvent(kOnCompleted, request, request->response_headers(),
request->was_cached());
}
void AtomNetworkDelegate::OnURLRequestDestroyed(net::URLRequest* request) {
const auto& it = login_handler_map_.find(request->identifier());
if (it != login_handler_map_.end()) {
it->second->NotifyRequestDestroyed();
it->second = nullptr;
login_handler_map_.erase(it);
}
callbacks_.erase(request->identifier());
}
net::NetworkDelegate::AuthRequiredResponse AtomNetworkDelegate::OnAuthRequired(
net::URLRequest* request,
const net::AuthChallengeInfo& auth_info,
const AuthCallback& callback,
net::AuthCredentials* credentials) {
auto* resource_request_info =
content::ResourceRequestInfo::ForRequest(request);
if (!resource_request_info)
return AUTH_REQUIRED_RESPONSE_NO_ACTION;
login_handler_map_.emplace(
request->identifier(),
new LoginHandler(request, auth_info, std::move(callback), credentials,
resource_request_info));
return AUTH_REQUIRED_RESPONSE_IO_PENDING;
}
bool AtomNetworkDelegate::OnCanGetCookies(const net::URLRequest& request,
const net::CookieList& cookie_list) {
return true;
}
bool AtomNetworkDelegate::OnCanSetCookie(
const net::URLRequest& request,
const net::CanonicalCookie& cookie_line,
net::CookieOptions* options) {
return true;
}
bool AtomNetworkDelegate::OnCanAccessFile(
const net::URLRequest& request,
const base::FilePath& original_path,
const base::FilePath& absolute_path) const {
return true;
}
bool AtomNetworkDelegate::OnCanEnablePrivacyMode(
const GURL& url,
const GURL& first_party_for_cookies) const {
return false;
}
bool AtomNetworkDelegate::OnAreExperimentalCookieFeaturesEnabled() const {
return true;
}
bool AtomNetworkDelegate::OnCancelURLRequestWithPolicyViolatingReferrerHeader(
const net::URLRequest& request,
const GURL& target_url,
const GURL& referrer_url) const {
return false;
}
// TODO(deepak1556) : Enable after hooking into the reporting service
// https://crbug.com/704259
bool AtomNetworkDelegate::OnCanQueueReportingReport(
const url::Origin& origin) const {
return false;
}
void AtomNetworkDelegate::OnCanSendReportingReports(
std::set<url::Origin> origins,
base::OnceCallback<void(std::set<url::Origin>)> result_callback) const {}
bool AtomNetworkDelegate::OnCanSetReportingClient(const url::Origin& origin,
const GURL& endpoint) const {
return false;
}
bool AtomNetworkDelegate::OnCanUseReportingClient(const url::Origin& origin,
const GURL& endpoint) const {
return false;
}
void AtomNetworkDelegate::OnErrorOccurred(net::URLRequest* request,
bool started) {
if (!base::ContainsKey(simple_listeners_, kOnErrorOccurred)) {
brightray::NetworkDelegate::OnCompleted(request, started);
if (!base::ContainsKey(simple_listeners_, kOnErrorOccurred))
return;
}
HandleSimpleEvent(kOnErrorOccurred, request, request->was_cached(),
request->status());

View File

@@ -8,14 +8,14 @@
#include <map>
#include <set>
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/synchronization/lock.h"
#include "base/values.h"
#include "brightray/browser/network_delegate.h"
#include "content/public/browser/resource_request_info.h"
#include "extensions/common/url_pattern.h"
#include "net/base/net_errors.h"
#include "net/base/network_delegate.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_response_headers.h"
@@ -27,7 +27,9 @@ using URLPatterns = std::set<URLPattern>;
const char* ResourceTypeToString(content::ResourceType type);
class AtomNetworkDelegate : public brightray::NetworkDelegate {
class LoginHandler;
class AtomNetworkDelegate : public net::NetworkDelegate {
public:
using ResponseCallback = base::Callback<void(const base::DictionaryValue&)>;
using SimpleListener = base::Callback<void(const base::DictionaryValue&)>;
@@ -86,6 +88,10 @@ class AtomNetworkDelegate : public brightray::NetworkDelegate {
int OnBeforeStartTransaction(net::URLRequest* request,
const net::CompletionCallback& callback,
net::HttpRequestHeaders* headers) override;
void OnBeforeSendHeaders(net::URLRequest* request,
const net::ProxyInfo& proxy_info,
const net::ProxyRetryInfoMap& proxy_retry_info,
net::HttpRequestHeaders* headers) override {}
void OnStartTransaction(net::URLRequest* request,
const net::HttpRequestHeaders& headers) override;
int OnHeadersReceived(
@@ -97,8 +103,43 @@ class AtomNetworkDelegate : public brightray::NetworkDelegate {
void OnBeforeRedirect(net::URLRequest* request,
const GURL& new_location) override;
void OnResponseStarted(net::URLRequest* request, int net_error) override;
void OnNetworkBytesReceived(net::URLRequest* request,
int64_t bytes_read) override {}
void OnNetworkBytesSent(net::URLRequest* request,
int64_t bytes_sent) override {}
void OnCompleted(net::URLRequest* request, bool started) override;
void OnURLRequestDestroyed(net::URLRequest* request) override;
void OnPACScriptError(int line_number, const base::string16& error) override {
}
AuthRequiredResponse OnAuthRequired(
net::URLRequest* request,
const net::AuthChallengeInfo& auth_info,
const AuthCallback& callback,
net::AuthCredentials* credentials) override;
bool OnCanGetCookies(const net::URLRequest& request,
const net::CookieList& cookie_list) override;
bool OnCanSetCookie(const net::URLRequest& request,
const net::CanonicalCookie& cookie_line,
net::CookieOptions* options) override;
bool OnCanAccessFile(const net::URLRequest& request,
const base::FilePath& original_path,
const base::FilePath& absolute_path) const override;
bool OnCanEnablePrivacyMode(
const GURL& url,
const GURL& first_party_for_cookies) const override;
bool OnAreExperimentalCookieFeaturesEnabled() const override;
bool OnCancelURLRequestWithPolicyViolatingReferrerHeader(
const net::URLRequest& request,
const GURL& target_url,
const GURL& referrer_url) const override;
bool OnCanQueueReportingReport(const url::Origin& origin) const override;
void OnCanSendReportingReports(std::set<url::Origin> origins,
base::OnceCallback<void(std::set<url::Origin>)>
result_callback) const override;
bool OnCanSetReportingClient(const url::Origin& origin,
const GURL& endpoint) const override;
bool OnCanUseReportingClient(const url::Origin& origin,
const GURL& endpoint) const override;
private:
void OnErrorOccurred(net::URLRequest* request, bool started);
@@ -124,9 +165,11 @@ class AtomNetworkDelegate : public brightray::NetworkDelegate {
T out,
const base::DictionaryValue& response);
std::map<uint64_t, scoped_refptr<LoginHandler>> login_handler_map_;
std::map<SimpleEvent, SimpleListenerInfo> simple_listeners_;
std::map<ResponseEvent, ResponseListenerInfo> response_listeners_;
std::map<uint64_t, net::CompletionCallback> callbacks_;
std::vector<std::string> ignore_connections_limit_domains_;
// Client id for devtools network emulation.
std::string client_id_;

View File

@@ -70,11 +70,8 @@ scoped_refptr<AtomURLRequest> AtomURLRequest::Create(
return nullptr;
}
scoped_refptr<brightray::URLRequestContextGetter> request_context_getter(
browser_context->url_request_context_getter());
browser_context->GetRequestContext());
DCHECK(request_context_getter);
if (!request_context_getter) {
return nullptr;
}
scoped_refptr<AtomURLRequest> atom_url_request(new AtomURLRequest(delegate));
if (content::BrowserThread::PostTask(
content::BrowserThread::IO, FROM_HERE,

View File

@@ -9,6 +9,7 @@
#include "atom/browser/api/atom_api_session.h"
#include "atom/browser/atom_browser_context.h"
#include "base/guid.h"
#include "base/memory/ptr_util.h"
#include "base/strings/string_util.h"
#include "native_mate/dictionary.h"
@@ -93,16 +94,15 @@ void URLRequestFetchJob::BeforeStartInUI(v8::Isolate* isolate,
if (options.Get("session", &val)) {
if (val->IsNull()) {
// We have to create the URLRequestContextGetter on UI thread.
url_request_context_getter_ = new brightray::URLRequestContextGetter(
this, nullptr, base::FilePath(), true,
BrowserThread::GetTaskRunnerForThread(BrowserThread::IO), nullptr,
content::URLRequestInterceptorScopedVector());
custom_browser_context_ =
AtomBrowserContext::From(base::GenerateGUID(), true);
url_request_context_getter_ =
custom_browser_context_->GetRequestContext();
} else {
mate::Handle<api::Session> session;
if (mate::ConvertFromV8(isolate, val, &session) && !session.IsEmpty()) {
AtomBrowserContext* browser_context = session->browser_context();
url_request_context_getter_ =
browser_context->url_request_context_getter();
url_request_context_getter_ = browser_context->GetRequestContext();
}
}
}

View File

@@ -8,16 +8,17 @@
#include <string>
#include "atom/browser/net/js_asker.h"
#include "brightray/browser/url_request_context_getter.h"
#include "content/browser/streams/stream.h"
#include "content/browser/streams/stream_read_observer.h"
#include "net/url_request/url_fetcher_delegate.h"
#include "net/url_request/url_request_context_getter.h"
namespace atom {
class AtomBrowserContext;
class URLRequestFetchJob : public JsAsker<net::URLRequestJob>,
public net::URLFetcherDelegate,
public brightray::URLRequestContextGetter::Delegate {
public net::URLFetcherDelegate {
public:
URLRequestFetchJob(net::URLRequest*, net::NetworkDelegate*);
~URLRequestFetchJob() override;
@@ -51,6 +52,7 @@ class URLRequestFetchJob : public JsAsker<net::URLRequestJob>,
void ClearPendingBuffer();
void ClearWriteBuffer();
scoped_refptr<AtomBrowserContext> custom_browser_context_;
scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_;
std::unique_ptr<net::URLFetcher> fetcher_;
std::unique_ptr<net::HttpResponseInfo> response_info_;

View File

@@ -4,6 +4,8 @@
#include "atom/browser/node_debugger.h"
#include <string>
#include "base/command_line.h"
#include "base/strings/utf_string_conversions.h"
#include "libplatform/libplatform.h"
@@ -25,10 +27,15 @@ void NodeDebugger::Start(node::MultiIsolatePlatform* platform) {
node::DebugOptions options;
for (auto& arg : base::CommandLine::ForCurrentProcess()->argv()) {
#if defined(OS_WIN)
options.ParseOption("Electron", base::UTF16ToUTF8(arg));
const std::string nice_arg = base::UTF16ToUTF8(arg);
#else
options.ParseOption("Electron", arg);
const std::string& nice_arg = arg;
#endif
// Stop handling arguments after a "--" to be consistent with Chromium
if (nice_arg == "--")
break;
options.ParseOption("Electron", nice_arg);
}
// Set process._debugWaitConnect if --inspect-brk was specified to stop

View File

@@ -264,6 +264,7 @@ OffScreenRenderWidgetHostView::OffScreenRenderWidgetHostView(
size_(native_window->GetSize()),
painting_(painting),
is_showing_(!render_widget_host_->is_hidden()),
mouse_wheel_phase_handler_(render_widget_host_, this),
weak_ptr_factory_(this) {
DCHECK(render_widget_host_);
bool is_guest_view_hack = parent_host_view_ != nullptr;
@@ -279,10 +280,8 @@ OffScreenRenderWidgetHostView::OffScreenRenderWidgetHostView(
local_surface_id_ = local_surface_id_allocator_.GenerateId();
// Surface synchronization is not supported with OSR.
DCHECK(!features::IsSurfaceSynchronizationEnabled());
#if defined(OS_MACOSX)
last_frame_root_background_color_ = SK_ColorTRANSPARENT;
CreatePlatformWidget(is_guest_view_hack);
#else
// On macOS the ui::Compositor is created/owned by the platform view.
@@ -303,7 +302,7 @@ OffScreenRenderWidgetHostView::OffScreenRenderWidgetHostView(
native_window_->AddObserver(this);
ResizeRootLayer();
ResizeRootLayer(false);
render_widget_host_->SetView(this);
InstallTransparency();
}
@@ -385,7 +384,7 @@ void OffScreenRenderWidgetHostView::InitAsChild(gfx::NativeView) {
parent_host_view_->set_child_host_view(this);
parent_host_view_->Hide();
ResizeRootLayer();
ResizeRootLayer(false);
Show();
}
@@ -514,6 +513,10 @@ void OffScreenRenderWidgetHostView::SubmitCompositorFrame(
TRACE_EVENT0("electron",
"OffScreenRenderWidgetHostView::SubmitCompositorFrame");
#if defined(OS_MACOSX)
last_frame_root_background_color_ = frame.metadata.root_background_color;
#endif
if (frame.metadata.root_scroll_offset != last_scroll_offset_) {
last_scroll_offset_ = frame.metadata.root_scroll_offset;
}
@@ -579,7 +582,7 @@ void OffScreenRenderWidgetHostView::InitAsPopup(
popup_position_ = pos;
ResizeRootLayer();
ResizeRootLayer(false);
Show();
}
@@ -743,10 +746,6 @@ OffScreenRenderWidgetHostView::DelegatedFrameHostCreateResizeLock() {
return std::make_unique<content::CompositorResizeLock>(this, desired_size);
}
viz::LocalSurfaceId OffScreenRenderWidgetHostView::GetLocalSurfaceId() const {
return local_surface_id_;
}
void OffScreenRenderWidgetHostView::OnFirstSurfaceActivation(
const viz::SurfaceInfo& surface_info) {}
@@ -774,8 +773,26 @@ bool OffScreenRenderWidgetHostView::IsAutoResizeEnabled() const {
return render_widget_host_->auto_resize_enabled();
}
viz::LocalSurfaceId OffScreenRenderWidgetHostView::GetLocalSurfaceId() const {
return local_surface_id_;
}
#endif // !defined(OS_MACOSX)
viz::FrameSinkId OffScreenRenderWidgetHostView::GetFrameSinkId() {
return GetDelegatedFrameHost()->frame_sink_id();
}
void OffScreenRenderWidgetHostView::DidNavigate() {
ResizeRootLayer(true);
#if defined(OS_MACOSX)
browser_compositor_->DidNavigate();
#else
if (delegated_frame_host_)
delegated_frame_host_->DidNavigate();
#endif
}
bool OffScreenRenderWidgetHostView::TransformPointToLocalCoordSpace(
const gfx::PointF& point,
const viz::SurfaceId& original_surface,
@@ -882,7 +899,7 @@ OffScreenRenderWidgetHostView::CreateSoftwareOutputDevice(
DCHECK(!copy_frame_generator_);
DCHECK(!software_output_device_);
ResizeRootLayer();
ResizeRootLayer(false);
software_output_device_ = new OffScreenOutputDevice(
transparent_, base::Bind(&OffScreenRenderWidgetHostView::OnPaint,
@@ -1034,7 +1051,7 @@ void OffScreenRenderWidgetHostView::WasResized() {
return;
}
ResizeRootLayer();
ResizeRootLayer(false);
if (render_widget_host_)
render_widget_host_->WasResized();
GetDelegatedFrameHost()->WasResized(local_surface_id_, size_,
@@ -1096,18 +1113,29 @@ void OffScreenRenderWidgetHostView::SendMouseWheelEvent(
return;
}
}
blink::WebMouseWheelEvent mouse_wheel_event(event);
mouse_wheel_phase_handler_.SendWheelEndIfNeeded();
mouse_wheel_phase_handler_.AddPhaseIfNeededAndScheduleEndEvent(
mouse_wheel_event, false);
if (!IsPopupWidget()) {
if (popup_host_view_) {
if (popup_host_view_->popup_position_.Contains(
event.PositionInWidget().x, event.PositionInWidget().y)) {
blink::WebMouseWheelEvent popup_event(event);
popup_event.SetPositionInWidget(
popup_event.PositionInWidget().x -
mouse_wheel_event.PositionInWidget().x,
mouse_wheel_event.PositionInWidget().y)) {
blink::WebMouseWheelEvent popup_mouse_wheel_event(mouse_wheel_event);
popup_mouse_wheel_event.SetPositionInWidget(
mouse_wheel_event.PositionInWidget().x -
popup_host_view_->popup_position_.x(),
popup_event.PositionInWidget().y -
mouse_wheel_event.PositionInWidget().y -
popup_host_view_->popup_position_.y());
popup_host_view_->ProcessMouseWheelEvent(popup_event,
ui::LatencyInfo());
popup_mouse_wheel_event.SetPositionInScreen(
popup_mouse_wheel_event.PositionInWidget().x,
popup_mouse_wheel_event.PositionInWidget().y);
popup_host_view_->SendMouseWheelEvent(popup_mouse_wheel_event);
return;
} else {
// Scrolling outside of the popup widget so destroy it.
@@ -1118,6 +1146,28 @@ void OffScreenRenderWidgetHostView::SendMouseWheelEvent(
base::BindOnce(&OffScreenRenderWidgetHostView::CancelWidget,
popup_host_view_->weak_ptr_factory_.GetWeakPtr()));
}
} else if (!guest_host_views_.empty()) {
for (auto guest_host_view : guest_host_views_) {
if (!guest_host_view->render_widget_host_ ||
!guest_host_view->render_widget_host_->GetView()) {
continue;
}
const gfx::Rect& guest_bounds =
guest_host_view->render_widget_host_->GetView()->GetViewBounds();
if (guest_bounds.Contains(mouse_wheel_event.PositionInWidget().x,
mouse_wheel_event.PositionInWidget().y)) {
blink::WebMouseWheelEvent guest_mouse_wheel_event(mouse_wheel_event);
guest_mouse_wheel_event.SetPositionInWidget(
mouse_wheel_event.PositionInWidget().x - guest_bounds.x(),
mouse_wheel_event.PositionInWidget().y - guest_bounds.y());
guest_mouse_wheel_event.SetPositionInScreen(
guest_mouse_wheel_event.PositionInWidget().x,
guest_mouse_wheel_event.PositionInWidget().y);
guest_host_view->SendMouseWheelEvent(guest_mouse_wheel_event);
return;
}
}
}
}
if (!render_widget_host_)
@@ -1183,8 +1233,10 @@ void OffScreenRenderWidgetHostView::SetupFrameRate(bool force) {
frame_rate_threshold_us_ = 1000000 / frame_rate_;
GetCompositor()->SetAuthoritativeVSyncInterval(
base::TimeDelta::FromMicroseconds(frame_rate_threshold_us_));
if (GetCompositor()) {
GetCompositor()->SetAuthoritativeVSyncInterval(
base::TimeDelta::FromMicroseconds(frame_rate_threshold_us_));
}
if (copy_frame_generator_.get()) {
copy_frame_generator_->set_frame_rate_threshold_us(
@@ -1213,7 +1265,7 @@ void OffScreenRenderWidgetHostView::InvalidateBounds(const gfx::Rect& bounds) {
}
}
void OffScreenRenderWidgetHostView::ResizeRootLayer() {
void OffScreenRenderWidgetHostView::ResizeRootLayer(bool force) {
SetupFrameRate(false);
const float compositorScaleFactor = GetCompositor()->device_scale_factor();
@@ -1225,7 +1277,8 @@ void OffScreenRenderWidgetHostView::ResizeRootLayer() {
else
size = popup_position_.size();
if (!scaleFactorDidChange && size == GetRootLayer()->bounds().size())
if (!force && !scaleFactorDidChange &&
size == GetRootLayer()->bounds().size())
return;
const gfx::Size& size_in_pixels =

View File

@@ -27,6 +27,7 @@
#include "content/browser/frame_host/render_widget_host_view_guest.h"
#include "content/browser/renderer_host/compositor_resize_lock.h"
#include "content/browser/renderer_host/delegated_frame_host.h"
#include "content/browser/renderer_host/input/mouse_wheel_phase_handler.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/browser/web_contents/web_contents_view.h"
@@ -108,12 +109,12 @@ class OffScreenRenderWidgetHostView
void SetNeedsBeginFrames(bool needs_begin_frames) override;
void SetWantsAnimateOnlyBeginFrames() override;
#if defined(OS_MACOSX)
ui::AcceleratedWidgetMac* GetAcceleratedWidgetMac() const override;
void SetActive(bool active) override;
void ShowDefinitionForSelection() override;
bool SupportsSpeech() const override;
void SpeakSelection() override;
bool IsSpeaking() const override;
bool ShouldContinueToPauseForFrame() override;
void StopSpeaking() override;
#endif // defined(OS_MACOSX)
@@ -169,7 +170,6 @@ class OffScreenRenderWidgetHostView
bool DelegatedFrameCanCreateResizeLock() const override;
std::unique_ptr<content::CompositorResizeLock>
DelegatedFrameHostCreateResizeLock() override;
viz::LocalSurfaceId GetLocalSurfaceId() const override;
void OnFirstSurfaceActivation(const viz::SurfaceInfo& surface_info) override;
void OnBeginFrame(base::TimeTicks frame_time) override;
void OnFrameTokenChanged(uint32_t frame_token) override;
@@ -181,6 +181,11 @@ class OffScreenRenderWidgetHostView
bool IsAutoResizeEnabled() const override;
#endif // !defined(OS_MACOSX)
viz::LocalSurfaceId GetLocalSurfaceId() const override;
viz::FrameSinkId GetFrameSinkId() override;
void DidNavigate() override;
bool TransformPointToLocalCoordSpace(const gfx::PointF& point,
const viz::SurfaceId& original_surface,
gfx::PointF* transformed_point) override;
@@ -205,6 +210,9 @@ class OffScreenRenderWidgetHostView
#if defined(OS_MACOSX)
void CreatePlatformWidget(bool is_guest_view_hack);
void DestroyPlatformWidget();
SkColor last_frame_root_background_color() const {
return last_frame_root_background_color_;
}
#endif
void CancelWidget();
@@ -260,11 +268,9 @@ class OffScreenRenderWidgetHostView
child_host_view_ = child_view;
}
viz::LocalSurfaceId local_surface_id() const { return local_surface_id_; }
private:
void SetupFrameRate(bool force);
void ResizeRootLayer();
void ResizeRootLayer(bool force);
viz::FrameSinkId AllocateFrameSinkId(bool is_guest_view_hack);
@@ -325,6 +331,8 @@ class OffScreenRenderWidgetHostView
#if defined(OS_MACOSX)
std::unique_ptr<content::BrowserCompositorMac> browser_compositor_;
SkColor last_frame_root_background_color_;
// Can not be managed by smart pointer because its header can not be included
// in the file that has the destructor.
MacHelper* mac_helper_;
@@ -333,6 +341,8 @@ class OffScreenRenderWidgetHostView
std::string selected_text_;
#endif
content::MouseWheelPhaseHandler mouse_wheel_phase_handler_;
viz::mojom::CompositorFrameSinkClient* renderer_compositor_frame_sink_ =
nullptr;

View File

@@ -22,7 +22,7 @@ class MacHelper : public content::BrowserCompositorMacClient,
virtual ~MacHelper() {}
// content::BrowserCompositorMacClient:
SkColor BrowserCompositorMacGetGutterColor(SkColor color) const override {
SkColor BrowserCompositorMacGetGutterColor() const override {
// When making an element on the page fullscreen the element's background
// may not match the page's, so use black as the gutter color to avoid
// flashes of brighter colors during the transition.
@@ -30,7 +30,7 @@ class MacHelper : public content::BrowserCompositorMacClient,
view_->render_widget_host()->delegate()->IsFullscreenForCurrentTab()) {
return SK_ColorBLACK;
}
return color;
return view_->last_frame_root_background_color();
}
void BrowserCompositorMacOnBeginFrame() override {}
@@ -81,7 +81,7 @@ bool OffScreenRenderWidgetHostView::IsSpeaking() const {
void OffScreenRenderWidgetHostView::StopSpeaking() {}
bool CefRenderWidgetHostViewOSR::ShouldContinueToPauseForFrame() {
bool OffScreenRenderWidgetHostView::ShouldContinueToPauseForFrame() {
return browser_compositor_->ShouldContinueToPauseForFrame();
}
@@ -98,6 +98,10 @@ void OffScreenRenderWidgetHostView::DestroyPlatformWidget() {
delete mac_helper_;
}
viz::LocalSurfaceId OffScreenRenderWidgetHostView::GetLocalSurfaceId() const {
return browser_compositor_->GetRendererLocalSurfaceId();
}
ui::Compositor* OffScreenRenderWidgetHostView::GetCompositor() const {
return browser_compositor_->GetCompositor();
}

View File

@@ -0,0 +1,163 @@
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/request_context_delegate.h"
#include "atom/browser/api/atom_api_protocol.h"
#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_network_delegate.h"
#include "atom/browser/net/atom_url_request_job_factory.h"
#include "atom/browser/net/cookie_details.h"
#include "atom/browser/net/http_protocol_handler.h"
#include "atom/common/options_switches.h"
#include "base/strings/string_number_conversions.h"
#include "base/task_scheduler/post_task.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/url_constants.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/url_request/data_protocol_handler.h"
#include "net/url_request/ftp_protocol_handler.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_intercepting_job_factory.h"
#include "url/url_constants.h"
using content::BrowserThread;
namespace atom {
namespace {
class NoCacheBackend : public net::HttpCache::BackendFactory {
int CreateBackend(net::NetLog* net_log,
std::unique_ptr<disk_cache::Backend>* backend,
const net::CompletionCallback& callback) override {
return net::ERR_FAILED;
}
};
} // namespace
RequestContextDelegate::RequestContextDelegate(bool use_cache)
: use_cache_(use_cache), weak_factory_(this) {}
RequestContextDelegate::~RequestContextDelegate() {}
std::unique_ptr<base::CallbackList<void(const CookieDetails*)>::Subscription>
RequestContextDelegate::RegisterCookieChangeCallback(
const base::Callback<void(const CookieDetails*)>& cb) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return cookie_change_sub_list_.Add(cb);
}
void RequestContextDelegate::NotifyCookieChange(
const net::CanonicalCookie& cookie,
net::CookieChangeCause cause) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
CookieDetails cookie_details(
&cookie, !(cause == net::CookieChangeCause::INSERTED), cause);
cookie_change_sub_list_.Notify(&cookie_details);
}
std::unique_ptr<net::NetworkDelegate>
RequestContextDelegate::CreateNetworkDelegate() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
return std::make_unique<AtomNetworkDelegate>();
}
std::unique_ptr<net::URLRequestJobFactory>
RequestContextDelegate::CreateURLRequestJobFactory(
net::URLRequestContext* url_request_context,
content::ProtocolHandlerMap* protocol_handlers) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
std::unique_ptr<AtomURLRequestJobFactory> job_factory(
new AtomURLRequestJobFactory);
for (auto& it : *protocol_handlers) {
job_factory->SetProtocolHandler(it.first,
base::WrapUnique(it.second.release()));
}
protocol_handlers->clear();
job_factory->SetProtocolHandler(url::kAboutScheme,
base::WrapUnique(new AboutProtocolHandler));
job_factory->SetProtocolHandler(
url::kDataScheme, base::WrapUnique(new net::DataProtocolHandler));
job_factory->SetProtocolHandler(
url::kFileScheme,
base::WrapUnique(
new asar::AsarProtocolHandler(base::CreateTaskRunnerWithTraits(
{base::MayBlock(), base::TaskPriority::USER_VISIBLE,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}))));
job_factory->SetProtocolHandler(
url::kHttpScheme,
base::WrapUnique(new HttpProtocolHandler(url::kHttpScheme)));
job_factory->SetProtocolHandler(
url::kHttpsScheme,
base::WrapUnique(new HttpProtocolHandler(url::kHttpsScheme)));
job_factory->SetProtocolHandler(
url::kWsScheme,
base::WrapUnique(new HttpProtocolHandler(url::kWsScheme)));
job_factory->SetProtocolHandler(
url::kWssScheme,
base::WrapUnique(new HttpProtocolHandler(url::kWssScheme)));
auto* host_resolver = url_request_context->host_resolver();
job_factory->SetProtocolHandler(
url::kFtpScheme, net::FtpProtocolHandler::Create(host_resolver));
return std::move(job_factory);
}
net::HttpCache::BackendFactory*
RequestContextDelegate::CreateHttpCacheBackendFactory(
const base::FilePath& base_path) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (!use_cache_) {
return new NoCacheBackend;
} else {
int max_size = 0;
base::StringToInt(
command_line->GetSwitchValueASCII(switches::kDiskCacheSize), &max_size);
base::FilePath cache_path = base_path.Append(FILE_PATH_LITERAL("Cache"));
return new net::HttpCache::DefaultBackend(
net::DISK_CACHE, net::CACHE_BACKEND_DEFAULT, cache_path, max_size);
}
}
std::unique_ptr<net::CertVerifier> RequestContextDelegate::CreateCertVerifier(
brightray::RequireCTDelegate* ct_delegate) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
return std::make_unique<AtomCertVerifier>(ct_delegate);
}
void RequestContextDelegate::GetCookieableSchemes(
std::vector<std::string>* cookie_schemes) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
const auto& standard_schemes = atom::api::GetStandardSchemes();
cookie_schemes->insert(cookie_schemes->end(), standard_schemes.begin(),
standard_schemes.end());
}
void RequestContextDelegate::OnCookieChanged(const net::CanonicalCookie& cookie,
net::CookieChangeCause cause) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindRepeating(&RequestContextDelegate::NotifyCookieChange,
weak_factory_.GetWeakPtr(), cookie, cause));
}
} // namespace atom

View File

@@ -0,0 +1,58 @@
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_REQUEST_CONTEXT_DELEGATE_H_
#define ATOM_BROWSER_REQUEST_CONTEXT_DELEGATE_H_
#include <string>
#include <vector>
#include "base/callback_list.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "brightray/browser/url_request_context_getter.h"
namespace atom {
struct CookieDetails;
class RequestContextDelegate
: public brightray::URLRequestContextGetter::Delegate {
public:
explicit RequestContextDelegate(bool use_cache);
~RequestContextDelegate() override;
// Register callbacks that needs to notified on any cookie store changes.
std::unique_ptr<base::CallbackList<void(const CookieDetails*)>::Subscription>
RegisterCookieChangeCallback(
const base::Callback<void(const CookieDetails*)>& cb);
protected:
std::unique_ptr<net::NetworkDelegate> CreateNetworkDelegate() override;
std::unique_ptr<net::URLRequestJobFactory> CreateURLRequestJobFactory(
net::URLRequestContext* url_request_context,
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;
void GetCookieableSchemes(std::vector<std::string>* cookie_schemes) override;
void OnCookieChanged(const net::CanonicalCookie& cookie,
net::CookieChangeCause cause) override;
private:
void NotifyCookieChange(const net::CanonicalCookie& cookie,
net::CookieChangeCause cause);
base::CallbackList<void(const CookieDetails*)> cookie_change_sub_list_;
bool use_cache_ = true;
base::WeakPtrFactory<RequestContextDelegate> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(RequestContextDelegate);
};
} // namespace atom
#endif // ATOM_BROWSER_REQUEST_CONTEXT_DELEGATE_H_

View File

@@ -56,8 +56,8 @@ END
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 3,0,0,3
PRODUCTVERSION 3,0,0,3
FILEVERSION 3,0,0,8
PRODUCTVERSION 3,0,0,8
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L

View File

@@ -97,11 +97,6 @@ NSAlert* CreateNSAlert(NativeWindow* parent_window,
NSArray* ns_buttons = [alert buttons];
int button_count = static_cast<int>([ns_buttons count]);
// Bind cancel id button to escape key if there is more than one button
if (button_count > 1 && cancel_id >= 0 && cancel_id < button_count) {
[[ns_buttons objectAtIndex:cancel_id] setKeyEquivalent:@"\e"];
}
if (default_id >= 0 && default_id < button_count) {
// Focus the button at default_id if the user opted to do so.
// The first button added gets set as the default selected.
@@ -110,6 +105,11 @@ NSAlert* CreateNSAlert(NativeWindow* parent_window,
[[ns_buttons objectAtIndex:default_id] setKeyEquivalent:@"\r"];
}
// Bind cancel id button to escape key if there is more than one button
if (button_count > 1 && cancel_id >= 0 && cancel_id < button_count) {
[[ns_buttons objectAtIndex:cancel_id] setKeyEquivalent:@"\e"];
}
if (!checkbox_label.empty()) {
alert.showsSuppressionButton = YES;
alert.suppressionButton.title = base::SysUTF8ToNSString(checkbox_label);

View File

@@ -41,9 +41,16 @@ const CGFloat kVerticalTitleMargin = 2;
@implementation StatusItemView
- (void)dealloc {
trayIcon_ = nil;
menuController_ = nil;
[super dealloc];
}
- (id)initWithImage:(NSImage*)image icon:(atom::TrayIconCocoa*)icon {
image_.reset([image copy]);
trayIcon_ = icon;
menuController_ = nil;
highlight_mode_ = atom::TrayIcon::HighlightMode::SELECTION;
ignoreDoubleClickEvents_ = NO;
forceHighlight_ = NO;
@@ -89,6 +96,7 @@ const CGFloat kVerticalTitleMargin = 2;
trackingArea_.reset();
}
[[NSStatusBar systemStatusBar] removeStatusItem:statusItem_];
[statusItem_ setView:nil];
statusItem_.reset();
}
@@ -474,11 +482,18 @@ void TrayIconCocoa::SetContextMenu(AtomMenuModel* menu_model) {
// Substribe to MenuClosed event.
if (menu_model_)
menu_model_->RemoveObserver(this);
menu_model->AddObserver(this);
// Create native menu.
menu_.reset([[AtomMenuController alloc] initWithModel:menu_model
useDefaultAccelerator:NO]);
menu_model_ = menu_model;
if (menu_model) {
menu_model->AddObserver(this);
// Create native menu.
menu_.reset([[AtomMenuController alloc] initWithModel:menu_model
useDefaultAccelerator:NO]);
} else {
menu_.reset();
}
[status_item_view_ setMenuController:menu_.get()];
}

View File

@@ -109,6 +109,30 @@ void WebContentsPreferences::Merge(const base::DictionaryValue& extend) {
dict_.MergeDictionary(&extend);
}
bool WebContentsPreferences::GetPreloadPath(
base::FilePath::StringType* path) const {
DCHECK(path);
base::FilePath::StringType preload;
if (dict_.GetString(options::kPreloadScript, &preload)) {
if (base::FilePath(preload).IsAbsolute()) {
*path = std::move(preload);
return true;
} else {
LOG(ERROR) << "preload script must have absolute path.";
}
} else if (dict_.GetString(options::kPreloadURL, &preload)) {
// Translate to file path if there is "preload-url" option.
base::FilePath preload_path;
if (net::FileURLToFilePath(GURL(preload), &preload_path)) {
*path = std::move(preload_path.value());
return true;
} else {
LOG(ERROR) << "preload url must be file:// protocol.";
}
}
return false;
}
// static
content::WebContents* WebContentsPreferences::GetWebContentsFromProcessID(
int process_id) {
@@ -171,19 +195,8 @@ void WebContentsPreferences::AppendCommandLineSwitches(
// The preload script.
base::FilePath::StringType preload;
if (dict_.GetString(options::kPreloadScript, &preload)) {
if (base::FilePath(preload).IsAbsolute())
command_line->AppendSwitchNative(switches::kPreloadScript, preload);
else
LOG(ERROR) << "preload script must have absolute path.";
} else if (dict_.GetString(options::kPreloadURL, &preload)) {
// Translate to file path if there is "preload-url" option.
base::FilePath preload_path;
if (net::FileURLToFilePath(GURL(preload), &preload_path))
command_line->AppendSwitchPath(switches::kPreloadScript, preload_path);
else
LOG(ERROR) << "preload url must be file:// protocol.";
}
if (GetPreloadPath(&preload))
command_line->AppendSwitchNative(switches::kPreloadScript, preload);
// Custom args for renderer process
base::Value* customArgs;

View File

@@ -48,6 +48,9 @@ class WebContentsPreferences
// Modify the WebPreferences according to preferences.
void OverrideWebkitPrefs(content::WebPreferences* prefs);
// Returns the preload script path.
bool GetPreloadPath(base::FilePath::StringType* path) const;
// Returns the web preferences.
base::DictionaryValue* dict() { return &dict_; }
const base::DictionaryValue* dict() const { return &dict_; }

View File

@@ -228,6 +228,9 @@ void WebContentsZoomController::DidFinishNavigation(
}
void WebContentsZoomController::WebContentsDestroyed() {
for (Observer& observer : observers_)
observer.OnZoomControllerWebContentsDestroyed();
observers_.Clear();
embedder_zoom_controller_ = nullptr;
}

View File

@@ -24,6 +24,7 @@ class WebContentsZoomController
virtual void OnZoomLevelChanged(content::WebContents* web_contents,
double level,
bool is_temporary) {}
virtual void OnZoomControllerWebContentsDestroyed() {}
protected:
virtual ~Observer() {}

View File

@@ -7,144 +7,60 @@
#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/guest_host.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
namespace atom {
namespace {
WebViewGuestDelegate::WebViewGuestDelegate(content::WebContents* embedder,
api::WebContents* api_web_contents)
: embedder_web_contents_(embedder), api_web_contents_(api_web_contents) {}
const int kDefaultWidth = 300;
const int kDefaultHeight = 300;
} // namespace
SetSizeParams::SetSizeParams() = default;
SetSizeParams::~SetSizeParams() = default;
WebViewGuestDelegate::WebViewGuestDelegate() {}
WebViewGuestDelegate::~WebViewGuestDelegate() {}
void WebViewGuestDelegate::Initialize(api::WebContents* api_web_contents) {
api_web_contents_ = api_web_contents;
Observe(api_web_contents->GetWebContents());
}
void WebViewGuestDelegate::Destroy() {
// Give the content module an opportunity to perform some cleanup.
ResetZoomController();
guest_host_->WillDestroy();
guest_host_ = nullptr;
}
void WebViewGuestDelegate::SetSize(const SetSizeParams& params) {
bool enable_auto_size =
params.enable_auto_size ? *params.enable_auto_size : auto_size_enabled_;
gfx::Size min_size = params.min_size ? *params.min_size : min_auto_size_;
gfx::Size max_size = params.max_size ? *params.max_size : max_auto_size_;
if (params.normal_size)
normal_size_ = *params.normal_size;
min_auto_size_ = min_size;
min_auto_size_.SetToMin(max_size);
max_auto_size_ = max_size;
max_auto_size_.SetToMax(min_size);
enable_auto_size &= !min_auto_size_.IsEmpty() && !max_auto_size_.IsEmpty();
auto* rvh = web_contents()->GetRenderViewHost();
if (enable_auto_size) {
// Autosize is being enabled.
rvh->EnableAutoResize(min_auto_size_, max_auto_size_);
normal_size_.SetSize(0, 0);
} else {
// Autosize is being disabled.
// Use default width/height if missing from partially defined normal size.
if (normal_size_.width() && !normal_size_.height())
normal_size_.set_height(GetDefaultSize().height());
if (!normal_size_.width() && normal_size_.height())
normal_size_.set_width(GetDefaultSize().width());
gfx::Size new_size;
if (!normal_size_.IsEmpty()) {
new_size = normal_size_;
} else if (!guest_size_.IsEmpty()) {
new_size = guest_size_;
} else {
new_size = GetDefaultSize();
}
bool changed_due_to_auto_resize = false;
if (auto_size_enabled_) {
// Autosize was previously enabled.
rvh->DisableAutoResize(new_size);
changed_due_to_auto_resize = true;
} else {
// Autosize was already disabled.
guest_host_->SizeContents(new_size);
}
UpdateGuestSize(new_size, changed_due_to_auto_resize);
}
auto_size_enabled_ = enable_auto_size;
}
void WebViewGuestDelegate::ResizeDueToAutoResize(const gfx::Size& new_size) {
UpdateGuestSize(new_size, auto_size_enabled_);
}
void WebViewGuestDelegate::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (navigation_handle->HasCommitted() && !navigation_handle->IsErrorPage()) {
auto is_main_frame = navigation_handle->IsInMainFrame();
auto url = navigation_handle->GetURL();
api_web_contents_->Emit("load-commit", url, is_main_frame);
}
}
void WebViewGuestDelegate::DidDetach() {
attached_ = false;
WebViewGuestDelegate::~WebViewGuestDelegate() {
ResetZoomController();
}
void WebViewGuestDelegate::DidAttach(int guest_proxy_routing_id) {
attached_ = true;
api_web_contents_->Emit("did-attach");
void WebViewGuestDelegate::AttachToIframe(
content::WebContents* embedder_web_contents,
int embedder_frame_id) {
embedder_web_contents_ = embedder_web_contents;
int embedder_process_id =
embedder_web_contents_->GetMainFrame()->GetProcess()->GetID();
auto* embedder_frame =
content::RenderFrameHost::FromID(embedder_process_id, embedder_frame_id);
DCHECK_EQ(embedder_web_contents_,
content::WebContents::FromRenderFrameHost(embedder_frame));
// Attach this inner WebContents |guest_web_contents| to the outer
// WebContents |embedder_web_contents|. The outer WebContents's
// frame |embedder_frame| hosts the inner WebContents.
api_web_contents_->web_contents()->AttachToOuterWebContentsFrame(
embedder_web_contents_, embedder_frame);
ResetZoomController();
embedder_zoom_controller_ =
WebContentsZoomController::FromWebContents(embedder_web_contents_);
auto* zoom_controller = api_web_contents_->GetZoomController();
embedder_zoom_controller_->AddObserver(this);
auto* zoom_controller = api_web_contents_->GetZoomController();
zoom_controller->SetEmbedderZoomController(embedder_zoom_controller_);
api_web_contents_->Emit("did-attach");
}
void WebViewGuestDelegate::DidDetach() {
ResetZoomController();
}
content::WebContents* WebViewGuestDelegate::GetOwnerWebContents() const {
return embedder_web_contents_;
}
void WebViewGuestDelegate::SetGuestHost(content::GuestHost* guest_host) {
guest_host_ = guest_host;
}
void WebViewGuestDelegate::WillAttach(
content::WebContents* embedder_web_contents,
int element_instance_id,
bool is_full_page_plugin,
const base::Closure& completion_callback) {
embedder_web_contents_ = embedder_web_contents;
is_full_page_plugin_ = is_full_page_plugin;
completion_callback.Run();
}
void WebViewGuestDelegate::OnZoomLevelChanged(
content::WebContents* web_contents,
double level,
@@ -161,23 +77,8 @@ void WebViewGuestDelegate::OnZoomLevelChanged(
}
}
void WebViewGuestDelegate::UpdateGuestSize(const gfx::Size& new_size,
bool due_to_auto_resize) {
if (due_to_auto_resize)
api_web_contents_->Emit("size-changed", guest_size_.width(),
guest_size_.height(), new_size.width(),
new_size.height());
guest_size_ = new_size;
}
gfx::Size WebViewGuestDelegate::GetDefaultSize() const {
if (is_full_page_plugin_) {
// Full page plugins default to the size of the owner's viewport.
return embedder_web_contents_->GetRenderWidgetHostView()
->GetVisibleViewportSize();
} else {
return gfx::Size(kDefaultWidth, kDefaultHeight);
}
void WebViewGuestDelegate::OnZoomControllerWebContentsDestroyed() {
ResetZoomController();
}
void WebViewGuestDelegate::ResetZoomController() {
@@ -187,10 +88,6 @@ void WebViewGuestDelegate::ResetZoomController() {
}
}
bool WebViewGuestDelegate::CanBeEmbeddedInsideCrossProcessFrames() {
return true;
}
content::RenderWidgetHost* WebViewGuestDelegate::GetOwnerRenderWidgetHost() {
return embedder_web_contents_->GetRenderViewHost()->GetWidget();
}

View File

@@ -7,7 +7,6 @@
#include "atom/browser/web_contents_zoom_controller.h"
#include "content/public/browser/browser_plugin_guest_delegate.h"
#include "content/public/browser/web_contents_observer.h"
namespace atom {
@@ -15,80 +14,33 @@ namespace api {
class WebContents;
}
// A struct of parameters for SetSize(). The parameters are all declared as
// scoped pointers since they are all optional. Null pointers indicate that the
// parameter has not been provided, and the last used value should be used. Note
// that when |enable_auto_size| is true, providing |normal_size| is not
// meaningful. This is because the normal size of the guestview is overridden
// whenever autosizing occurs.
struct SetSizeParams {
SetSizeParams();
~SetSizeParams();
std::unique_ptr<bool> enable_auto_size;
std::unique_ptr<gfx::Size> min_size;
std::unique_ptr<gfx::Size> max_size;
std::unique_ptr<gfx::Size> normal_size;
};
class WebViewGuestDelegate : public content::BrowserPluginGuestDelegate,
public content::WebContentsObserver,
public WebContentsZoomController::Observer {
public:
WebViewGuestDelegate();
WebViewGuestDelegate(content::WebContents* embedder,
api::WebContents* api_web_contents);
~WebViewGuestDelegate() override;
void Initialize(api::WebContents* api_web_contents);
// Called when the WebContents is going to be destroyed.
void Destroy();
// Used to toggle autosize mode for this GuestView, and set both the automatic
// and normal sizes.
void SetSize(const SetSizeParams& params);
// Invoked when the contents auto-resized and the container should match it.
void ResizeDueToAutoResize(const gfx::Size& new_size);
// Return true if attached.
bool IsAttached() const { return attached_; }
// Attach to the iframe.
void AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id);
protected:
// content::WebContentsObserver:
void DidFinishNavigation(
content::NavigationHandle* navigation_handle) override;
// content::BrowserPluginGuestDelegate:
void DidAttach(int guest_proxy_routing_id) final;
void DidDetach() final;
content::WebContents* GetOwnerWebContents() const final;
void SetGuestHost(content::GuestHost* guest_host) final;
void WillAttach(content::WebContents* embedder_web_contents,
int element_instance_id,
bool is_full_page_plugin,
const base::Closure& completion_callback) final;
bool CanBeEmbeddedInsideCrossProcessFrames() override;
content::RenderWidgetHost* GetOwnerRenderWidgetHost() override;
content::SiteInstance* GetOwnerSiteInstance() override;
content::RenderWidgetHost* GetOwnerRenderWidgetHost() final;
content::SiteInstance* GetOwnerSiteInstance() final;
content::WebContents* CreateNewGuestWindow(
const content::WebContents::CreateParams& create_params) override;
const content::WebContents::CreateParams& create_params) final;
// WebContentsZoomController::Observer:
void OnZoomLevelChanged(content::WebContents* web_contents,
double level,
bool is_temporary) override;
void OnZoomControllerWebContentsDestroyed() override;
private:
// This method is invoked when the contents auto-resized to give the container
// an opportunity to match it if it wishes.
//
// This gives the derived class an opportunity to inform its container element
// or perform other actions.
void UpdateGuestSize(const gfx::Size& new_size, bool due_to_auto_resize);
// Returns the default size of the guestview.
gfx::Size GetDefaultSize() const;
void ResetZoomController();
// The WebContents that attaches this guest view.
@@ -98,34 +50,6 @@ class WebViewGuestDelegate : public content::BrowserPluginGuestDelegate,
// to subscribe for zoom changes.
WebContentsZoomController* embedder_zoom_controller_ = nullptr;
// The size of the container element.
gfx::Size element_size_;
// The size of the guest content. Note: In autosize mode, the container
// element may not match the size of the guest.
gfx::Size guest_size_;
// A pointer to the guest_host.
content::GuestHost* guest_host_ = nullptr;
// Indicates whether autosize mode is enabled or not.
bool auto_size_enabled_ = false;
// The maximum size constraints of the container element in autosize mode.
gfx::Size max_auto_size_;
// The minimum size constraints of the container element in autosize mode.
gfx::Size min_auto_size_;
// The size that will be used when autosize mode is disabled.
gfx::Size normal_size_;
// Whether the guest view is inside a plugin document.
bool is_full_page_plugin_ = false;
// Whether attached.
bool attached_ = false;
api::WebContents* api_web_contents_ = nullptr;
DISALLOW_COPY_AND_ASSIGN(WebViewGuestDelegate);

View File

@@ -12,20 +12,10 @@
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/node_includes.h"
#include "base/hash.h"
#include "base/process/process_handle.h"
#include "base/strings/stringprintf.h"
#include "native_mate/dictionary.h"
#include "url/origin.h"
#include "v8/include/v8-profiler.h"
// This is defined in later versions of Chromium, remove this if you see
// compiler complaining duplicate defines.
#if defined(OS_WIN) || defined(OS_FUCHSIA)
#define CrPRIdPid "ld"
#else
#define CrPRIdPid "d"
#endif
namespace std {
// The hash function used by DoubleIDWeakMap.
@@ -100,16 +90,6 @@ int32_t GetObjectHash(v8::Local<v8::Object> object) {
return object->GetIdentityHash();
}
std::string GetContextID(v8::Isolate* isolate) {
// When a page is reloaded, V8 and blink may have optimizations that do not
// free blink::WebLocalFrame and v8::Context and reuse them for the new page,
// while we always recreate node::Environment when a page is loaded.
// So the only reliable way to return an identity for a page, is to return the
// address of the node::Environment instance.
node::Environment* env = node::Environment::GetCurrent(isolate);
return base::StringPrintf("%" CrPRIdPid "-%p", base::GetCurrentProcId(), env);
}
void TakeHeapSnapshot(v8::Isolate* isolate) {
isolate->GetHeapProfiler()->TakeHeapSnapshot();
}
@@ -132,7 +112,6 @@ void Initialize(v8::Local<v8::Object> exports,
dict.SetMethod("setHiddenValue", &SetHiddenValue);
dict.SetMethod("deleteHiddenValue", &DeleteHiddenValue);
dict.SetMethod("getObjectHash", &GetObjectHash);
dict.SetMethod("getContextId", &GetContextID);
dict.SetMethod("takeHeapSnapshot", &TakeHeapSnapshot);
dict.SetMethod("setRemoteCallbackFreer", &atom::RemoteCallbackFreer::BindTo);
dict.SetMethod("setRemoteObjectFreer", &atom::RemoteObjectFreer::BindTo);

View File

@@ -31,6 +31,22 @@ bool IsPDFViewerEnabled() {
#endif
}
bool IsFakeLocationProviderEnabled() {
#if defined(OVERRIDE_LOCATION_PROVIDER)
return true;
#else
return false;
#endif
}
bool IsViewApiEnabled() {
#if defined(ENABLE_VIEW_API)
return true;
#else
return false;
#endif
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
@@ -39,6 +55,9 @@ void Initialize(v8::Local<v8::Object> exports,
dict.SetMethod("isDesktopCapturerEnabled", &IsDesktopCapturerEnabled);
dict.SetMethod("isOffscreenRenderingEnabled", &IsOffscreenRenderingEnabled);
dict.SetMethod("isPDFViewerEnabled", &IsPDFViewerEnabled);
dict.SetMethod("isFakeLocationProviderEnabled",
&IsFakeLocationProviderEnabled);
dict.SetMethod("isViewApiEnabled", &IsViewApiEnabled);
}
} // namespace

View File

@@ -8,7 +8,7 @@
#define ATOM_MAJOR_VERSION 3
#define ATOM_MINOR_VERSION 0
#define ATOM_PATCH_VERSION 0
#define ATOM_PRE_RELEASE_VERSION -beta.3
#define ATOM_PRE_RELEASE_VERSION -beta.8
#ifndef ATOM_STRINGIFY
#define ATOM_STRINGIFY(n) ATOM_STRINGIFY_HELPER(n)

View File

@@ -211,6 +211,7 @@ void NodeBindings::Initialize() {
// Init node.
// (we assume node::Init would not modify the parameters under embedded mode).
// NOTE: If you change this line, please ping @codebytere or @MarshallOfSound
node::Init(nullptr, nullptr, nullptr, nullptr);
#if defined(OS_WIN)

View File

@@ -215,6 +215,12 @@ const char kWidevineCdmPath[] = "widevine-cdm-path";
// Widevine CDM version.
const char kWidevineCdmVersion[] = "widevine-cdm-version";
// Forces the maximum disk space to be used by the disk cache, in bytes.
const char kDiskCacheSize[] = "disk-cache-size";
// Ignore the limit of 6 connections per host.
const char kIgnoreConnectionsLimit[] = "ignore-connections-limit";
} // namespace switches
} // namespace atom

View File

@@ -112,6 +112,9 @@ extern const char kWebviewTag[];
extern const char kWidevineCdmPath[];
extern const char kWidevineCdmVersion[];
extern const char kDiskCacheSize[];
extern const char kIgnoreConnectionsLimit[];
} // namespace switches
} // namespace atom

View File

@@ -13,6 +13,7 @@
#include "atom/renderer/api/atom_api_spell_check_client.h"
#include "base/memory/memory_pressure_listener.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/public/renderer/render_frame_visitor.h"
#include "content/public/renderer/render_view.h"
#include "native_mate/dictionary.h"
@@ -62,6 +63,29 @@ namespace api {
namespace {
content::RenderFrame* GetRenderFrame(v8::Local<v8::Value> value) {
v8::Local<v8::Context> context =
v8::Local<v8::Object>::Cast(value)->CreationContext();
if (context.IsEmpty())
return nullptr;
blink::WebLocalFrame* frame = blink::WebLocalFrame::FrameForContext(context);
if (!frame)
return nullptr;
return content::RenderFrame::FromWebFrame(frame);
}
class RenderFrameStatus : public content::RenderFrameObserver {
public:
explicit RenderFrameStatus(content::RenderFrame* render_frame)
: content::RenderFrameObserver(render_frame) {}
~RenderFrameStatus() final {}
bool is_ok() { return render_frame() != nullptr; }
// RenderFrameObserver implementation.
void OnDestruct() final {}
};
class ScriptExecutionCallback : public blink::WebScriptExecutionCallback {
public:
using CompletionCallback =
@@ -170,20 +194,23 @@ v8::Local<v8::Value> WebFrame::RegisterEmbedderCustomElement(
blink::WebString::FromUTF16(name), options);
}
void WebFrame::RegisterElementResizeCallback(
int element_instance_id,
const GuestViewContainer::ResizeCallback& callback) {
auto* guest_view_container = GuestViewContainer::FromID(element_instance_id);
if (guest_view_container)
guest_view_container->RegisterElementResizeCallback(callback);
}
int WebFrame::GetWebFrameId(v8::Local<v8::Value> content_window) {
// Get the WebLocalFrame before (possibly) executing any user-space JS while
// getting the |params|. We track the status of the RenderFrame via an
// observer in case it is deleted during user code execution.
content::RenderFrame* render_frame = GetRenderFrame(content_window);
RenderFrameStatus render_frame_status(render_frame);
void WebFrame::AttachGuest(int id) {
content::RenderFrame::FromWebFrame(web_frame_)->AttachGuest(id);
}
if (!render_frame_status.is_ok())
return -1;
void WebFrame::DetachGuest(int id) {
content::RenderFrame::FromWebFrame(web_frame_)->DetachGuest(id);
blink::WebLocalFrame* frame = render_frame->GetWebFrame();
// Parent must exist.
blink::WebFrame* parent_frame = frame->Parent();
DCHECK(parent_frame);
DCHECK(parent_frame->IsWebLocalFrame());
return render_frame->GetRoutingID();
}
void WebFrame::SetSpellCheckProvider(mate::Arguments* args,
@@ -464,10 +491,7 @@ void WebFrame::BuildPrototype(v8::Isolate* isolate,
&WebFrame::SetLayoutZoomLevelLimits)
.SetMethod("registerEmbedderCustomElement",
&WebFrame::RegisterEmbedderCustomElement)
.SetMethod("registerElementResizeCallback",
&WebFrame::RegisterElementResizeCallback)
.SetMethod("attachGuest", &WebFrame::AttachGuest)
.SetMethod("detachGuest", &WebFrame::DetachGuest)
.SetMethod("getWebFrameId", &WebFrame::GetWebFrameId)
.SetMethod("setSpellCheckProvider", &WebFrame::SetSpellCheckProvider)
.SetMethod("registerURLSchemeAsBypassingCSP",
&WebFrame::RegisterURLSchemeAsBypassingCSP)

View File

@@ -9,7 +9,6 @@
#include <string>
#include <vector>
#include "atom/renderer/guest_view_container.h"
#include "native_mate/handle.h"
#include "native_mate/wrappable.h"
#include "third_party/WebKit/public/platform/WebCache.h"
@@ -54,11 +53,7 @@ class WebFrame : public mate::Wrappable<WebFrame> {
v8::Local<v8::Value> RegisterEmbedderCustomElement(
const base::string16& name,
v8::Local<v8::Object> options);
void RegisterElementResizeCallback(
int element_instance_id,
const GuestViewContainer::ResizeCallback& callback);
void AttachGuest(int element_instance_id);
void DetachGuest(int element_instance_id);
int GetWebFrameId(v8::Local<v8::Value> content_window);
// Set the provider that will be used by SpellCheckClient for spell check.
void SetSpellCheckProvider(mate::Arguments* args,

View File

@@ -79,6 +79,8 @@ void AtomRendererClient::RunScriptsAtDocumentEnd(
void AtomRendererClient::DidCreateScriptContext(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
RendererClientBase::DidCreateScriptContext(context, render_frame);
// Only allow node integration for the main frame, unless it is a devtools
// extension page.
if (!render_frame->IsMainFrame() && !IsDevToolsExtension(render_frame))

View File

@@ -12,8 +12,10 @@
#include "atom/common/options_switches.h"
#include "atom/renderer/api/atom_api_renderer_ipc.h"
#include "atom/renderer/atom_render_frame_observer.h"
#include "base/base_paths.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "chrome/renderer/printing/print_web_view_helper.h"
#include "content/public/renderer/render_frame.h"
#include "native_mate/dictionary.h"
@@ -81,6 +83,12 @@ base::CommandLine::StringVector GetArgv() {
return base::CommandLine::ForCurrentProcess()->argv();
}
base::FilePath::StringType GetExecPath() {
base::FilePath path;
PathService::Get(base::FILE_EXE, &path);
return path.value();
}
void InitializeBindings(v8::Local<v8::Object> binding,
v8::Local<v8::Context> context) {
auto* isolate = context->GetIsolate();
@@ -89,6 +97,7 @@ void InitializeBindings(v8::Local<v8::Object> binding,
b.SetMethod("crash", AtomBindings::Crash);
b.SetMethod("hang", AtomBindings::Hang);
b.SetMethod("getArgv", GetArgv);
b.SetMethod("getExecPath", GetExecPath);
b.SetMethod("getHeapStatistics", &AtomBindings::GetHeapStatistics);
b.SetMethod("getProcessMemoryInfo", &AtomBindings::GetProcessMemoryInfo);
b.SetMethod("getSystemMemoryInfo", &AtomBindings::GetSystemMemoryInfo);
@@ -97,7 +106,7 @@ void InitializeBindings(v8::Local<v8::Object> binding,
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kGuestInstanceID))
b.Set(options::kGuestInstanceID,
command_line->GetSwitchValueASCII(switches::kGuestInstanceID));
command_line->GetSwitchValueASCII(switches::kGuestInstanceID));
}
class AtomSandboxedRenderFrameObserver : public AtomRenderFrameObserver {
@@ -153,21 +162,19 @@ void AtomSandboxedRendererClient::RenderViewCreated(
void AtomSandboxedRendererClient::DidCreateScriptContext(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
RendererClientBase::DidCreateScriptContext(context, render_frame);
// Only allow preload for the main frame or
// For devtools we still want to run the preload_bundle script
if (!render_frame->IsMainFrame() && !IsDevTools(render_frame))
return;
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
base::FilePath preload_script_path =
command_line->GetSwitchValuePath(switches::kPreloadScript);
auto* isolate = context->GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context);
// Wrap the bundle into a function that receives the binding object and the
// preload script path as arguments.
std::string left = "(function(binding, preloadPath, require) {\n";
std::string left = "(function(binding, require) {\n";
std::string right = "\n})";
// Compile the wrapper and run it to get the function object
auto script = v8::Script::Compile(v8::String::Concat(
@@ -180,10 +187,10 @@ void AtomSandboxedRendererClient::DidCreateScriptContext(
auto binding = v8::Object::New(isolate);
InitializeBindings(binding, context);
AddRenderBindings(isolate, binding);
v8::Local<v8::Value> args[] = {
binding, mate::ConvertToV8(isolate, preload_script_path.value())};
v8::Local<v8::Value> args[] = {binding};
// Execute the function with proper arguments
ignore_result(func->Call(context, v8::Null(isolate), 2, args));
ignore_result(
func->Call(context, v8::Null(isolate), node::arraysize(args), args));
}
void AtomSandboxedRendererClient::WillReleaseScriptContext(

View File

@@ -14,15 +14,17 @@
#include "atom/renderer/atom_render_frame_observer.h"
#include "atom/renderer/atom_render_view_observer.h"
#include "atom/renderer/content_settings_observer.h"
#include "atom/renderer/guest_view_container.h"
#include "atom/renderer/preferences_manager.h"
#include "base/command_line.h"
#include "base/process/process.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "chrome/renderer/media/chrome_key_systems.h"
#include "chrome/renderer/pepper/pepper_helper.h"
#include "chrome/renderer/printing/print_web_view_helper.h"
#include "chrome/renderer/tts_dispatcher.h"
#include "content/public/common/content_constants.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "native_mate/dictionary.h"
#include "third_party/WebKit/Source/platform/weborigin/SchemeRegistry.h"
@@ -34,7 +36,6 @@
#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#include "base/strings/sys_string_conversions.h"
#endif
@@ -46,6 +47,14 @@
#include "atom/common/atom_constants.h"
#endif // defined(ENABLE_PDF_VIEWER)
// This is defined in later versions of Chromium, remove this if you see
// compiler complaining duplicate defines.
#if defined(OS_WIN) || defined(OS_FUCHSIA)
#define CrPRIdPid "ld"
#else
#define CrPRIdPid "d"
#endif
namespace atom {
namespace {
@@ -80,6 +89,20 @@ RendererClientBase::RendererClientBase() {
RendererClientBase::~RendererClientBase() {}
void RendererClientBase::DidCreateScriptContext(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
// global.setHidden("contextId", `${processId}-${++nextContextId}`)
std::string context_id = base::StringPrintf(
"%" CrPRIdPid "-%d", base::GetProcId(base::Process::Current().Handle()),
++next_context_id_);
v8::Isolate* isolate = context->GetIsolate();
v8::Local<v8::String> key = mate::StringToSymbol(isolate, "contextId");
v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key);
v8::Local<v8::Value> value = mate::ConvertToV8(isolate, context_id);
context->Global()->SetPrivate(context, private_key, value);
}
void RendererClientBase::AddRenderBindings(
v8::Isolate* isolate,
v8::Local<v8::Object> binding_object) {
@@ -132,15 +155,6 @@ void RendererClientBase::RenderThreadStarted() {
SetCurrentProcessExplicitAppUserModelID(app_id.c_str());
}
#endif
#if defined(OS_MACOSX)
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
bool scroll_bounce = command_line->HasSwitch(switches::kScrollBounce);
CFPreferencesSetAppValue(CFSTR("NSScrollViewRubberbanding"),
scroll_bounce ? kCFBooleanTrue : kCFBooleanFalse,
kCFPreferencesCurrentApplication);
CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
#endif
}
void RendererClientBase::RenderFrameCreated(
@@ -206,17 +220,6 @@ bool RendererClientBase::OverrideCreatePlugin(
return true;
}
content::BrowserPluginDelegate* RendererClientBase::CreateBrowserPluginDelegate(
content::RenderFrame* render_frame,
const std::string& mime_type,
const GURL& original_url) {
if (mime_type == content::kBrowserPluginMimeType) {
return new GuestViewContainer(render_frame);
} else {
return nullptr;
}
}
void RendererClientBase::AddSupportedKeySystems(
std::vector<std::unique_ptr<::media::KeySystemProperties>>* key_systems) {
AddChromeKeySystems(key_systems);

View File

@@ -21,7 +21,7 @@ class RendererClientBase : public content::ContentRendererClient {
~RendererClientBase() override;
virtual void DidCreateScriptContext(v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) = 0;
content::RenderFrame* render_frame);
virtual void WillReleaseScriptContext(v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) = 0;
virtual void DidClearWindowObject(content::RenderFrame* render_frame);
@@ -46,10 +46,6 @@ class RendererClientBase : public content::ContentRendererClient {
bool OverrideCreatePlugin(content::RenderFrame* render_frame,
const blink::WebPluginParams& params,
blink::WebPlugin** plugin) override;
content::BrowserPluginDelegate* CreateBrowserPluginDelegate(
content::RenderFrame* render_frame,
const std::string& mime_type,
const GURL& original_url) override;
void AddSupportedKeySystems(
std::vector<std::unique_ptr<::media::KeySystemProperties>>* key_systems)
override;
@@ -57,6 +53,9 @@ class RendererClientBase : public content::ContentRendererClient {
private:
std::unique_ptr<PreferencesManager> preferences_manager_;
bool isolated_world_;
// An increasing ID used for indentifying an V8 context in this process.
int next_context_id_ = 0;
};
} // namespace atom

View File

@@ -36,6 +36,7 @@ static_library("brightray") {
"//components/prefs",
"//content/public/browser",
"//content/shell:resources",
"//net:extras",
"//net:net_with_v8",
"//skia",
"//ui/views",

View File

@@ -111,6 +111,8 @@
'link_settings': {
'libraries': [
# Following libraries are always linked statically.
'<(libchromiumcontent_dir)/libbase_static.a',
'<(libchromiumcontent_dir)/libextras.a',
'<(libchromiumcontent_dir)/libgtkui.a',
'<(libchromiumcontent_dir)/libhttp_server.a',
'<(libchromiumcontent_dir)/libdevice_service.a',
@@ -204,6 +206,8 @@
'link_settings': {
'libraries': [
# Following libraries are always linked statically.
'<(libchromiumcontent_dir)/libbase_static.a',
'<(libchromiumcontent_dir)/libextras.a',
'<(libchromiumcontent_dir)/libhttp_server.a',
'<(libchromiumcontent_dir)/libdevice_service.a',
'<(libchromiumcontent_dir)/libdom_keycode_converter.a',
@@ -340,6 +344,7 @@
'-ldxgi.lib',
# Following libs are always linked statically.
'<(libchromiumcontent_dir)/base_static.lib',
'<(libchromiumcontent_dir)/extras.lib',
'<(libchromiumcontent_dir)/sandbox.lib',
'<(libchromiumcontent_dir)/sandbox_helper_win.lib',
'<(libchromiumcontent_dir)/http_server.lib',

View File

@@ -11,7 +11,6 @@
#include "brightray/browser/brightray_paths.h"
#include "brightray/browser/browser_client.h"
#include "brightray/browser/inspectable_web_contents_impl.h"
#include "brightray/browser/network_delegate.h"
#include "brightray/browser/special_storage_policy.h"
#include "brightray/browser/zoom_level_delegate.h"
#include "brightray/common/application_info.h"
@@ -20,7 +19,6 @@
#include "components/prefs/pref_service.h"
#include "components/prefs/pref_service_factory.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/storage_partition.h"
#include "net/base/escape.h"
@@ -37,25 +35,10 @@ std::string MakePartitionName(const std::string& input) {
} // namespace
class BrowserContext::ResourceContext : public content::ResourceContext {
public:
ResourceContext() : getter_(nullptr) {}
void set_url_request_context_getter(URLRequestContextGetter* getter) {
getter_ = getter;
}
private:
net::HostResolver* GetHostResolver() override {
return getter_->host_resolver();
}
net::URLRequestContext* GetRequestContext() override {
return getter_->GetURLRequestContext();
}
URLRequestContextGetter* getter_;
};
// static
void BrowserContextDeleter::Destruct(const BrowserContext* browser_context) {
browser_context->OnDestruct();
}
// static
BrowserContext::BrowserContextMap BrowserContext::browser_context_map_;
@@ -72,7 +55,6 @@ scoped_refptr<BrowserContext> BrowserContext::Get(const std::string& partition,
BrowserContext::BrowserContext(const std::string& partition, bool in_memory)
: in_memory_(in_memory),
resource_context_(new ResourceContext),
storage_policy_(new SpecialStoragePolicy),
weak_factory_(this) {
if (!PathService::Get(DIR_USER_DATA, &path_)) {
@@ -88,6 +70,8 @@ BrowserContext::BrowserContext(const std::string& partition, bool in_memory)
content::BrowserContext::Initialize(this, path_);
io_handle_ = new URLRequestContextGetter::Handle(GetWeakPtr());
browser_context_map_[PartitionKey(partition, in_memory)] = GetWeakPtr();
}
@@ -95,13 +79,14 @@ BrowserContext::~BrowserContext() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
NotifyWillBeDestroyed(this);
ShutdownStoragePartitions();
if (BrowserThread::IsMessageLoopValid(BrowserThread::IO)) {
BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE,
resource_context_.release());
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&URLRequestContextGetter::NotifyContextShutdownOnIO,
base::RetainedRef(url_request_getter_)));
io_handle_->ShutdownOnUIThread();
}
void BrowserContext::OnDestruct() const {
if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
delete this;
} else {
BrowserThread::DeleteSoon(BrowserThread::UI, FROM_HERE, this);
}
}
@@ -135,17 +120,10 @@ URLRequestContextGetter* BrowserContext::GetRequestContext() {
net::URLRequestContextGetter* BrowserContext::CreateRequestContext(
content::ProtocolHandlerMap* protocol_handlers,
content::URLRequestInterceptorScopedVector protocol_interceptors) {
DCHECK(!url_request_getter_.get());
url_request_getter_ = new URLRequestContextGetter(
this, static_cast<NetLog*>(BrowserClient::Get()->GetNetLog()), GetPath(),
in_memory_, BrowserThread::GetTaskRunnerForThread(BrowserThread::IO),
protocol_handlers, std::move(protocol_interceptors));
resource_context_->set_url_request_context_getter(url_request_getter_.get());
return url_request_getter_.get();
}
std::unique_ptr<net::NetworkDelegate> BrowserContext::CreateNetworkDelegate() {
return std::make_unique<NetworkDelegate>();
return io_handle_
->CreateMainRequestContextGetter(protocol_handlers,
std::move(protocol_interceptors))
.get();
}
std::string BrowserContext::GetMediaDeviceIDSalt() {
@@ -171,7 +149,7 @@ bool BrowserContext::IsOffTheRecord() const {
}
content::ResourceContext* BrowserContext::GetResourceContext() {
return resource_context_.get();
return io_handle_->GetResourceContext();
}
content::DownloadManagerDelegate* BrowserContext::GetDownloadManagerDelegate() {
@@ -214,17 +192,19 @@ BrowserContext::CreateRequestContextForStoragePartition(
bool in_memory,
content::ProtocolHandlerMap* protocol_handlers,
content::URLRequestInterceptorScopedVector request_interceptors) {
NOTREACHED();
return nullptr;
}
net::URLRequestContextGetter* BrowserContext::CreateMediaRequestContext() {
return url_request_getter_.get();
return io_handle_->GetMainRequestContextGetter().get();
}
net::URLRequestContextGetter*
BrowserContext::CreateMediaRequestContextForStoragePartition(
const base::FilePath& partition_path,
bool in_memory) {
NOTREACHED();
return nullptr;
}

View File

@@ -23,9 +23,15 @@ class SpecialStoragePolicy;
namespace brightray {
class BrowserContext : public base::RefCounted<BrowserContext>,
public content::BrowserContext,
public brightray::URLRequestContextGetter::Delegate {
class BrowserContext;
struct BrowserContextDeleter {
static void Destruct(const BrowserContext* browser_context);
};
class BrowserContext
: public base::RefCountedThreadSafe<BrowserContext, BrowserContextDeleter>,
public content::BrowserContext {
public:
// Get the BrowserContext according to its |partition| and |in_memory|,
// empty pointer when be returned when there is no matching BrowserContext.
@@ -66,14 +72,14 @@ class BrowserContext : public base::RefCounted<BrowserContext>,
const base::FilePath& partition_path,
bool in_memory) override;
std::string GetMediaDeviceIDSalt() override;
URLRequestContextGetter* url_request_context_getter() const {
return url_request_getter_.get();
}
base::FilePath GetPath() const override;
void InitPrefs();
PrefService* prefs() { return prefs_.get(); }
virtual std::string GetUserAgent() const = 0;
virtual void OnMainRequestContextCreated(URLRequestContextGetter* getter) {}
protected:
BrowserContext(const std::string& partition, bool in_memory);
~BrowserContext() override;
@@ -81,16 +87,14 @@ class BrowserContext : public base::RefCounted<BrowserContext>,
// Subclasses should override this to register custom preferences.
virtual void RegisterPrefs(PrefRegistrySimple* pref_registry) {}
// URLRequestContextGetter::Delegate:
std::unique_ptr<net::NetworkDelegate> CreateNetworkDelegate() override;
base::FilePath GetPath() const override;
private:
friend class base::RefCounted<BrowserContext>;
class ResourceContext;
friend class base::RefCountedThreadSafe<BrowserContext,
BrowserContextDeleter>;
friend class base::DeleteHelper<BrowserContext>;
friend struct BrowserContextDeleter;
void RegisterInternalPrefs(PrefRegistrySimple* pref_registry);
void OnDestruct() const;
// partition_id => browser_context
struct PartitionKey {
@@ -117,11 +121,12 @@ class BrowserContext : public base::RefCounted<BrowserContext>,
base::FilePath path_;
bool in_memory_;
std::unique_ptr<ResourceContext> resource_context_;
scoped_refptr<URLRequestContextGetter> url_request_getter_;
scoped_refptr<storage::SpecialStoragePolicy> storage_policy_;
std::unique_ptr<PrefService> prefs_;
std::unique_ptr<MediaDeviceIDSalt> media_device_id_salt_;
// Self-destructing class responsible for creating URLRequestContextGetter
// on the UI thread and deletes itself on the IO thread.
URLRequestContextGetter::Handle* io_handle_;
base::WeakPtrFactory<BrowserContext> weak_factory_;

View File

@@ -15,6 +15,7 @@
#include <glib.h> // for g_setenv()
#endif
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/message_loop/message_loop.h"
@@ -178,14 +179,23 @@ void OverrideAppLogsPath() {
}
#endif
int BrowserMainParts::PreEarlyInitialization() {
std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);
// TODO(deepak1556): Disable guest webcontents based on OOPIF feature.
// Disable surface synchronization and async wheel events to make OSR work.
feature_list->InitializeFromCommandLine(
"",
"GuestViewCrossProcessFrames,SurfaceSynchronization,AsyncWheelEvents");
void BrowserMainParts::InitializeFeatureList() {
auto* cmd_line = base::CommandLine::ForCurrentProcess();
const auto enable_features =
cmd_line->GetSwitchValueASCII(switches::kEnableFeatures);
auto disable_features =
cmd_line->GetSwitchValueASCII(switches::kDisableFeatures);
auto feature_list = std::make_unique<base::FeatureList>();
feature_list->InitializeFromCommandLine(enable_features, disable_features);
base::FeatureList::SetInstance(std::move(feature_list));
}
bool BrowserMainParts::ShouldContentCreateFeatureList() {
return false;
}
int BrowserMainParts::PreEarlyInitialization() {
InitializeFeatureList();
OverrideAppLogsPath();
#if defined(USE_X11)
views::LinuxUI::SetInstance(BuildGtkUi());

View File

@@ -33,6 +33,7 @@ class BrowserMainParts : public content::BrowserMainParts {
protected:
// content::BrowserMainParts:
bool ShouldContentCreateFeatureList() override;
int PreEarlyInitialization() override;
void ToolkitInitialized() override;
void PreMainMessageLoopStart() override;
@@ -42,6 +43,8 @@ class BrowserMainParts : public content::BrowserMainParts {
int PreCreateThreads() override;
void PostDestroyThreads() override;
void InitializeFeatureList();
private:
#if defined(OS_MACOSX)
void InitializeMainNib();

View File

@@ -5,14 +5,9 @@
namespace brightray {
InspectableWebContents* InspectableWebContents::Create(
const content::WebContents::CreateParams& create_params) {
auto* contents = content::WebContents::Create(create_params);
return Create(contents);
}
InspectableWebContents* InspectableWebContents::Create(
content::WebContents* web_contents) {
return new InspectableWebContentsImpl(web_contents);
content::WebContents* web_contents,
bool is_guest) {
return new InspectableWebContentsImpl(web_contents, is_guest);
}
} // namespace brightray

View File

@@ -20,12 +20,10 @@ class InspectableWebContentsView;
class InspectableWebContents {
public:
static InspectableWebContents* Create(
const content::WebContents::CreateParams&);
// The returned InspectableWebContents takes ownership of the passed-in
// WebContents.
static InspectableWebContents* Create(content::WebContents*);
static InspectableWebContents* Create(content::WebContents* web_contents,
bool is_guest);
virtual ~InspectableWebContents() {}
@@ -37,6 +35,8 @@ class InspectableWebContents {
virtual void SetDelegate(InspectableWebContentsDelegate* delegate) = 0;
virtual InspectableWebContentsDelegate* GetDelegate() const = 0;
virtual bool IsGuest() const = 0;
virtual void ReleaseWebContents() = 0;
virtual void SetDevToolsWebContents(content::WebContents* devtools) = 0;
virtual void SetDockState(const std::string& state) = 0;
virtual void ShowDevTools() = 0;

View File

@@ -167,14 +167,18 @@ int ResponseWriter::Initialize(const net::CompletionCallback& callback) {
int ResponseWriter::Write(net::IOBuffer* buffer,
int num_bytes,
const net::CompletionCallback& callback) {
auto* id = new base::Value(stream_id_);
base::Value* chunk = new base::Value(std::string(buffer->data(), num_bytes));
std::string chunk = std::string(buffer->data(), num_bytes);
if (!base::IsStringUTF8(chunk))
return num_bytes;
base::Value* id = new base::Value(stream_id_);
base::Value* chunk_value = new base::Value(chunk);
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::BindOnce(&InspectableWebContentsImpl::CallClientFunction, bindings_,
"DevToolsAPI.streamWrite", base::Owned(id),
base::Owned(chunk), nullptr));
base::Owned(chunk_value), nullptr));
return num_bytes;
}
@@ -198,15 +202,20 @@ void InspectableWebContentsImpl::RegisterPrefs(PrefRegistrySimple* registry) {
}
InspectableWebContentsImpl::InspectableWebContentsImpl(
content::WebContents* web_contents)
content::WebContents* web_contents,
bool is_guest)
: frontend_loaded_(false),
can_dock_(true),
delegate_(nullptr),
pref_service_(
static_cast<BrowserContext*>(web_contents->GetBrowserContext())
->prefs()),
web_contents_(web_contents),
is_guest_(is_guest),
view_(CreateInspectableContentsView(this)),
weak_factory_(this) {
auto* context =
static_cast<BrowserContext*>(web_contents_->GetBrowserContext());
pref_service_ = context->prefs();
if (is_guest)
return;
auto* bounds_dict = pref_service_->GetDictionary(kDevToolsBoundsPref);
if (bounds_dict) {
DictionaryToRect(*bounds_dict, &devtools_bounds_);
@@ -231,8 +240,6 @@ InspectableWebContentsImpl::InspectableWebContentsImpl(
display.y() + (display.height() - devtools_bounds_.height()) / 2);
}
}
view_.reset(CreateInspectableContentsView(this));
}
InspectableWebContentsImpl::~InspectableWebContentsImpl() {
@@ -278,6 +285,14 @@ InspectableWebContentsDelegate* InspectableWebContentsImpl::GetDelegate()
return delegate_;
}
bool InspectableWebContentsImpl::IsGuest() const {
return is_guest_;
}
void InspectableWebContentsImpl::ReleaseWebContents() {
web_contents_.release();
}
void InspectableWebContentsImpl::SetDockState(const std::string& state) {
if (state == "detach") {
can_dock_ = false;
@@ -328,7 +343,8 @@ void InspectableWebContentsImpl::CloseDevTools() {
managed_devtools_web_contents_.reset();
}
embedder_message_dispatcher_.reset();
web_contents_->Focus();
if (!IsGuest())
web_contents_->Focus();
}
}
@@ -468,7 +484,7 @@ void InspectableWebContentsImpl::LoadNetworkResource(
net::URLFetcher* fetcher =
(net::URLFetcher::Create(gurl, net::URLFetcher::GET, this)).release();
pending_requests_[fetcher] = callback;
fetcher->SetRequestContext(browser_context->url_request_context_getter());
fetcher->SetRequestContext(browser_context->GetRequestContext());
fetcher->SetExtraRequestHeaders(headers);
fetcher->SaveResponseWithWriter(
std::unique_ptr<net::URLFetcherResponseWriter>(
@@ -719,6 +735,8 @@ void InspectableWebContentsImpl::WebContentsDestroyed() {
for (const auto& pair : pending_requests_)
delete pair.first;
pending_requests_.clear();
if (view_ && view_->GetDelegate())
view_->GetDelegate()->DevToolsClosed();
}

View File

@@ -39,7 +39,7 @@ class InspectableWebContentsImpl
public:
static void RegisterPrefs(PrefRegistrySimple* pref_registry);
explicit InspectableWebContentsImpl(content::WebContents*);
InspectableWebContentsImpl(content::WebContents* web_contents, bool is_guest);
~InspectableWebContentsImpl() override;
InspectableWebContentsView* GetView() const override;
@@ -48,6 +48,8 @@ class InspectableWebContentsImpl
void SetDelegate(InspectableWebContentsDelegate* delegate) override;
InspectableWebContentsDelegate* GetDelegate() const override;
bool IsGuest() const override;
void ReleaseWebContents() override;
void SetDevToolsWebContents(content::WebContents* devtools) override;
void SetDockState(const std::string& state) override;
void ShowDevTools() override;
@@ -214,6 +216,7 @@ class InspectableWebContentsImpl
// The external devtools assigned by SetDevToolsWebContents.
content::WebContents* external_devtools_web_contents_ = nullptr;
bool is_guest_;
std::unique_ptr<InspectableWebContentsView> view_;
using ExtensionsAPIs = std::map<std::string, std::string>;

View File

@@ -14,6 +14,7 @@ using brightray::InspectableWebContentsViewMac;
@private
brightray::InspectableWebContentsViewMac* inspectableWebContentsView_;
base::scoped_nsobject<NSView> fake_view_;
base::scoped_nsobject<NSWindow> devtools_window_;
BOOL devtools_visible_;
BOOL devtools_docked_;

View File

@@ -32,11 +32,17 @@
name:NSWindowDidBecomeMainNotification
object:nil];
auto* contents =
inspectableWebContentsView_->inspectable_web_contents()->GetWebContents();
auto contentsView = contents->GetNativeView();
[contentsView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[self addSubview:contentsView];
if (inspectableWebContentsView_->inspectable_web_contents()->IsGuest()) {
fake_view_.reset([[NSView alloc] init]);
[fake_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[self addSubview:fake_view_];
} else {
auto* contents = inspectableWebContentsView_->inspectable_web_contents()
->GetWebContents();
auto contentsView = contents->GetNativeView();
[contentsView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[self addSubview:contentsView];
}
// See https://code.google.com/p/chromium/issues/detail?id=348490.
[self setWantsLayer:YES];
@@ -75,7 +81,7 @@
if (visible && devtools_docked_) {
webContents->SetAllowOtherViews(true);
devToolsWebContents->SetAllowOtherViews(true);
} else {
} else if (!inspectable_web_contents->IsGuest()) {
webContents->SetAllowOtherViews(false);
}
@@ -194,7 +200,7 @@
- (void)viewDidBecomeFirstResponder:(NSNotification*)notification {
auto* inspectable_web_contents =
inspectableWebContentsView_->inspectable_web_contents();
if (!inspectable_web_contents)
if (!inspectable_web_contents || inspectable_web_contents->IsGuest())
return;
auto* webContents = inspectable_web_contents->GetWebContents();
auto webContentsView = webContents->GetNativeView();

View File

@@ -1,161 +0,0 @@
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "brightray/browser/network_delegate.h"
#include <string>
#include <vector>
#include "base/command_line.h"
#include "base/strings/string_split.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/url_request/url_request.h"
namespace brightray {
namespace {
// Ignore the limit of 6 connections per host.
const char kIgnoreConnectionsLimit[] = "ignore-connections-limit";
} // namespace
NetworkDelegate::NetworkDelegate() {
auto* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(kIgnoreConnectionsLimit)) {
std::string value =
command_line->GetSwitchValueASCII(kIgnoreConnectionsLimit);
ignore_connections_limit_domains_ = base::SplitString(
value, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
}
}
NetworkDelegate::~NetworkDelegate() {}
int NetworkDelegate::OnBeforeURLRequest(net::URLRequest* request,
const net::CompletionCallback& callback,
GURL* new_url) {
for (const auto& domain : ignore_connections_limit_domains_) {
if (request->url().DomainIs(domain)) {
// Allow unlimited concurrent connections.
request->SetPriority(net::MAXIMUM_PRIORITY);
request->SetLoadFlags(request->load_flags() | net::LOAD_IGNORE_LIMITS);
break;
}
}
return net::OK;
}
int NetworkDelegate::OnBeforeStartTransaction(
net::URLRequest* request,
const net::CompletionCallback& callback,
net::HttpRequestHeaders* headers) {
return net::OK;
}
void NetworkDelegate::OnStartTransaction(
net::URLRequest* request,
const net::HttpRequestHeaders& headers) {}
void NetworkDelegate::OnBeforeSendHeaders(
net::URLRequest* request,
const net::ProxyInfo& proxy_info,
const net::ProxyRetryInfoMap& proxy_retry_info,
net::HttpRequestHeaders* headers) {}
int NetworkDelegate::OnHeadersReceived(
net::URLRequest* request,
const net::CompletionCallback& callback,
const net::HttpResponseHeaders* original_response_headers,
scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
GURL* allowed_unsafe_redirect_url) {
return net::OK;
}
void NetworkDelegate::OnBeforeRedirect(net::URLRequest* request,
const GURL& new_location) {}
void NetworkDelegate::OnResponseStarted(net::URLRequest* request,
int net_error) {}
void NetworkDelegate::OnNetworkBytesReceived(net::URLRequest* request,
int64_t bytes_read) {}
void NetworkDelegate::OnNetworkBytesSent(net::URLRequest* request,
int64_t bytes_sent) {}
void NetworkDelegate::OnCompleted(net::URLRequest* request, bool started) {}
void NetworkDelegate::OnURLRequestDestroyed(net::URLRequest* request) {}
void NetworkDelegate::OnPACScriptError(int line_number,
const base::string16& error) {}
NetworkDelegate::AuthRequiredResponse NetworkDelegate::OnAuthRequired(
net::URLRequest* request,
const net::AuthChallengeInfo& auth_info,
const AuthCallback& callback,
net::AuthCredentials* credentials) {
return AUTH_REQUIRED_RESPONSE_NO_ACTION;
}
bool NetworkDelegate::OnCanGetCookies(const net::URLRequest& request,
const net::CookieList& cookie_list) {
return true;
}
bool NetworkDelegate::OnCanSetCookie(const net::URLRequest& request,
const net::CanonicalCookie& cookie_line,
net::CookieOptions* options) {
return true;
}
bool NetworkDelegate::OnCanAccessFile(
const net::URLRequest& request,
const base::FilePath& original_path,
const base::FilePath& absolute_path) const {
return true;
}
bool NetworkDelegate::OnCanEnablePrivacyMode(
const GURL& url,
const GURL& first_party_for_cookies) const {
return false;
}
bool NetworkDelegate::OnAreExperimentalCookieFeaturesEnabled() const {
return true;
}
bool NetworkDelegate::OnCancelURLRequestWithPolicyViolatingReferrerHeader(
const net::URLRequest& request,
const GURL& target_url,
const GURL& referrer_url) const {
return false;
}
// TODO(deepak1556) : Enable after hooking into the reporting service
// https://crbug.com/704259
bool NetworkDelegate::OnCanQueueReportingReport(
const url::Origin& origin) const {
return false;
}
void NetworkDelegate::OnCanSendReportingReports(
std::set<url::Origin> origins,
base::OnceCallback<void(std::set<url::Origin>)> result_callback) const {}
bool NetworkDelegate::OnCanSetReportingClient(const url::Origin& origin,
const GURL& endpoint) const {
return false;
}
bool NetworkDelegate::OnCanUseReportingClient(const url::Origin& origin,
const GURL& endpoint) const {
return false;
}
} // namespace brightray

View File

@@ -1,88 +0,0 @@
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#ifndef BRIGHTRAY_BROWSER_NETWORK_DELEGATE_H_
#define BRIGHTRAY_BROWSER_NETWORK_DELEGATE_H_
#include <set>
#include <string>
#include <vector>
#include "net/base/network_delegate.h"
namespace brightray {
class NetworkDelegate : public net::NetworkDelegate {
public:
NetworkDelegate();
~NetworkDelegate() override;
protected:
int OnBeforeURLRequest(net::URLRequest* request,
const net::CompletionCallback& callback,
GURL* new_url) override;
int OnBeforeStartTransaction(net::URLRequest* request,
const net::CompletionCallback& callback,
net::HttpRequestHeaders* headers) override;
void OnBeforeSendHeaders(net::URLRequest* request,
const net::ProxyInfo& proxy_info,
const net::ProxyRetryInfoMap& proxy_retry_info,
net::HttpRequestHeaders* headers) override;
void OnStartTransaction(net::URLRequest* request,
const net::HttpRequestHeaders& headers) override;
int OnHeadersReceived(
net::URLRequest* request,
const net::CompletionCallback& callback,
const net::HttpResponseHeaders* original_response_headers,
scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
GURL* allowed_unsafe_redirect_url) override;
void OnBeforeRedirect(net::URLRequest* request,
const GURL& new_location) override;
void OnResponseStarted(net::URLRequest* request, int net_error) override;
void OnNetworkBytesReceived(net::URLRequest* request,
int64_t bytes_read) override;
void OnNetworkBytesSent(net::URLRequest* request,
int64_t bytes_sent) override;
void OnCompleted(net::URLRequest* request, bool started) override;
void OnURLRequestDestroyed(net::URLRequest* request) override;
void OnPACScriptError(int line_number, const base::string16& error) override;
AuthRequiredResponse OnAuthRequired(
net::URLRequest* request,
const net::AuthChallengeInfo& auth_info,
const AuthCallback& callback,
net::AuthCredentials* credentials) override;
bool OnCanGetCookies(const net::URLRequest& request,
const net::CookieList& cookie_list) override;
bool OnCanSetCookie(const net::URLRequest& request,
const net::CanonicalCookie& cookie_line,
net::CookieOptions* options) override;
bool OnCanAccessFile(const net::URLRequest& request,
const base::FilePath& original_path,
const base::FilePath& absolute_path) const override;
bool OnCanEnablePrivacyMode(
const GURL& url,
const GURL& first_party_for_cookies) const override;
bool OnAreExperimentalCookieFeaturesEnabled() const override;
bool OnCancelURLRequestWithPolicyViolatingReferrerHeader(
const net::URLRequest& request,
const GURL& target_url,
const GURL& referrer_url) const override;
bool OnCanQueueReportingReport(const url::Origin& origin) const override;
void OnCanSendReportingReports(std::set<url::Origin> origins,
base::OnceCallback<void(std::set<url::Origin>)>
result_callback) const override;
bool OnCanSetReportingClient(const url::Origin& origin,
const GURL& endpoint) const override;
bool OnCanUseReportingClient(const url::Origin& origin,
const GURL& endpoint) const override;
private:
std::vector<std::string> ignore_connections_limit_domains_;
DISALLOW_COPY_AND_ASSIGN(NetworkDelegate);
};
} // namespace brightray
#endif // BRIGHTRAY_BROWSER_NETWORK_DELEGATE_H_

View File

@@ -12,14 +12,15 @@
#include "base/strings/string_util.h"
#include "base/task_scheduler/post_task.h"
#include "brightray/browser/browser_client.h"
#include "brightray/browser/browser_context.h"
#include "brightray/browser/net/require_ct_delegate.h"
#include "brightray/browser/net_log.h"
#include "brightray/browser/network_delegate.h"
#include "brightray/common/switches.h"
#include "components/network_session_configurator/common/network_switches.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.h"
#include "content/public/browser/devtools_network_transaction_factory.h"
#include "content/public/browser/resource_context.h"
#include "net/base/host_mapping_rules.h"
#include "net/cert/cert_verifier.h"
#include "net/cert/ct_known_logs.h"
@@ -29,6 +30,7 @@
#include "net/cookies/cookie_monster.h"
#include "net/cookies/cookie_store.h"
#include "net/dns/mapped_host_resolver.h"
#include "net/extras/sqlite/sqlite_channel_id_store.h"
#include "net/http/http_auth_filter.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_auth_preferences.h"
@@ -58,83 +60,107 @@ using content::BrowserThread;
namespace brightray {
std::string URLRequestContextGetter::Delegate::GetUserAgent() {
return base::EmptyString();
}
class ResourceContext : public content::ResourceContext {
public:
ResourceContext() = default;
~ResourceContext() override = default;
std::unique_ptr<net::NetworkDelegate>
URLRequestContextGetter::Delegate::CreateNetworkDelegate() {
return nullptr;
}
std::unique_ptr<net::URLRequestJobFactory>
URLRequestContextGetter::Delegate::CreateURLRequestJobFactory(
content::ProtocolHandlerMap* protocol_handlers) {
std::unique_ptr<net::URLRequestJobFactoryImpl> job_factory(
new net::URLRequestJobFactoryImpl);
for (auto& it : *protocol_handlers) {
job_factory->SetProtocolHandler(it.first,
base::WrapUnique(it.second.release()));
net::HostResolver* GetHostResolver() override {
if (request_context_)
return request_context_->host_resolver();
return nullptr;
}
protocol_handlers->clear();
job_factory->SetProtocolHandler(
url::kDataScheme, base::WrapUnique(new net::DataProtocolHandler));
job_factory->SetProtocolHandler(
url::kFileScheme,
base::WrapUnique(
new net::FileProtocolHandler(base::CreateTaskRunnerWithTraits(
{base::MayBlock(), base::TaskPriority::USER_VISIBLE,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}))));
net::URLRequestContext* GetRequestContext() override {
return request_context_;
}
return std::move(job_factory);
private:
friend class URLRequestContextGetter;
net::URLRequestContext* request_context_ = nullptr;
DISALLOW_COPY_AND_ASSIGN(ResourceContext);
};
URLRequestContextGetter::Handle::Handle(
base::WeakPtr<BrowserContext> browser_context)
: resource_context_(new ResourceContext),
browser_context_(browser_context),
initialized_(false) {}
URLRequestContextGetter::Handle::~Handle() {}
content::ResourceContext* URLRequestContextGetter::Handle::GetResourceContext()
const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
LazyInitialize();
return resource_context_.get();
}
net::HttpCache::BackendFactory*
URLRequestContextGetter::Delegate::CreateHttpCacheBackendFactory(
const base::FilePath& base_path) {
auto* command_line = base::CommandLine::ForCurrentProcess();
int max_size = 0;
base::StringToInt(command_line->GetSwitchValueASCII(switches::kDiskCacheSize),
&max_size);
base::FilePath cache_path = base_path.Append(FILE_PATH_LITERAL("Cache"));
return new net::HttpCache::DefaultBackend(
net::DISK_CACHE, net::CACHE_BACKEND_DEFAULT, cache_path, max_size);
scoped_refptr<URLRequestContextGetter>
URLRequestContextGetter::Handle::CreateMainRequestContextGetter(
content::ProtocolHandlerMap* protocol_handlers,
content::URLRequestInterceptorScopedVector protocol_interceptors) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(!main_request_context_getter_.get());
main_request_context_getter_ = new URLRequestContextGetter(
BrowserClient::Get()->GetNetLog(), resource_context_.get(),
browser_context_->IsOffTheRecord(), browser_context_->GetUserAgent(),
browser_context_->GetPath(), protocol_handlers,
std::move(protocol_interceptors));
browser_context_->OnMainRequestContextCreated(
main_request_context_getter_.get());
return main_request_context_getter_;
}
std::unique_ptr<net::CertVerifier>
URLRequestContextGetter::Delegate::CreateCertVerifier(
RequireCTDelegate* ct_delegate) {
return net::CertVerifier::CreateDefault();
scoped_refptr<URLRequestContextGetter>
URLRequestContextGetter::Handle::GetMainRequestContextGetter() const {
return main_request_context_getter_;
}
net::SSLConfigService*
URLRequestContextGetter::Delegate::CreateSSLConfigService() {
return new net::SSLConfigServiceDefaults;
void URLRequestContextGetter::Handle::LazyInitialize() const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (initialized_)
return;
initialized_ = true;
content::BrowserContext::EnsureResourceContextInitialized(
browser_context_.get());
}
std::vector<std::string>
URLRequestContextGetter::Delegate::GetCookieableSchemes() {
return {"http", "https", "ws", "wss"};
void URLRequestContextGetter::Handle::ShutdownOnUIThread() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (main_request_context_getter_.get()) {
if (BrowserThread::IsThreadInitialized(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&URLRequestContextGetter::NotifyContextShuttingDown,
base::RetainedRef(main_request_context_getter_),
std::move(resource_context_)));
}
}
if (!BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this))
delete this;
}
URLRequestContextGetter::URLRequestContextGetter(
Delegate* delegate,
NetLog* net_log,
const base::FilePath& base_path,
ResourceContext* resource_context,
bool in_memory,
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
const std::string& user_agent,
const base::FilePath& base_path,
content::ProtocolHandlerMap* protocol_handlers,
content::URLRequestInterceptorScopedVector protocol_interceptors)
: delegate_(delegate),
: job_factory_(nullptr),
delegate_(nullptr),
net_log_(net_log),
resource_context_(resource_context),
protocol_interceptors_(std::move(protocol_interceptors)),
base_path_(base_path),
in_memory_(in_memory),
io_task_runner_(io_task_runner),
protocol_interceptors_(std::move(protocol_interceptors)),
job_factory_(nullptr),
user_agent_(user_agent),
context_shutting_down_(false) {
// Must first be created on the UI thread.
DCHECK_CURRENTLY_ON(BrowserThread::UI);
@@ -142,48 +168,30 @@ URLRequestContextGetter::URLRequestContextGetter(
if (protocol_handlers)
std::swap(protocol_handlers_, *protocol_handlers);
if (delegate_)
user_agent_ = delegate_->GetUserAgent();
// We must create the proxy config service on the UI loop on Linux because it
// must synchronously run on the glib message loop. This will be passed to
// the URLRequestContextStorage on the IO thread in GetURLRequestContext().
proxy_config_service_ =
net::ProxyResolutionService::CreateSystemProxyConfigService(
io_task_runner_);
BrowserThread::GetTaskRunnerForThread(BrowserThread::IO));
}
URLRequestContextGetter::~URLRequestContextGetter() {}
void URLRequestContextGetter::NotifyContextShutdownOnIO() {
void URLRequestContextGetter::NotifyContextShuttingDown(
std::unique_ptr<ResourceContext> resource_context) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
context_shutting_down_ = true;
cookie_change_sub_.reset();
resource_context.reset();
net::URLRequestContextGetter::NotifyContextShuttingDown();
url_request_context_.reset();
storage_.reset();
http_network_session_.reset();
http_auth_preferences_.reset();
host_mapping_rules_.reset();
url_request_context_.reset();
storage_.reset();
ct_delegate_.reset();
net::URLRequestContextGetter::NotifyContextShuttingDown();
}
void URLRequestContextGetter::OnCookieChanged(
const net::CanonicalCookie& cookie,
net::CookieChangeCause cause) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (!delegate_ || context_shutting_down_)
return;
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::BindOnce(&Delegate::NotifyCookieChange, base::Unretained(delegate_),
cookie, !(cause == net::CookieChangeCause::INSERTED),
cause));
}
net::HostResolver* URLRequestContextGetter::host_resolver() {
return url_request_context_->host_resolver();
}
net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() {
@@ -208,28 +216,46 @@ net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() {
storage_->set_network_delegate(delegate_->CreateNetworkDelegate());
std::unique_ptr<net::CookieStore> cookie_store;
scoped_refptr<net::SQLiteChannelIDStore> channel_id_db;
// Create a single task runner to use with the CookieStore and
// ChannelIDStore.
scoped_refptr<base::SequencedTaskRunner> cookie_background_task_runner =
base::CreateSequencedTaskRunnerWithTraits(
{base::MayBlock(), base::TaskPriority::BACKGROUND,
base::TaskShutdownBehavior::BLOCK_SHUTDOWN});
auto cookie_path = in_memory_
? base::FilePath()
: base_path_.Append(FILE_PATH_LITERAL("Cookies"));
std::unique_ptr<net::CookieStore> cookie_store =
content::CreateCookieStore(content::CookieStoreConfig(
cookie_path, false, false, nullptr));
storage_->set_cookie_store(std::move(cookie_store));
if (!in_memory_) {
channel_id_db = new net::SQLiteChannelIDStore(
base_path_.Append(FILE_PATH_LITERAL("Origin Bound Certs")),
cookie_background_task_runner);
}
std::unique_ptr<net::ChannelIDService> channel_id_service(
new net::ChannelIDService(
new net::DefaultChannelIDStore(channel_id_db.get())));
content::CookieStoreConfig cookie_config(cookie_path, false, false,
nullptr);
cookie_config.channel_id_service = channel_id_service.get();
cookie_config.background_task_runner = cookie_background_task_runner;
cookie_store = content::CreateCookieStore(cookie_config);
cookie_store->SetChannelIDServiceID(channel_id_service->GetUniqueID());
// Set custom schemes that can accept cookies.
net::CookieMonster* cookie_monster =
static_cast<net::CookieMonster*>(url_request_context_->cookie_store());
cookie_monster->SetCookieableSchemes(delegate_->GetCookieableSchemes());
static_cast<net::CookieMonster*>(cookie_store.get());
std::vector<std::string> cookie_schemes({"http", "https", "ws", "wss"});
delegate_->GetCookieableSchemes(&cookie_schemes);
cookie_monster->SetCookieableSchemes(cookie_schemes);
// Cookie store will outlive notifier by order of declaration
// in the header.
cookie_change_sub_ =
url_request_context_->cookie_store()
->GetChangeDispatcher()
.AddCallbackForAllChanges(
base::Bind(&URLRequestContextGetter::OnCookieChanged, this));
storage_->set_channel_id_service(std::make_unique<net::ChannelIDService>(
new net::DefaultChannelIDStore(nullptr)));
cookie_store->GetChangeDispatcher().AddCallbackForAllChanges(
base::Bind(&URLRequestContextGetter::OnCookieChanged,
base::RetainedRef(this)));
storage_->set_cookie_store(std::move(cookie_store));
storage_->set_channel_id_service(std::move(channel_id_service));
storage_->set_http_user_agent_settings(
base::WrapUnique(new net::StaticHttpUserAgentSettings(
@@ -307,7 +333,7 @@ net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() {
storage_->set_transport_security_state(std::move(transport_security_state));
storage_->set_cert_verifier(
delegate_->CreateCertVerifier(ct_delegate_.get()));
storage_->set_ssl_config_service(delegate_->CreateSSLConfigService());
storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults());
storage_->set_http_auth_handler_factory(std::move(auth_handler_factory));
std::unique_ptr<net::HttpServerProperties> server_properties(
new net::HttpServerPropertiesImpl);
@@ -360,7 +386,8 @@ net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() {
std::move(backend), false));
std::unique_ptr<net::URLRequestJobFactory> job_factory =
delegate_->CreateURLRequestJobFactory(&protocol_handlers_);
delegate_->CreateURLRequestJobFactory(url_request_context_.get(),
&protocol_handlers_);
job_factory_ = job_factory.get();
// Set up interceptors in the reverse order.
@@ -378,6 +405,9 @@ net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() {
storage_->set_job_factory(std::move(top_job_factory));
}
if (resource_context_)
resource_context_->request_context_ = url_request_context_.get();
return url_request_context_.get();
}
@@ -386,4 +416,11 @@ URLRequestContextGetter::GetNetworkTaskRunner() const {
return BrowserThread::GetTaskRunnerForThread(BrowserThread::IO);
}
void URLRequestContextGetter::OnCookieChanged(
const net::CanonicalCookie& cookie,
net::CookieChangeCause cause) const {
if (delegate_)
delegate_->OnCookieChanged(cookie, cause);
}
} // namespace brightray

View File

@@ -22,10 +22,6 @@
#include "base/debug/leak_tracker.h"
#endif
namespace base {
class MessageLoop;
}
namespace net {
class HostMappingRules;
class HostResolver;
@@ -38,6 +34,8 @@ class URLRequestJobFactory;
namespace brightray {
class BrowserContext;
class ResourceContext;
class RequireCTDelegate;
class NetLog;
@@ -48,55 +46,76 @@ class URLRequestContextGetter : public net::URLRequestContextGetter {
Delegate() {}
virtual ~Delegate() {}
virtual std::unique_ptr<net::NetworkDelegate> CreateNetworkDelegate();
virtual std::string GetUserAgent();
virtual std::unique_ptr<net::NetworkDelegate> CreateNetworkDelegate() = 0;
virtual std::unique_ptr<net::URLRequestJobFactory>
CreateURLRequestJobFactory(content::ProtocolHandlerMap* protocol_handlers);
CreateURLRequestJobFactory(
net::URLRequestContext* url_request_context,
content::ProtocolHandlerMap* protocol_handlers) = 0;
virtual net::HttpCache::BackendFactory* CreateHttpCacheBackendFactory(
const base::FilePath& base_path);
const base::FilePath& base_path) = 0;
virtual std::unique_ptr<net::CertVerifier> CreateCertVerifier(
RequireCTDelegate* ct_delegate);
virtual net::SSLConfigService* CreateSSLConfigService();
virtual std::vector<std::string> GetCookieableSchemes();
virtual void NotifyCookieChange(const net::CanonicalCookie& cookie,
bool removed,
net::CookieChangeCause cause) {}
RequireCTDelegate* ct_delegate) = 0;
virtual void GetCookieableSchemes(
std::vector<std::string>* cookie_schemes) {}
virtual void OnCookieChanged(const net::CanonicalCookie& cookie,
net::CookieChangeCause cause) {}
};
URLRequestContextGetter(
Delegate* delegate,
NetLog* net_log,
const base::FilePath& base_path,
ResourceContext* resource_context,
bool in_memory,
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
const std::string& user_agent,
const base::FilePath& base_path,
content::ProtocolHandlerMap* protocol_handlers,
content::URLRequestInterceptorScopedVector protocol_interceptors);
// net::CookieChangeDispatcher::CookieChangedCallback implementation.
void OnCookieChanged(const net::CanonicalCookie& cookie,
net::CookieChangeCause cause);
// net::URLRequestContextGetter:
net::URLRequestContext* GetURLRequestContext() override;
scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
const override;
net::HostResolver* host_resolver();
net::URLRequestJobFactory* job_factory() const { return job_factory_; }
void set_delegate(Delegate* delegate) { delegate_ = delegate; }
void NotifyContextShutdownOnIO();
// Discard reference to URLRequestContext and inform observers to
// shutdown. Must be called only on IO thread.
void NotifyContextShuttingDown(std::unique_ptr<ResourceContext>);
private:
friend class BrowserContext;
// Responsible for destroying URLRequestContextGetter
// on the IO thread.
class Handle {
public:
explicit Handle(base::WeakPtr<BrowserContext> browser_context);
~Handle();
scoped_refptr<URLRequestContextGetter> CreateMainRequestContextGetter(
content::ProtocolHandlerMap* protocol_handlers,
content::URLRequestInterceptorScopedVector protocol_interceptors);
content::ResourceContext* GetResourceContext() const;
scoped_refptr<URLRequestContextGetter> GetMainRequestContextGetter() const;
void ShutdownOnUIThread();
private:
void LazyInitialize() const;
scoped_refptr<URLRequestContextGetter> main_request_context_getter_;
std::unique_ptr<ResourceContext> resource_context_;
base::WeakPtr<BrowserContext> browser_context_;
mutable bool initialized_;
DISALLOW_COPY_AND_ASSIGN(Handle);
};
~URLRequestContextGetter() override;
Delegate* delegate_;
NetLog* net_log_;
base::FilePath base_path_;
bool in_memory_;
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
std::string user_agent_;
// net::CookieChangeDispatcher::CookieChangedCallback implementation.
void OnCookieChanged(const net::CanonicalCookie& cookie,
net::CookieChangeCause cause) const;
#if DCHECK_IS_ON()
base::debug::LeakTracker<URLRequestContextGetter> leak_tracker_;
@@ -110,11 +129,16 @@ class URLRequestContextGetter : public net::URLRequestContextGetter {
std::unique_ptr<net::HttpAuthPreferences> http_auth_preferences_;
std::unique_ptr<net::HttpNetworkSession> http_network_session_;
std::unique_ptr<net::CookieChangeSubscription> cookie_change_sub_;
net::URLRequestJobFactory* job_factory_;
Delegate* delegate_;
NetLog* net_log_;
ResourceContext* resource_context_;
content::ProtocolHandlerMap protocol_handlers_;
content::URLRequestInterceptorScopedVector protocol_interceptors_;
net::URLRequestJobFactory* job_factory_; // weak ref
base::FilePath base_path_;
bool in_memory_;
std::string user_agent_;
bool context_shutting_down_;
DISALLOW_COPY_AND_ASSIGN(URLRequestContextGetter);

View File

@@ -81,7 +81,8 @@ InspectableWebContentsViewViews::InspectableWebContentsViewViews(
title_(base::ASCIIToUTF16("Developer Tools")) {
set_owned_by_client();
if (inspectable_web_contents_->GetWebContents()->GetNativeView()) {
if (!inspectable_web_contents_->IsGuest() &&
inspectable_web_contents_->GetWebContents()->GetNativeView()) {
views::WebView* contents_web_view = new views::WebView(nullptr);
contents_web_view->SetWebContents(
inspectable_web_contents_->GetWebContents());

View File

@@ -50,9 +50,6 @@ const char kAuthServerWhitelist[] = "auth-server-whitelist";
const char kAuthNegotiateDelegateWhitelist[] =
"auth-negotiate-delegate-whitelist";
// Forces the maximum disk space to be used by the disk cache, in bytes.
const char kDiskCacheSize[] = "disk-cache-size";
} // namespace switches
} // namespace brightray

View File

@@ -17,7 +17,6 @@ extern const char kProxyPacUrl[];
extern const char kDisableHttp2[];
extern const char kAuthServerWhitelist[];
extern const char kAuthNegotiateDelegateWhitelist[];
extern const char kDiskCacheSize[];
} // namespace switches

View File

@@ -51,8 +51,6 @@
'browser/net/require_ct_delegate.h',
'browser/net_log.cc',
'browser/net_log.h',
'browser/network_delegate.cc',
'browser/network_delegate.h',
'browser/notification_delegate.h',
'browser/notification_presenter.cc',
'browser/notification_presenter.h',

View File

@@ -182,6 +182,10 @@ tray.setHighlightMode('off')
webContents.openDevTools({detach: true})
// Replace with
webContents.openDevTools({mode: 'detach'})
// Removed
webContents.setSize(options)
// There is no replacement for this API
```
## `webFrame`
@@ -198,6 +202,18 @@ webFrame.registerURLSchemeAsPrivileged('app', {secure: true})
protocol.registerStandardSchemes(['app'], {secure: true})
```
## `<webview>`
```js
// Removed
webview.setAttribute('disableguestresize', '')
// There is no replacement for this API
// Removed
webview.setAttribute('guestinstance', instanceId)
// There is no replacement for this API
```
## Node Headers URL
This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url`

View File

@@ -1231,7 +1231,7 @@ mode set (but with a value within the valid range), `normal` will be assumed.
#### `win.setOverlayIcon(overlay, description)` _Windows_
* `overlay` [NativeImage](native-image.md) - the icon to display on the bottom
* `overlay` [NativeImage](native-image.md) | null - the icon to display on the bottom
right corner of the taskbar icon. If this parameter is `null`, the overlay is
cleared
* `description` String - a description that will be provided to Accessibility

View File

@@ -8,6 +8,19 @@ Electron's `process` object is extended from the
[Node.js `process` object](https://nodejs.org/api/process.html).
It adds the following events, properties, and methods:
## Sandbox
In sandboxed renderers the `process` object contains only a subset of the APIs:
- `crash()`
- `hang()`
- `getHeapStatistics()`
- `getProcessMemoryInfo()`
- `getSystemMemoryInfo()`
- `argv`
- `execPath`
- `env`
- `platform`
## Events
### Event: 'loaded'

View File

@@ -136,7 +136,7 @@ The DPI scale is performed relative to the display containing the DIP point.
### `screen.screenToDipRect(window, rect)` _Windows_
* `window` [BrowserWindow](browser-window.md)
* `window` [BrowserWindow](browser-window.md) | null
* `rect` [Rectangle](structures/rectangle.md)
Returns [`Rectangle`](structures/rectangle.md)
@@ -147,7 +147,7 @@ If `window` is null, scaling will be performed to the display nearest to `rect`.
### `screen.dipToScreenRect(window, rect)` _Windows_
* `window` [BrowserWindow](browser-window.md)
* `window` [BrowserWindow](browser-window.md) | null
* `rect` [Rectangle](structures/rectangle.md)
Returns [`Rectangle`](structures/rectangle.md)

View File

@@ -194,7 +194,7 @@ Sets the `image` associated with this tray icon.
#### `tray.setPressedImage(image)` _macOS_
* `image` [NativeImage](native-image.md)
* `image` ([NativeImage](native-image.md) | String)
Sets the `image` associated with this tray icon when pressed on macOS.
@@ -275,7 +275,7 @@ The `position` is only available on Windows, and it is (0, 0) by default.
#### `tray.setContextMenu(menu)`
* `menu` Menu
* `menu` Menu | null
Sets the context menu for this icon.

View File

@@ -1381,23 +1381,6 @@ win.webContents.on('did-finish-load', () => {
Shows pop-up dictionary that searches the selected word on the page.
#### `contents.setSize(options)`
Set the size of the page. This is only supported for `<webview>` guest contents.
* `options` Object
* `enableAutoSize` Boolean (optional) - true to make the webview container automatically
resize within the bounds specified by the attributes normal, min and max.
* `normal` [Size](structures/size.md) (optional) - Normal size of the page. This can be used in
combination with the [`disableguestresize`](webview-tag.md#disableguestresize)
attribute to manually resize the webview guest contents.
* `min` [Size](structures/size.md) (optional) - Minimum size of the page. This can be used in
combination with the [`disableguestresize`](webview-tag.md#disableguestresize)
attribute to manually resize the webview guest contents.
* `max` [Size](structures/size.md) (optional) - Maximium size of the page. This can be used in
combination with the [`disableguestresize`](webview-tag.md#disableguestresize)
attribute to manually resize the webview guest contents.
#### `contents.isOffscreen()`
Returns `Boolean` - Indicates whether *offscreen rendering* is enabled.

View File

@@ -167,6 +167,7 @@ Set the security origin of the isolated world.
Returns `Object`:
* `images` [MemoryUsageDetails](structures/memory-usage-details.md)
* `scripts` [MemoryUsageDetails](structures/memory-usage-details.md)
* `cssStyleSheets` [MemoryUsageDetails](structures/memory-usage-details.md)
* `xslStyleSheets` [MemoryUsageDetails](structures/memory-usage-details.md)
* `fonts` [MemoryUsageDetails](structures/memory-usage-details.md)

View File

@@ -1,5 +1,15 @@
# `<webview>` Tag
## Warning
Electron's `webview` tag is based on [Chromium's `webview`][chrome-webview], which
is undergoing dramatic architectural changes. This impacts the stability of `webviews`,
including rendering, navigation, and event routing. We currently recommend to not
use the `webview` tag and to consider alternatives, like `iframe`, Electron's `BrowserView`,
or an architecture that avoids embedded content altogether.
## Overview
> Display external web content in an isolated frame and process.
Process: [Renderer](../glossary.md#renderer-process)
@@ -234,59 +244,6 @@ A list of strings which specifies the blink features to be disabled separated by
The full list of supported feature strings can be found in the
[RuntimeEnabledFeatures.json5][runtime-enabled-features] file.
### `guestinstance`
```html
<webview src="https://www.github.com/" guestinstance="3"></webview>
```
A value that links the webview to a specific webContents. When a webview
first loads a new webContents is created and this attribute is set to its
instance identifier. Setting this attribute on a new or existing webview
connects it to the existing webContents that currently renders in a different
webview.
The existing webview will see the `destroy` event and will then create a new
webContents when a new url is loaded.
### `disableguestresize`
```html
<webview src="https://www.github.com/" disableguestresize></webview>
```
When this attribute is present the `webview` contents will be prevented from
resizing when the `webview` element itself is resized.
This can be used in combination with
[`webContents.setSize`](web-contents.md#contentssetsizeoptions) to manually
resize the webview contents in reaction to a window size change. This can
make resizing faster compared to relying on the webview element bounds to
automatically resize the contents.
```javascript
const {webContents} = require('electron')
// We assume that `win` points to a `BrowserWindow` instance containing a
// `<webview>` with `disableguestresize`.
win.on('resize', () => {
const [width, height] = win.getContentSize()
for (let wc of webContents.getAllWebContents()) {
// Check if `wc` belongs to a webview in the `win` window.
if (wc.hostWebContents &&
wc.hostWebContents.id === win.webContents.id) {
wc.setSize({
normal: {
width: width,
height: height
}
})
}
}
})
```
## Methods
The `webview` tag has the following methods:
@@ -914,3 +871,4 @@ Emitted when DevTools is closed.
Emitted when DevTools is focused / opened.
[runtime-enabled-features]: https://cs.chromium.org/chromium/src/third_party/blink/renderer/platform/runtime_enabled_features.json5?l=70
[chrome-webview]: https://developer.chrome.com/apps/tags/webview

View File

@@ -81,7 +81,8 @@ improve the security of your application.
10. [Do not use `enableBlinkFeatures`](#10-do-not-use-enableblinkfeatures)
11. [`<webview>`: Do not use `allowpopups`](#11-do-not-use-allowpopups)
12. [`<webview>`: Verify options and params](#12-verify-webview-options-before-creation)
13. [Disable or limit navigation](#13-disable-or-limit-navigation)
14. [Disable or limit creation of new windows](#13-disable-or-limit-creation-of-new-windows)
## 1) Only Load Secure Content
@@ -536,7 +537,7 @@ for newly created [`<webview>`][webview-tag] tags.
Before a [`<webview>`][webview-tag] tag is attached, Electron will fire the
`will-attach-webview` event on the hosting `webContents`. Use the event to
prevent the creation of webviews with possibly insecure options.
prevent the creation of `webViews` with possibly insecure options.
```js
app.on('web-contents-created', (event, contents) => {
@@ -559,6 +560,93 @@ app.on('web-contents-created', (event, contents) => {
Again, this list merely minimizes the risk, it does not remove it. If your goal
is to display a website, a browser will be a more secure option.
## 13) Disable or limit navigation
If your app has no need to navigate or only needs to navigate to known pages,
it is a good idea to limit navigation outright to that known scope, disallowing
any other kinds of navigation.
### Why?
Navigation is a common attack vector. If an attacker can convince your app to
navigate away from its current page, they can possibly force your app to open
web sites on the Internet. Even if your `webContents` are configured to be more
secure (like having `nodeIntegration` disabled or `contextIsolation` enabled),
getting your app to open a random web site will make the work of exploiting your
app a lot easier.
A common attack pattern is that the attacker convinces your app's users to
interact with the app in such a way that it navigates to one of the attacker's
pages. This is usually done via links, plugins, or other user-generated content.
### How?
If your app has no need for navigation, you can call `event.preventDefault()`
in a [`will-navigate`][will-navigate] handler. If you know which pages your app
might navigate to, check the URL in the event handler and only let navigation
occur if it matches the URLs you're expecting.
We recommend that you use Node's parser for URLs. Simple string comparisons can
sometimes be fooled - a `startsWith('https://google.com')` test would let
`https://google.com.attacker.com` through.
```js
const URL = require('url')
app.on('web-contents-created', (event, contents) => {
contents.on('will-navigate', (event, navigationUrl) => {
const parsedUrl = new URL(navigationUrl)
if (parsedUrl.hostname !== 'my-own-server.com') {
event.preventDefault()
}
})
})
```
## 14) Disable or limit creation of new windows
If you have a known set of windows, it's a good idea to limit the creation of
additional windows in your app.
### Why?
Much like navigation, the creation of new `webContents` is a common attack
vector. Attackers attempt to convince your app to create new windows, frames,
or other renderer processes with more privileges than they had before; or
with pages opened that they couldn't open before.
If you have no need to create windows in addition to the ones you know you'll
need to create, disabling the creation buys you a little bit of extra
security at no cost. This is commonly the case for apps that open one
`BrowserWindow` and do not need to open an arbitrary number of additional
windows at runtime.
### How?
[`webContents`][web-contents] will emit the [`new-window`][new-window] event
before creating new windows. That event will be passed, amongst other
parameters, the `url` the window was requested to open and the options used to
create it. We recommend that you use the event to scrutinize the creation of
windows, limiting it to only what you need.
```js
const { shell } = require('electron')
app.on('web-contents-created', (event, contents) => {
contents.on('new-window', (event, navigationUrl) => {
// In this example, we'll ask the operating system
// to open this event's url in the default browser.
event.preventDefault()
shell.openExternal(navigationUrl)
})
})
```
[browser-window]: ../api/browser-window.md
[browser-view]: ../api/browser-view.md
[webview-tag]: ../api/webview-tag.md
[web-contents]: ../api/web-contents.md
[new-window]: ../api/web-contents.md#event-new-window
[will-navigate]: ../api/web-contents.md#event-will-navigate

View File

@@ -4,7 +4,7 @@
'product_name%': 'Electron',
'company_name%': 'GitHub, Inc',
'company_abbr%': 'github',
'version%': '3.0.0-beta.3',
'version%': '3.0.0-beta.8',
'js2c_input_dir': '<(SHARED_INTERMEDIATE_DIR)/js2c',
},
'includes': [
@@ -340,6 +340,16 @@
'link_settings': {
'libraries': [ '<@(libchromiumcontent_v8_libraries)' ],
},
'sources': [
'<@(lib_sources_location_provider)',
],
'defines': [
# Enable fake location provider to mock geolocation
# responses in component build. Should not be enabled
# for release build. If you need to test with chromium's
# location provider, remove this definition.
'OVERRIDE_LOCATION_PROVIDER',
],
}],
['OS=="win"', {
'sources': [

View File

@@ -3,7 +3,7 @@
'variables': {
'variables': {
'enable_desktop_capturer%': 1,
'enable_osr%': 0, # FIXME(alexeykuzmin)
'enable_osr%': 1,
'enable_pdf_viewer%': 0, # FIXME(deepak1556)
'enable_run_as_node%': 1,
'enable_view_api%': 0,

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