Merge pull request #12168 from electron/easier-web-contents-preferences

Cleanup the static methods of WebContentsPreferences
This commit is contained in:
Cheng Zhao 2018-03-22 15:58:04 +09:00 committed by GitHub
commit 67f052a6e1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 160 additions and 198 deletions

View file

@ -115,14 +115,13 @@ BrowserWindow::BrowserWindow(v8::Isolate* isolate,
// These preferences will be used when the webContent launches new // These preferences will be used when the webContent launches new
// render processes. // render processes.
auto* existing_preferences = auto* existing_preferences =
WebContentsPreferences::FromWebContents(web_contents->web_contents()); WebContentsPreferences::From(web_contents->web_contents());
base::DictionaryValue web_preferences_dict; base::DictionaryValue web_preferences_dict;
if (mate::ConvertFromV8(isolate, web_preferences.GetHandle(), if (mate::ConvertFromV8(isolate, web_preferences.GetHandle(),
&web_preferences_dict)) { &web_preferences_dict)) {
existing_preferences->web_preferences()->Clear(); existing_preferences->dict()->Clear();
existing_preferences->Merge(web_preferences_dict); existing_preferences->Merge(web_preferences_dict);
} }
} else { } else {
// Creates the WebContents used by BrowserWindow. // Creates the WebContents used by BrowserWindow.
web_contents = WebContents::Create(isolate, web_preferences); web_contents = WebContents::Create(isolate, web_preferences);

View file

@ -1122,11 +1122,10 @@ void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) {
// created after loading a page. // created after loading a page.
const auto view = web_contents()->GetRenderWidgetHostView(); const auto view = web_contents()->GetRenderWidgetHostView();
if (view) { if (view) {
WebContentsPreferences* web_preferences = auto* web_preferences = WebContentsPreferences::From(web_contents());
WebContentsPreferences::FromWebContents(web_contents());
std::string color_name; std::string color_name;
if (web_preferences->web_preferences()->GetString(options::kBackgroundColor, if (web_preferences->dict()->GetString(options::kBackgroundColor,
&color_name)) { &color_name)) {
view->SetBackgroundColor(ParseHexColor(color_name)); view->SetBackgroundColor(ParseHexColor(color_name));
} else { } else {
view->SetBackgroundColor(SK_ColorTRANSPARENT); view->SetBackgroundColor(SK_ColorTRANSPARENT);
@ -1840,11 +1839,10 @@ void WebContents::OnGetZoomLevel(content::RenderFrameHost* rfh,
} }
v8::Local<v8::Value> WebContents::GetWebPreferences(v8::Isolate* isolate) { v8::Local<v8::Value> WebContents::GetWebPreferences(v8::Isolate* isolate) {
WebContentsPreferences* web_preferences = auto* web_preferences = WebContentsPreferences::From(web_contents());
WebContentsPreferences::FromWebContents(web_contents());
if (!web_preferences) if (!web_preferences)
return v8::Null(isolate); return v8::Null(isolate);
return mate::ConvertToV8(isolate, *web_preferences->web_preferences()); return mate::ConvertToV8(isolate, *web_preferences->dict());
} }
v8::Local<v8::Value> WebContents::GetLastWebPreferences(v8::Isolate* isolate) { v8::Local<v8::Value> WebContents::GetLastWebPreferences(v8::Isolate* isolate) {
@ -1852,7 +1850,7 @@ v8::Local<v8::Value> WebContents::GetLastWebPreferences(v8::Isolate* isolate) {
WebContentsPreferences::FromWebContents(web_contents()); WebContentsPreferences::FromWebContents(web_contents());
if (!web_preferences) if (!web_preferences)
return v8::Null(isolate); return v8::Null(isolate);
return mate::ConvertToV8(isolate, *web_preferences->last_web_preferences()); return mate::ConvertToV8(isolate, *web_preferences->last_dict());
} }
v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow() { v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow() {

View file

@ -34,7 +34,7 @@ void AddGuest(int guest_instance_id,
->SetDefaultZoomFactor(zoom_factor); ->SetDefaultZoomFactor(zoom_factor);
} }
WebContentsPreferences::FromWebContents(guest_web_contents)->Merge(options); WebContentsPreferences::From(guest_web_contents)->Merge(options);
} }
void RemoveGuest(content::WebContents* embedder, int guest_instance_id) { void RemoveGuest(content::WebContents* embedder, int guest_instance_id) {

View file

@ -173,17 +173,15 @@ void AtomBrowserClient::RenderProcessWillLaunch(
host->AddFilter( host->AddFilter(
new WidevineCdmMessageFilter(process_id, host->GetBrowserContext())); new WidevineCdmMessageFilter(process_id, host->GetBrowserContext()));
content::WebContents* web_contents = GetWebContentsFromProcessID(process_id); ProcessPreferences prefs;
ProcessPreferences process_prefs; auto* web_preferences = WebContentsPreferences::From(
process_prefs.sandbox = GetWebContentsFromProcessID(process_id));
WebContentsPreferences::IsPreferenceEnabled("sandbox", web_contents); if (web_preferences) {
process_prefs.native_window_open = prefs.sandbox = web_preferences->IsEnabled("sandbox");
WebContentsPreferences::IsPreferenceEnabled("nativeWindowOpen", prefs.native_window_open = web_preferences->IsEnabled("nativeWindowOpen");
web_contents); prefs.disable_popups = web_preferences->IsEnabled("disablePopups");
process_prefs.disable_popups = }
WebContentsPreferences::IsPreferenceEnabled("disablePopups", AddProcessPreferences(host->GetID(), prefs);
web_contents);
AddProcessPreferences(host->GetID(), process_prefs);
// ensure the ProcessPreferences is removed later // ensure the ProcessPreferences is removed later
host->AddObserver(this); host->AddObserver(this);
} }
@ -211,8 +209,10 @@ void AtomBrowserClient::OverrideWebkitPrefs(
prefs->allow_running_insecure_content = false; prefs->allow_running_insecure_content = false;
// Custom preferences of guest page. // Custom preferences of guest page.
auto web_contents = content::WebContents::FromRenderViewHost(host); auto* web_contents = content::WebContents::FromRenderViewHost(host);
WebContentsPreferences::OverrideWebkitPrefs(web_contents, prefs); auto* web_preferences = WebContentsPreferences::From(web_contents);
if (web_preferences)
web_preferences->OverrideWebkitPrefs(prefs);
} }
void AtomBrowserClient::OverrideSiteInstanceForNavigation( void AtomBrowserClient::OverrideSiteInstanceForNavigation(
@ -235,10 +235,9 @@ void AtomBrowserClient::OverrideSiteInstanceForNavigation(
// Do we have an affinity site to manage ? // Do we have an affinity site to manage ?
std::string affinity; std::string affinity;
auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); auto* web_contents = content::WebContents::FromRenderFrameHost(rfh);
auto* web_preferences = web_contents ? auto* web_preferences = WebContentsPreferences::From(web_contents);
WebContentsPreferences::FromWebContents(web_contents) : nullptr;
if (web_preferences && if (web_preferences &&
web_preferences->web_preferences()->GetString("affinity", &affinity) && web_preferences->dict()->GetString("affinity", &affinity) &&
!affinity.empty()) { !affinity.empty()) {
affinity = base::ToLowerASCII(affinity); affinity = base::ToLowerASCII(affinity);
auto iter = site_per_affinities.find(affinity); auto iter = site_per_affinities.find(affinity);
@ -323,8 +322,9 @@ void AtomBrowserClient::AppendExtraCommandLineSwitches(
content::WebContents* web_contents = GetWebContentsFromProcessID(process_id); content::WebContents* web_contents = GetWebContentsFromProcessID(process_id);
if (web_contents) { if (web_contents) {
WebContentsPreferences::AppendExtraCommandLineSwitches( auto* web_preferences = WebContentsPreferences::From(web_contents);
web_contents, command_line); if (web_preferences)
web_preferences->AppendCommandLineSwitches(command_line);
SessionPreferences::AppendExtraCommandLineSwitches( SessionPreferences::AppendExtraCommandLineSwitches(
web_contents->GetBrowserContext(), command_line); web_contents->GetBrowserContext(), command_line);

View file

@ -118,15 +118,16 @@ class AtomBrowserClient : public brightray::BrowserClient,
int exit_code) override; int exit_code) override;
private: private:
bool ShouldCreateNewSiteInstance(content::RenderFrameHost* render_frame_host,
content::BrowserContext* browser_context,
content::SiteInstance* current_instance,
const GURL& dest_url);
struct ProcessPreferences { struct ProcessPreferences {
bool sandbox = false; bool sandbox = false;
bool native_window_open = false; bool native_window_open = false;
bool disable_popups = false; bool disable_popups = false;
}; };
bool ShouldCreateNewSiteInstance(content::RenderFrameHost* render_frame_host,
content::BrowserContext* browser_context,
content::SiteInstance* current_instance,
const GURL& dest_url);
void AddProcessPreferences(int process_id, ProcessPreferences prefs); void AddProcessPreferences(int process_id, ProcessPreferences prefs);
void RemoveProcessPreferences(int process_id); void RemoveProcessPreferences(int process_id);
bool IsProcessObserved(int process_id); bool IsProcessObserved(int process_id);

View file

@ -55,13 +55,13 @@ void AtomJavaScriptDialogManager::RunJavaScriptDialog(
origin_counts_[origin]++; origin_counts_[origin]++;
std::string checkbox_string; std::string checkbox;
if (origin_counts_[origin] > 1 && if (origin_counts_[origin] > 1) {
WebContentsPreferences::IsPreferenceEnabled("safeDialogs", auto* web_preferences = WebContentsPreferences::From(web_contents);
web_contents)) { if (web_preferences &&
if (!WebContentsPreferences::GetString("safeDialogsMessage", web_preferences->IsEnabled("safeDialogs") &&
&checkbox_string, web_contents)) { !web_preferences->dict()->GetString("safeDialogsMessage", &checkbox)) {
checkbox_string = "Prevent this app from creating additional dialogs"; checkbox = "Prevent this app from creating additional dialogs";
} }
} }
@ -70,7 +70,7 @@ void AtomJavaScriptDialogManager::RunJavaScriptDialog(
relay ? relay->window.get() : nullptr, relay ? relay->window.get() : nullptr,
atom::MessageBoxType::MESSAGE_BOX_TYPE_NONE, buttons, -1, 0, atom::MessageBoxType::MESSAGE_BOX_TYPE_NONE, buttons, -1, 0,
atom::MessageBoxOptions::MESSAGE_BOX_NONE, "", atom::MessageBoxOptions::MESSAGE_BOX_NONE, "",
base::UTF16ToUTF8(message_text), "", checkbox_string, base::UTF16ToUTF8(message_text), "", checkbox,
false, gfx::ImageSkia(), false, gfx::ImageSkia(),
base::Bind(&AtomJavaScriptDialogManager::OnMessageBoxCallback, base::Bind(&AtomJavaScriptDialogManager::OnMessageBoxCallback,
base::Unretained(this), base::Unretained(this),

View file

@ -6,6 +6,7 @@
#include <vector> #include <vector>
#include "atom/browser/atom_browser_client.h"
#include "atom/browser/web_contents_preferences.h" #include "atom/browser/web_contents_preferences.h"
#include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/permission_type.h" #include "content/public/browser/permission_type.h"
@ -19,11 +20,12 @@ namespace atom {
namespace { namespace {
bool WebContentsDestroyed(int process_id) { bool WebContentsDestroyed(int process_id) {
auto contents = content::WebContents* web_contents =
WebContentsPreferences::GetWebContentsFromProcessID(process_id); static_cast<AtomBrowserClient*>(AtomBrowserClient::Get())->
if (!contents) GetWebContentsFromProcessID(process_id);
if (!web_contents)
return true; return true;
return contents->IsBeingDestroyed(); return web_contents->IsBeingDestroyed();
} }
void PermissionRequestResponseCallbackWrapper( void PermissionRequestResponseCallbackWrapper(

View file

@ -80,9 +80,10 @@ void OnPdfResourceIntercepted(
if (!web_contents) if (!web_contents)
return; return;
if (!WebContentsPreferences::IsPreferenceEnabled("plugins", web_contents)) { auto* web_preferences = WebContentsPreferences::From(web_contents);
auto browser_context = web_contents->GetBrowserContext(); if (!web_preferences || !web_preferences->IsEnabled("plugins")) {
auto download_manager = auto* browser_context = web_contents->GetBrowserContext();
auto* download_manager =
content::BrowserContext::GetDownloadManager(browser_context); content::BrowserContext::GetDownloadManager(browser_context);
download_manager->DownloadUrl( download_manager->DownloadUrl(

View file

@ -1370,22 +1370,21 @@ void NativeWindowViews::ShowAutofillPopup(
bool is_offsceen = false; bool is_offsceen = false;
bool is_embedder_offscreen = false; bool is_embedder_offscreen = false;
auto* web_contents_preferences = auto* web_preferences = WebContentsPreferences::From(web_contents);
WebContentsPreferences::FromWebContents(web_contents); if (web_preferences) {
if (web_contents_preferences) { web_preferences->dict()->GetBoolean("offscreen", &is_offsceen);
const auto* web_preferences = web_contents_preferences->web_preferences();
web_preferences->GetBoolean("offscreen", &is_offsceen);
int guest_instance_id = 0; int guest_instance_id = 0;
web_preferences->GetInteger(options::kGuestInstanceID, &guest_instance_id); web_preferences->dict()->GetInteger(options::kGuestInstanceID,
&guest_instance_id);
if (guest_instance_id) { if (guest_instance_id) {
auto manager = WebViewManager::GetWebViewManager(web_contents); auto* manager = WebViewManager::GetWebViewManager(web_contents);
if (manager) { if (manager) {
auto embedder = manager->GetEmbedder(guest_instance_id); auto* embedder = manager->GetEmbedder(guest_instance_id);
if (embedder) { if (embedder) {
is_embedder_offscreen = WebContentsPreferences::IsPreferenceEnabled( auto* embedder_prefs = WebContentsPreferences::From(embedder);
"offscreen", embedder); is_embedder_offscreen = embedder_prefs &&
embedder_prefs->IsEnabled("offscreen");
} }
} }
} }

View file

@ -45,7 +45,7 @@ WebContentsPreferences::WebContentsPreferences(
copied.Delete("isGuest"); copied.Delete("isGuest");
copied.Delete("session"); copied.Delete("session");
mate::ConvertFromV8(isolate, copied.GetHandle(), &web_preferences_); mate::ConvertFromV8(isolate, copied.GetHandle(), &dict_);
web_contents->SetUserData(UserDataKey(), base::WrapUnique(this)); web_contents->SetUserData(UserDataKey(), base::WrapUnique(this));
instances_.push_back(this); instances_.push_back(this);
@ -70,7 +70,8 @@ WebContentsPreferences::WebContentsPreferences(
SetDefaultBoolIfUndefined(options::kScrollBounce, false); SetDefaultBoolIfUndefined(options::kScrollBounce, false);
#endif #endif
SetDefaultBoolIfUndefined("offscreen", false); SetDefaultBoolIfUndefined("offscreen", false);
last_web_preferences_.MergeDictionary(&web_preferences_);
last_dict_ = std::move(*dict_.CreateDeepCopy());
} }
WebContentsPreferences::~WebContentsPreferences() { WebContentsPreferences::~WebContentsPreferences() {
@ -79,18 +80,25 @@ WebContentsPreferences::~WebContentsPreferences() {
instances_.end()); instances_.end());
} }
bool WebContentsPreferences::SetDefaultBoolIfUndefined(const std::string key, bool WebContentsPreferences::SetDefaultBoolIfUndefined(
bool val) { const base::StringPiece& key, bool val) {
bool existing; bool existing;
if (!web_preferences_.GetBoolean(key, &existing)) { if (!dict_.GetBoolean(key, &existing)) {
web_preferences_.SetBoolean(key, val); dict_.SetBoolean(key, val);
return val; return val;
} }
return existing; return existing;
} }
bool WebContentsPreferences::IsEnabled(const base::StringPiece& name,
bool default_value) {
bool bool_value = default_value;
dict_.GetBoolean(name, &bool_value);
return bool_value;
}
void WebContentsPreferences::Merge(const base::DictionaryValue& extend) { void WebContentsPreferences::Merge(const base::DictionaryValue& extend) {
web_preferences_.MergeDictionary(&extend); dict_.MergeDictionary(&extend);
} }
// static // static
@ -105,69 +113,62 @@ content::WebContents* WebContentsPreferences::GetWebContentsFromProcessID(
} }
// static // static
void WebContentsPreferences::AppendExtraCommandLineSwitches( WebContentsPreferences* WebContentsPreferences::From(
content::WebContents* web_contents, base::CommandLine* command_line) { content::WebContents* web_contents) {
WebContentsPreferences* self = FromWebContents(web_contents); if (!web_contents)
if (!self) return nullptr;
return; return FromWebContents(web_contents);
}
base::DictionaryValue& web_preferences = self->web_preferences_;
// We are appending args to a webContents so let's save the current state
// of our preferences object so that during the lifetime of the WebContents
// we can fetch the options used to initally configure the WebContents
self->last_web_preferences_.Clear();
self->last_web_preferences_.MergeDictionary(&web_preferences);
void WebContentsPreferences::AppendCommandLineSwitches(
base::CommandLine* command_line) {
bool b; bool b;
// Check if plugins are enabled. // Check if plugins are enabled.
if (web_preferences.GetBoolean("plugins", &b) && b) if (dict_.GetBoolean("plugins", &b) && b)
command_line->AppendSwitch(switches::kEnablePlugins); command_line->AppendSwitch(switches::kEnablePlugins);
// Experimental flags. // Experimental flags.
if (web_preferences.GetBoolean(options::kExperimentalFeatures, &b) && b) if (dict_.GetBoolean(options::kExperimentalFeatures, &b) && b)
command_line->AppendSwitch( command_line->AppendSwitch(
::switches::kEnableExperimentalWebPlatformFeatures); ::switches::kEnableExperimentalWebPlatformFeatures);
if (web_preferences.GetBoolean(options::kExperimentalCanvasFeatures, &b) && b) if (dict_.GetBoolean(options::kExperimentalCanvasFeatures, &b) && b)
command_line->AppendSwitch(::switches::kEnableExperimentalCanvasFeatures); command_line->AppendSwitch(::switches::kEnableExperimentalCanvasFeatures);
// Check if we have node integration specified. // Check if we have node integration specified.
bool node_integration = true; bool node_integration = true;
web_preferences.GetBoolean(options::kNodeIntegration, &node_integration); dict_.GetBoolean(options::kNodeIntegration, &node_integration);
command_line->AppendSwitchASCII(switches::kNodeIntegration, command_line->AppendSwitchASCII(switches::kNodeIntegration,
node_integration ? "true" : "false"); node_integration ? "true" : "false");
// Whether to enable node integration in Worker. // Whether to enable node integration in Worker.
if (web_preferences.GetBoolean(options::kNodeIntegrationInWorker, &b) && b) if (dict_.GetBoolean(options::kNodeIntegrationInWorker, &b) && b)
command_line->AppendSwitch(switches::kNodeIntegrationInWorker); command_line->AppendSwitch(switches::kNodeIntegrationInWorker);
// Check if webview tag creation is enabled, default to nodeIntegration value. // Check if webview tag creation is enabled, default to nodeIntegration value.
// TODO(kevinsawicki): Default to false in 2.0 // TODO(kevinsawicki): Default to false in 2.0
bool webview_tag = node_integration; bool webview_tag = node_integration;
web_preferences.GetBoolean(options::kWebviewTag, &webview_tag); dict_.GetBoolean(options::kWebviewTag, &webview_tag);
command_line->AppendSwitchASCII(switches::kWebviewTag, command_line->AppendSwitchASCII(switches::kWebviewTag,
webview_tag ? "true" : "false"); webview_tag ? "true" : "false");
// If the `sandbox` option was passed to the BrowserWindow's webPreferences, // If the `sandbox` option was passed to the BrowserWindow's webPreferences,
// pass `--enable-sandbox` to the renderer so it won't have any node.js // pass `--enable-sandbox` to the renderer so it won't have any node.js
// integration. // integration.
bool sandbox = false; if (dict_.GetBoolean("sandbox", &b) && b)
if (web_preferences.GetBoolean("sandbox", &sandbox) && sandbox) {
command_line->AppendSwitch(switches::kEnableSandbox); command_line->AppendSwitch(switches::kEnableSandbox);
} else if (!command_line->HasSwitch(switches::kEnableSandbox)) { else if (!command_line->HasSwitch(switches::kEnableSandbox))
command_line->AppendSwitch(::switches::kNoSandbox); command_line->AppendSwitch(::switches::kNoSandbox);
} if (dict_.GetBoolean("nativeWindowOpen", &b) && b)
if (web_preferences.GetBoolean("nativeWindowOpen", &b) && b)
command_line->AppendSwitch(switches::kNativeWindowOpen); command_line->AppendSwitch(switches::kNativeWindowOpen);
// The preload script. // The preload script.
base::FilePath::StringType preload; base::FilePath::StringType preload;
if (web_preferences.GetString(options::kPreloadScript, &preload)) { if (dict_.GetString(options::kPreloadScript, &preload)) {
if (base::FilePath(preload).IsAbsolute()) if (base::FilePath(preload).IsAbsolute())
command_line->AppendSwitchNative(switches::kPreloadScript, preload); command_line->AppendSwitchNative(switches::kPreloadScript, preload);
else else
LOG(ERROR) << "preload script must have absolute path."; LOG(ERROR) << "preload script must have absolute path.";
} else if (web_preferences.GetString(options::kPreloadURL, &preload)) { } else if (dict_.GetString(options::kPreloadURL, &preload)) {
// Translate to file path if there is "preload-url" option. // Translate to file path if there is "preload-url" option.
base::FilePath preload_path; base::FilePath preload_path;
if (net::FileURLToFilePath(GURL(preload), &preload_path)) if (net::FileURLToFilePath(GURL(preload), &preload_path))
@ -178,49 +179,44 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches(
// Custom args for renderer process // Custom args for renderer process
base::Value* customArgs; base::Value* customArgs;
if ((web_preferences.Get(options::kCustomArgs, &customArgs)) if (dict_.Get(options::kCustomArgs, &customArgs) &&
&& (customArgs->is_list())) { customArgs->is_list()) {
for (const base::Value& customArg : customArgs->GetList()) { for (const base::Value& customArg : customArgs->GetList()) {
if (customArg.is_string()) { if (customArg.is_string())
command_line->AppendArg(customArg.GetString()); command_line->AppendArg(customArg.GetString());
}
} }
} }
// Run Electron APIs and preload script in isolated world // Run Electron APIs and preload script in isolated world
bool isolated; if (dict_.GetBoolean(options::kContextIsolation, &b) && b)
if (web_preferences.GetBoolean(options::kContextIsolation, &isolated) &&
isolated)
command_line->AppendSwitch(switches::kContextIsolation); command_line->AppendSwitch(switches::kContextIsolation);
// --background-color. // --background-color.
std::string color; std::string s;
if (web_preferences.GetString(options::kBackgroundColor, &color)) if (dict_.GetString(options::kBackgroundColor, &s))
command_line->AppendSwitchASCII(switches::kBackgroundColor, color); command_line->AppendSwitchASCII(switches::kBackgroundColor, s);
// --guest-instance-id, which is used to identify guest WebContents. // --guest-instance-id, which is used to identify guest WebContents.
int guest_instance_id = 0; int guest_instance_id = 0;
if (web_preferences.GetInteger(options::kGuestInstanceID, &guest_instance_id)) if (dict_.GetInteger(options::kGuestInstanceID, &guest_instance_id))
command_line->AppendSwitchASCII(switches::kGuestInstanceID, command_line->AppendSwitchASCII(switches::kGuestInstanceID,
base::IntToString(guest_instance_id)); base::IntToString(guest_instance_id));
// Pass the opener's window id. // Pass the opener's window id.
int opener_id; int opener_id;
if (web_preferences.GetInteger(options::kOpenerID, &opener_id)) if (dict_.GetInteger(options::kOpenerID, &opener_id))
command_line->AppendSwitchASCII(switches::kOpenerID, command_line->AppendSwitchASCII(switches::kOpenerID,
base::IntToString(opener_id)); base::IntToString(opener_id));
#if defined(OS_MACOSX) #if defined(OS_MACOSX)
// Enable scroll bounce. // Enable scroll bounce.
bool scroll_bounce; if (dict_.GetBoolean(options::kScrollBounce, &b) && b)
if (web_preferences.GetBoolean(options::kScrollBounce, &scroll_bounce) &&
scroll_bounce)
command_line->AppendSwitch(switches::kScrollBounce); command_line->AppendSwitch(switches::kScrollBounce);
#endif #endif
// Custom command line switches. // Custom command line switches.
const base::ListValue* args; const base::ListValue* args;
if (web_preferences.GetList("commandLineSwitches", &args)) { if (dict_.GetList("commandLineSwitches", &args)) {
for (size_t i = 0; i < args->GetSize(); ++i) { for (size_t i = 0; i < args->GetSize(); ++i) {
std::string arg; std::string arg;
if (args->GetString(i, &arg) && !arg.empty()) if (args->GetString(i, &arg) && !arg.empty())
@ -229,26 +225,21 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches(
} }
// Enable blink features. // Enable blink features.
std::string blink_features; if (dict_.GetString(options::kBlinkFeatures, &s))
if (web_preferences.GetString(options::kBlinkFeatures, &blink_features)) command_line->AppendSwitchASCII(::switches::kEnableBlinkFeatures, s);
command_line->AppendSwitchASCII(::switches::kEnableBlinkFeatures,
blink_features);
// Disable blink features. // Disable blink features.
std::string disable_blink_features; if (dict_.GetString(options::kDisableBlinkFeatures, &s))
if (web_preferences.GetString(options::kDisableBlinkFeatures, command_line->AppendSwitchASCII(::switches::kDisableBlinkFeatures, s);
&disable_blink_features))
command_line->AppendSwitchASCII(::switches::kDisableBlinkFeatures,
disable_blink_features);
if (guest_instance_id) { if (guest_instance_id) {
// Webview `document.visibilityState` tracks window visibility so we need // Webview `document.visibilityState` tracks window visibility so we need
// to let it know if the window happens to be hidden right now. // to let it know if the window happens to be hidden right now.
auto manager = WebViewManager::GetWebViewManager(web_contents); auto* manager = WebViewManager::GetWebViewManager(web_contents_);
if (manager) { if (manager) {
auto embedder = manager->GetEmbedder(guest_instance_id); auto* embedder = manager->GetEmbedder(guest_instance_id);
if (embedder) { if (embedder) {
auto* relay = NativeWindowRelay::FromWebContents(web_contents); auto* relay = NativeWindowRelay::FromWebContents(embedder);
if (relay) { if (relay) {
auto* window = relay->window.get(); auto* window = relay->window.get();
if (window) { if (window) {
@ -261,51 +252,34 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches(
} }
} }
} }
// We are appending args to a webContents so let's save the current state
// of our preferences object so that during the lifetime of the WebContents
// we can fetch the options used to initally configure the WebContents
last_dict_ = std::move(*dict_.CreateDeepCopy());
} }
bool WebContentsPreferences::IsPreferenceEnabled(
const std::string& attribute_name,
content::WebContents* web_contents) {
WebContentsPreferences* self;
if (!web_contents)
return false;
self = FromWebContents(web_contents);
if (!self)
return false;
base::DictionaryValue& web_preferences = self->web_preferences_;
bool bool_value = false;
web_preferences.GetBoolean(attribute_name, &bool_value);
return bool_value;
}
// static
void WebContentsPreferences::OverrideWebkitPrefs( void WebContentsPreferences::OverrideWebkitPrefs(
content::WebContents* web_contents, content::WebPreferences* prefs) { content::WebPreferences* prefs) {
WebContentsPreferences* self = FromWebContents(web_contents);
if (!self)
return;
bool b; bool b;
if (self->web_preferences_.GetBoolean("javascript", &b)) if (dict_.GetBoolean("javascript", &b))
prefs->javascript_enabled = b; prefs->javascript_enabled = b;
if (self->web_preferences_.GetBoolean("images", &b)) if (dict_.GetBoolean("images", &b))
prefs->images_enabled = b; prefs->images_enabled = b;
if (self->web_preferences_.GetBoolean("textAreasAreResizable", &b)) if (dict_.GetBoolean("textAreasAreResizable", &b))
prefs->text_areas_are_resizable = b; prefs->text_areas_are_resizable = b;
if (self->web_preferences_.GetBoolean("webgl", &b)) { if (dict_.GetBoolean("webgl", &b)) {
prefs->webgl1_enabled = b; prefs->webgl1_enabled = b;
prefs->webgl2_enabled = b; prefs->webgl2_enabled = b;
} }
if (self->web_preferences_.GetBoolean("webSecurity", &b)) { if (dict_.GetBoolean("webSecurity", &b)) {
prefs->web_security_enabled = b; prefs->web_security_enabled = b;
prefs->allow_running_insecure_content = !b; prefs->allow_running_insecure_content = !b;
} }
if (self->web_preferences_.GetBoolean("allowRunningInsecureContent", &b)) if (dict_.GetBoolean("allowRunningInsecureContent", &b))
prefs->allow_running_insecure_content = b; prefs->allow_running_insecure_content = b;
const base::DictionaryValue* fonts = nullptr; const base::DictionaryValue* fonts = nullptr;
if (self->web_preferences_.GetDictionary("defaultFontFamily", &fonts)) { if (dict_.GetDictionary("defaultFontFamily", &fonts)) {
base::string16 font; base::string16 font;
if (fonts->GetString("standard", &font)) if (fonts->GetString("standard", &font))
prefs->standard_font_family_map[content::kCommonScript] = font; prefs->standard_font_family_map[content::kCommonScript] = font;
@ -321,37 +295,28 @@ void WebContentsPreferences::OverrideWebkitPrefs(
prefs->fantasy_font_family_map[content::kCommonScript] = font; prefs->fantasy_font_family_map[content::kCommonScript] = font;
} }
int size; int size;
if (self->GetInteger("defaultFontSize", &size)) if (GetInteger("defaultFontSize", &size))
prefs->default_font_size = size; prefs->default_font_size = size;
if (self->GetInteger("defaultMonospaceFontSize", &size)) if (GetInteger("defaultMonospaceFontSize", &size))
prefs->default_fixed_font_size = size; prefs->default_fixed_font_size = size;
if (self->GetInteger("minimumFontSize", &size)) if (GetInteger("minimumFontSize", &size))
prefs->minimum_font_size = size; prefs->minimum_font_size = size;
std::string encoding; std::string encoding;
if (self->web_preferences_.GetString("defaultEncoding", &encoding)) if (dict_.GetString("defaultEncoding", &encoding))
prefs->default_encoding = encoding; prefs->default_encoding = encoding;
} }
bool WebContentsPreferences::GetInteger(const std::string& attributeName, bool WebContentsPreferences::GetInteger(const base::StringPiece& attribute_name,
int* intValue) { int* val) {
// if it is already an integer, no conversion needed // if it is already an integer, no conversion needed
if (web_preferences_.GetInteger(attributeName, intValue)) if (dict_.GetInteger(attribute_name, val))
return true; return true;
base::string16 stringValue; std::string str;
if (web_preferences_.GetString(attributeName, &stringValue)) if (dict_.GetString(attribute_name, &str))
return base::StringToInt(stringValue, intValue); return base::StringToInt(str, val);
return false; return false;
} }
bool WebContentsPreferences::GetString(const std::string& attribute_name,
std::string* string_value,
content::WebContents* web_contents) {
WebContentsPreferences* self = FromWebContents(web_contents);
if (!self)
return false;
return self->web_preferences()->GetString(attribute_name, string_value);
}
} // namespace atom } // namespace atom

View file

@ -29,52 +29,49 @@ namespace atom {
class WebContentsPreferences class WebContentsPreferences
: public content::WebContentsUserData<WebContentsPreferences> { : public content::WebContentsUserData<WebContentsPreferences> {
public: public:
// Get WebContents according to process ID. // Get self from WebContents.
// FIXME(zcbenz): This method does not belong here. static WebContentsPreferences* From(content::WebContents* web_contents);
static content::WebContents* GetWebContentsFromProcessID(int process_id);
// Append command paramters according to |web_contents|'s preferences.
static void AppendExtraCommandLineSwitches(
content::WebContents* web_contents, base::CommandLine* command_line);
static bool IsPreferenceEnabled(const std::string& attribute_name,
content::WebContents* web_contents);
static bool GetString(const std::string& attribute_name,
std::string* string_value,
content::WebContents* web_contents);
// Modify the WebPreferences according to |web_contents|'s preferences.
static void OverrideWebkitPrefs(
content::WebContents* web_contents, content::WebPreferences* prefs);
WebContentsPreferences(content::WebContents* web_contents, WebContentsPreferences(content::WebContents* web_contents,
const mate::Dictionary& web_preferences); const mate::Dictionary& web_preferences);
~WebContentsPreferences() override; ~WebContentsPreferences() override;
// $.extend(|web_preferences_|, |new_web_preferences|). // A simple way to know whether a Boolean property is enabled.
bool IsEnabled(const base::StringPiece& name, bool default_value = false);
// $.extend(|web_preferences|, |new_web_preferences|).
void Merge(const base::DictionaryValue& new_web_preferences); void Merge(const base::DictionaryValue& new_web_preferences);
// Append command paramters according to preferences.
void AppendCommandLineSwitches(base::CommandLine* command_line);
// Modify the WebPreferences according to preferences.
void OverrideWebkitPrefs(content::WebPreferences* prefs);
// Returns the web preferences. // Returns the web preferences.
base::DictionaryValue* web_preferences() { return &web_preferences_; } base::DictionaryValue* dict() { return &dict_; }
base::DictionaryValue* last_web_preferences() { const base::DictionaryValue* dict() const { return &dict_; }
return &last_web_preferences_; base::DictionaryValue* last_dict() { return &last_dict_; }
}
private: private:
friend class content::WebContentsUserData<WebContentsPreferences>; friend class content::WebContentsUserData<WebContentsPreferences>;
friend class AtomBrowserClient;
// Get WebContents according to process ID.
static content::WebContents* GetWebContentsFromProcessID(int process_id);
// Set preference value to given bool if user did not provide value // Set preference value to given bool if user did not provide value
bool SetDefaultBoolIfUndefined(const std::string key, bool val); bool SetDefaultBoolIfUndefined(const base::StringPiece& key, bool val);
// Get preferences value as integer possibly coercing it from a string // Get preferences value as integer possibly coercing it from a string
bool GetInteger(const std::string& attributeName, int* intValue); bool GetInteger(const base::StringPiece& attribute_name, int* val);
static std::vector<WebContentsPreferences*> instances_; static std::vector<WebContentsPreferences*> instances_;
content::WebContents* web_contents_; content::WebContents* web_contents_;
base::DictionaryValue web_preferences_;
base::DictionaryValue last_web_preferences_; base::DictionaryValue dict_;
base::DictionaryValue last_dict_;
DISALLOW_COPY_AND_ASSIGN(WebContentsPreferences); DISALLOW_COPY_AND_ASSIGN(WebContentsPreferences);
}; };