Merge pull request #11396 from electron/enable_base_dchecks

fix: enable additional dchecks
This commit is contained in:
Cheng Zhao 2018-01-04 21:19:12 +09:00 committed by GitHub
commit 6bc7c8cc49
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
54 changed files with 426 additions and 222 deletions

View file

@ -45,6 +45,7 @@ int NodeMain(int argc, char *argv[]) {
// V8 requires a task scheduler apparently
base::TaskScheduler::CreateAndStartWithDefaultParams("Electron");
// Initialize gin::IsolateHolder.
JavascriptEnvironment gin_env;
int exec_argc;

View file

@ -532,7 +532,6 @@ App::App(v8::Isolate* isolate) {
static_cast<AtomBrowserClient*>(AtomBrowserClient::Get())->set_delegate(this);
Browser::Get()->AddObserver(this);
content::GpuDataManager::GetInstance()->AddObserver(this);
content::BrowserChildProcessObserver::Add(this);
base::ProcessId pid = base::GetCurrentProcId();
std::unique_ptr<atom::ProcessMetric> process_metric(
new atom::ProcessMetric(
@ -599,6 +598,7 @@ void App::OnFinishLaunching(const base::DictionaryValue& launch_info) {
}
void App::OnPreMainMessageLoopRun() {
content::BrowserChildProcessObserver::Add(this);
if (process_singleton_) {
process_singleton_->OnBrowserReady();
}
@ -851,7 +851,7 @@ void App::SetDesktopName(const std::string& desktop_name) {
}
std::string App::GetLocale() {
return l10n_util::GetApplicationLocale("");
return g_browser_process->GetApplicationLocale();
}
bool App::MakeSingleInstance(
@ -867,9 +867,10 @@ bool App::MakeSingleInstance(
switch (process_singleton_->NotifyOtherProcessOrCreate()) {
case ProcessSingleton::NotifyResult::LOCK_ERROR:
case ProcessSingleton::NotifyResult::PROFILE_IN_USE:
case ProcessSingleton::NotifyResult::PROCESS_NOTIFIED:
case ProcessSingleton::NotifyResult::PROCESS_NOTIFIED: {
process_singleton_.reset();
return true;
}
case ProcessSingleton::NotifyResult::PROCESS_NONE:
default: // Shouldn't be needed, but VS warns if it is not there.
return false;

View file

@ -9,6 +9,7 @@
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/memory/ptr_util.h"
#include "content/public/browser/devtools_agent_host.h"
@ -48,20 +49,11 @@ void Debugger::DispatchProtocolMessage(DevToolsAgentHost* agent_host,
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
v8::Local<v8::String> local_message =
v8::String::NewFromUtf8(isolate(), message.data());
v8::MaybeLocal<v8::Value> parsed_message = v8::JSON::Parse(
isolate()->GetCurrentContext(), local_message);
if (parsed_message.IsEmpty()) {
std::unique_ptr<base::Value> parsed_message = base::JSONReader::Read(message);
if (!parsed_message || !parsed_message->is_dict())
return;
}
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
if (!mate::ConvertFromV8(isolate(), parsed_message.ToLocalChecked(),
dict.get())) {
return;
}
base::DictionaryValue* dict =
static_cast<base::DictionaryValue*>(parsed_message.get());
int id;
if (!dict->GetInteger("id", &id)) {
std::string method;

View file

@ -33,6 +33,7 @@
#include "brightray/browser/media/media_device_id_salt.h"
#include "brightray/browser/net/devtools_network_conditions.h"
#include "brightray/browser/net/devtools_network_controller_handle.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_thread.h"
@ -439,6 +440,17 @@ void DownloadIdCallback(content::DownloadManager* download_manager,
std::vector<content::DownloadItem::ReceivedSlice>());
}
void SetDevToolsNetworkEmulationClientIdInIO(
brightray::URLRequestContextGetter* context_getter,
const std::string& client_id) {
if (!context_getter)
return;
auto network_delegate =
static_cast<AtomNetworkDelegate*>(context_getter->network_delegate());
if (network_delegate)
network_delegate->SetDevToolsNetworkEmulationClientId(client_id);
}
} // namespace
Session::Session(v8::Isolate* isolate, AtomBrowserContext* browser_context)
@ -548,16 +560,24 @@ void Session::EnableNetworkEmulation(const mate::Dictionary& options) {
browser_context_->network_controller_handle()->SetNetworkState(
devtools_network_emulation_client_id_, std::move(conditions));
browser_context_->network_delegate()->SetDevToolsNetworkEmulationClientId(
devtools_network_emulation_client_id_);
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(
&SetDevToolsNetworkEmulationClientIdInIO,
base::RetainedRef(browser_context_->url_request_context_getter()),
devtools_network_emulation_client_id_));
}
void Session::DisableNetworkEmulation() {
std::unique_ptr<brightray::DevToolsNetworkConditions> conditions;
browser_context_->network_controller_handle()->SetNetworkState(
devtools_network_emulation_client_id_, std::move(conditions));
browser_context_->network_delegate()->SetDevToolsNetworkEmulationClientId(
std::string());
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(
&SetDevToolsNetworkEmulationClientIdInIO,
base::RetainedRef(browser_context_->url_request_context_getter()),
std::string()));
}
void Session::SetCertVerifyProc(v8::Local<v8::Value> val,
@ -623,7 +643,7 @@ void Session::SetUserAgent(const std::string& user_agent,
mate::Arguments* args) {
browser_context_->SetUserAgent(user_agent);
std::string accept_lang = l10n_util::GetApplicationLocale("");
std::string accept_lang = g_browser_process->GetApplicationLocale();
args->GetNext(&accept_lang);
scoped_refptr<brightray::URLRequestContextGetter> getter(

View file

@ -1341,6 +1341,7 @@ void WebContents::Print(mate::Arguments* args) {
std::vector<printing::PrinterBasicInfo> WebContents::GetPrinterList() {
std::vector<printing::PrinterBasicInfo> printers;
auto print_backend = printing::PrintBackend::CreateInstance(nullptr);
base::ThreadRestrictions::ScopedAllowIO allow_io;
print_backend->EnumeratePrinters(&printers);
return printers;
}

View file

@ -74,10 +74,16 @@ void WebRequest::SetListener(Method method, Event type, mate::Arguments* args) {
return;
}
auto delegate = browser_context_->network_delegate();
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(method, base::Unretained(delegate), type,
patterns, listener));
auto url_request_context_getter =
browser_context_->url_request_context_getter();
if (!url_request_context_getter)
return;
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(method,
base::Unretained(static_cast<AtomNetworkDelegate*>(
url_request_context_getter->network_delegate())),
type, patterns, listener));
}
// static

View file

@ -54,7 +54,6 @@ class GeoURLRequestContextGetter : public net::URLRequestContextGetter {
AtomAccessTokenStore::AtomAccessTokenStore()
: request_context_getter_(new internal::GeoURLRequestContextGetter) {
device::GeolocationProvider::GetInstance()->UserDidOptIntoLocationServices();
}
AtomAccessTokenStore::~AtomAccessTokenStore() {

View file

@ -202,10 +202,6 @@ void AtomBrowserClient::OverrideWebkitPrefs(
WebContentsPreferences::OverrideWebkitPrefs(web_contents, prefs);
}
std::string AtomBrowserClient::GetApplicationLocale() {
return l10n_util::GetApplicationLocale("");
}
void AtomBrowserClient::OverrideSiteInstanceForNavigation(
content::RenderFrameHost* render_frame_host,
content::BrowserContext* browser_context,
@ -235,9 +231,7 @@ void AtomBrowserClient::OverrideSiteInstanceForNavigation(
// Remember the original web contents for the pending renderer process.
auto pending_process = (*new_instance)->GetProcess();
pending_processes_[pending_process->GetID()] =
content::WebContents::FromRenderFrameHost(render_frame_host);;
// Clear the entry in map when process ends.
pending_process->AddObserver(this);
content::WebContents::FromRenderFrameHost(render_frame_host);
}
void AtomBrowserClient::AppendExtraCommandLineSwitches(

View file

@ -53,7 +53,6 @@ class AtomBrowserClient : public brightray::BrowserClient,
CreateSpeechRecognitionManagerDelegate() override;
void OverrideWebkitPrefs(content::RenderViewHost* render_view_host,
content::WebPreferences* prefs) override;
std::string GetApplicationLocale() override;
void OverrideSiteInstanceForNavigation(
content::RenderFrameHost* render_frame_host,
content::BrowserContext* browser_context,

View file

@ -71,7 +71,6 @@ AtomBrowserContext::AtomBrowserContext(const std::string& partition,
bool in_memory,
const base::DictionaryValue& options)
: brightray::BrowserContext(partition, in_memory),
network_delegate_(new AtomNetworkDelegate),
cookie_delegate_(new AtomCookieDelegate) {
// Construct user agent string.
Browser* browser = Browser::Get();
@ -104,8 +103,9 @@ void AtomBrowserContext::SetUserAgent(const std::string& user_agent) {
user_agent_ = user_agent;
}
net::NetworkDelegate* AtomBrowserContext::CreateNetworkDelegate() {
return network_delegate_;
std::unique_ptr<net::NetworkDelegate>
AtomBrowserContext::CreateNetworkDelegate() {
return base::MakeUnique<AtomNetworkDelegate>();
}
net::CookieMonsterDelegate* AtomBrowserContext::CreateCookieDelegate() {

View file

@ -32,7 +32,7 @@ class AtomBrowserContext : public brightray::BrowserContext {
void SetUserAgent(const std::string& user_agent);
// brightray::URLRequestContextGetter::Delegate:
net::NetworkDelegate* CreateNetworkDelegate() override;
std::unique_ptr<net::NetworkDelegate> CreateNetworkDelegate() override;
net::CookieMonsterDelegate* CreateCookieDelegate() override;
std::string GetUserAgent() override;
std::unique_ptr<net::URLRequestJobFactory> CreateURLRequestJobFactory(
@ -52,7 +52,6 @@ class AtomBrowserContext : public brightray::BrowserContext {
void RegisterPrefs(PrefRegistrySimple* pref_registry) override;
AtomBlobReader* GetBlobReader();
AtomNetworkDelegate* network_delegate() const { return network_delegate_; }
AtomCookieDelegate* cookie_delegate() const {
return cookie_delegate_.get();
}
@ -70,8 +69,6 @@ class AtomBrowserContext : public brightray::BrowserContext {
std::string user_agent_;
bool use_cache_;
// Managed by brightray::BrowserContext.
AtomNetworkDelegate* network_delegate_;
scoped_refptr<AtomCookieDelegate> cookie_delegate_;
DISALLOW_COPY_AND_ASSIGN(AtomBrowserContext);

View file

@ -24,6 +24,7 @@
#include "content/public/browser/child_process_security_policy.h"
#include "device/geolocation/geolocation_delegate.h"
#include "device/geolocation/geolocation_provider.h"
#include "ui/base/l10n/l10n_util.h"
#include "v8/include/v8-debug.h"
#if defined(USE_X11)
@ -38,7 +39,10 @@ namespace {
// A provider of Geolocation services to override AccessTokenStore.
class AtomGeolocationDelegate : public device::GeolocationDelegate {
public:
AtomGeolocationDelegate() = default;
AtomGeolocationDelegate() {
device::GeolocationProvider::GetInstance()
->UserDidOptIntoLocationServices();
}
scoped_refptr<device::AccessTokenStore> CreateAccessTokenStore() final {
return new AtomAccessTokenStore();
@ -149,6 +153,12 @@ void AtomBrowserMainParts::PostEarlyInitialization() {
node_bindings_->set_uv_env(env);
}
int AtomBrowserMainParts::PreCreateThreads() {
fake_browser_process_->SetApplicationLocale(
l10n_util::GetApplicationLocale(""));
return brightray::BrowserMainParts::PreCreateThreads();
}
void AtomBrowserMainParts::PreMainMessageLoopRun() {
js_env_->OnMessageLoopCreated();
@ -185,6 +195,7 @@ void AtomBrowserMainParts::PreMainMessageLoopRun() {
Browser::Get()->DidFinishLaunching(*empty_info);
#endif
// Notify observers that main thread message loop was initialized.
Browser::Get()->PreMainMessageLoopRun();
}

View file

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

View file

@ -21,6 +21,32 @@
namespace atom {
namespace {
// Generate default file path to save the download.
void CreateDownloadPath(
const GURL& url,
const std::string& content_disposition,
const std::string& suggested_filename,
const std::string& mime_type,
const base::FilePath& default_download_path,
const AtomDownloadManagerDelegate::CreateDownloadPathCallback& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
auto generated_name =
net::GenerateFileName(url, content_disposition, std::string(),
suggested_filename, mime_type, "download");
if (!base::PathExists(default_download_path))
base::CreateDirectory(default_download_path);
base::FilePath path(default_download_path.Append(generated_name));
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(callback, path));
}
} // namespace
AtomDownloadManagerDelegate::AtomDownloadManagerDelegate(
content::DownloadManager* manager)
: download_manager_(manager),
@ -46,30 +72,6 @@ void AtomDownloadManagerDelegate::GetItemSavePath(content::DownloadItem* item,
*path = download->GetSavePath();
}
void AtomDownloadManagerDelegate::CreateDownloadPath(
const GURL& url,
const std::string& content_disposition,
const std::string& suggested_filename,
const std::string& mime_type,
const base::FilePath& default_download_path,
const CreateDownloadPathCallback& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
auto generated_name = net::GenerateFileName(url,
content_disposition,
std::string(),
suggested_filename,
mime_type,
"download");
if (!base::PathExists(default_download_path))
base::CreateDirectory(default_download_path);
base::FilePath path(default_download_path.Append(generated_name));
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(callback, path));
}
void AtomDownloadManagerDelegate::OnDownloadPathGenerated(
uint32_t download_id,
const content::DownloadTargetCallback& callback,
@ -164,14 +166,10 @@ bool AtomDownloadManagerDelegate::DetermineDownloadTarget(
content::BrowserThread::PostTask(
content::BrowserThread::FILE, FROM_HERE,
base::Bind(&AtomDownloadManagerDelegate::CreateDownloadPath,
weak_ptr_factory_.GetWeakPtr(),
download->GetURL(),
base::Bind(&CreateDownloadPath, download->GetURL(),
download->GetContentDisposition(),
download->GetSuggestedFilename(),
download->GetMimeType(),
default_download_path,
download_path_callback));
download->GetSuggestedFilename(), download->GetMimeType(),
default_download_path, download_path_callback));
return true;
}

View file

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

View file

@ -14,6 +14,7 @@
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "brightray/browser/brightray_paths.h"
@ -151,6 +152,7 @@ void Browser::WillFinishLaunching() {
void Browser::DidFinishLaunching(const base::DictionaryValue& launch_info) {
// Make sure the userData directory is created.
base::ThreadRestrictions::ScopedAllowIO allow_io;
base::FilePath user_data;
if (PathService::Get(brightray::DIR_USER_DATA, &user_data))
base::CreateDirectoryAndGetError(user_data, nullptr);

View file

@ -20,6 +20,7 @@
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "base/win/registry.h"
#include "base/win/win_util.h"
#include "base/win/windows_version.h"
@ -334,6 +335,7 @@ PCWSTR Browser::GetAppUserModelID() {
std::string Browser::GetExecutableFileVersion() const {
base::FilePath path;
if (PathService::Get(base::FILE_EXE, &path)) {
base::ThreadRestrictions::ScopedAllowIO allow_io;
std::unique_ptr<FileVersionInfo> version_info(
FileVersionInfo::CreateFileVersionInfo(path));
return base::UTF16ToUTF8(version_info->product_version());

View file

@ -101,24 +101,20 @@ void URLRequestAsarJob::InitializeFileJob(
}
void URLRequestAsarJob::Start() {
if (type_ == TYPE_ASAR) {
int flags = base::File::FLAG_OPEN |
base::File::FLAG_READ |
base::File::FLAG_ASYNC;
int rv = stream_->Open(archive_->path(), flags,
base::Bind(&URLRequestAsarJob::DidOpen,
weak_ptr_factory_.GetWeakPtr()));
if (rv != net::ERR_IO_PENDING)
DidOpen(rv);
} else if (type_ == TYPE_FILE) {
if (type_ == TYPE_ASAR || type_ == TYPE_FILE) {
auto* meta_info = new FileMetaInfo();
if (type_ == TYPE_ASAR) {
meta_info->file_path = archive_->path();
meta_info->file_exists = true;
meta_info->is_directory = false;
meta_info->file_size = file_info_.size;
}
file_task_runner_->PostTaskAndReply(
FROM_HERE,
base::Bind(&URLRequestAsarJob::FetchMetaInfo, file_path_,
base::Bind(&URLRequestAsarJob::FetchMetaInfo, file_path_, type_,
base::Unretained(meta_info)),
base::Bind(&URLRequestAsarJob::DidFetchMetaInfo,
weak_ptr_factory_.GetWeakPtr(),
base::Owned(meta_info)));
weak_ptr_factory_.GetWeakPtr(), base::Owned(meta_info)));
} else {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
@ -194,15 +190,11 @@ std::unique_ptr<net::SourceStream> URLRequestAsarJob::SetUpSourceStream() {
}
bool URLRequestAsarJob::GetMimeType(std::string* mime_type) const {
if (type_ == TYPE_ASAR) {
return net::GetMimeTypeFromFile(file_path_, mime_type);
} else {
if (meta_info_.mime_type_result) {
*mime_type = meta_info_.mime_type;
return true;
}
return false;
if (meta_info_.mime_type_result) {
*mime_type = meta_info_.mime_type;
return true;
}
return false;
}
void URLRequestAsarJob::SetExtraRequestHeaders(
@ -238,12 +230,16 @@ void URLRequestAsarJob::GetResponseInfo(net::HttpResponseInfo* info) {
}
void URLRequestAsarJob::FetchMetaInfo(const base::FilePath& file_path,
JobType type,
FileMetaInfo* meta_info) {
base::File::Info file_info;
meta_info->file_exists = base::GetFileInfo(file_path, &file_info);
if (meta_info->file_exists) {
meta_info->file_size = file_info.size;
meta_info->is_directory = file_info.is_directory;
if (type == TYPE_FILE) {
base::File::Info file_info;
meta_info->file_exists = base::GetFileInfo(file_path, &file_info);
if (meta_info->file_exists) {
meta_info->file_path = file_path;
meta_info->file_size = file_info.size;
meta_info->is_directory = file_info.is_directory;
}
}
// On Windows GetMimeTypeFromFile() goes to the registry. Thus it should be
// done in WorkerPool.
@ -261,9 +257,9 @@ void URLRequestAsarJob::DidFetchMetaInfo(const FileMetaInfo* meta_info) {
int flags = base::File::FLAG_OPEN |
base::File::FLAG_READ |
base::File::FLAG_ASYNC;
int rv = stream_->Open(file_path_, flags,
base::Bind(&URLRequestAsarJob::DidOpen,
weak_ptr_factory_.GetWeakPtr()));
int rv = stream_->Open(
meta_info_.file_path, flags,
base::Bind(&URLRequestAsarJob::DidOpen, weak_ptr_factory_.GetWeakPtr()));
if (rv != net::ERR_IO_PENDING)
DidOpen(rv);
}

View file

@ -63,6 +63,13 @@ class URLRequestAsarJob : public net::URLRequestJob {
void GetResponseInfo(net::HttpResponseInfo* info) override;
private:
// The type of this job.
enum JobType {
TYPE_ERROR,
TYPE_ASAR,
TYPE_FILE,
};
// Meta information about the file. It's used as a member in the
// URLRequestFileJob and also passed between threads because disk access is
// necessary to obtain it.
@ -80,10 +87,13 @@ class URLRequestAsarJob : public net::URLRequestJob {
bool file_exists;
// Flag showing whether the file name actually refers to a directory.
bool is_directory;
// Path to the file.
base::FilePath file_path;
};
// Fetches file info on a background thread.
static void FetchMetaInfo(const base::FilePath& file_path,
JobType type,
FileMetaInfo* meta_info);
// Callback after fetching file info on a background thread.
@ -99,12 +109,6 @@ class URLRequestAsarJob : public net::URLRequestJob {
// Callback after data is asynchronously read from the file into |buf|.
void DidRead(scoped_refptr<net::IOBuffer> buf, int result);
// The type of this job.
enum JobType {
TYPE_ERROR,
TYPE_ASAR,
TYPE_FILE,
};
JobType type_;
std::shared_ptr<Archive> archive_;

View file

@ -94,25 +94,27 @@ class CertVerifierRequest : public AtomCertVerifier::Request {
request->default_result = net::ErrorToString(error);
request->error_code = error;
request->certificate = params_.certificate();
auto response_callback = base::Bind(&CertVerifierRequest::OnResponseInUI,
weak_ptr_factory_.GetWeakPtr());
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&CertVerifierRequest::OnVerifyRequestInUI,
weak_ptr_factory_.GetWeakPtr(),
cert_verifier_->verify_proc(),
base::Passed(&request)));
cert_verifier_->verify_proc(), base::Passed(&request),
response_callback));
}
void OnVerifyRequestInUI(const AtomCertVerifier::VerifyProc& verify_proc,
std::unique_ptr<VerifyRequestParams> request) {
verify_proc.Run(*(request.get()),
base::Bind(&CertVerifierRequest::OnResponseInUI,
weak_ptr_factory_.GetWeakPtr()));
static void OnVerifyRequestInUI(
const AtomCertVerifier::VerifyProc& verify_proc,
std::unique_ptr<VerifyRequestParams> request,
const base::Callback<void(int)>& response_callback) {
verify_proc.Run(*(request.get()), response_callback);
}
void OnResponseInUI(int result) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(&CertVerifierRequest::NotifyResponseInIO,
weak_ptr_factory_.GetWeakPtr(), result));
static void OnResponseInUI(base::WeakPtr<CertVerifierRequest> self,
int result) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&CertVerifierRequest::NotifyResponseInIO, self, result));
}
void NotifyResponseInIO(int result) {

View file

@ -41,20 +41,38 @@ const char* ResourceTypeToString(content::ResourceType type) {
}
}
int32_t GetWebContentsID(int process_id, int frame_id) {
auto* webContents = content::WebContents::FromRenderFrameHost(
content::RenderFrameHost::FromID(process_id, frame_id));
return atom::api::WebContents::GetIDFromWrappedClass(webContents);
}
namespace {
using ResponseHeadersContainer =
std::pair<scoped_refptr<net::HttpResponseHeaders>*, const std::string&>;
void RunSimpleListener(const AtomNetworkDelegate::SimpleListener& listener,
std::unique_ptr<base::DictionaryValue> details) {
std::unique_ptr<base::DictionaryValue> details,
int render_process_id,
int render_frame_id) {
int32_t id = GetWebContentsID(render_process_id, render_frame_id);
// id must be greater than zero
if (id)
details->SetInteger("webContentsId", id);
return listener.Run(*(details.get()));
}
void RunResponseListener(
const AtomNetworkDelegate::ResponseListener& listener,
std::unique_ptr<base::DictionaryValue> details,
int render_process_id,
int render_frame_id,
const AtomNetworkDelegate::ResponseCallback& callback) {
int32_t id = GetWebContentsID(render_process_id, render_frame_id);
// id must be greater than zero
if (id)
details->SetInteger("webContentsId", id);
return listener.Run(*(details.get()), callback);
}
@ -78,16 +96,6 @@ void ToDictionary(base::DictionaryValue* details, net::URLRequest* request) {
details->SetDouble("timestamp", base::Time::Now().ToDoubleT() * 1000);
const auto* info = content::ResourceRequestInfo::ForRequest(request);
if (info) {
int process_id = info->GetChildID();
int frame_id = info->GetRenderFrameID();
auto* webContents = content::WebContents::FromRenderFrameHost(
content::RenderFrameHost::FromID(process_id, frame_id));
int webContentsId = atom::api::WebContents::GetIDFromWrappedClass(
webContents);
// webContentsId must be greater than zero
if (webContentsId)
details->SetInteger("webContentsId", webContentsId);
details->SetString("resourceType",
ResourceTypeToString(info->GetResourceType()));
} else {
@ -239,7 +247,6 @@ void AtomNetworkDelegate::SetResponseListenerInIO(
void AtomNetworkDelegate::SetDevToolsNetworkEmulationClientId(
const std::string& client_id) {
base::AutoLock auto_lock(lock_);
client_id_ = client_id;
}
@ -258,16 +265,10 @@ int AtomNetworkDelegate::OnBeforeStartTransaction(
net::URLRequest* request,
const net::CompletionCallback& callback,
net::HttpRequestHeaders* headers) {
std::string client_id;
{
base::AutoLock auto_lock(lock_);
client_id = client_id_;
}
if (!client_id.empty())
if (!client_id_.empty())
headers->SetHeader(
DevToolsNetworkTransaction::kDevToolsEmulateNetworkConditionsClientId,
client_id);
client_id_);
if (!base::ContainsKey(response_listeners_, kOnBeforeSendHeaders))
return brightray::NetworkDelegate::OnBeforeStartTransaction(
request, callback, headers);
@ -382,6 +383,10 @@ int AtomNetworkDelegate::HandleResponseEvent(
std::unique_ptr<base::DictionaryValue> details(new base::DictionaryValue);
FillDetailsObject(details.get(), request, args...);
int render_process_id, render_frame_id;
content::ResourceRequestInfo::GetRenderFrameForRequest(
request, &render_process_id, &render_frame_id);
// The |request| could be destroyed before the |callback| is called.
callbacks_[request->identifier()] = callback;
@ -391,7 +396,7 @@ int AtomNetworkDelegate::HandleResponseEvent(
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(RunResponseListener, info.listener, base::Passed(&details),
response));
render_process_id, render_frame_id, response));
return net::ERR_IO_PENDING;
}
@ -405,9 +410,14 @@ void AtomNetworkDelegate::HandleSimpleEvent(
std::unique_ptr<base::DictionaryValue> details(new base::DictionaryValue);
FillDetailsObject(details.get(), request, args...);
int render_process_id, render_frame_id;
content::ResourceRequestInfo::GetRenderFrameForRequest(
request, &render_process_id, &render_frame_id);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(RunSimpleListener, info.listener, base::Passed(&details)));
base::Bind(RunSimpleListener, info.listener, base::Passed(&details),
render_process_id, render_frame_id));
}
template<typename T>

View file

@ -118,8 +118,6 @@ class AtomNetworkDelegate : public brightray::NetworkDelegate {
std::map<ResponseEvent, ResponseListenerInfo> response_listeners_;
std::map<uint64_t, net::CompletionCallback> callbacks_;
base::Lock lock_;
// Client id for devtools network emulation.
std::string client_id_;

View file

@ -87,7 +87,7 @@ StringType AddQuoteForArg(const StringType& arg) {
} // namespace
StringType GetWaitEventName(base::ProcessId pid) {
return base::StringPrintf(L"%s-%d", kWaitEventName, static_cast<int>(pid));
return base::StringPrintf(L"%ls-%d", kWaitEventName, static_cast<int>(pid));
}
StringType ArgvToCommandLineString(const StringVector& argv) {

View file

@ -8,6 +8,7 @@
#include "base/bind.h"
#include "base/memory/ptr_util.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "content/public/browser/stream_handle.h"
#include "content/public/browser/stream_info.h"
#include "content/public/browser/web_contents.h"
@ -193,7 +194,7 @@ void PdfViewerHandler::GetStrings(const base::ListValue* args) {
SET_STRING("tooltipZoomOut", "Zoom out");
#undef SET_STRING
webui::SetLoadTimeDataDefaults(l10n_util::GetApplicationLocale(""),
webui::SetLoadTimeDataDefaults(g_browser_process->GetApplicationLocale(),
result.get());
ResolveJavascriptCallback(*callback_id, *result);
}

View file

@ -78,11 +78,13 @@ class BundledDataSource : public content::URLDataSource {
}
std::string GetMimeType(const std::string& path) const override {
std::string filename = PathWithoutParams(path);
base::FilePath::StringType ext =
base::FilePath::FromUTF8Unsafe(PathWithoutParams(path)).Extension();
std::string mime_type;
net::GetMimeTypeFromFile(
base::FilePath::FromUTF8Unsafe(filename), &mime_type);
return mime_type;
if (!ext.empty() &&
net::GetWellKnownMimeTypeFromExtension(ext.substr(1), &mime_type))
return mime_type;
return "text/html";
}
bool ShouldAddContentSecurityPolicy() const override { return false; }

View file

@ -8,6 +8,7 @@
#include "base/environment.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_proxy.h"
@ -51,6 +52,7 @@ void SetWindowType(::Window xwindow, const std::string& type) {
}
bool ShouldUseGlobalMenuBar() {
base::ThreadRestrictions::ScopedAllowIO allow_io;
std::unique_ptr<base::Environment> env(base::Environment::Create());
if (env->HasVar("ELECTRON_FORCE_WINDOW_MENU_BAR"))
return false;

View file

@ -15,6 +15,7 @@
#include "base/files/file_util.h"
#include "base/strings/pattern.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "native_mate/object_template_builder.h"
#include "net/base/data_url.h"
#include "third_party/skia/include/core/SkBitmap.h"
@ -130,8 +131,11 @@ bool AddImageSkiaRep(gfx::ImageSkia* image,
const base::FilePath& path,
double scale_factor) {
std::string file_contents;
if (!asar::ReadFileToString(path, &file_contents))
return false;
{
base::ThreadRestrictions::ScopedAllowIO allow_io;
if (!asar::ReadFileToString(path, &file_contents))
return false;
}
const unsigned char* data =
reinterpret_cast<const unsigned char*>(file_contents.data());

View file

@ -14,6 +14,8 @@
#include "base/logging.h"
#include "base/pickle.h"
#include "base/strings/string_number_conversions.h"
#include "base/task_scheduler/post_task.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#if defined(OS_WIN)
@ -115,17 +117,17 @@ bool FillFileInfoWithNode(Archive::FileInfo* info,
} // namespace
Archive::Archive(const base::FilePath& path)
: path_(path),
file_(path_, base::File::FLAG_OPEN | base::File::FLAG_READ),
: path_(path), file_(base::File::FILE_OK), header_size_(0) {
base::ThreadRestrictions::ScopedAllowIO allow_io;
file_.Initialize(path_, base::File::FLAG_OPEN | base::File::FLAG_READ);
#if defined(OS_WIN)
fd_(_open_osfhandle(
reinterpret_cast<intptr_t>(file_.GetPlatformFile()), 0)),
fd_ =
_open_osfhandle(reinterpret_cast<intptr_t>(file_.GetPlatformFile()), 0);
#elif defined(OS_POSIX)
fd_(file_.GetPlatformFile()),
fd_ = file_.GetPlatformFile();
#else
fd_(-1),
fd_ = -1;
#endif
header_size_(0) {
}
Archive::~Archive() {
@ -136,6 +138,8 @@ Archive::~Archive() {
file_.TakePlatformFile();
}
#endif
base::ThreadRestrictions::ScopedAllowIO allow_io;
file_.Close();
}
bool Archive::Init() {
@ -151,7 +155,10 @@ bool Archive::Init() {
int len;
buf.resize(8);
len = file_.ReadAtCurrentPos(buf.data(), buf.size());
{
base::ThreadRestrictions::ScopedAllowIO allow_io;
len = file_.ReadAtCurrentPos(buf.data(), buf.size());
}
if (len != static_cast<int>(buf.size())) {
PLOG(ERROR) << "Failed to read header size from " << path_.value();
return false;
@ -165,7 +172,10 @@ bool Archive::Init() {
}
buf.resize(size);
len = file_.ReadAtCurrentPos(buf.data(), buf.size());
{
base::ThreadRestrictions::ScopedAllowIO allow_io;
len = file_.ReadAtCurrentPos(buf.data(), buf.size());
}
if (len != static_cast<int>(buf.size())) {
PLOG(ERROR) << "Failed to read header from " << path_.value();
return false;

View file

@ -11,6 +11,7 @@
#include "base/files/file_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/threading/thread_restrictions.h"
#include "content/public/common/content_switches.h"
namespace crash_reporter {
@ -53,6 +54,7 @@ bool CrashReporter::GetUploadToServer() {
std::vector<CrashReporter::UploadReportResult>
CrashReporter::GetUploadedReports(const base::FilePath& crashes_dir) {
base::ThreadRestrictions::ScopedAllowIO allow_io;
std::string file_content;
std::vector<CrashReporter::UploadReportResult> result;
base::FilePath uploads_path =

View file

@ -17,6 +17,7 @@
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/process/memory.h"
#include "base/threading/thread_restrictions.h"
#include "vendor/breakpad/src/client/linux/handler/exception_handler.h"
#include "vendor/breakpad/src/common/linux/linux_libc_support.h"
@ -90,8 +91,10 @@ bool CrashReporterLinux::GetUploadToServer() {
}
void CrashReporterLinux::EnableCrashDumping(const base::FilePath& crashes_dir) {
base::CreateDirectory(crashes_dir);
{
base::ThreadRestrictions::ScopedAllowIO allow_io;
base::CreateDirectory(crashes_dir);
}
std::string log_file = crashes_dir.Append("uploads.log").value();
strncpy(g_crash_log_path, log_file.c_str(), sizeof(g_crash_log_path));

View file

@ -13,6 +13,7 @@
#include "base/strings/string_piece.h"
#include "base/strings/stringprintf.h"
#include "base/strings/sys_string_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "vendor/crashpad/client/crashpad_client.h"
#include "vendor/crashpad/client/crashpad_info.h"
#include "vendor/crashpad/client/settings.h"
@ -139,8 +140,11 @@ std::vector<CrashReporter::UploadReportResult>
CrashReporterMac::GetUploadedReports(const base::FilePath& crashes_dir) {
std::vector<CrashReporter::UploadReportResult> uploaded_reports;
if (!base::PathExists(crashes_dir)) {
return uploaded_reports;
{
base::ThreadRestrictions::ScopedAllowIO allow_io;
if (!base::PathExists(crashes_dir)) {
return uploaded_reports;
}
}
// Load crashpad database.
std::unique_ptr<crashpad::CrashReportDatabase> database =

View file

@ -320,8 +320,12 @@ base::Value* V8ValueConverter::FromV8ValueImpl(
if (val->IsInt32())
return new base::Value(val->ToInt32()->Value());
if (val->IsNumber())
return new base::Value(val->ToNumber()->Value());
if (val->IsNumber()) {
double val_as_double = val->ToNumber()->Value();
if (!std::isfinite(val_as_double))
return nullptr;
return new base::Value(val_as_double);
}
if (val->IsString()) {
v8::String::Utf8Value utf8(val->ToString());

View file

@ -215,6 +215,10 @@ void WebFrame::RegisterURLSchemeAsBypassingCSP(const std::string& scheme) {
void WebFrame::RegisterURLSchemeAsPrivileged(const std::string& scheme,
mate::Arguments* args) {
// TODO(deepak1556): blink::SchemeRegistry methods should be called
// before any renderer threads are created. Fixing this would break
// current api. Change it with 2.0.
// Read optional flags
bool secure = true;
bool bypassCSP = true;

View file

@ -113,6 +113,11 @@ void RendererClientBase::RenderThreadStarted() {
blink::SchemeRegistry::RegisterURLSchemeAsSecure(
WTF::String::FromUTF8(scheme.data(), scheme.length()));
// Allow file scheme to handle service worker by default.
// FIXME(zcbenz): Can this be moved elsewhere?
blink::WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers("file");
blink::SchemeRegistry::RegisterURLSchemeAsSupportingFetchAPI("file");
preferences_manager_.reset(new PreferencesManager);
#if defined(OS_WIN)
@ -145,10 +150,6 @@ void RendererClientBase::RenderFrameCreated(
new ContentSettingsObserver(render_frame);
new printing::PrintWebViewHelper(render_frame);
// Allow file scheme to handle service worker by default.
// FIXME(zcbenz): Can this be moved elsewhere?
blink::WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers("file");
// This is required for widevine plugin detection provided during runtime.
blink::ResetPluginCache();

View file

@ -4,6 +4,7 @@
#include "brightray/browser/browser_client.h"
#include "base/lazy_instance.h"
#include "base/path_service.h"
#include "brightray/browser/browser_context.h"
#include "brightray/browser/browser_main_parts.h"
@ -11,16 +12,41 @@
#include "brightray/browser/media/media_capture_devices_dispatcher.h"
#include "brightray/browser/notification_presenter.h"
#include "brightray/browser/platform_notification_service.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/url_constants.h"
using content::BrowserThread;
namespace brightray {
namespace {
BrowserClient* g_browser_client;
base::LazyInstance<std::string>::DestructorAtExit
g_io_thread_application_locale = LAZY_INSTANCE_INITIALIZER;
std::string g_application_locale;
void SetApplicationLocaleOnIOThread(const std::string& locale) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
g_io_thread_application_locale.Get() = locale;
}
} // namespace
// static
void BrowserClient::SetApplicationLocale(const std::string& locale) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&SetApplicationLocaleOnIOThread, locale))) {
g_io_thread_application_locale.Get() = locale;
}
g_application_locale = locale;
}
BrowserClient* BrowserClient::Get() {
return g_browser_client;
}
@ -88,4 +114,10 @@ content::DevToolsManagerDelegate* BrowserClient::GetDevToolsManagerDelegate() {
return new DevToolsManagerDelegate;
}
std::string BrowserClient::GetApplicationLocale() {
if (BrowserThread::CurrentlyOn(BrowserThread::IO))
return g_io_thread_application_locale.Get();
return g_application_locale;
}
} // namespace brightray

View file

@ -20,6 +20,7 @@ class PlatformNotificationService;
class BrowserClient : public content::ContentBrowserClient {
public:
static BrowserClient* Get();
static void SetApplicationLocale(const std::string& locale);
BrowserClient();
~BrowserClient();
@ -47,6 +48,7 @@ class BrowserClient : public content::ContentBrowserClient {
net::NetLog* GetNetLog() override;
base::FilePath GetDefaultDownloadDirectory() override;
content::DevToolsManagerDelegate* GetDevToolsManagerDelegate() override;
std::string GetApplicationLocale() override;
protected:
// Subclasses should override this to provide their own BrowserMainParts

View file

@ -7,6 +7,7 @@
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "brightray/browser/brightray_paths.h"
#include "brightray/browser/browser_client.h"
#include "brightray/browser/inspectable_web_contents_impl.h"
@ -101,9 +102,13 @@ BrowserContext::~BrowserContext() {
void BrowserContext::InitPrefs() {
auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences"));
PrefServiceFactory prefs_factory;
prefs_factory.SetUserPrefsFile(prefs_path,
JsonPrefStore::GetTaskRunnerForFile(
prefs_path, BrowserThread::GetBlockingPool()).get());
scoped_refptr<JsonPrefStore> pref_store =
base::MakeRefCounted<JsonPrefStore>(prefs_path);
{
base::ThreadRestrictions::ScopedAllowIO allow_io;
pref_store->ReadPrefs(); // Synchronous.
}
prefs_factory.set_user_prefs(pref_store);
auto registry = make_scoped_refptr(new PrefRegistrySimple);
RegisterInternalPrefs(registry.get());
@ -140,8 +145,8 @@ net::URLRequestContextGetter* BrowserContext::CreateRequestContext(
return url_request_getter_.get();
}
net::NetworkDelegate* BrowserContext::CreateNetworkDelegate() {
return new NetworkDelegate;
std::unique_ptr<net::NetworkDelegate> BrowserContext::CreateNetworkDelegate() {
return base::MakeUnique<NetworkDelegate>();
}
std::string BrowserContext::GetMediaDeviceIDSalt() {

View file

@ -90,7 +90,7 @@ class BrowserContext : public base::RefCounted<BrowserContext>,
virtual void RegisterPrefs(PrefRegistrySimple* pref_registry) {}
// URLRequestContextGetter::Delegate:
net::NetworkDelegate* CreateNetworkDelegate() override;
std::unique_ptr<net::NetworkDelegate> CreateNetworkDelegate() override;
base::FilePath GetPath() const override;

View file

@ -16,6 +16,7 @@
#include "base/message_loop/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "brightray/browser/browser_client.h"
#include "brightray/browser/browser_context.h"
#include "brightray/browser/devtools_manager_delegate.h"
#include "brightray/browser/media/media_capture_devices_dispatcher.h"
@ -275,6 +276,12 @@ int BrowserMainParts::PreCreateThreads() {
if (!views::LayoutProvider::Get())
layout_provider_.reset(new views::LayoutProvider());
// Initialize the app locale.
BrowserClient::SetApplicationLocale(l10n_util::GetApplicationLocale(""));
// Manage global state of net and other IO thread related.
io_thread_ = base::MakeUnique<IOThread>();
return 0;
}
@ -283,6 +290,8 @@ void BrowserMainParts::PostDestroyThreads() {
device::BluetoothAdapterFactory::Shutdown();
bluez::DBusBluezManagerWrapperLinux::Shutdown();
#endif
io_thread_.reset();
}
} // namespace brightray

View file

@ -11,6 +11,7 @@
#include "base/macros.h"
#include "base/path_service.h"
#include "brightray/browser/brightray_paths.h"
#include "brightray/browser/io_thread.h"
#include "content/public/browser/browser_main_parts.h"
#include "ui/views/layout/layout_provider.h"
@ -50,6 +51,8 @@ class BrowserMainParts : public content::BrowserMainParts {
void OverrideAppLogsPath();
#endif
std::unique_ptr<IOThread> io_thread_;
#if defined(TOOLKIT_VIEWS)
std::unique_ptr<ViewsDelegate> views_delegate_;
#endif

View file

@ -0,0 +1,48 @@
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "brightray/browser/io_thread.h"
#include "content/public/browser/browser_thread.h"
#include "net/proxy/proxy_service.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_builder.h"
#if defined(USE_NSS_CERTS)
#include "net/cert_net/nss_ocsp.h"
#endif
using content::BrowserThread;
namespace brightray {
IOThread::IOThread() {
BrowserThread::SetIOThreadDelegate(this);
}
IOThread::~IOThread() {
BrowserThread::SetIOThreadDelegate(nullptr);
}
void IOThread::Init() {
net::URLRequestContextBuilder builder;
builder.set_proxy_service(net::ProxyService::CreateDirect());
builder.DisableHttpCache();
url_request_context_ = builder.Build();
#if defined(USE_NSS_CERTS)
net::SetMessageLoopForNSSHttpIO();
net::SetURLRequestContextForNSSHttpIO(url_request_context_.get());
#endif
}
void IOThread::CleanUp() {
#if defined(USE_NSS_CERTS)
net::ShutdownNSSHttpIO();
net::SetURLRequestContextForNSSHttpIO(nullptr);
#endif
url_request_context_.reset();
}
} // namespace brightray

View file

@ -0,0 +1,37 @@
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef BRIGHTRAY_BROWSER_IO_THREAD_H_
#define BRIGHTRAY_BROWSER_IO_THREAD_H_
#include <memory>
#include "base/macros.h"
#include "content/public/browser/browser_thread_delegate.h"
namespace net {
class URLRequestContext;
}
namespace brightray {
class IOThread : public content::BrowserThreadDelegate {
public:
IOThread();
~IOThread() override;
protected:
// BrowserThreadDelegate Implementation, runs on the IO thread.
void Init() override;
void CleanUp() override;
private:
std::unique_ptr<net::URLRequestContext> url_request_context_;
DISALLOW_COPY_AND_ASSIGN(IOThread);
};
} // namespace brightray
#endif // BRIGHTRAY_BROWSER_IO_THREAD_H_

View file

@ -12,6 +12,7 @@
#include "base/strings/string_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/worker_pool.h"
#include "brightray/browser/browser_client.h"
#include "brightray/browser/net/devtools_network_controller_handle.h"
#include "brightray/browser/net/devtools_network_transaction_factory.h"
#include "brightray/browser/net/require_ct_delegate.h"
@ -53,13 +54,8 @@
#include "net/url_request/url_request_intercepting_job_factory.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "storage/browser/quota/special_storage_policy.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/url_constants.h"
#if defined(USE_NSS_CERTS)
#include "net/cert_net/nss_ocsp.h"
#endif
using content::BrowserThread;
namespace brightray {
@ -142,7 +138,7 @@ URLRequestContextGetter::URLRequestContextGetter(
protocol_interceptors_(std::move(protocol_interceptors)),
job_factory_(nullptr) {
// Must first be created on the UI thread.
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (protocol_handlers)
std::swap(protocol_handlers_, *protocol_handlers);
@ -158,9 +154,6 @@ URLRequestContextGetter::URLRequestContextGetter(
}
URLRequestContextGetter::~URLRequestContextGetter() {
#if defined(USE_NSS_CERTS)
net::SetURLRequestContextForNSSHttpIO(NULL);
#endif
}
net::HostResolver* URLRequestContextGetter::host_resolver() {
@ -168,29 +161,24 @@ net::HostResolver* URLRequestContextGetter::host_resolver() {
}
net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!url_request_context_.get()) {
ct_delegate_.reset(new RequireCTDelegate);
auto& command_line = *base::CommandLine::ForCurrentProcess();
url_request_context_.reset(new net::URLRequestContext);
#if defined(USE_NSS_CERTS)
net::SetURLRequestContextForNSSHttpIO(url_request_context_.get());
#endif
// --log-net-log
if (net_log_) {
net_log_->StartLogging();
url_request_context_->set_net_log(net_log_);
}
network_delegate_.reset(delegate_->CreateNetworkDelegate());
url_request_context_->set_network_delegate(network_delegate_.get());
storage_.reset(
new net::URLRequestContextStorage(url_request_context_.get()));
storage_->set_network_delegate(delegate_->CreateNetworkDelegate());
auto cookie_path = in_memory_ ?
base::FilePath() : base_path_.Append(FILE_PATH_LITERAL("Cookies"));
auto cookie_config = content::CookieStoreConfig(
@ -205,10 +193,10 @@ net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() {
storage_->set_channel_id_service(base::MakeUnique<net::ChannelIDService>(
new net::DefaultChannelIDStore(nullptr)));
std::string accept_lang = l10n_util::GetApplicationLocale("");
storage_->set_http_user_agent_settings(base::WrapUnique(
new net::StaticHttpUserAgentSettings(
net::HttpUtil::GenerateAcceptLanguageHeader(accept_lang),
storage_->set_http_user_agent_settings(
base::WrapUnique(new net::StaticHttpUserAgentSettings(
net::HttpUtil::GenerateAcceptLanguageHeader(
BrowserClient::Get()->GetApplicationLocale()),
user_agent_)));
std::unique_ptr<net::HostResolver> host_resolver(

View file

@ -15,6 +15,7 @@
#include "net/http/http_cache.h"
#include "net/http/transport_security_state.h"
#include "net/http/url_security_manager.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
namespace base {
@ -44,7 +45,9 @@ class URLRequestContextGetter : public net::URLRequestContextGetter {
Delegate() {}
virtual ~Delegate() {}
virtual net::NetworkDelegate* CreateNetworkDelegate() { return nullptr; }
virtual std::unique_ptr<net::NetworkDelegate> CreateNetworkDelegate() {
return nullptr;
}
virtual net::CookieMonsterDelegate* CreateCookieDelegate() {
return nullptr;
}
@ -77,6 +80,11 @@ class URLRequestContextGetter : public net::URLRequestContextGetter {
net::HostResolver* host_resolver();
net::URLRequestJobFactory* job_factory() const { return job_factory_; }
net::NetworkDelegate* network_delegate() const {
if (url_request_context_)
return url_request_context_->network_delegate();
return nullptr;
}
private:
Delegate* delegate_;
@ -91,7 +99,6 @@ class URLRequestContextGetter : public net::URLRequestContextGetter {
std::unique_ptr<RequireCTDelegate> ct_delegate_;
std::unique_ptr<net::ProxyConfigService> proxy_config_service_;
std::unique_ptr<net::NetworkDelegate> network_delegate_;
std::unique_ptr<net::URLRequestContextStorage> storage_;
std::unique_ptr<net::URLRequestContext> url_request_context_;
std::unique_ptr<net::HostMappingRules> host_mapping_rules_;

View file

@ -13,6 +13,7 @@
#include "base/files/file_util.h"
#include "base/md5.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "base/win/windows_version.h"
#include "brightray/browser/win/notification_presenter_win7.h"
@ -68,6 +69,7 @@ NotificationPresenterWin::~NotificationPresenterWin() {
}
bool NotificationPresenterWin::Init() {
base::ThreadRestrictions::ScopedAllowIO allow_io;
return temp_dir_.CreateUniqueTempDir();
}
@ -82,6 +84,7 @@ base::string16 NotificationPresenterWin::SaveIconToFilesystem(
filename = std::to_string(now.ToInternalValue()) + ".png";
}
base::ThreadRestrictions::ScopedAllowIO allow_io;
base::FilePath path = temp_dir_.GetPath().Append(base::UTF8ToUTF16(filename));
if (base::PathExists(path))
return path.value();

View file

@ -29,6 +29,8 @@
'browser/inspectable_web_contents_view.h',
'browser/inspectable_web_contents_view_mac.h',
'browser/inspectable_web_contents_view_mac.mm',
'browser/io_thread.cc',
'browser/io_thread.h',
'browser/mac/bry_inspectable_web_contents_view.h',
'browser/mac/bry_inspectable_web_contents_view.mm',
'browser/mac/cocoa_notification.h',

View file

@ -20,8 +20,12 @@ BrowserProcess::~BrowserProcess() {
g_browser_process = NULL;
}
void BrowserProcess::SetApplicationLocale(const std::string& locale) {
locale_ = locale;
}
std::string BrowserProcess::GetApplicationLocale() {
return l10n_util::GetApplicationLocale("");
return locale_;
}
IconManager* BrowserProcess::GetIconManager() {

View file

@ -28,6 +28,7 @@ class BrowserProcess {
BrowserProcess();
~BrowserProcess();
void SetApplicationLocale(const std::string& locale);
std::string GetApplicationLocale();
IconManager* GetIconManager();
@ -36,6 +37,7 @@ class BrowserProcess {
private:
std::unique_ptr<printing::PrintJobManager> print_job_manager_;
std::unique_ptr<IconManager> icon_manager_;
std::string locale_;
DISALLOW_COPY_AND_ASSIGN(BrowserProcess);
};

View file

@ -77,7 +77,6 @@
#include "base/rand_util.h"
#include "base/sequenced_task_runner_helpers.h"
#include "base/single_thread_task_runner.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
@ -85,6 +84,7 @@
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
@ -722,6 +722,7 @@ ProcessSingleton::ProcessSingleton(
: notification_callback_(notification_callback),
current_pid_(base::GetCurrentProcId()) {
// The user_data_dir may have not been created yet.
base::ThreadRestrictions::ScopedAllowIO allow_io;
base::CreateDirectoryAndGetError(user_data_dir, nullptr);
socket_path_ = user_data_dir.Append(kSingletonSocketFilename);
@ -734,6 +735,10 @@ ProcessSingleton::ProcessSingleton(
ProcessSingleton::~ProcessSingleton() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Manually free resources with IO explicitly allowed.
base::ThreadRestrictions::ScopedAllowIO allow_io;
watcher_ = nullptr;
ignore_result(socket_dir_.Delete());
}
ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
@ -960,6 +965,7 @@ void ProcessSingleton::DisablePromptForTesting() {
}
bool ProcessSingleton::Create() {
base::ThreadRestrictions::ScopedAllowIO allow_io;
int sock;
sockaddr_un addr;

View file

@ -189,8 +189,7 @@ ProcessSingleton::ProcessSingleton(
is_virtualized_(false),
lock_file_(INVALID_HANDLE_VALUE),
user_data_dir_(user_data_dir),
should_kill_remote_process_callback_(
base::Bind(&TerminateAppWithError)) {
should_kill_remote_process_callback_(base::Bind(&TerminateAppWithError)) {
// The user_data_dir may have not been created yet.
base::CreateDirectoryAndGetError(user_data_dir, nullptr);
}

View file

@ -134,7 +134,8 @@ describe('debugger module', () => {
})
})
it('handles invalid unicode characters in message', (done) => {
// TODO(deepak1556): Find a way to enable this spec.
xit('handles invalid unicode characters in message', (done) => {
try {
w.webContents.debugger.attach()
} catch (err) {

View file

@ -17,7 +17,6 @@ describe('webFrame module', function () {
describe('webFrame.registerURLSchemeAsPrivileged', function () {
it('supports fetch api by default', function (done) {
webFrame.registerURLSchemeAsPrivileged('file')
var url = 'file://' + fixtures + '/assets/logo.png'
window.fetch(url).then(function (response) {
assert(response.ok)

View file

@ -4,7 +4,7 @@ const http = require('http')
const path = require('path')
const ws = require('ws')
const url = require('url')
const {ipcRenderer, remote, webFrame} = require('electron')
const {ipcRenderer, remote} = require('electron')
const {closeWindow} = require('./window-helpers')
const {app, BrowserWindow, ipcMain, protocol, session, webContents} = remote
@ -1043,13 +1043,6 @@ describe('chromium feature', () => {
})
it('should not open when pdf is requested as sub resource', (done) => {
createBrowserWindow({plugins: true, preload: 'preload-pdf-loaded.js'})
webFrame.registerURLSchemeAsPrivileged('file', {
secure: false,
bypassCSP: false,
allowServiceWorkers: false,
corsEnabled: false
})
fetch(pdfSource).then((res) => {
assert.equal(res.status, 200)
assert.notEqual(document.title, 'cat.pdf')

@ -1 +1 @@
Subproject commit 734f8be87b4962386f532b9b2ea35c6ac0cb9f44
Subproject commit 09055d917f976509d4008fa5d24307a2e2d2d895