Merge branch 'master' into expect-debugger-spec

This commit is contained in:
John Kleinschmidt 2018-06-19 11:22:25 -04:00 committed by GitHub
commit faef453df5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
257 changed files with 4731 additions and 2535 deletions

View file

@ -1,6 +1,14 @@
build-steps: &build-steps build-steps: &build-steps
steps: steps:
- checkout - checkout
- run:
name: Install Node.js 10 on MacOS
command: |
if [ "$INSTALL_MACOS_NODE" == "true" ]; then
echo 'Installing Node.js 10 for MacOS'
brew update
brew install node@10
fi
- run: - run:
name: Check for release name: Check for release
command: | command: |
@ -117,7 +125,7 @@ build-steps: &build-steps
build-defaults: &build-defaults build-defaults: &build-defaults
docker: docker:
- image: electronbuilds/electron:0.0.7 - image: electronbuilds/electron:0.0.8
<<: *build-steps <<: *build-steps
version: 2 version: 2
@ -241,16 +249,18 @@ jobs:
environment: environment:
TARGET_ARCH: x64 TARGET_ARCH: x64
RUN_TESTS: true RUN_TESTS: true
INSTALL_MACOS_NODE: true
macos: macos:
xcode: "9.0" xcode: "8.3.3"
<<: *build-steps <<: *build-steps
electron-osx-x64-release-nightly: electron-osx-x64-release-nightly:
environment: environment:
TARGET_ARCH: x64 TARGET_ARCH: x64
RUN_RELEASE_BUILD: true RUN_RELEASE_BUILD: true
INSTALL_MACOS_NODE: true
macos: macos:
xcode: "9.0" xcode: "8.3.3"
<<: *build-steps <<: *build-steps
electron-mas-x64: electron-mas-x64:
@ -258,8 +268,9 @@ jobs:
TARGET_ARCH: x64 TARGET_ARCH: x64
MAS_BUILD: 1 MAS_BUILD: 1
RUN_TESTS: true RUN_TESTS: true
INSTALL_MACOS_NODE: true
macos: macos:
xcode: "9.0" xcode: "8.3.3"
<<: *build-steps <<: *build-steps
electron-mas-x64-release-nightly: electron-mas-x64-release-nightly:
@ -267,8 +278,9 @@ jobs:
TARGET_ARCH: x64 TARGET_ARCH: x64
MAS_BUILD: 1 MAS_BUILD: 1
RUN_RELEASE_BUILD: true RUN_RELEASE_BUILD: true
INSTALL_MACOS_NODE: true
macos: macos:
xcode: "9.0" xcode: "8.3.3"
<<: *build-steps <<: *build-steps

View file

@ -2,7 +2,14 @@
Thank you for your Pull Request. Please provide a description above and review Thank you for your Pull Request. Please provide a description above and review
the requirements below. the requirements below.
Bug fixes and new features should include tests and possibly benchmarks.
Contributors guide: https://github.com/electron/electron/blob/master/CONTRIBUTING.md Contributors guide: https://github.com/electron/electron/blob/master/CONTRIBUTING.md
--> -->
##### Checklist
<!-- Remove items that do not apply. For completed items, change [ ] to [x]. -->
- [ ] PR description included and stakeholders cc'd
- [ ] `npm test` passes
- [ ] tests are [changed or added](https://github.com/electron/electron/blob/master/docs/development/testing.md)
- [ ] relevant documentation is changed or added
- [ ] commit messages or PR title follow semantic [commit guidelines](https://github.com/electron/electron/blob/master/docs/development/pull-requests.md#commit-message-guidelines)

View file

@ -7,8 +7,8 @@ ENV HOME=/home
RUN chmod a+rwx /home RUN chmod a+rwx /home
# Install node.js # Install node.js
RUN curl -sL https://deb.nodesource.com/setup_8.x | bash - RUN curl -sL https://deb.nodesource.com/setup_10.x | bash -
RUN apt-get update && apt-get install -y nodejs RUN apt-get install -y nodejs
# Install wget used by crash reporter # Install wget used by crash reporter
RUN apt-get install -y wget RUN apt-get install -y wget

View file

@ -3,8 +3,8 @@ FROM electronbuilds/libchromiumcontent:0.0.4
USER root USER root
# Install node.js # Install node.js
RUN curl -sL https://deb.nodesource.com/setup_8.x | bash - RUN curl -sL https://deb.nodesource.com/setup_10.x | bash -
RUN apt-get update && apt-get install -y nodejs RUN apt-get install -y nodejs
# Install wget used by crash reporter # Install wget used by crash reporter
RUN apt-get install -y wget RUN apt-get install -y wget

65
appveyor.yml Normal file
View file

@ -0,0 +1,65 @@
version: 1.0.{build}
build_cloud: electron-16
image: electron-16-vs2017
environment:
DISABLE_CRASH_REPORTER_TESTS: true
matrix:
- TARGET_ARCH: ia32
- TARGET_ARCH: x64
build_script:
- ps: >-
if(($env:APPVEYOR_PULL_REQUEST_HEAD_REPO_NAME -split "/")[0] -eq ($env:APPVEYOR_REPO_NAME -split "/")[0]) {
Write-warning "Skipping PR build for branch"; Exit-AppveyorBuild
} else {
Add-Path "$env:ProgramFiles (x86)\Windows Kits\10\Debuggers\x64"
$env:path = "$env:ProgramFiles (x86)\Windows Kits\10\Debuggers\x64;$env:path"
$Message = (git log --format=%B -n 1 HEAD) | Out-String
if ((Test-Path Env:\RUN_RELEASE_BUILD)) {
$env:ELECTRON_RELEASE = '1'
Write-Output "release build triggered from api"
}
if ((Test-Path Env:\ELECTRON_RELEASE)) {
Write-Output "Running release build"
python script\bootstrap.py --target_arch=$env:TARGET_ARCH
python script\build.py -c R
python script\create-dist.py
} else {
Write-Output "Running debug build"
python script\bootstrap.py --target_arch=$env:TARGET_ARCH --dev
python script\build.py -c D
}
if ($? -ne 'True') {
throw "Build failed with exit code $?"
} else {
"Build succeeded."
}
}
test_script:
- ps: >-
if (Test-Path Env:\ELECTRON_RELEASE) {
Write-Output "Skipping tests for release build"
} else {
Write-Output "Running tests for debug build"
python script\test.py --ci
if ($LASTEXITCODE -ne '0') {
throw "Tests failed with exit code $LASTEXITCODE"
} else {
Write-Output "Tests succeeded."
}
python script\verify-ffmpeg.py
if ($LASTEXITCODE -ne '0') {
throw "Verify ffmpeg failed with exit code $LASTEXITCODE"
} else {
"Verify ffmpeg succeeded."
}
}
artifacts:
- path: out
name: out

View file

@ -20,7 +20,6 @@
#include "content/public/common/user_agent.h" #include "content/public/common/user_agent.h"
#include "media/media_features.h" #include "media/media_features.h"
#include "ppapi/shared_impl/ppapi_permissions.h" #include "ppapi/shared_impl/ppapi_permissions.h"
#include "third_party/widevine/cdm/stub/widevine_cdm_version.h"
#include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util.h"
#include "url/url_constants.h" #include "url/url_constants.h"
@ -90,20 +89,6 @@ content::PepperPluginInfo CreateWidevineCdmInfo(const base::FilePath& path,
kWidevineCdmPluginMimeType, kWidevineCdmPluginExtension, kWidevineCdmPluginMimeType, kWidevineCdmPluginExtension,
kWidevineCdmPluginMimeTypeDescription); kWidevineCdmPluginMimeTypeDescription);
// Add the supported codecs as if they came from the component manifest.
std::vector<std::string> codecs;
codecs.push_back(kCdmSupportedCodecVp8);
codecs.push_back(kCdmSupportedCodecVp9);
#if BUILDFLAG(USE_PROPRIETARY_CODECS)
codecs.push_back(kCdmSupportedCodecAvc1);
#endif // BUILDFLAG(USE_PROPRIETARY_CODECS)
std::string codec_string = base::JoinString(
codecs, std::string(1, kCdmSupportedCodecsValueDelimiter));
widevine_cdm_mime_type.additional_param_names.push_back(
base::ASCIIToUTF16(kCdmSupportedCodecsParamName));
widevine_cdm_mime_type.additional_param_values.push_back(
base::ASCIIToUTF16(codec_string));
widevine_cdm.mime_types.push_back(widevine_cdm_mime_type); widevine_cdm.mime_types.push_back(widevine_cdm_mime_type);
widevine_cdm.permissions = kWidevineCdmPluginPermissions; widevine_cdm.permissions = kWidevineCdmPluginPermissions;
@ -224,4 +209,36 @@ void AtomContentClient::AddPepperPlugins(
#endif // defined(ENABLE_PDF_VIEWER) #endif // defined(ENABLE_PDF_VIEWER)
} }
void AtomContentClient::AddContentDecryptionModules(
std::vector<content::CdmInfo>* cdms,
std::vector<media::CdmHostFilePath>* cdm_host_file_paths) {
#if defined(WIDEVINE_CDM_AVAILABLE) && BUILDFLAG(ENABLE_LIBRARY_CDMS)
auto command_line = base::CommandLine::ForCurrentProcess();
base::FilePath widevine_cdm_path =
command_line->GetSwitchValuePath(switches::kWidevineCdmPath);
if (widevine_cdm_path.empty())
return;
if (!base::PathExists(widevine_cdm_path))
return;
auto widevine_cdm_version =
command_line->GetSwitchValueASCII(switches::kWidevineCdmVersion);
if (widevine_cdm_version.empty())
return;
std::vector<media::VideoCodec> supported_video_codecs;
supported_video_codecs.push_back(media::VideoCodec::kCodecVP8);
supported_video_codecs.push_back(media::VideoCodec::kCodecVP9);
#if BUILDFLAG(USE_PROPRIETARY_CODECS)
supported_video_codecs.push_back(media::VideoCodec::kCodecH264);
#endif // BUILDFLAG(USE_PROPRIETARY_CODECS)
content::CdmRegistry::GetInstance()->RegisterCdm(
content::CdmInfo(kWidevineCdmDisplayName, kWidevineCdmGuid,
base::Version(widevine_cdm_version), widevine_cdm_path,
kWidevineCdmFileSystemId, supported_video_codecs, false,
kWidevineKeySystem, false));
#endif // defined(WIDEVINE_CDM_AVAILABLE) && BUILDFLAG(ENABLE_LIBRARY_CDMS)
}
} // namespace atom } // namespace atom

View file

@ -26,6 +26,9 @@ class AtomContentClient : public brightray::ContentClient {
void AddAdditionalSchemes(Schemes* schemes) override; void AddAdditionalSchemes(Schemes* schemes) override;
void AddPepperPlugins( void AddPepperPlugins(
std::vector<content::PepperPluginInfo>* plugins) override; std::vector<content::PepperPluginInfo>* plugins) override;
void AddContentDecryptionModules(
std::vector<content::CdmInfo>* cdms,
std::vector<media::CdmHostFilePath>* cdm_host_file_paths) override;
private: private:
DISALLOW_COPY_AND_ASSIGN(AtomContentClient); DISALLOW_COPY_AND_ASSIGN(AtomContentClient);

View file

@ -22,6 +22,7 @@
#include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_paths.h"
#include "content/public/common/content_switches.h" #include "content/public/common/content_switches.h"
#include "ipc/ipc_features.h" #include "ipc/ipc_features.h"
#include "services/service_manager/sandbox/switches.h"
#include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h" #include "ui/base/resource/resource_bundle.h"
@ -83,7 +84,7 @@ bool AtomMainDelegate::BasicStartupComplete(int* exit_code) {
#endif // !defined(OS_WIN) #endif // !defined(OS_WIN)
// Only enable logging when --enable-logging is specified. // Only enable logging when --enable-logging is specified.
std::unique_ptr<base::Environment> env(base::Environment::Create()); auto env = base::Environment::Create();
if (!command_line->HasSwitch(::switches::kEnableLogging) && if (!command_line->HasSwitch(::switches::kEnableLogging) &&
!env->HasVar("ELECTRON_ENABLE_LOGGING")) { !env->HasVar("ELECTRON_ENABLE_LOGGING")) {
settings.logging_dest = logging::LOG_NONE; settings.logging_dest = logging::LOG_NONE;
@ -141,7 +142,8 @@ void AtomMainDelegate::PreSandboxStartup() {
if (command_line->HasSwitch(switches::kEnableSandbox)) { if (command_line->HasSwitch(switches::kEnableSandbox)) {
// Disable setuid sandbox since it is not longer required on // Disable setuid sandbox since it is not longer required on
// linux(namespace sandbox is available on most distros). // linux(namespace sandbox is available on most distros).
command_line->AppendSwitch(::switches::kDisableSetuidSandbox); command_line->AppendSwitch(
service_manager::switches::kDisableSetuidSandbox);
} else { } else {
// Disable renderer sandbox for most of node's functions. // Disable renderer sandbox for most of node's functions.
command_line->AppendSwitch(::switches::kNoSandbox); command_line->AppendSwitch(::switches::kNoSandbox);
@ -203,7 +205,7 @@ bool AtomMainDelegate::DelaySandboxInitialization(
std::unique_ptr<brightray::ContentClient> std::unique_ptr<brightray::ContentClient>
AtomMainDelegate::CreateContentClient() { AtomMainDelegate::CreateContentClient() {
return std::unique_ptr<brightray::ContentClient>(new AtomContentClient); return std::make_unique<AtomContentClient>();
} }
} // namespace atom } // namespace atom

View file

@ -38,11 +38,12 @@ int NodeMain(int argc, char* argv[]) {
base::ThreadTaskRunnerHandle handle(uv_task_runner); base::ThreadTaskRunnerHandle handle(uv_task_runner);
// Initialize feature list. // Initialize feature list.
std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList); auto feature_list = std::make_unique<base::FeatureList>();
feature_list->InitializeFromCommandLine("", ""); feature_list->InitializeFromCommandLine("", "");
base::FeatureList::SetInstance(std::move(feature_list)); base::FeatureList::SetInstance(std::move(feature_list));
gin::V8Initializer::LoadV8Snapshot(); gin::V8Initializer::LoadV8Snapshot(
gin::V8Initializer::V8SnapshotFileType::kWithAdditionalContext);
gin::V8Initializer::LoadV8Natives(); gin::V8Initializer::LoadV8Natives();
// V8 requires a task scheduler apparently // V8 requires a task scheduler apparently

View file

@ -20,6 +20,7 @@
#include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/image_converter.h" #include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/net_converter.h" #include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/native_mate_converters/network_converter.h"
#include "atom/common/native_mate_converters/value_converter.h" #include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h" #include "atom/common/node_includes.h"
#include "atom/common/options_switches.h" #include "atom/common/options_switches.h"
@ -47,6 +48,7 @@
#include "native_mate/object_template_builder.h" #include "native_mate/object_template_builder.h"
#include "net/ssl/client_cert_identity.h" #include "net/ssl/client_cert_identity.h"
#include "net/ssl/ssl_cert_request_info.h" #include "net/ssl/ssl_cert_request_info.h"
#include "services/network/public/cpp/network_switches.h"
#include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/image/image.h" #include "ui/gfx/image/image.h"
@ -547,9 +549,9 @@ App::App(v8::Isolate* isolate) {
Browser::Get()->AddObserver(this); Browser::Get()->AddObserver(this);
content::GpuDataManager::GetInstance()->AddObserver(this); content::GpuDataManager::GetInstance()->AddObserver(this);
base::ProcessId pid = base::GetCurrentProcId(); base::ProcessId pid = base::GetCurrentProcId();
std::unique_ptr<atom::ProcessMetric> process_metric(new atom::ProcessMetric( auto process_metric = std::make_unique<atom::ProcessMetric>(
content::PROCESS_TYPE_BROWSER, pid, content::PROCESS_TYPE_BROWSER, pid,
base::ProcessMetrics::CreateCurrentProcessMetrics())); base::ProcessMetrics::CreateCurrentProcessMetrics());
app_metrics_[pid] = std::move(process_metric); app_metrics_[pid] = std::move(process_metric);
Init(isolate); Init(isolate);
} }
@ -695,7 +697,7 @@ bool App::CanCreateWindow(
WindowOpenDisposition disposition, WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& features, const blink::mojom::WindowFeatures& features,
const std::vector<std::string>& additional_features, const std::vector<std::string>& additional_features,
const scoped_refptr<content::ResourceRequestBody>& body, const scoped_refptr<network::ResourceRequestBody>& body,
bool user_gesture, bool user_gesture,
bool opener_suppressed, bool opener_suppressed,
bool* no_javascript_access) { bool* no_javascript_access) {
@ -811,9 +813,8 @@ void App::ChildProcessLaunched(int process_type, base::ProcessHandle handle) {
std::unique_ptr<base::ProcessMetrics> metrics( std::unique_ptr<base::ProcessMetrics> metrics(
base::ProcessMetrics::CreateProcessMetrics(handle)); base::ProcessMetrics::CreateProcessMetrics(handle));
#endif #endif
std::unique_ptr<atom::ProcessMetric> process_metric( app_metrics_[pid] = std::make_unique<atom::ProcessMetric>(process_type, pid,
new atom::ProcessMetric(process_type, pid, std::move(metrics))); std::move(metrics));
app_metrics_[pid] = std::move(process_metric);
} }
void App::ChildProcessDisconnected(base::ProcessId pid) { void App::ChildProcessDisconnected(base::ProcessId pid) {
@ -1305,7 +1306,7 @@ void AppendSwitch(const std::string& switch_string, mate::Arguments* args) {
if (base::EndsWith(switch_string, "-path", if (base::EndsWith(switch_string, "-path",
base::CompareCase::INSENSITIVE_ASCII) || base::CompareCase::INSENSITIVE_ASCII) ||
switch_string == switches::kLogNetLog) { switch_string == network::switches::kLogNetLog) {
base::FilePath path; base::FilePath path;
args->GetNext(&path); args->GetNext(&path);
command_line->AppendSwitchPath(switch_string, path); command_line->AppendSwitchPath(switch_string, path);

View file

@ -147,7 +147,7 @@ class App : public AtomBrowserClient::Delegate,
WindowOpenDisposition disposition, WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& features, const blink::mojom::WindowFeatures& features,
const std::vector<std::string>& additional_features, const std::vector<std::string>& additional_features,
const scoped_refptr<content::ResourceRequestBody>& body, const scoped_refptr<network::ResourceRequestBody>& body,
bool user_gesture, bool user_gesture,
bool opener_suppressed, bool opener_suppressed,
bool* no_javascript_access) override; bool* no_javascript_access) override;

View file

@ -155,7 +155,7 @@ void BrowserWindow::BeforeUnloadDialogCancelled() {
window_unresponsive_closure_.Cancel(); window_unresponsive_closure_.Cancel();
} }
void BrowserWindow::OnRendererUnresponsive(content::RenderWidgetHost*) { void BrowserWindow::OnRendererUnresponsive(content::RenderProcessHost*) {
// Schedule the unresponsive shortly later, since we may receive the // Schedule the unresponsive shortly later, since we may receive the
// responsive event soon. This could happen after the whole application had // responsive event soon. This could happen after the whole application had
// blocked for a while. // blocked for a while.
@ -270,6 +270,14 @@ void BrowserWindow::OnWindowResize() {
TopLevelWindow::OnWindowResize(); TopLevelWindow::OnWindowResize();
} }
void BrowserWindow::OnWindowLeaveFullScreen() {
TopLevelWindow::OnWindowLeaveFullScreen();
#if defined(OS_MACOSX)
if (web_contents()->IsFullscreenForCurrentTab())
web_contents()->ExitFullscreen(true);
#endif
}
void BrowserWindow::Focus() { void BrowserWindow::Focus() {
if (api_web_contents_->IsOffScreen()) if (api_web_contents_->IsOffScreen())
FocusOnWebView(); FocusOnWebView();
@ -336,7 +344,7 @@ v8::Local<v8::Value> BrowserWindow::GetWebContents(v8::Isolate* isolate) {
// Convert draggable regions in raw format to SkRegion format. // Convert draggable regions in raw format to SkRegion format.
std::unique_ptr<SkRegion> BrowserWindow::DraggableRegionsToSkRegion( std::unique_ptr<SkRegion> BrowserWindow::DraggableRegionsToSkRegion(
const std::vector<DraggableRegion>& regions) { const std::vector<DraggableRegion>& regions) {
std::unique_ptr<SkRegion> sk_region(new SkRegion); auto sk_region = std::make_unique<SkRegion>();
for (const DraggableRegion& region : regions) { for (const DraggableRegion& region : regions) {
sk_region->op( sk_region->op(
region.bounds.x(), region.bounds.y(), region.bounds.right(), region.bounds.x(), region.bounds.y(), region.bounds.right(),

View file

@ -49,7 +49,7 @@ class BrowserWindow : public TopLevelWindow,
void RenderViewCreated(content::RenderViewHost* render_view_host) override; void RenderViewCreated(content::RenderViewHost* render_view_host) override;
void DidFirstVisuallyNonEmptyPaint() override; void DidFirstVisuallyNonEmptyPaint() override;
void BeforeUnloadDialogCancelled() override; void BeforeUnloadDialogCancelled() override;
void OnRendererUnresponsive(content::RenderWidgetHost*) override; void OnRendererUnresponsive(content::RenderProcessHost*) override;
bool OnMessageReceived(const IPC::Message& message, bool OnMessageReceived(const IPC::Message& message,
content::RenderFrameHost* rfh) override; content::RenderFrameHost* rfh) override;
@ -66,6 +66,7 @@ class BrowserWindow : public TopLevelWindow,
void OnWindowBlur() override; void OnWindowBlur() override;
void OnWindowFocus() override; void OnWindowFocus() override;
void OnWindowResize() override; void OnWindowResize() override;
void OnWindowLeaveFullScreen() override;
void Focus() override; void Focus() override;
void Blur() override; void Blur() override;
void SetBackgroundColor(const std::string& color_name) override; void SetBackgroundColor(const std::string& color_name) override;

View file

@ -42,10 +42,10 @@ std::vector<gfx::Rect> CalculateNonDraggableRegions(
int width, int width,
int height) { int height) {
std::vector<gfx::Rect> result; std::vector<gfx::Rect> result;
std::unique_ptr<SkRegion> non_draggable(new SkRegion); SkRegion non_draggable;
non_draggable->op(0, 0, width, height, SkRegion::kUnion_Op); non_draggable.op(0, 0, width, height, SkRegion::kUnion_Op);
non_draggable->op(*draggable, SkRegion::kDifference_Op); non_draggable.op(*draggable, SkRegion::kDifference_Op);
for (SkRegion::Iterator it(*non_draggable); !it.done(); it.next()) { for (SkRegion::Iterator it(non_draggable); !it.done(); it.next()) {
result.push_back(gfx::SkIRectToRect(it.rect())); result.push_back(gfx::SkIRectToRect(it.rect()));
} }
return result; return result;

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.
#include "atom/browser/api/atom_api_button.h"
#include "atom/common/api/constructor.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
namespace atom {
namespace api {
Button::Button(views::Button* button) : View(button) {
view()->set_owned_by_client();
}
Button::~Button() {}
void Button::ButtonPressed(views::Button* sender, const ui::Event& event) {
Emit("click");
}
// static
mate::WrappableBase* Button::New(mate::Arguments* args) {
args->ThrowError("Button can not be created directly");
return nullptr;
}
// static
void Button::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "Button"));
}
} // namespace api
} // namespace atom
namespace {
using atom::api::Button;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("Button",
mate::CreateConstructor<Button>(isolate, base::Bind(&Button::New)));
}
} // namespace
NODE_BUILTIN_MODULE_CONTEXT_AWARE(atom_browser_button, Initialize)

View file

@ -0,0 +1,38 @@
// 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_API_ATOM_API_BUTTON_H_
#define ATOM_BROWSER_API_ATOM_API_BUTTON_H_
#include "atom/browser/api/atom_api_view.h"
#include "native_mate/handle.h"
#include "ui/views/controls/button/button.h"
namespace atom {
namespace api {
class Button : public View, public views::ButtonListener {
public:
static mate::WrappableBase* New(mate::Arguments* args);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
protected:
explicit Button(views::Button* view);
~Button() override;
// views::ButtonListener:
void ButtonPressed(views::Button* sender, const ui::Event& event) override;
private:
DISALLOW_COPY_AND_ASSIGN(Button);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_BUTTON_H_

View file

@ -14,7 +14,7 @@
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "native_mate/dictionary.h" #include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h" #include "native_mate/object_template_builder.h"
#include "net/cookies/cookie_monster.h" #include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_store.h" #include "net/cookies/cookie_store.h"
#include "net/cookies/cookie_util.h" #include "net/cookies/cookie_util.h"
#include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context.h"
@ -55,24 +55,20 @@ struct Converter<net::CanonicalCookie> {
}; };
template <> template <>
struct Converter<net::CookieStore::ChangeCause> { struct Converter<net::CookieChangeCause> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const net::CookieStore::ChangeCause& val) { const net::CookieChangeCause& val) {
switch (val) { switch (val) {
case net::CookieStore::ChangeCause::INSERTED: case net::CookieChangeCause::INSERTED:
case net::CookieStore::ChangeCause::EXPLICIT: case net::CookieChangeCause::EXPLICIT:
case net::CookieStore::ChangeCause::EXPLICIT_DELETE_BETWEEN:
case net::CookieStore::ChangeCause::EXPLICIT_DELETE_PREDICATE:
case net::CookieStore::ChangeCause::EXPLICIT_DELETE_SINGLE:
case net::CookieStore::ChangeCause::EXPLICIT_DELETE_CANONICAL:
return mate::StringToV8(isolate, "explicit"); return mate::StringToV8(isolate, "explicit");
case net::CookieStore::ChangeCause::OVERWRITE: case net::CookieChangeCause::OVERWRITE:
return mate::StringToV8(isolate, "overwrite"); return mate::StringToV8(isolate, "overwrite");
case net::CookieStore::ChangeCause::EXPIRED: case net::CookieChangeCause::EXPIRED:
return mate::StringToV8(isolate, "expired"); return mate::StringToV8(isolate, "expired");
case net::CookieStore::ChangeCause::EVICTED: case net::CookieChangeCause::EVICTED:
return mate::StringToV8(isolate, "evicted"); return mate::StringToV8(isolate, "evicted");
case net::CookieStore::ChangeCause::EXPIRED_OVERWRITE: case net::CookieChangeCause::EXPIRED_OVERWRITE:
return mate::StringToV8(isolate, "expired-overwrite"); return mate::StringToV8(isolate, "expired-overwrite");
default: default:
return mate::StringToV8(isolate, "unknown"); return mate::StringToV8(isolate, "unknown");
@ -229,10 +225,27 @@ void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter,
: base::Time::FromDoubleT(last_access_date); : base::Time::FromDoubleT(last_access_date);
} }
GetCookieStore(getter)->SetCookieWithDetailsAsync( std::unique_ptr<net::CanonicalCookie> canonical_cookie(
GURL(url), name, value, domain, path, creation_time, expiration_time, net::CanonicalCookie::CreateSanitizedCookie(
last_access_time, secure, http_only, net::CookieSameSite::DEFAULT_MODE, GURL(url), name, value, domain, path, creation_time, expiration_time,
net::COOKIE_PRIORITY_DEFAULT, base::BindOnce(OnSetCookie, callback)); last_access_time, secure, http_only,
net::CookieSameSite::DEFAULT_MODE, net::COOKIE_PRIORITY_DEFAULT));
auto completion_callback = base::BindOnce(OnSetCookie, callback);
if (!canonical_cookie || !canonical_cookie->IsCanonical()) {
std::move(completion_callback).Run(false);
return;
}
if (url.empty()) {
std::move(completion_callback).Run(false);
return;
}
if (name.empty()) {
std::move(completion_callback).Run(false);
return;
}
GetCookieStore(getter)->SetCanonicalCookieAsync(
std::move(canonical_cookie), secure, http_only,
std::move(completion_callback));
} }
} // namespace } // namespace

View file

@ -32,11 +32,8 @@ Debugger::Debugger(v8::Isolate* isolate, content::WebContents* web_contents)
Debugger::~Debugger() {} Debugger::~Debugger() {}
void Debugger::AgentHostClosed(DevToolsAgentHost* agent_host, void Debugger::AgentHostClosed(DevToolsAgentHost* agent_host) {
bool replaced_with_another_client) {
std::string detach_reason = "target closed"; std::string detach_reason = "target closed";
if (replaced_with_another_client)
detach_reason = "replaced with devtools";
Emit("detach", detach_reason); Emit("detach", detach_reason);
} }
@ -110,7 +107,7 @@ void Debugger::Detach() {
if (!agent_host_.get()) if (!agent_host_.get())
return; return;
agent_host_->DetachClient(this); agent_host_->DetachClient(this);
AgentHostClosed(agent_host_.get(), false); AgentHostClosed(agent_host_.get());
agent_host_ = nullptr; agent_host_ = nullptr;
} }

View file

@ -46,8 +46,7 @@ class Debugger : public mate::TrackableObject<Debugger>,
~Debugger() override; ~Debugger() override;
// content::DevToolsAgentHostClient: // content::DevToolsAgentHostClient:
void AgentHostClosed(content::DevToolsAgentHost* agent_host, void AgentHostClosed(content::DevToolsAgentHost* agent_host) override;
bool replaced_with_another_client) override;
void DispatchProtocolMessage(content::DevToolsAgentHost* agent_host, void DispatchProtocolMessage(content::DevToolsAgentHost* agent_host,
const std::string& message) override; const std::string& message) override;

View file

@ -12,7 +12,10 @@ using base::PlatformThreadRef;
#include "atom/common/native_mate_converters/gfx_converter.h" #include "atom/common/native_mate_converters/gfx_converter.h"
#include "base/strings/string_number_conversions.h" #include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h" #include "base/strings/utf_string_conversions.h"
#include "base/task_scheduler/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/media/desktop_media_list.h" #include "chrome/browser/media/desktop_media_list.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/desktop_capture.h" #include "content/public/browser/desktop_capture.h"
#include "native_mate/dictionary.h" #include "native_mate/dictionary.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h"
@ -45,54 +48,42 @@ struct Converter<atom::api::DesktopCapturer::Source> {
} // namespace mate } // namespace mate
namespace atom { namespace {
namespace api { void EmitFinished(
const std::vector<atom::api::DesktopCapturer::Source>& sources,
DesktopCapturer::DesktopCapturer(v8::Isolate* isolate) { atom::api::DesktopCapturer* cap) {
Init(isolate); cap->Emit("finished", sources);
} }
DesktopCapturer::~DesktopCapturer() {} void StartHandlingTask(bool capture_window,
bool capture_screen,
void DesktopCapturer::StartHandling(bool capture_window, const gfx::Size& thumbnail_size,
bool capture_screen, atom::api::DesktopCapturer* cap) {
const gfx::Size& thumbnail_size) {
webrtc::DesktopCaptureOptions options =
content::CreateDesktopCaptureOptions();
#if defined(OS_WIN) #if defined(OS_WIN)
using_directx_capturer_ = options.allow_directx_capturer(); cap->using_directx_capturer_ =
content::desktop_capture::CreateDesktopCaptureOptions()
.allow_directx_capturer();
#endif // defined(OS_WIN) #endif // defined(OS_WIN)
std::unique_ptr<webrtc::DesktopCapturer> screen_capturer( std::unique_ptr<webrtc::DesktopCapturer> screen_capturer(
capture_screen ? webrtc::DesktopCapturer::CreateScreenCapturer(options) capture_screen ? content::desktop_capture::CreateScreenCapturer()
: nullptr); : nullptr);
std::unique_ptr<webrtc::DesktopCapturer> window_capturer( std::unique_ptr<webrtc::DesktopCapturer> window_capturer(
capture_window ? webrtc::DesktopCapturer::CreateWindowCapturer(options) capture_window ? content::desktop_capture::CreateScreenCapturer()
: nullptr); : nullptr);
media_list_.reset(new NativeDesktopMediaList(std::move(screen_capturer), cap->media_list_.reset(new NativeDesktopMediaList(
std::move(window_capturer))); std::move(screen_capturer), std::move(window_capturer)));
media_list_->SetThumbnailSize(thumbnail_size); cap->media_list_->SetThumbnailSize(thumbnail_size);
media_list_->StartUpdating(this); cap->media_list_->StartUpdating(cap);
} }
void DesktopCapturer::OnSourceAdded(int index) {} void OnRefreshFinishedTask(atom::api::DesktopCapturer* cap) {
const auto media_list_sources = cap->media_list_->GetSources();
void DesktopCapturer::OnSourceRemoved(int index) {} std::vector<atom::api::DesktopCapturer::Source> sources;
void DesktopCapturer::OnSourceMoved(int old_index, int new_index) {}
void DesktopCapturer::OnSourceNameChanged(int index) {}
void DesktopCapturer::OnSourceThumbnailChanged(int index) {}
bool DesktopCapturer::OnRefreshFinished() {
const auto media_list_sources = media_list_->GetSources();
std::vector<DesktopCapturer::Source> sources;
for (const auto& media_list_source : media_list_sources) { for (const auto& media_list_source : media_list_sources) {
sources.emplace_back( sources.emplace_back(
DesktopCapturer::Source{media_list_source, std::string()}); atom::api::DesktopCapturer::Source{media_list_source, std::string()});
} }
#if defined(OS_WIN) #if defined(OS_WIN)
@ -100,7 +91,7 @@ bool DesktopCapturer::OnRefreshFinished() {
// to provide an association between it and desktopCapturer/getUserMedia. // to provide an association between it and desktopCapturer/getUserMedia.
// This is only required when using the DirectX capturer, otherwise the IDs // This is only required when using the DirectX capturer, otherwise the IDs
// across the APIs already match. // across the APIs already match.
if (using_directx_capturer_) { if (cap->using_directx_capturer_) {
std::vector<std::string> device_names; std::vector<std::string> device_names;
// Crucially, this list of device names will be in the same order as // Crucially, this list of device names will be in the same order as
// |media_list_sources|. // |media_list_sources|.
@ -133,7 +124,46 @@ bool DesktopCapturer::OnRefreshFinished() {
// supports capturing the entire desktop on Linux. Revisit this if individual // supports capturing the entire desktop on Linux. Revisit this if individual
// screen support is added. // screen support is added.
Emit("finished", sources); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(EmitFinished, sources, cap));
}
} // namespace
namespace atom {
namespace api {
DesktopCapturer::DesktopCapturer(v8::Isolate* isolate) {
Init(isolate);
capture_thread_ = base::CreateSequencedTaskRunnerWithTraits(
{base::WithBaseSyncPrimitives(), base::MayBlock(),
base::TaskPriority::USER_VISIBLE});
}
DesktopCapturer::~DesktopCapturer() {}
void DesktopCapturer::StartHandling(bool capture_window,
bool capture_screen,
const gfx::Size& thumbnail_size) {
capture_thread_->PostTask(
FROM_HERE, base::BindOnce(StartHandlingTask, capture_window,
capture_screen, thumbnail_size, this));
}
void DesktopCapturer::OnSourceAdded(int index) {}
void DesktopCapturer::OnSourceRemoved(int index) {}
void DesktopCapturer::OnSourceMoved(int old_index, int new_index) {}
void DesktopCapturer::OnSourceNameChanged(int index) {}
void DesktopCapturer::OnSourceThumbnailChanged(int index) {}
bool DesktopCapturer::OnRefreshFinished() {
capture_thread_->PostTask(FROM_HERE,
base::BindOnce(OnRefreshFinishedTask, this));
return false; return false;
} }

View file

@ -34,6 +34,11 @@ class DesktopCapturer : public mate::EventEmitter<DesktopCapturer>,
bool capture_screen, bool capture_screen,
const gfx::Size& thumbnail_size); const gfx::Size& thumbnail_size);
std::unique_ptr<DesktopMediaList> media_list_;
#if defined(OS_WIN)
bool using_directx_capturer_;
#endif // defined(OS_WIN)
protected: protected:
explicit DesktopCapturer(v8::Isolate* isolate); explicit DesktopCapturer(v8::Isolate* isolate);
~DesktopCapturer() override; ~DesktopCapturer() override;
@ -47,10 +52,7 @@ class DesktopCapturer : public mate::EventEmitter<DesktopCapturer>,
bool OnRefreshFinished() override; bool OnRefreshFinished() override;
private: private:
std::unique_ptr<DesktopMediaList> media_list_; scoped_refptr<base::SequencedTaskRunner> capture_thread_;
#if defined(OS_WIN)
bool using_directx_capturer_;
#endif // defined(OS_WIN)
DISALLOW_COPY_AND_ASSIGN(DesktopCapturer); DISALLOW_COPY_AND_ASSIGN(DesktopCapturer);
}; };

View file

@ -20,21 +20,22 @@
namespace mate { namespace mate {
template <> template <>
struct Converter<content::DownloadItem::DownloadState> { struct Converter<download::DownloadItem::DownloadState> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, static v8::Local<v8::Value> ToV8(
content::DownloadItem::DownloadState state) { v8::Isolate* isolate,
download::DownloadItem::DownloadState state) {
std::string download_state; std::string download_state;
switch (state) { switch (state) {
case content::DownloadItem::IN_PROGRESS: case download::DownloadItem::IN_PROGRESS:
download_state = "progressing"; download_state = "progressing";
break; break;
case content::DownloadItem::COMPLETE: case download::DownloadItem::COMPLETE:
download_state = "completed"; download_state = "completed";
break; break;
case content::DownloadItem::CANCELLED: case download::DownloadItem::CANCELLED:
download_state = "cancelled"; download_state = "cancelled";
break; break;
case content::DownloadItem::INTERRUPTED: case download::DownloadItem::INTERRUPTED:
download_state = "interrupted"; download_state = "interrupted";
break; break;
default: default:
@ -57,7 +58,7 @@ std::map<uint32_t, v8::Global<v8::Object>> g_download_item_objects;
} // namespace } // namespace
DownloadItem::DownloadItem(v8::Isolate* isolate, DownloadItem::DownloadItem(v8::Isolate* isolate,
content::DownloadItem* download_item) download::DownloadItem* download_item)
: download_item_(download_item) { : download_item_(download_item) {
download_item_->AddObserver(this); download_item_->AddObserver(this);
Init(isolate); Init(isolate);
@ -75,7 +76,7 @@ DownloadItem::~DownloadItem() {
g_download_item_objects.erase(weak_map_id()); g_download_item_objects.erase(weak_map_id());
} }
void DownloadItem::OnDownloadUpdated(content::DownloadItem* item) { void DownloadItem::OnDownloadUpdated(download::DownloadItem* item) {
if (download_item_->IsDone()) { if (download_item_->IsDone()) {
Emit("done", item->GetState()); Emit("done", item->GetState());
// Destroy the item once item is downloaded. // Destroy the item once item is downloaded.
@ -86,7 +87,7 @@ void DownloadItem::OnDownloadUpdated(content::DownloadItem* item) {
} }
} }
void DownloadItem::OnDownloadDestroyed(content::DownloadItem* download_item) { void DownloadItem::OnDownloadDestroyed(download::DownloadItem* download_item) {
download_item_ = nullptr; download_item_ = nullptr;
// Destroy the native class immediately when downloadItem is destroyed. // Destroy the native class immediately when downloadItem is destroyed.
delete this; delete this;
@ -148,7 +149,7 @@ const std::vector<GURL>& DownloadItem::GetURLChain() const {
return download_item_->GetUrlChain(); return download_item_->GetUrlChain();
} }
content::DownloadItem::DownloadState DownloadItem::GetState() const { download::DownloadItem::DownloadState DownloadItem::GetState() const {
return download_item_->GetState(); return download_item_->GetState();
} }
@ -206,7 +207,7 @@ void DownloadItem::BuildPrototype(v8::Isolate* isolate,
// static // static
mate::Handle<DownloadItem> DownloadItem::Create(v8::Isolate* isolate, mate::Handle<DownloadItem> DownloadItem::Create(v8::Isolate* isolate,
content::DownloadItem* item) { download::DownloadItem* item) {
auto* existing = TrackableObject::FromWrappedClass(isolate, item); auto* existing = TrackableObject::FromWrappedClass(isolate, item);
if (existing) if (existing)
return mate::CreateHandle(isolate, static_cast<DownloadItem*>(existing)); return mate::CreateHandle(isolate, static_cast<DownloadItem*>(existing));

View file

@ -10,7 +10,7 @@
#include "atom/browser/api/trackable_object.h" #include "atom/browser/api/trackable_object.h"
#include "base/files/file_path.h" #include "base/files/file_path.h"
#include "content/public/browser/download_item.h" #include "components/download/public/common/download_item.h"
#include "native_mate/handle.h" #include "native_mate/handle.h"
#include "url/gurl.h" #include "url/gurl.h"
@ -19,10 +19,10 @@ namespace atom {
namespace api { namespace api {
class DownloadItem : public mate::TrackableObject<DownloadItem>, class DownloadItem : public mate::TrackableObject<DownloadItem>,
public content::DownloadItem::Observer { public download::DownloadItem::Observer {
public: public:
static mate::Handle<DownloadItem> Create(v8::Isolate* isolate, static mate::Handle<DownloadItem> Create(v8::Isolate* isolate,
content::DownloadItem* item); download::DownloadItem* item);
static void BuildPrototype(v8::Isolate* isolate, static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype); v8::Local<v8::FunctionTemplate> prototype);
@ -40,7 +40,7 @@ class DownloadItem : public mate::TrackableObject<DownloadItem>,
std::string GetContentDisposition() const; std::string GetContentDisposition() const;
const GURL& GetURL() const; const GURL& GetURL() const;
const std::vector<GURL>& GetURLChain() const; const std::vector<GURL>& GetURLChain() const;
content::DownloadItem::DownloadState GetState() const; download::DownloadItem::DownloadState GetState() const;
bool IsDone() const; bool IsDone() const;
void SetSavePath(const base::FilePath& path); void SetSavePath(const base::FilePath& path);
base::FilePath GetSavePath() const; base::FilePath GetSavePath() const;
@ -49,16 +49,16 @@ class DownloadItem : public mate::TrackableObject<DownloadItem>,
double GetStartTime() const; double GetStartTime() const;
protected: protected:
DownloadItem(v8::Isolate* isolate, content::DownloadItem* download_item); DownloadItem(v8::Isolate* isolate, download::DownloadItem* download_item);
~DownloadItem() override; ~DownloadItem() override;
// Override content::DownloadItem::Observer methods // Override download::DownloadItem::Observer methods
void OnDownloadUpdated(content::DownloadItem* download) override; void OnDownloadUpdated(download::DownloadItem* download) override;
void OnDownloadDestroyed(content::DownloadItem* download) override; void OnDownloadDestroyed(download::DownloadItem* download) override;
private: private:
base::FilePath save_path_; base::FilePath save_path_;
content::DownloadItem* download_item_; download::DownloadItem* download_item_;
DISALLOW_COPY_AND_ASSIGN(DownloadItem); DISALLOW_COPY_AND_ASSIGN(DownloadItem);
}; };

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.
#include "atom/browser/api/atom_api_label_button.h"
#include "atom/common/api/constructor.h"
#include "base/strings/utf_string_conversions.h"
#include "native_mate/dictionary.h"
#include "ui/views/controls/button/label_button.h"
#include "atom/common/node_includes.h"
namespace atom {
namespace api {
LabelButton::LabelButton(const std::string& text)
: Button(new views::LabelButton(this, base::UTF8ToUTF16(text))) {}
LabelButton::~LabelButton() {}
// static
mate::WrappableBase* LabelButton::New(mate::Arguments* args,
const std::string& text) {
// Constructor call.
auto* view = new LabelButton(text);
view->InitWith(args->isolate(), args->GetThis());
return view;
}
// static
void LabelButton::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "LabelButton"));
}
} // namespace api
} // namespace atom
namespace {
using atom::api::LabelButton;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("LabelButton", mate::CreateConstructor<LabelButton>(
isolate, base::Bind(&LabelButton::New)));
}
} // namespace
NODE_BUILTIN_MODULE_CONTEXT_AWARE(atom_browser_label_button, Initialize)

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_API_ATOM_API_LABEL_BUTTON_H_
#define ATOM_BROWSER_API_ATOM_API_LABEL_BUTTON_H_
#include <string>
#include "atom/browser/api/atom_api_button.h"
namespace atom {
namespace api {
class LabelButton : public Button {
public:
static mate::WrappableBase* New(mate::Arguments* args,
const std::string& text);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
protected:
explicit LabelButton(const std::string& text);
~LabelButton() override;
private:
DISALLOW_COPY_AND_ASSIGN(LabelButton);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_LABEL_BUTTON_H_

View file

@ -46,8 +46,8 @@ void MenuViews::PopupAt(TopLevelWindow* window,
int32_t window_id = window->weak_map_id(); int32_t window_id = window->weak_map_id();
auto close_callback = base::Bind( auto close_callback = base::Bind(
&MenuViews::OnClosed, weak_factory_.GetWeakPtr(), window_id, callback); &MenuViews::OnClosed, weak_factory_.GetWeakPtr(), window_id, callback);
menu_runners_[window_id] = std::unique_ptr<MenuRunner>( menu_runners_[window_id] =
new MenuRunner(model(), flags, close_callback)); std::make_unique<MenuRunner>(model(), flags, close_callback);
menu_runners_[window_id]->RunMenuAt( menu_runners_[window_id]->RunMenuAt(
native_window->widget(), NULL, gfx::Rect(location, gfx::Size()), native_window->widget(), NULL, gfx::Rect(location, gfx::Size()),
views::MENU_ANCHOR_TOPLEFT, ui::MENU_SOURCE_MOUSE); views::MENU_ANCHOR_TOPLEFT, ui::MENU_SOURCE_MOUSE);

View file

@ -0,0 +1,90 @@
// 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/api/atom_api_net_log.h"
#include "atom/browser/atom_browser_client.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "base/callback.h"
#include "content/public/common/content_switches.h"
#include "native_mate/dictionary.h"
#include "native_mate/handle.h"
#include "atom/common/node_includes.h"
namespace atom {
namespace api {
NetLog::NetLog(v8::Isolate* isolate) {
Init(isolate);
net_log_ = atom::AtomBrowserClient::Get()->GetNetLog();
}
NetLog::~NetLog() {}
// static
v8::Local<v8::Value> NetLog::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new NetLog(isolate)).ToV8();
}
void NetLog::StartLogging(mate::Arguments* args) {
base::FilePath log_path;
if (!args->GetNext(&log_path) || log_path.empty()) {
args->ThrowError("The first parameter must be a valid string");
return;
}
net_log_->StartDynamicLogging(log_path);
}
bool NetLog::IsCurrentlyLogging() {
return net_log_->IsDynamicLogging();
}
base::FilePath::StringType NetLog::GetCurrentlyLoggingPath() {
return net_log_->GetDynamicLoggingPath().value();
}
void NetLog::StopLogging(mate::Arguments* args) {
base::OnceClosure callback;
args->GetNext(&callback);
net_log_->StopDynamicLogging(std::move(callback));
}
// static
void NetLog::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "NetLog"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetProperty("currentlyLogging", &NetLog::IsCurrentlyLogging)
.SetProperty("currentlyLoggingPath", &NetLog::GetCurrentlyLoggingPath)
.SetMethod("startLogging", &NetLog::StartLogging)
.SetMethod("_stopLogging", &NetLog::StopLogging);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::NetLog;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("netLog", NetLog::Create(isolate));
dict.Set("NetLog", NetLog::GetConstructor(isolate)->GetFunction());
}
} // namespace
NODE_BUILTIN_MODULE_CONTEXT_AWARE(atom_browser_net_log, Initialize)

View file

@ -0,0 +1,42 @@
// 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_API_ATOM_API_NET_LOG_H_
#define ATOM_BROWSER_API_ATOM_API_NET_LOG_H_
#include <string>
#include "brightray/browser/net_log.h"
#include "native_mate/wrappable.h"
namespace atom {
namespace api {
class NetLog : public mate::Wrappable<NetLog> {
public:
static v8::Local<v8::Value> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
void StartLogging(mate::Arguments* args);
bool IsCurrentlyLogging();
base::FilePath::StringType GetCurrentlyLoggingPath();
void StopLogging(mate::Arguments* args);
protected:
explicit NetLog(v8::Isolate* isolate);
~NetLog() override;
private:
brightray::NetLog* net_log_;
DISALLOW_COPY_AND_ASSIGN(NetLog);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_NET_LOG_H_

View file

@ -9,6 +9,7 @@
#include "atom/common/native_mate_converters/gfx_converter.h" #include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/native_mate_converters/image_converter.h" #include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/native_mate_converters/string16_converter.h"
#include "base/guid.h"
#include "base/strings/utf_string_conversions.h" #include "base/strings/utf_string_conversions.h"
#include "brightray/browser/browser_client.h" #include "brightray/browser/browser_client.h"
#include "native_mate/constructor.h" #include "native_mate/constructor.h"
@ -197,7 +198,7 @@ void Notification::Close() {
void Notification::Show() { void Notification::Show() {
Close(); Close();
if (presenter_) { if (presenter_) {
notification_ = presenter_->CreateNotification(this); notification_ = presenter_->CreateNotification(this, base::GenerateGUID());
if (notification_) { if (notification_) {
brightray::NotificationOptions options; brightray::NotificationOptions options;
options.title = title_; options.title = title_;

View file

@ -6,28 +6,26 @@
#include <string> #include <string>
#include "content/public/browser/browser_thread.h" #include "base/task_scheduler/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "native_mate/dictionary.h" #include "native_mate/dictionary.h"
#include "atom/common/node_includes.h" #include "atom/common/node_includes.h"
using content::BrowserThread;
namespace mate { namespace mate {
template <> template <>
struct Converter<device::PowerSaveBlocker::PowerSaveBlockerType> { struct Converter<device::mojom::WakeLockType> {
static bool FromV8(v8::Isolate* isolate, static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val, v8::Local<v8::Value> val,
device::PowerSaveBlocker::PowerSaveBlockerType* out) { device::mojom::WakeLockType* out) {
using device::PowerSaveBlocker;
std::string type; std::string type;
if (!ConvertFromV8(isolate, val, &type)) if (!ConvertFromV8(isolate, val, &type))
return false; return false;
if (type == "prevent-app-suspension") if (type == "prevent-app-suspension")
*out = PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension; *out = device::mojom::WakeLockType::kPreventAppSuspension;
else if (type == "prevent-display-sleep") else if (type == "prevent-display-sleep")
*out = PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep; *out = device::mojom::WakeLockType::kPreventDisplaySleep;
else else
return false; return false;
return true; return true;
@ -42,7 +40,7 @@ namespace api {
PowerSaveBlocker::PowerSaveBlocker(v8::Isolate* isolate) PowerSaveBlocker::PowerSaveBlocker(v8::Isolate* isolate)
: current_blocker_type_( : current_blocker_type_(
device::PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension) { device::mojom::WakeLockType::kPreventAppSuspension) {
Init(isolate); Init(isolate);
} }
@ -54,37 +52,39 @@ void PowerSaveBlocker::UpdatePowerSaveBlocker() {
return; return;
} }
// |kPowerSaveBlockPreventAppSuspension| keeps system active, but allows // |WakeLockType::kPreventAppSuspension| keeps system active, but allows
// screen to be turned off. // screen to be turned off.
// |kPowerSaveBlockPreventDisplaySleep| keeps system and screen active, has a // |WakeLockType::kPreventDisplaySleep| keeps system and screen active, has a
// higher precedence level than |kPowerSaveBlockPreventAppSuspension|. // higher precedence level than |WakeLockType::kPreventAppSuspension|.
// //
// Only the highest-precedence blocker type takes effect. // Only the highest-precedence blocker type takes effect.
device::PowerSaveBlocker::PowerSaveBlockerType new_blocker_type = device::mojom::WakeLockType new_blocker_type =
device::PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension; device::mojom::WakeLockType::kPreventAppSuspension;
for (const auto& element : power_save_blocker_types_) { for (const auto& element : power_save_blocker_types_) {
if (element.second == if (element.second ==
device::PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep) { device::mojom::WakeLockType::kPreventDisplaySleep) {
new_blocker_type = new_blocker_type =
device::PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep; device::mojom::WakeLockType::kPreventDisplaySleep;
break; break;
} }
} }
if (!power_save_blocker_ || new_blocker_type != current_blocker_type_) { if (!power_save_blocker_ || new_blocker_type != current_blocker_type_) {
std::unique_ptr<device::PowerSaveBlocker> new_blocker( auto new_blocker = std::make_unique<device::PowerSaveBlocker>(
new device::PowerSaveBlocker( new_blocker_type, device::mojom::WakeLockReason::kOther,
new_blocker_type, device::PowerSaveBlocker::kReasonOther, ATOM_PRODUCT_NAME, base::ThreadTaskRunnerHandle::Get(),
ATOM_PRODUCT_NAME, // This task runner may be used by some device service
BrowserThread::GetTaskRunnerForThread(BrowserThread::UI), // implementation bits to interface with dbus client code, which in
BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE))); // turn imposes some subtle thread affinity on the clients. We
// therefore require a single-thread runner.
base::CreateSingleThreadTaskRunnerWithTraits(
{base::MayBlock(), base::TaskPriority::BACKGROUND}));
power_save_blocker_.swap(new_blocker); power_save_blocker_.swap(new_blocker);
current_blocker_type_ = new_blocker_type; current_blocker_type_ = new_blocker_type;
} }
} }
int PowerSaveBlocker::Start( int PowerSaveBlocker::Start(device::mojom::WakeLockType type) {
device::PowerSaveBlocker::PowerSaveBlockerType type) {
static int count = 0; static int count = 0;
power_save_blocker_types_[count] = type; power_save_blocker_types_[count] = type;
UpdatePowerSaveBlocker(); UpdatePowerSaveBlocker();

View file

@ -33,19 +33,18 @@ class PowerSaveBlocker : public mate::TrackableObject<PowerSaveBlocker> {
private: private:
void UpdatePowerSaveBlocker(); void UpdatePowerSaveBlocker();
int Start(device::PowerSaveBlocker::PowerSaveBlockerType type); int Start(device::mojom::WakeLockType type);
bool Stop(int id); bool Stop(int id);
bool IsStarted(int id); bool IsStarted(int id);
std::unique_ptr<device::PowerSaveBlocker> power_save_blocker_; std::unique_ptr<device::PowerSaveBlocker> power_save_blocker_;
// Currnet blocker type used by |power_save_blocker_| // Current blocker type used by |power_save_blocker_|
device::PowerSaveBlocker::PowerSaveBlockerType current_blocker_type_; device::mojom::WakeLockType current_blocker_type_;
// Map from id to the corresponding blocker type for each request. // Map from id to the corresponding blocker type for each request.
using PowerSaveBlockerTypeMap = using WakeLockTypeMap = std::map<int, device::mojom::WakeLockType>;
std::map<int, device::PowerSaveBlocker::PowerSaveBlockerType>; WakeLockTypeMap power_save_blocker_types_;
PowerSaveBlockerTypeMap power_save_blocker_types_;
DISALLOW_COPY_AND_ASSIGN(PowerSaveBlocker); DISALLOW_COPY_AND_ASSIGN(PowerSaveBlocker);
}; };

View file

@ -117,9 +117,8 @@ class Protocol : public mate::TrackableObject<Protocol> {
request_context_getter->job_factory()); request_context_getter->job_factory());
if (job_factory->IsHandledProtocol(scheme)) if (job_factory->IsHandledProtocol(scheme))
return PROTOCOL_REGISTERED; return PROTOCOL_REGISTERED;
std::unique_ptr<CustomProtocolHandler<RequestJob>> protocol_handler( auto protocol_handler = std::make_unique<CustomProtocolHandler<RequestJob>>(
new CustomProtocolHandler<RequestJob>( isolate, request_context_getter.get(), handler);
isolate, request_context_getter.get(), handler));
if (job_factory->SetProtocolHandler(scheme, std::move(protocol_handler))) if (job_factory->SetProtocolHandler(scheme, std::move(protocol_handler)))
return PROTOCOL_OK; return PROTOCOL_OK;
else else
@ -166,9 +165,8 @@ class Protocol : public mate::TrackableObject<Protocol> {
// It is possible a protocol is handled but can not be intercepted. // It is possible a protocol is handled but can not be intercepted.
if (!job_factory->HasProtocolHandler(scheme)) if (!job_factory->HasProtocolHandler(scheme))
return PROTOCOL_FAIL; return PROTOCOL_FAIL;
std::unique_ptr<CustomProtocolHandler<RequestJob>> protocol_handler( auto protocol_handler = std::make_unique<CustomProtocolHandler<RequestJob>>(
new CustomProtocolHandler<RequestJob>( isolate, request_context_getter.get(), handler);
isolate, request_context_getter.get(), handler));
if (!job_factory->InterceptProtocol(scheme, std::move(protocol_handler))) if (!job_factory->InterceptProtocol(scheme, std::move(protocol_handler)))
return PROTOCOL_INTERCEPTED; return PROTOCOL_INTERCEPTED;
return PROTOCOL_OK; return PROTOCOL_OK;

View file

@ -33,10 +33,10 @@
#include "brightray/browser/media/media_device_id_salt.h" #include "brightray/browser/media/media_device_id_salt.h"
#include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process.h"
#include "chrome/common/pref_names.h" #include "chrome/common/pref_names.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/prefs/pref_service.h" #include "components/prefs/pref_service.h"
#include "content/common/devtools/devtools_network_conditions.h"
#include "content/common/devtools/devtools_network_controller.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_item_utils.h"
#include "content/public/browser/download_manager_delegate.h" #include "content/public/browser/download_manager_delegate.h"
#include "content/public/browser/storage_partition.h" #include "content/public/browser/storage_partition.h"
#include "native_mate/dictionary.h" #include "native_mate/dictionary.h"
@ -46,11 +46,13 @@
#include "net/dns/host_cache.h" #include "net/dns/host_cache.h"
#include "net/http/http_auth_handler_factory.h" #include "net/http/http_auth_handler_factory.h"
#include "net/http/http_auth_preferences.h" #include "net/http/http_auth_preferences.h"
#include "net/proxy/proxy_config_service_fixed.h" #include "net/proxy_resolution/proxy_config_service_fixed.h"
#include "net/proxy/proxy_service.h" #include "net/proxy_resolution/proxy_service.h"
#include "net/url_request/static_http_user_agent_settings.h" #include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h" #include "net/url_request/url_request_context_getter.h"
#include "services/network/throttling/network_conditions.h"
#include "services/network/throttling/throttling_controller.h"
#include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util.h"
using atom::api::Cookies; using atom::api::Cookies;
@ -261,8 +263,8 @@ class ResolveProxyHelper {
const GURL& url) { const GURL& url) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
net::ProxyService* proxy_service = net::ProxyResolutionService* proxy_service =
context_getter->GetURLRequestContext()->proxy_service(); context_getter->GetURLRequestContext()->proxy_resolution_service();
net::CompletionCallback completion_callback = base::Bind( net::CompletionCallback completion_callback = base::Bind(
&ResolveProxyHelper::OnResolveProxyCompleted, base::Unretained(this)); &ResolveProxyHelper::OnResolveProxyCompleted, base::Unretained(this));
@ -278,7 +280,7 @@ class ResolveProxyHelper {
Session::ResolveProxyCallback callback_; Session::ResolveProxyCallback callback_;
net::ProxyInfo proxy_info_; net::ProxyInfo proxy_info_;
net::ProxyService::PacRequest* pac_req_; net::ProxyResolutionService::Request* pac_req_;
scoped_refptr<base::SingleThreadTaskRunner> original_thread_; scoped_refptr<base::SingleThreadTaskRunner> original_thread_;
DISALLOW_COPY_AND_ASSIGN(ResolveProxyHelper); DISALLOW_COPY_AND_ASSIGN(ResolveProxyHelper);
@ -344,7 +346,8 @@ void DoCacheActionInIO(
void SetProxyInIO(scoped_refptr<net::URLRequestContextGetter> getter, void SetProxyInIO(scoped_refptr<net::URLRequestContextGetter> getter,
const net::ProxyConfig& config, const net::ProxyConfig& config,
const base::Closure& callback) { const base::Closure& callback) {
auto* proxy_service = getter->GetURLRequestContext()->proxy_service(); auto* proxy_service =
getter->GetURLRequestContext()->proxy_resolution_service();
proxy_service->ResetConfigService( proxy_service->ResetConfigService(
base::WrapUnique(new net::ProxyConfigServiceFixed(config))); base::WrapUnique(new net::ProxyConfigServiceFixed(config)));
// Refetches and applies the new pac script if provided. // Refetches and applies the new pac script if provided.
@ -409,7 +412,7 @@ void AllowNTLMCredentialsForDomainsInIO(
auto* auth_preferences = const_cast<net::HttpAuthPreferences*>( auto* auth_preferences = const_cast<net::HttpAuthPreferences*>(
auth_handler->http_auth_preferences()); auth_handler->http_auth_preferences());
if (auth_preferences) if (auth_preferences)
auth_preferences->set_server_whitelist(domains); auth_preferences->SetServerWhitelist(domains);
} }
} }
@ -432,10 +435,10 @@ void DownloadIdCallback(content::DownloadManager* download_manager,
base::GenerateGUID(), id, path, path, url_chain, GURL(), GURL(), GURL(), base::GenerateGUID(), id, path, path, url_chain, GURL(), GURL(), GURL(),
GURL(), mime_type, mime_type, start_time, base::Time(), etag, GURL(), mime_type, mime_type, start_time, base::Time(), etag,
last_modified, offset, length, std::string(), last_modified, offset, length, std::string(),
content::DownloadItem::INTERRUPTED, download::DownloadItem::INTERRUPTED,
content::DownloadDangerType::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
content::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT, false, base::Time(), download::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT, false, base::Time(),
false, std::vector<content::DownloadItem::ReceivedSlice>()); false, std::vector<download::DownloadItem::ReceivedSlice>());
} }
void SetDevToolsNetworkEmulationClientIdInIO( void SetDevToolsNetworkEmulationClientIdInIO(
@ -505,16 +508,18 @@ Session::~Session() {
} }
void Session::OnDownloadCreated(content::DownloadManager* manager, void Session::OnDownloadCreated(content::DownloadManager* manager,
content::DownloadItem* item) { download::DownloadItem* item) {
if (item->IsSavePackageDownload()) if (item->IsSavePackageDownload())
return; return;
v8::Locker locker(isolate()); v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate()); v8::HandleScope handle_scope(isolate());
auto handle = DownloadItem::Create(isolate(), item); auto handle = DownloadItem::Create(isolate(), item);
if (item->GetState() == content::DownloadItem::INTERRUPTED) if (item->GetState() == download::DownloadItem::INTERRUPTED)
handle->SetSavePath(item->GetTargetFilePath()); handle->SetSavePath(item->GetTargetFilePath());
bool prevent_default = Emit("will-download", handle, item->GetWebContents()); content::WebContents* web_contents =
content::DownloadItemUtils::GetWebContents(item);
bool prevent_default = Emit("will-download", handle, web_contents);
if (prevent_default) { if (prevent_default) {
item->Cancel(true); item->Cancel(true);
item->Remove(); item->Remove();
@ -575,20 +580,20 @@ void Session::SetDownloadPath(const base::FilePath& path) {
} }
void Session::EnableNetworkEmulation(const mate::Dictionary& options) { void Session::EnableNetworkEmulation(const mate::Dictionary& options) {
std::unique_ptr<content::DevToolsNetworkConditions> conditions; std::unique_ptr<network::NetworkConditions> conditions;
bool offline = false; bool offline = false;
double latency = 0.0, download_throughput = 0.0, upload_throughput = 0.0; double latency = 0.0, download_throughput = 0.0, upload_throughput = 0.0;
if (options.Get("offline", &offline) && offline) { if (options.Get("offline", &offline) && offline) {
conditions.reset(new content::DevToolsNetworkConditions(offline)); conditions.reset(new network::NetworkConditions(offline));
} else { } else {
options.Get("latency", &latency); options.Get("latency", &latency);
options.Get("downloadThroughput", &download_throughput); options.Get("downloadThroughput", &download_throughput);
options.Get("uploadThroughput", &upload_throughput); options.Get("uploadThroughput", &upload_throughput);
conditions.reset(new content::DevToolsNetworkConditions( conditions.reset(new network::NetworkConditions(
false, latency, download_throughput, upload_throughput)); false, latency, download_throughput, upload_throughput));
} }
content::DevToolsNetworkController::SetNetworkState( network::ThrottlingController::SetConditions(
devtools_network_emulation_client_id_, std::move(conditions)); devtools_network_emulation_client_id_, std::move(conditions));
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE, BrowserThread::IO, FROM_HERE,
@ -599,8 +604,8 @@ void Session::EnableNetworkEmulation(const mate::Dictionary& options) {
} }
void Session::DisableNetworkEmulation() { void Session::DisableNetworkEmulation() {
auto conditions = std::make_unique<content::DevToolsNetworkConditions>(); auto conditions = std::make_unique<network::NetworkConditions>();
content::DevToolsNetworkController::SetNetworkState( network::ThrottlingController::SetConditions(
devtools_network_emulation_client_id_, std::move(conditions)); devtools_network_emulation_client_id_, std::move(conditions));
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE, BrowserThread::IO, FROM_HERE,

View file

@ -95,7 +95,7 @@ class Session : public mate::TrackableObject<Session>,
// content::DownloadManager::Observer: // content::DownloadManager::Observer:
void OnDownloadCreated(content::DownloadManager* manager, void OnDownloadCreated(content::DownloadManager* manager,
content::DownloadItem* item) override; download::DownloadItem* item) override;
private: private:
// Cached object. // Cached object.

View file

@ -0,0 +1,67 @@
// 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/api/atom_api_text_field.h"
#include "atom/common/api/constructor.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
namespace atom {
namespace api {
TextField::TextField() : View(new views::Textfield()) {
view()->set_owned_by_client();
}
TextField::~TextField() {}
void TextField::SetText(const base::string16& new_text) {
text_field()->SetText(new_text);
}
base::string16 TextField::GetText() const {
return text_field()->text();
}
// static
mate::WrappableBase* TextField::New(mate::Arguments* args) {
// Constructor call.
auto* view = new TextField();
view->InitWith(args->isolate(), args->GetThis());
return view;
}
// static
void TextField::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "TextField"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("setText", &TextField::SetText)
.SetMethod("getText", &TextField::GetText);
}
} // namespace api
} // namespace atom
namespace {
using atom::api::TextField;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.Set("TextField", mate::CreateConstructor<TextField>(
isolate, base::Bind(&TextField::New)));
}
} // namespace
NODE_BUILTIN_MODULE_CONTEXT_AWARE(atom_browser_text_field, Initialize)

View file

@ -0,0 +1,42 @@
// 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_API_ATOM_API_TEXT_FIELD_H_
#define ATOM_BROWSER_API_ATOM_API_TEXT_FIELD_H_
#include "atom/browser/api/atom_api_view.h"
#include "native_mate/handle.h"
#include "ui/views/controls/textfield/textfield.h"
namespace atom {
namespace api {
class TextField : public View {
public:
static mate::WrappableBase* New(mate::Arguments* args);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
void SetText(const base::string16& new_text);
base::string16 GetText() const;
private:
TextField();
~TextField() override;
views::Textfield* text_field() const {
return static_cast<views::Textfield*>(view());
}
private:
DISALLOW_COPY_AND_ASSIGN(TextField);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_TEXT_FIELD_H_

View file

@ -51,6 +51,7 @@
#include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/image_converter.h" #include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/net_converter.h" #include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/native_mate_converters/network_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/value_converter.h" #include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/options_switches.h" #include "atom/common/options_switches.h"
@ -71,6 +72,7 @@
#include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/common/view_messages.h" #include "content/common/view_messages.h"
#include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/favicon_status.h" #include "content/public/browser/favicon_status.h"
#include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_details.h"
@ -82,7 +84,6 @@
#include "content/public/browser/render_view_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.h"
#include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/resource_request_details.h"
#include "content/public/browser/service_worker_context.h" #include "content/public/browser/service_worker_context.h"
#include "content/public/browser/site_instance.h" #include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h" #include "content/public/browser/storage_partition.h"
@ -96,7 +97,6 @@
#include "third_party/WebKit/public/web/WebFindOptions.h" #include "third_party/WebKit/public/web/WebFindOptions.h"
#include "ui/display/screen.h" #include "ui/display/screen.h"
#include "ui/events/base_event_utils.h" #include "ui/events/base_event_utils.h"
#include "ui/latency/latency_info.h"
#if !defined(OS_MACOSX) #if !defined(OS_MACOSX)
#include "ui/aura/window.h" #include "ui/aura/window.h"
@ -302,8 +302,7 @@ content::ServiceWorkerContext* GetServiceWorkerContext(
// Called when CapturePage is done. // Called when CapturePage is done.
void OnCapturePageDone(const base::Callback<void(const gfx::Image&)>& callback, void OnCapturePageDone(const base::Callback<void(const gfx::Image&)>& callback,
const SkBitmap& bitmap, const SkBitmap& bitmap) {
content::ReadbackResponse response) {
// Hack to enable transparency in captured image // Hack to enable transparency in captured image
// TODO(nitsakh) Remove hack once fixed in chromium // TODO(nitsakh) Remove hack once fixed in chromium
const_cast<SkBitmap&>(bitmap).setAlphaType(kPremul_SkAlphaType); const_cast<SkBitmap&>(bitmap).setAlphaType(kPremul_SkAlphaType);
@ -550,7 +549,7 @@ void WebContents::OnCreateWindow(
const std::string& frame_name, const std::string& frame_name,
WindowOpenDisposition disposition, WindowOpenDisposition disposition,
const std::vector<std::string>& features, const std::vector<std::string>& features,
const scoped_refptr<content::ResourceRequestBody>& body) { const scoped_refptr<network::ResourceRequestBody>& body) {
if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
Emit("-new-window", target_url, frame_name, disposition, features, body, Emit("-new-window", target_url, frame_name, disposition, features, body,
referrer); referrer);
@ -699,11 +698,13 @@ void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
void WebContents::RendererUnresponsive( void WebContents::RendererUnresponsive(
content::WebContents* source, content::WebContents* source,
const content::WebContentsUnresponsiveState& unresponsive_state) { content::RenderWidgetHost* render_widget_host) {
Emit("unresponsive"); Emit("unresponsive");
} }
void WebContents::RendererResponsive(content::WebContents* source) { void WebContents::RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) {
Emit("responsive"); Emit("responsive");
for (ExtendedWebContentsObserver& observer : observers_) for (ExtendedWebContentsObserver& observer : observers_)
observer.OnRendererResponsive(); observer.OnRendererResponsive();
@ -772,9 +773,7 @@ void WebContents::RequestToLockMouse(content::WebContents* web_contents,
std::unique_ptr<content::BluetoothChooser> WebContents::RunBluetoothChooser( std::unique_ptr<content::BluetoothChooser> WebContents::RunBluetoothChooser(
content::RenderFrameHost* frame, content::RenderFrameHost* frame,
const content::BluetoothChooser::EventHandler& event_handler) { const content::BluetoothChooser::EventHandler& event_handler) {
std::unique_ptr<BluetoothChooser> bluetooth_chooser( return std::make_unique<BluetoothChooser>(this, event_handler);
new BluetoothChooser(this, event_handler));
return std::move(bluetooth_chooser);
} }
content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
@ -785,6 +784,13 @@ content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
return dialog_manager_.get(); 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) { void WebContents::BeforeUnloadFired(const base::TimeTicks& proceed_time) {
// Do nothing, we override this method just to avoid compilation error since // Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired. // there are two virtual functions named BeforeUnloadFired.
@ -819,8 +825,10 @@ void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
Emit("media-started-playing"); Emit("media-started-playing");
} }
void WebContents::MediaStoppedPlaying(const MediaPlayerInfo& video_type, void WebContents::MediaStoppedPlaying(
const MediaPlayerId& id) { const MediaPlayerInfo& video_type,
const MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) {
Emit("media-paused"); Emit("media-paused");
} }
@ -869,30 +877,6 @@ void WebContents::DidStopLoading() {
Emit("did-stop-loading"); Emit("did-stop-loading");
} }
void WebContents::DidGetResourceResponseStart(
const content::ResourceRequestDetails& details) {
// Plznavigate is using blob URLs to deliver the body
// of the main resource to the renderer process. This
// gets better in the future with kNavigationMojoResponse
// feature, which replaces this mechanism with Mojo Datapipe.
if (details.url.SchemeIsBlob() &&
(details.resource_type == content::RESOURCE_TYPE_MAIN_FRAME ||
details.resource_type == content::RESOURCE_TYPE_SUB_FRAME))
return;
Emit("-did-get-response-details", details.socket_address.IsEmpty(),
details.url, details.original_url, details.http_response_code,
details.method, details.referrer, details.headers.get(),
ResourceTypeToString(details.resource_type));
}
void WebContents::DidGetRedirectForResourceRequest(
const content::ResourceRedirectDetails& details) {
Emit("-did-get-redirect-request", details.url, details.new_url,
(details.resource_type == content::RESOURCE_TYPE_MAIN_FRAME),
details.http_response_code, details.method, details.referrer,
details.headers.get());
}
void WebContents::DidStartNavigation( void WebContents::DidStartNavigation(
content::NavigationHandle* navigation_handle) { content::NavigationHandle* navigation_handle) {
bool is_main_frame = navigation_handle->IsInMainFrame(); bool is_main_frame = navigation_handle->IsInMainFrame();
@ -1037,8 +1021,19 @@ void WebContents::ShowAutofillPopup(content::RenderFrameHost* frame_host,
const std::vector<base::string16>& values, const std::vector<base::string16>& values,
const std::vector<base::string16>& labels) { const std::vector<base::string16>& labels) {
bool offscreen = IsOffScreen() || (embedder_ && embedder_->IsOffScreen()); bool offscreen = IsOffScreen() || (embedder_ && embedder_->IsOffScreen());
CommonWebContentsDelegate::ShowAutofillPopup(offscreen, frame_host, bounds, gfx::RectF popup_bounds(bounds);
values, labels); content::RenderFrameHost* embedder_frame_host = nullptr;
if (embedder_) {
auto* embedder_view = embedder_->web_contents()->GetMainFrame()->GetView();
auto* view = web_contents()->GetMainFrame()->GetView();
auto offset = view->GetViewBounds().origin() -
embedder_view->GetViewBounds().origin();
popup_bounds.Offset(offset.x(), offset.y());
embedder_frame_host = embedder_->web_contents()->GetMainFrame();
}
CommonWebContentsDelegate::ShowAutofillPopup(
frame_host, embedder_frame_host, offscreen, popup_bounds, values, labels);
} }
#endif #endif
@ -1166,7 +1161,7 @@ void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) {
if (options.Get("extraHeaders", &extra_headers)) if (options.Get("extraHeaders", &extra_headers))
params.extra_headers = extra_headers; params.extra_headers = extra_headers;
scoped_refptr<content::ResourceRequestBody> body; scoped_refptr<network::ResourceRequestBody> body;
if (options.Get("postData", &body)) { if (options.Get("postData", &body)) {
params.post_data = body; params.post_data = body;
params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
@ -1203,10 +1198,10 @@ void WebContents::DownloadURL(const GURL& url) {
auto* browser_context = web_contents()->GetBrowserContext(); auto* browser_context = web_contents()->GetBrowserContext();
auto* download_manager = auto* download_manager =
content::BrowserContext::GetDownloadManager(browser_context); content::BrowserContext::GetDownloadManager(browser_context);
std::unique_ptr<download::DownloadUrlParameters> download_params(
download_manager->DownloadUrl( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
content::DownloadUrlParameters::CreateForWebContentsMainFrame(
web_contents(), url, NO_TRAFFIC_ANNOTATION_YET)); web_contents(), url, NO_TRAFFIC_ANNOTATION_YET));
download_manager->DownloadUrl(std::move(download_params));
} }
GURL WebContents::GetURL() const { GURL WebContents::GetURL() const {
@ -1606,17 +1601,24 @@ bool WebContents::SendIPCMessage(bool all_frames,
void WebContents::SendInputEvent(v8::Isolate* isolate, void WebContents::SendInputEvent(v8::Isolate* isolate,
v8::Local<v8::Value> input_event) { v8::Local<v8::Value> input_event) {
auto* const view = static_cast<content::RenderWidgetHostViewBase*>( content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView()); web_contents()->GetRenderWidgetHostView();
if (!view) if (!view)
return; return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
blink::WebInputEvent::Type type = blink::WebInputEvent::Type type =
mate::GetWebInputEventType(isolate, input_event); mate::GetWebInputEventType(isolate, input_event);
if (blink::WebInputEvent::IsMouseEventType(type)) { if (blink::WebInputEvent::IsMouseEventType(type)) {
blink::WebMouseEvent mouse_event; blink::WebMouseEvent mouse_event;
if (mate::ConvertFromV8(isolate, input_event, &mouse_event)) { if (mate::ConvertFromV8(isolate, input_event, &mouse_event)) {
view->ProcessMouseEvent(mouse_event, ui::LatencyInfo()); if (IsOffScreen()) {
#if defined(ENABLE_OSR)
GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event);
#endif
} else {
rwh->ForwardMouseEvent(mouse_event);
}
return; return;
} }
} else if (blink::WebInputEvent::IsKeyboardEventType(type)) { } else if (blink::WebInputEvent::IsKeyboardEventType(type)) {
@ -1624,13 +1626,20 @@ void WebContents::SendInputEvent(v8::Isolate* isolate,
blink::WebKeyboardEvent::kRawKeyDown, blink::WebKeyboardEvent::kRawKeyDown,
blink::WebInputEvent::kNoModifiers, ui::EventTimeForNow()); blink::WebInputEvent::kNoModifiers, ui::EventTimeForNow());
if (mate::ConvertFromV8(isolate, input_event, &keyboard_event)) { if (mate::ConvertFromV8(isolate, input_event, &keyboard_event)) {
view->ProcessKeyboardEvent(keyboard_event, ui::LatencyInfo()); rwh->ForwardKeyboardEvent(keyboard_event);
return; return;
} }
} else if (type == blink::WebInputEvent::kMouseWheel) { } else if (type == blink::WebInputEvent::kMouseWheel) {
blink::WebMouseWheelEvent mouse_wheel_event; blink::WebMouseWheelEvent mouse_wheel_event;
if (mate::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (mate::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
view->ProcessMouseWheelEvent(mouse_wheel_event, ui::LatencyInfo()); if (IsOffScreen()) {
#if defined(ENABLE_OSR)
GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent(
mouse_wheel_event);
#endif
} else {
rwh->ForwardWheelEvent(mouse_wheel_event);
}
return; return;
} }
} }
@ -1649,18 +1658,12 @@ void WebContents::BeginFrameSubscription(mate::Arguments* args) {
return; return;
} }
auto* const view = web_contents()->GetRenderWidgetHostView(); frame_subscriber_.reset(
if (view) { new FrameSubscriber(isolate(), web_contents(), callback, only_dirty));
std::unique_ptr<FrameSubscriber> frame_subscriber(
new FrameSubscriber(isolate(), view, callback, only_dirty));
view->BeginFrameSubscription(std::move(frame_subscriber));
}
} }
void WebContents::EndFrameSubscription() { void WebContents::EndFrameSubscription() {
auto* const view = web_contents()->GetRenderWidgetHostView(); frame_subscriber_.reset();
if (view)
view->EndFrameSubscription();
} }
void WebContents::StartDrag(const mate::Dictionary& item, void WebContents::StartDrag(const mate::Dictionary& item,
@ -1733,8 +1736,7 @@ void WebContents::CapturePage(mate::Arguments* args) {
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size,
base::Bind(&OnCapturePageDone, callback), base::BindOnce(&OnCapturePageDone, callback));
kBGRA_8888_SkColorType);
} }
void WebContents::OnCursorChange(const content::WebCursor& cursor) { void WebContents::OnCursorChange(const content::WebCursor& cursor) {
@ -1833,8 +1835,7 @@ int WebContents::GetFrameRate() const {
void WebContents::Invalidate() { void WebContents::Invalidate() {
if (IsOffScreen()) { if (IsOffScreen()) {
#if defined(ENABLE_OSR) #if defined(ENABLE_OSR)
auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>( auto* osr_rwhv = GetOffScreenRenderWidgetHostView();
web_contents()->GetRenderWidgetHostView());
if (osr_rwhv) if (osr_rwhv)
osr_rwhv->Invalidate(); osr_rwhv->Invalidate();
#endif #endif
@ -1977,7 +1978,8 @@ v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
void WebContents::GrantOriginAccess(const GURL& url) { void WebContents::GrantOriginAccess(const GURL& url) {
content::ChildProcessSecurityPolicy::GetInstance()->GrantOrigin( content::ChildProcessSecurityPolicy::GetInstance()->GrantOrigin(
web_contents()->GetMainFrame()->GetProcess()->GetID(), url::Origin(url)); web_contents()->GetMainFrame()->GetProcess()->GetID(),
url::Origin::Create(url));
} }
// static // static

View file

@ -31,15 +31,15 @@ namespace brightray {
class InspectableWebContents; class InspectableWebContents;
} }
namespace content {
class ResourceRequestBody;
}
namespace mate { namespace mate {
class Arguments; class Arguments;
class Dictionary; class Dictionary;
} // namespace mate } // namespace mate
namespace network {
class ResourceRequestBody;
}
namespace atom { namespace atom {
struct SetSizeParams; struct SetSizeParams;
@ -47,9 +47,11 @@ class AtomBrowserContext;
class AtomJavaScriptDialogManager; class AtomJavaScriptDialogManager;
class WebContentsZoomController; class WebContentsZoomController;
class WebViewGuestDelegate; class WebViewGuestDelegate;
class FrameSubscriber;
#if defined(ENABLE_OSR) #if defined(ENABLE_OSR)
class OffScreenWebContentsView; class OffScreenWebContentsView;
class OffScreenRenderWidgetHostView;
#endif #endif
namespace api { namespace api {
@ -228,7 +230,7 @@ class WebContents : public mate::TrackableObject<WebContents>,
const std::string& frame_name, const std::string& frame_name,
WindowOpenDisposition disposition, WindowOpenDisposition disposition,
const std::vector<std::string>& features, const std::vector<std::string>& features,
const scoped_refptr<content::ResourceRequestBody>& body); const scoped_refptr<network::ResourceRequestBody>& body);
// Returns the web preferences of current WebContents. // Returns the web preferences of current WebContents.
v8::Local<v8::Value> GetWebPreferences(v8::Isolate* isolate); v8::Local<v8::Value> GetWebPreferences(v8::Isolate* isolate);
@ -310,8 +312,10 @@ class WebContents : public mate::TrackableObject<WebContents>,
void ExitFullscreenModeForTab(content::WebContents* source) override; void ExitFullscreenModeForTab(content::WebContents* source) override;
void RendererUnresponsive( void RendererUnresponsive(
content::WebContents* source, content::WebContents* source,
const content::WebContentsUnresponsiveState& unresponsive_state) override; content::RenderWidgetHost* render_widget_host) override;
void RendererResponsive(content::WebContents* source) override; void RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) override;
bool HandleContextMenu(const content::ContextMenuParams& params) override; bool HandleContextMenu(const content::ContextMenuParams& params) override;
bool OnGoToEntryOffset(int offset) override; bool OnGoToEntryOffset(int offset) override;
void FindReply(content::WebContents* web_contents, void FindReply(content::WebContents* web_contents,
@ -335,6 +339,8 @@ class WebContents : public mate::TrackableObject<WebContents>,
const content::BluetoothChooser::EventHandler& handler) override; const content::BluetoothChooser::EventHandler& handler) override;
content::JavaScriptDialogManager* GetJavaScriptDialogManager( content::JavaScriptDialogManager* GetJavaScriptDialogManager(
content::WebContents* source) override; content::WebContents* source) override;
void ResizeDueToAutoResize(content::WebContents* web_contents,
const gfx::Size& new_size) override;
// content::WebContentsObserver: // content::WebContentsObserver:
void BeforeUnloadFired(const base::TimeTicks& proceed_time) override; void BeforeUnloadFired(const base::TimeTicks& proceed_time) override;
@ -351,10 +357,6 @@ class WebContents : public mate::TrackableObject<WebContents>,
const base::string16& error_description) override; const base::string16& error_description) override;
void DidStartLoading() override; void DidStartLoading() override;
void DidStopLoading() override; void DidStopLoading() override;
void DidGetResourceResponseStart(
const content::ResourceRequestDetails& details) override;
void DidGetRedirectForResourceRequest(
const content::ResourceRedirectDetails& details) override;
void DidStartNavigation( void DidStartNavigation(
content::NavigationHandle* navigation_handle) override; content::NavigationHandle* navigation_handle) override;
void DidFinishNavigation( void DidFinishNavigation(
@ -372,8 +374,10 @@ class WebContents : public mate::TrackableObject<WebContents>,
base::ProcessId plugin_pid) override; base::ProcessId plugin_pid) override;
void MediaStartedPlaying(const MediaPlayerInfo& video_type, void MediaStartedPlaying(const MediaPlayerInfo& video_type,
const MediaPlayerId& id) override; const MediaPlayerId& id) override;
void MediaStoppedPlaying(const MediaPlayerInfo& video_type, void MediaStoppedPlaying(
const MediaPlayerId& id) override; const MediaPlayerInfo& video_type,
const MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) override;
void DidChangeThemeColor(SkColor theme_color) override; void DidChangeThemeColor(SkColor theme_color) override;
// brightray::InspectableWebContentsDelegate: // brightray::InspectableWebContentsDelegate:
@ -399,6 +403,7 @@ class WebContents : public mate::TrackableObject<WebContents>,
#if defined(ENABLE_OSR) #if defined(ENABLE_OSR)
OffScreenWebContentsView* GetOffScreenWebContentsView() const; OffScreenWebContentsView* GetOffScreenWebContentsView() const;
OffScreenRenderWidgetHostView* GetOffScreenRenderWidgetHostView() const;
#endif #endif
// Called when we receive a CursorChange message from chromium. // Called when we receive a CursorChange message from chromium.
@ -436,6 +441,8 @@ class WebContents : public mate::TrackableObject<WebContents>,
std::unique_ptr<AtomJavaScriptDialogManager> dialog_manager_; std::unique_ptr<AtomJavaScriptDialogManager> dialog_manager_;
std::unique_ptr<WebViewGuestDelegate> guest_delegate_; std::unique_ptr<WebViewGuestDelegate> guest_delegate_;
std::unique_ptr<FrameSubscriber> frame_subscriber_;
// The host webcontents that may contain this webcontents. // The host webcontents that may contain this webcontents.
WebContents* embedder_ = nullptr; WebContents* embedder_ = nullptr;

View file

@ -3,6 +3,7 @@
// found in the LICENSE file. // found in the LICENSE file.
#include "atom/browser/api/atom_api_web_contents.h" #include "atom/browser/api/atom_api_web_contents.h"
#include "content/public/browser/render_widget_host_view.h"
#import <Cocoa/Cocoa.h> #import <Cocoa/Cocoa.h>

View file

@ -4,6 +4,7 @@
#include "atom/browser/api/atom_api_web_contents.h" #include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/osr/osr_render_widget_host_view.h"
#include "atom/browser/osr/osr_web_contents_view.h" #include "atom/browser/osr/osr_web_contents_view.h"
#include "content/browser/web_contents/web_contents_impl.h" #include "content/browser/web_contents/web_contents_impl.h"
@ -21,6 +22,12 @@ OffScreenWebContentsView* WebContents::GetOffScreenWebContentsView() const {
return static_cast<OffScreenWebContentsView*>(impl->GetView()); return static_cast<OffScreenWebContentsView*>(impl->GetView());
} }
OffScreenRenderWidgetHostView* WebContents::GetOffScreenRenderWidgetHostView()
const {
return static_cast<OffScreenRenderWidgetHostView*>(
web_contents()->GetRenderWidgetHostView());
}
} // namespace api } // namespace api
} // namespace atom } // namespace atom

View file

@ -26,10 +26,11 @@ void PreventDefault(mate::Arguments* args) {
// Create a pure JavaScript Event object. // Create a pure JavaScript Event object.
v8::Local<v8::Object> CreateEventObject(v8::Isolate* isolate) { v8::Local<v8::Object> CreateEventObject(v8::Isolate* isolate) {
if (event_template.IsEmpty()) { if (event_template.IsEmpty()) {
event_template.Reset(isolate, event_template.Reset(
ObjectTemplateBuilder(isolate) isolate,
.SetMethod("preventDefault", &PreventDefault) ObjectTemplateBuilder(isolate, v8::ObjectTemplate::New(isolate))
.Build()); .SetMethod("preventDefault", &PreventDefault)
.Build());
} }
return v8::Local<v8::ObjectTemplate>::New(isolate, event_template) return v8::Local<v8::ObjectTemplate>::New(isolate, event_template)

View file

@ -5,104 +5,82 @@
#include "atom/browser/api/frame_subscriber.h" #include "atom/browser/api/frame_subscriber.h"
#include "atom/common/native_mate_converters/gfx_converter.h" #include "atom/common/native_mate_converters/gfx_converter.h"
#include "base/bind.h" #include "components/viz/common/frame_sinks/copy_output_request.h"
#include "content/public/browser/render_widget_host.h" #include "components/viz/service/frame_sinks/frame_sink_manager_impl.h"
#include "ui/display/display.h" #include "components/viz/service/surfaces/surface_manager.h"
#include "ui/display/screen.h" #include "content/browser/compositor/surface_utils.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "atom/common/node_includes.h" #include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/skbitmap_operations.h"
namespace atom { namespace atom {
namespace api { namespace api {
FrameSubscriber::FrameSubscriber(v8::Isolate* isolate, FrameSubscriber::FrameSubscriber(v8::Isolate* isolate,
content::RenderWidgetHostView* view, content::WebContents* web_contents,
const FrameCaptureCallback& callback, const FrameCaptureCallback& callback,
bool only_dirty) bool only_dirty)
: isolate_(isolate), : content::WebContentsObserver(web_contents),
view_(view), isolate_(isolate),
callback_(callback), callback_(callback),
only_dirty_(only_dirty), only_dirty_(only_dirty) {}
source_id_for_copy_request_(base::UnguessableToken::Create()),
weak_factory_(this) {}
FrameSubscriber::~FrameSubscriber() = default; FrameSubscriber::~FrameSubscriber() = default;
bool FrameSubscriber::ShouldCaptureFrame( gfx::Rect FrameSubscriber::GetDamageRect() {
const gfx::Rect& dirty_rect, auto* view = web_contents()->GetRenderWidgetHostView();
base::TimeTicks present_time, if (view == nullptr)
scoped_refptr<media::VideoFrame>* storage, return gfx::Rect();
DeliverFrameCallback* callback) {
if (!view_)
return false;
if (dirty_rect.IsEmpty()) auto* view_base = static_cast<content::RenderWidgetHostViewBase*>(view);
return false; viz::SurfaceManager* surface_manager =
content::GetFrameSinkManager()->surface_manager();
viz::Surface* surface =
surface_manager->GetSurfaceForId(view_base->GetCurrentSurfaceId());
if (surface == nullptr)
return gfx::Rect();
gfx::Rect rect = gfx::Rect(view_->GetVisibleViewportSize()); if (surface->HasActiveFrame()) {
if (only_dirty_) const viz::CompositorFrame& frame = surface->GetActiveFrame();
rect = dirty_rect; viz::RenderPass* root_pass = frame.render_pass_list.back().get();
gfx::Size frame_size = root_pass->output_rect.size();
gfx::Size view_size = rect.size(); gfx::Rect damage_rect =
gfx::Size bitmap_size = view_size; gfx::ToEnclosingRect(gfx::RectF(root_pass->damage_rect));
gfx::NativeView native_view = view_->GetNativeView(); damage_rect.Intersect(gfx::Rect(frame_size));
const float scale = display::Screen::GetScreen() return gfx::ScaleToEnclosedRect(damage_rect,
->GetDisplayNearestView(native_view) 1.0f / frame.device_scale_factor());
.device_scale_factor(); } else {
if (scale > 1.0f) return gfx::Rect();
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
rect = gfx::Rect(rect.origin(), bitmap_size);
view_->CopyFromSurface(
rect, rect.size(),
base::Bind(&FrameSubscriber::OnFrameDelivered, weak_factory_.GetWeakPtr(),
callback_, rect),
kBGRA_8888_SkColorType);
return false;
}
const base::UnguessableToken& FrameSubscriber::GetSourceIdForCopyRequest() {
return source_id_for_copy_request_;
}
void FrameSubscriber::OnFrameDelivered(const FrameCaptureCallback& callback,
const gfx::Rect& damage_rect,
const SkBitmap& bitmap,
content::ReadbackResponse response) {
if (response != content::ReadbackResponse::READBACK_SUCCESS)
return;
v8::Locker locker(isolate_);
v8::HandleScope handle_scope(isolate_);
size_t rgb_row_size = bitmap.width() * bitmap.bytesPerPixel();
v8::MaybeLocal<v8::Object> buffer =
node::Buffer::New(isolate_, rgb_row_size * bitmap.height());
if (buffer.IsEmpty())
return;
auto local_buffer = buffer.ToLocalChecked();
{
auto* source = static_cast<const unsigned char*>(bitmap.getPixels());
auto* target = node::Buffer::Data(local_buffer);
for (int y = 0; y < bitmap.height(); ++y) {
memcpy(target, source, rgb_row_size);
source += bitmap.rowBytes();
target += rgb_row_size;
}
} }
}
v8::Local<v8::Value> damage = void FrameSubscriber::DidReceiveCompositorFrame() {
mate::Converter<gfx::Rect>::ToV8(isolate_, damage_rect); auto* view = web_contents()->GetRenderWidgetHostView();
if (view == nullptr)
return;
callback_.Run(local_buffer, damage); view->CopyFromSurface(
gfx::Rect(), view->GetViewBounds().size(),
base::BindOnce(&FrameSubscriber::Done, base::Unretained(this),
GetDamageRect()));
}
void FrameSubscriber::Done(const gfx::Rect& damage, const SkBitmap& frame) {
if (frame.drawsNothing())
return;
const_cast<SkBitmap&>(frame).setAlphaType(kPremul_SkAlphaType);
v8::Local<v8::Value> damage_rect =
mate::Converter<gfx::Rect>::ToV8(isolate_, damage);
if (only_dirty_) {
const SkBitmap& damageFrame = SkBitmapOperations::CreateTiledBitmap(
frame, damage.x(), damage.y(), damage.width(), damage.height());
callback_.Run(gfx::Image::CreateFrom1xBitmap(damageFrame), damage_rect);
} else {
callback_.Run(gfx::Image::CreateFrom1xBitmap(frame), damage_rect);
}
} }
} // namespace api } // namespace api

View file

@ -5,51 +5,40 @@
#ifndef ATOM_BROWSER_API_FRAME_SUBSCRIBER_H_ #ifndef ATOM_BROWSER_API_FRAME_SUBSCRIBER_H_
#define ATOM_BROWSER_API_FRAME_SUBSCRIBER_H_ #define ATOM_BROWSER_API_FRAME_SUBSCRIBER_H_
#include "content/public/browser/web_contents.h"
#include "base/callback.h" #include "base/callback.h"
#include "base/memory/weak_ptr.h" #include "components/viz/common/frame_sinks/copy_output_result.h"
#include "content/browser/renderer_host/render_widget_host_view_frame_subscriber.h" #include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/readback_types.h" #include "ui/gfx/image/image.h"
#include "content/public/browser/render_widget_host_view.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/geometry/size.h"
#include "v8/include/v8.h" #include "v8/include/v8.h"
namespace atom { namespace atom {
namespace api { namespace api {
class FrameSubscriber : public content::RenderWidgetHostViewFrameSubscriber { class WebContents;
class FrameSubscriber : public content::WebContentsObserver {
public: public:
using FrameCaptureCallback = using FrameCaptureCallback =
base::Callback<void(v8::Local<v8::Value>, v8::Local<v8::Value>)>; base::Callback<void(const gfx::Image&, v8::Local<v8::Value>)>;
FrameSubscriber(v8::Isolate* isolate, FrameSubscriber(v8::Isolate* isolate,
content::RenderWidgetHostView* view, content::WebContents* web_contents,
const FrameCaptureCallback& callback, const FrameCaptureCallback& callback,
bool only_dirty); bool only_dirty);
~FrameSubscriber() override; ~FrameSubscriber();
bool ShouldCaptureFrame(const gfx::Rect& damage_rect,
base::TimeTicks present_time,
scoped_refptr<media::VideoFrame>* storage,
DeliverFrameCallback* callback) override;
const base::UnguessableToken& GetSourceIdForCopyRequest() override;
private: private:
void OnFrameDelivered(const FrameCaptureCallback& callback, gfx::Rect GetDamageRect();
const gfx::Rect& damage_rect, void DidReceiveCompositorFrame() override;
const SkBitmap& bitmap, void Done(const gfx::Rect& damage, const SkBitmap& frame);
content::ReadbackResponse response);
v8::Isolate* isolate_; v8::Isolate* isolate_;
content::RenderWidgetHostView* view_;
FrameCaptureCallback callback_; FrameCaptureCallback callback_;
bool only_dirty_; bool only_dirty_;
base::UnguessableToken source_id_for_copy_request_;
base::WeakPtrFactory<FrameSubscriber> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(FrameSubscriber); DISALLOW_COPY_AND_ASSIGN(FrameSubscriber);
}; };

View file

@ -22,7 +22,7 @@ SavePageHandler::SavePageHandler(content::WebContents* web_contents,
SavePageHandler::~SavePageHandler() {} SavePageHandler::~SavePageHandler() {}
void SavePageHandler::OnDownloadCreated(content::DownloadManager* manager, void SavePageHandler::OnDownloadCreated(content::DownloadManager* manager,
content::DownloadItem* item) { download::DownloadItem* item) {
// OnDownloadCreated is invoked during WebContents::SavePage, so the |item| // OnDownloadCreated is invoked during WebContents::SavePage, so the |item|
// here is the one stated by WebContents::SavePage. // here is the one stated by WebContents::SavePage.
item->AddObserver(this); item->AddObserver(this);
@ -48,12 +48,12 @@ bool SavePageHandler::Handle(const base::FilePath& full_path,
return result; return result;
} }
void SavePageHandler::OnDownloadUpdated(content::DownloadItem* item) { void SavePageHandler::OnDownloadUpdated(download::DownloadItem* item) {
if (item->IsDone()) { if (item->IsDone()) {
v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Locker locker(isolate); v8::Locker locker(isolate);
v8::HandleScope handle_scope(isolate); v8::HandleScope handle_scope(isolate);
if (item->GetState() == content::DownloadItem::COMPLETE) { if (item->GetState() == download::DownloadItem::COMPLETE) {
callback_.Run(v8::Null(isolate)); callback_.Run(v8::Null(isolate));
} else { } else {
v8::Local<v8::String> error_message = v8::Local<v8::String> error_message =
@ -64,7 +64,7 @@ void SavePageHandler::OnDownloadUpdated(content::DownloadItem* item) {
} }
} }
void SavePageHandler::Destroy(content::DownloadItem* item) { void SavePageHandler::Destroy(download::DownloadItem* item) {
item->RemoveObserver(this); item->RemoveObserver(this);
delete this; delete this;
} }

View file

@ -7,7 +7,7 @@
#include <string> #include <string>
#include "content/public/browser/download_item.h" #include "components/download/public/common/download_item.h"
#include "content/public/browser/download_manager.h" #include "content/public/browser/download_manager.h"
#include "content/public/browser/save_page_type.h" #include "content/public/browser/save_page_type.h"
#include "v8/include/v8.h" #include "v8/include/v8.h"
@ -26,7 +26,7 @@ namespace api {
// A self-destroyed class for handling save page request. // A self-destroyed class for handling save page request.
class SavePageHandler : public content::DownloadManager::Observer, class SavePageHandler : public content::DownloadManager::Observer,
public content::DownloadItem::Observer { public download::DownloadItem::Observer {
public: public:
using SavePageCallback = base::Callback<void(v8::Local<v8::Value>)>; using SavePageCallback = base::Callback<void(v8::Local<v8::Value>)>;
@ -38,14 +38,14 @@ class SavePageHandler : public content::DownloadManager::Observer,
const content::SavePageType& save_type); const content::SavePageType& save_type);
private: private:
void Destroy(content::DownloadItem* item); void Destroy(download::DownloadItem* item);
// content::DownloadManager::Observer: // content::DownloadManager::Observer:
void OnDownloadCreated(content::DownloadManager* manager, void OnDownloadCreated(content::DownloadManager* manager,
content::DownloadItem* item) override; download::DownloadItem* item) override;
// content::DownloadItem::Observer: // download::DownloadItem::Observer:
void OnDownloadUpdated(content::DownloadItem* item) override; void OnDownloadUpdated(download::DownloadItem* item) override;
content::WebContents* web_contents_; // weak content::WebContents* web_contents_; // weak
SavePageCallback callback_; SavePageCallback callback_;

View file

@ -1,28 +0,0 @@
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_ATOM_ACCESS_TOKEN_STORE_H_
#define ATOM_BROWSER_ATOM_ACCESS_TOKEN_STORE_H_
#include "device/geolocation/access_token_store.h"
namespace atom {
class AtomAccessTokenStore : public device::AccessTokenStore {
public:
AtomAccessTokenStore() = default;
// device::AccessTokenStore:
void LoadAccessTokens(const LoadAccessTokensCallback& callback) override {}
void SaveAccessToken(const GURL& server_url,
const base::string16& access_token) override {}
private:
~AtomAccessTokenStore() override = default;
DISALLOW_COPY_AND_ASSIGN(AtomAccessTokenStore);
};
} // namespace atom
#endif // ATOM_BROWSER_ATOM_ACCESS_TOKEN_STORE_H_

View file

@ -11,7 +11,6 @@
#include "storage/browser/blob/blob_data_handle.h" #include "storage/browser/blob/blob_data_handle.h"
#include "storage/browser/blob/blob_reader.h" #include "storage/browser/blob/blob_reader.h"
#include "storage/browser/blob/blob_storage_context.h" #include "storage/browser/blob/blob_storage_context.h"
#include "storage/browser/fileapi/file_system_context.h"
#include "atom/common/node_includes.h" #include "atom/common/node_includes.h"
@ -46,9 +45,8 @@ void RunCallbackInUI(const AtomBlobReader::CompletionCallback& callback,
} // namespace } // namespace
AtomBlobReader::AtomBlobReader(content::ChromeBlobStorageContext* blob_context, AtomBlobReader::AtomBlobReader(content::ChromeBlobStorageContext* blob_context)
storage::FileSystemContext* file_system_context) : blob_context_(blob_context) {}
: blob_context_(blob_context), file_system_context_(file_system_context) {}
AtomBlobReader::~AtomBlobReader() {} AtomBlobReader::~AtomBlobReader() {}
@ -65,7 +63,7 @@ void AtomBlobReader::StartReading(
return; return;
} }
auto blob_reader = blob_data_handle->CreateReader(file_system_context_.get()); auto blob_reader = blob_data_handle->CreateReader();
BlobReadHelper* blob_read_helper = BlobReadHelper* blob_read_helper =
new BlobReadHelper(std::move(blob_reader), callback); new BlobReadHelper(std::move(blob_reader), callback);
blob_read_helper->Read(); blob_read_helper->Read();

View file

@ -20,7 +20,6 @@ class IOBuffer;
namespace storage { namespace storage {
class BlobDataHandle; class BlobDataHandle;
class BlobReader; class BlobReader;
class FileSystemContext;
} // namespace storage } // namespace storage
namespace v8 { namespace v8 {
@ -37,8 +36,7 @@ class AtomBlobReader {
public: public:
using CompletionCallback = base::Callback<void(v8::Local<v8::Value>)>; using CompletionCallback = base::Callback<void(v8::Local<v8::Value>)>;
AtomBlobReader(content::ChromeBlobStorageContext* blob_context, explicit AtomBlobReader(content::ChromeBlobStorageContext* blob_context);
storage::FileSystemContext* file_system_context);
~AtomBlobReader(); ~AtomBlobReader();
void StartReading(const std::string& uuid, void StartReading(const std::string& uuid,
@ -69,7 +67,6 @@ class AtomBlobReader {
}; };
scoped_refptr<content::ChromeBlobStorageContext> blob_context_; scoped_refptr<content::ChromeBlobStorageContext> blob_context_;
scoped_refptr<storage::FileSystemContext> file_system_context_;
DISALLOW_COPY_AND_ASSIGN(AtomBlobReader); DISALLOW_COPY_AND_ASSIGN(AtomBlobReader);
}; };

View file

@ -17,6 +17,7 @@
#include "atom/browser/atom_resource_dispatcher_host_delegate.h" #include "atom/browser/atom_resource_dispatcher_host_delegate.h"
#include "atom/browser/atom_speech_recognition_manager_delegate.h" #include "atom/browser/atom_speech_recognition_manager_delegate.h"
#include "atom/browser/child_web_contents_tracker.h" #include "atom/browser/child_web_contents_tracker.h"
#include "atom/browser/login_handler.h"
#include "atom/browser/native_window.h" #include "atom/browser/native_window.h"
#include "atom/browser/session_preferences.h" #include "atom/browser/session_preferences.h"
#include "atom/browser/web_contents_permission_helper.h" #include "atom/browser/web_contents_permission_helper.h"
@ -32,7 +33,6 @@
#include "base/strings/string_util.h" #include "base/strings/string_util.h"
#include "chrome/browser/printing/printing_message_filter.h" #include "chrome/browser/printing/printing_message_filter.h"
#include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h" #include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
#include "chrome/browser/renderer_host/pepper/widevine_cdm_message_filter.h"
#include "chrome/browser/speech/tts_message_filter.h" #include "chrome/browser/speech/tts_message_filter.h"
#include "content/public/browser/browser_ppapi_host.h" #include "content/public/browser/browser_ppapi_host.h"
#include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/client_certificate_delegate.h"
@ -44,14 +44,24 @@
#include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents.h"
#include "content/public/common/content_paths.h" #include "content/public/common/content_paths.h"
#include "content/public/common/content_switches.h" #include "content/public/common/content_switches.h"
#include "content/public/common/resource_request_body.h"
#include "content/public/common/url_constants.h" #include "content/public/common/url_constants.h"
#include "content/public/common/web_preferences.h" #include "content/public/common/web_preferences.h"
#include "net/ssl/ssl_cert_request_info.h" #include "net/ssl/ssl_cert_request_info.h"
#include "ppapi/host/ppapi_host.h" #include "ppapi/host/ppapi_host.h"
#include "services/network/public/cpp/resource_request_body.h"
#include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util.h"
#include "v8/include/v8.h" #include "v8/include/v8.h"
#if defined(USE_NSS_CERTS)
#include "net/ssl/client_cert_store_nss.h"
#elif defined(OS_WIN)
#include "net/ssl/client_cert_store_win.h"
#elif defined(OS_MACOSX)
#include "net/ssl/client_cert_store_mac.h"
#elif defined(USE_OPENSSL)
#include "net/ssl/client_cert_store.h"
#endif
using content::BrowserThread; using content::BrowserThread;
namespace atom { namespace atom {
@ -166,7 +176,8 @@ bool AtomBrowserClient::RendererDisablesPopups(int process_id) {
} }
void AtomBrowserClient::RenderProcessWillLaunch( void AtomBrowserClient::RenderProcessWillLaunch(
content::RenderProcessHost* host) { content::RenderProcessHost* host,
service_manager::mojom::ServiceRequest* service_request) {
// When a render process is crashed, it might be reused. // When a render process is crashed, it might be reused.
int process_id = host->GetID(); int process_id = host->GetID();
if (IsProcessObserved(process_id)) if (IsProcessObserved(process_id))
@ -174,8 +185,6 @@ void AtomBrowserClient::RenderProcessWillLaunch(
host->AddFilter(new printing::PrintingMessageFilter(process_id)); host->AddFilter(new printing::PrintingMessageFilter(process_id));
host->AddFilter(new TtsMessageFilter(process_id, host->GetBrowserContext())); host->AddFilter(new TtsMessageFilter(process_id, host->GetBrowserContext()));
host->AddFilter(
new WidevineCdmMessageFilter(process_id, host->GetBrowserContext()));
ProcessPreferences prefs; ProcessPreferences prefs;
auto* web_preferences = auto* web_preferences =
@ -415,7 +424,7 @@ bool AtomBrowserClient::CanCreateWindow(
WindowOpenDisposition disposition, WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& features, const blink::mojom::WindowFeatures& features,
const std::vector<std::string>& additional_features, const std::vector<std::string>& additional_features,
const scoped_refptr<content::ResourceRequestBody>& body, const scoped_refptr<network::ResourceRequestBody>& body,
bool user_gesture, bool user_gesture,
bool opener_suppressed, bool opener_suppressed,
bool* no_javascript_access) { bool* no_javascript_access) {
@ -472,6 +481,33 @@ void AtomBrowserClient::SiteInstanceDeleting(
} }
} }
std::unique_ptr<net::ClientCertStore> AtomBrowserClient::CreateClientCertStore(
content::ResourceContext* resource_context) {
#if defined(USE_NSS_CERTS)
return std::make_unique<net::ClientCertStoreNSS>(
net::ClientCertStoreNSS::PasswordDelegateFactory());
#elif defined(OS_WIN)
return std::make_unique<net::ClientCertStoreWin>();
#elif defined(OS_MACOSX)
return std::make_unique<net::ClientCertStoreMac>();
#elif defined(USE_OPENSSL)
return std::unique_ptr<net::ClientCertStore>();
#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);
}
brightray::BrowserMainParts* AtomBrowserClient::OverrideCreateBrowserMainParts( brightray::BrowserMainParts* AtomBrowserClient::OverrideCreateBrowserMainParts(
const content::MainFunctionParams&) { const content::MainFunctionParams&) {
v8::V8::Initialize(); // Init V8 before creating main parts. v8::V8::Initialize(); // Init V8 before creating main parts.

View file

@ -48,7 +48,9 @@ class AtomBrowserClient : public brightray::BrowserClient,
protected: protected:
// content::ContentBrowserClient: // content::ContentBrowserClient:
void RenderProcessWillLaunch(content::RenderProcessHost* host) override; void RenderProcessWillLaunch(
content::RenderProcessHost* host,
service_manager::mojom::ServiceRequest* service_request) override;
content::SpeechRecognitionManagerDelegate* content::SpeechRecognitionManagerDelegate*
CreateSpeechRecognitionManagerDelegate() override; CreateSpeechRecognitionManagerDelegate() override;
void OverrideWebkitPrefs(content::RenderViewHost* render_view_host, void OverrideWebkitPrefs(content::RenderViewHost* render_view_host,
@ -95,13 +97,23 @@ class AtomBrowserClient : public brightray::BrowserClient,
WindowOpenDisposition disposition, WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& features, const blink::mojom::WindowFeatures& features,
const std::vector<std::string>& additional_features, const std::vector<std::string>& additional_features,
const scoped_refptr<content::ResourceRequestBody>& body, const scoped_refptr<network::ResourceRequestBody>& body,
bool user_gesture, bool user_gesture,
bool opener_suppressed, bool opener_suppressed,
bool* no_javascript_access) override; bool* no_javascript_access) override;
void GetAdditionalAllowedSchemesForFileSystem( void GetAdditionalAllowedSchemesForFileSystem(
std::vector<std::string>* schemes) override; std::vector<std::string>* schemes) override;
void SiteInstanceDeleting(content::SiteInstance* site_instance) override; 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;
// brightray::BrowserClient: // brightray::BrowserClient:
brightray::BrowserMainParts* OverrideCreateBrowserMainParts( brightray::BrowserMainParts* OverrideCreateBrowserMainParts(

View file

@ -28,7 +28,6 @@
#include "base/strings/string_util.h" #include "base/strings/string_util.h"
#include "base/strings/stringprintf.h" #include "base/strings/stringprintf.h"
#include "base/task_scheduler/post_task.h" #include "base/task_scheduler/post_task.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_paths.h"
#include "chrome/common/pref_names.h" #include "chrome/common/pref_names.h"
#include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_registry_simple.h"
@ -203,10 +202,9 @@ std::vector<std::string> AtomBrowserContext::GetCookieableSchemes() {
return default_schemes; return default_schemes;
} }
void AtomBrowserContext::NotifyCookieChange( void AtomBrowserContext::NotifyCookieChange(const net::CanonicalCookie& cookie,
const net::CanonicalCookie& cookie, bool removed,
bool removed, net::CookieChangeCause cause) {
net::CookieStore::ChangeCause cause) {
CookieDetails cookie_details(&cookie, removed, cause); CookieDetails cookie_details(&cookie, removed, cause);
cookie_change_sub_list_.Notify(&cookie_details); cookie_change_sub_list_.Notify(&cookie_details);
} }
@ -225,10 +223,7 @@ AtomBlobReader* AtomBrowserContext::GetBlobReader() {
if (!blob_reader_.get()) { if (!blob_reader_.get()) {
content::ChromeBlobStorageContext* blob_context = content::ChromeBlobStorageContext* blob_context =
content::ChromeBlobStorageContext::GetFor(this); content::ChromeBlobStorageContext::GetFor(this);
storage::FileSystemContext* file_system_context = blob_reader_.reset(new AtomBlobReader(blob_context));
content::BrowserContext::GetStoragePartition(this, nullptr)
->GetFileSystemContext();
blob_reader_.reset(new AtomBlobReader(blob_context, file_system_context));
} }
return blob_reader_.get(); return blob_reader_.get();
} }

View file

@ -48,7 +48,7 @@ class AtomBrowserContext : public brightray::BrowserContext {
std::vector<std::string> GetCookieableSchemes() override; std::vector<std::string> GetCookieableSchemes() override;
void NotifyCookieChange(const net::CanonicalCookie& cookie, void NotifyCookieChange(const net::CanonicalCookie& cookie,
bool removed, bool removed,
net::CookieStore::ChangeCause cause) override; net::CookieChangeCause cause) override;
// content::BrowserContext: // content::BrowserContext:
content::DownloadManagerDelegate* GetDownloadManagerDelegate() override; content::DownloadManagerDelegate* GetDownloadManagerDelegate() override;

View file

@ -6,7 +6,6 @@
#include "atom/browser/api/atom_api_app.h" #include "atom/browser/api/atom_api_app.h"
#include "atom/browser/api/trackable_object.h" #include "atom/browser/api/trackable_object.h"
#include "atom/browser/atom_access_token_store.h"
#include "atom/browser/atom_browser_client.h" #include "atom/browser/atom_browser_client.h"
#include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_context.h"
#include "atom/browser/bridge_task_runner.h" #include "atom/browser/bridge_task_runner.h"
@ -20,11 +19,12 @@
#include "base/threading/thread_task_runner_handle.h" #include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process.h"
#include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/child_process_security_policy.h"
#include "device/geolocation/geolocation_delegate.h" #include "content/public/common/result_codes.h"
#include "device/geolocation/geolocation_provider.h" #include "content/public/common/service_manager_connection.h"
#include "services/device/public/mojom/constants.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
#include "ui/base/idle/idle.h" #include "ui/base/idle/idle.h"
#include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util.h"
#include "v8/include/v8-debug.h"
#if defined(USE_X11) #if defined(USE_X11)
#include "chrome/browser/ui/libgtkui/gtk_util.h" #include "chrome/browser/ui/libgtkui/gtk_util.h"
@ -48,22 +48,6 @@ namespace atom {
namespace { namespace {
// A provider of Geolocation services to override AccessTokenStore.
class AtomGeolocationDelegate : public device::GeolocationDelegate {
public:
AtomGeolocationDelegate() {
device::GeolocationProvider::GetInstance()
->UserDidOptIntoLocationServices();
}
scoped_refptr<device::AccessTokenStore> CreateAccessTokenStore() final {
return new AtomAccessTokenStore();
}
private:
DISALLOW_COPY_AND_ASSIGN(AtomGeolocationDelegate);
};
template <typename T> template <typename T>
void Erase(T* container, typename T::iterator iter) { void Erase(T* container, typename T::iterator iter) {
container->erase(iter); container->erase(iter);
@ -126,11 +110,16 @@ void AtomBrowserMainParts::RegisterDestructionCallback(
destructors_.insert(destructors_.begin(), std::move(callback)); destructors_.insert(destructors_.begin(), std::move(callback));
} }
void AtomBrowserMainParts::PreEarlyInitialization() { int AtomBrowserMainParts::PreEarlyInitialization() {
brightray::BrowserMainParts::PreEarlyInitialization(); const int result = brightray::BrowserMainParts::PreEarlyInitialization();
if (result != content::RESULT_CODE_NORMAL_EXIT)
return result;
#if defined(OS_POSIX) #if defined(OS_POSIX)
HandleSIGCHLD(); HandleSIGCHLD();
#endif #endif
return content::RESULT_CODE_NORMAL_EXIT;
} }
void AtomBrowserMainParts::PostEarlyInitialization() { void AtomBrowserMainParts::PostEarlyInitialization() {
@ -223,8 +212,7 @@ void AtomBrowserMainParts::PreMainMessageLoopRun() {
#if !defined(OS_MACOSX) #if !defined(OS_MACOSX)
// The corresponding call in macOS is in AtomApplicationDelegate. // The corresponding call in macOS is in AtomApplicationDelegate.
Browser::Get()->WillFinishLaunching(); Browser::Get()->WillFinishLaunching();
std::unique_ptr<base::DictionaryValue> empty_info(new base::DictionaryValue); Browser::Get()->DidFinishLaunching(base::DictionaryValue());
Browser::Get()->DidFinishLaunching(*empty_info);
#endif #endif
// Notify observers that main thread message loop was initialized. // Notify observers that main thread message loop was initialized.
@ -241,8 +229,9 @@ void AtomBrowserMainParts::PostMainMessageLoopStart() {
#if defined(OS_POSIX) #if defined(OS_POSIX)
HandleShutdownSignals(); HandleShutdownSignals();
#endif #endif
device::GeolocationProvider::SetGeolocationDelegate( // TODO(deepak1556): Enable this optionally based on response
new AtomGeolocationDelegate()); // from AtomPermissionManager.
GetGeolocationControl()->UserDidOptIntoLocationServices();
} }
void AtomBrowserMainParts::PostMainMessageLoopRun() { void AtomBrowserMainParts::PostMainMessageLoopRun() {
@ -267,4 +256,19 @@ void AtomBrowserMainParts::PostMainMessageLoopRun() {
} }
} }
device::mojom::GeolocationControl*
AtomBrowserMainParts::GetGeolocationControl() {
if (geolocation_control_)
return geolocation_control_.get();
auto request = mojo::MakeRequest(&geolocation_control_);
if (!content::ServiceManagerConnection::GetForProcess())
return geolocation_control_.get();
service_manager::Connector* connector =
content::ServiceManagerConnection::GetForProcess()->GetConnector();
connector->BindInterface(device::mojom::kServiceName, std::move(request));
return geolocation_control_.get();
}
} // namespace atom } // namespace atom

View file

@ -12,6 +12,7 @@
#include "base/timer/timer.h" #include "base/timer/timer.h"
#include "brightray/browser/browser_main_parts.h" #include "brightray/browser/browser_main_parts.h"
#include "content/public/browser/browser_context.h" #include "content/public/browser/browser_context.h"
#include "services/device/public/mojom/geolocation_control.mojom.h"
class BrowserProcess; class BrowserProcess;
@ -57,7 +58,7 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts {
protected: protected:
// content::BrowserMainParts: // content::BrowserMainParts:
void PreEarlyInitialization() override; int PreEarlyInitialization() override;
void PostEarlyInitialization() override; void PostEarlyInitialization() override;
int PreCreateThreads() override; int PreCreateThreads() override;
void ToolkitInitialized() override; void ToolkitInitialized() override;
@ -86,6 +87,8 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts {
std::unique_ptr<brightray::ViewsDelegate> views_delegate_; std::unique_ptr<brightray::ViewsDelegate> views_delegate_;
#endif #endif
device::mojom::GeolocationControl* GetGeolocationControl();
// A fake BrowserProcess object that used to feed the source code from chrome. // A fake BrowserProcess object that used to feed the source code from chrome.
std::unique_ptr<BrowserProcess> fake_browser_process_; std::unique_ptr<BrowserProcess> fake_browser_process_;
@ -108,6 +111,8 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts {
// List of callbacks should be executed before destroying JS env. // List of callbacks should be executed before destroying JS env.
std::list<base::OnceClosure> destructors_; std::list<base::OnceClosure> destructors_;
device::mojom::GeolocationControlPtr geolocation_control_;
static AtomBrowserMainParts* self_; static AtomBrowserMainParts* self_;
DISALLOW_COPY_AND_ASSIGN(AtomBrowserMainParts); DISALLOW_COPY_AND_ASSIGN(AtomBrowserMainParts);

View file

@ -14,10 +14,13 @@
#include "atom/common/options_switches.h" #include "atom/common/options_switches.h"
#include "base/bind.h" #include "base/bind.h"
#include "base/files/file_util.h" #include "base/files/file_util.h"
#include "base/task_scheduler/post_task.h"
#include "chrome/common/pref_names.h" #include "chrome/common/pref_names.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/prefs/pref_service.h" #include "components/prefs/pref_service.h"
#include "content/public/browser/browser_context.h" #include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_item_utils.h"
#include "content/public/browser/download_manager.h" #include "content/public/browser/download_manager.h"
#include "net/base/filename_util.h" #include "net/base/filename_util.h"
@ -26,15 +29,11 @@ namespace atom {
namespace { namespace {
// Generate default file path to save the download. // Generate default file path to save the download.
void CreateDownloadPath( base::FilePath CreateDownloadPath(const GURL& url,
const GURL& url, const std::string& content_disposition,
const std::string& content_disposition, const std::string& suggested_filename,
const std::string& suggested_filename, const std::string& mime_type,
const std::string& mime_type, const base::FilePath& default_download_path) {
const base::FilePath& default_download_path,
const AtomDownloadManagerDelegate::CreateDownloadPathCallback& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
auto generated_name = auto generated_name =
net::GenerateFileName(url, content_disposition, std::string(), net::GenerateFileName(url, content_disposition, std::string(),
suggested_filename, mime_type, "download"); suggested_filename, mime_type, "download");
@ -42,9 +41,7 @@ void CreateDownloadPath(
if (!base::PathExists(default_download_path)) if (!base::PathExists(default_download_path))
base::CreateDirectory(default_download_path); base::CreateDirectory(default_download_path);
base::FilePath path(default_download_path.Append(generated_name)); return default_download_path.Append(generated_name);
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::BindOnce(callback, path));
} }
} // namespace } // namespace
@ -62,7 +59,7 @@ AtomDownloadManagerDelegate::~AtomDownloadManagerDelegate() {
} }
} }
void AtomDownloadManagerDelegate::GetItemSavePath(content::DownloadItem* item, void AtomDownloadManagerDelegate::GetItemSavePath(download::DownloadItem* item,
base::FilePath* path) { base::FilePath* path) {
v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Locker locker(isolate); v8::Locker locker(isolate);
@ -84,7 +81,8 @@ void AtomDownloadManagerDelegate::OnDownloadPathGenerated(
return; return;
NativeWindow* window = nullptr; NativeWindow* window = nullptr;
content::WebContents* web_contents = item->GetWebContents(); content::WebContents* web_contents =
content::DownloadItemUtils::GetWebContents(item);
auto* relay = auto* relay =
web_contents ? NativeWindowRelay::FromWebContents(web_contents) : nullptr; web_contents ? NativeWindowRelay::FromWebContents(web_contents) : nullptr;
if (relay) if (relay)
@ -121,10 +119,10 @@ void AtomDownloadManagerDelegate::OnDownloadPathGenerated(
// Running the DownloadTargetCallback with an empty FilePath signals that the // Running the DownloadTargetCallback with an empty FilePath signals that the
// download should be cancelled. // download should be cancelled.
// If user cancels the file save dialog, run the callback with empty FilePath. // If user cancels the file save dialog, run the callback with empty FilePath.
callback.Run(path, content::DownloadItem::TARGET_DISPOSITION_PROMPT, callback.Run(path, download::DownloadItem::TARGET_DISPOSITION_PROMPT,
content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, path, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, path,
path.empty() ? content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED path.empty() ? download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED
: content::DOWNLOAD_INTERRUPT_REASON_NONE); : download::DOWNLOAD_INTERRUPT_REASON_NONE);
} }
void AtomDownloadManagerDelegate::Shutdown() { void AtomDownloadManagerDelegate::Shutdown() {
@ -133,16 +131,16 @@ void AtomDownloadManagerDelegate::Shutdown() {
} }
bool AtomDownloadManagerDelegate::DetermineDownloadTarget( bool AtomDownloadManagerDelegate::DetermineDownloadTarget(
content::DownloadItem* download, download::DownloadItem* download,
const content::DownloadTargetCallback& callback) { const content::DownloadTargetCallback& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!download->GetForcedFilePath().empty()) { if (!download->GetForcedFilePath().empty()) {
callback.Run(download->GetForcedFilePath(), callback.Run(download->GetForcedFilePath(),
content::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download->GetForcedFilePath(), download->GetForcedFilePath(),
content::DOWNLOAD_INTERRUPT_REASON_NONE); download::DOWNLOAD_INTERRUPT_REASON_NONE);
return true; return true;
} }
@ -150,9 +148,10 @@ bool AtomDownloadManagerDelegate::DetermineDownloadTarget(
base::FilePath save_path; base::FilePath save_path;
GetItemSavePath(download, &save_path); GetItemSavePath(download, &save_path);
if (!save_path.empty()) { if (!save_path.empty()) {
callback.Run(save_path, content::DownloadItem::TARGET_DISPOSITION_OVERWRITE, callback.Run(save_path,
content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, save_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
content::DOWNLOAD_INTERRUPT_REASON_NONE); download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
save_path, download::DOWNLOAD_INTERRUPT_REASON_NONE);
return true; return true;
} }
@ -161,28 +160,29 @@ bool AtomDownloadManagerDelegate::DetermineDownloadTarget(
base::FilePath default_download_path = base::FilePath default_download_path =
browser_context->prefs()->GetFilePath(prefs::kDownloadDefaultDirectory); browser_context->prefs()->GetFilePath(prefs::kDownloadDefaultDirectory);
CreateDownloadPathCallback download_path_callback = base::PostTaskWithTraitsAndReplyWithResult(
base::Bind(&AtomDownloadManagerDelegate::OnDownloadPathGenerated, FROM_HERE,
weak_ptr_factory_.GetWeakPtr(), download->GetId(), callback); {base::MayBlock(), base::TaskPriority::BACKGROUND,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
content::BrowserThread::PostTask(
content::BrowserThread::FILE, FROM_HERE,
base::BindOnce(&CreateDownloadPath, download->GetURL(), base::BindOnce(&CreateDownloadPath, download->GetURL(),
download->GetContentDisposition(), download->GetContentDisposition(),
download->GetSuggestedFilename(), download->GetMimeType(), download->GetSuggestedFilename(), download->GetMimeType(),
default_download_path, download_path_callback)); default_download_path),
base::BindOnce(&AtomDownloadManagerDelegate::OnDownloadPathGenerated,
weak_ptr_factory_.GetWeakPtr(), download->GetId(),
callback));
return true; return true;
} }
bool AtomDownloadManagerDelegate::ShouldOpenDownload( bool AtomDownloadManagerDelegate::ShouldOpenDownload(
content::DownloadItem* download, download::DownloadItem* download,
const content::DownloadOpenDelayedCallback& callback) { const content::DownloadOpenDelayedCallback& callback) {
return true; return true;
} }
void AtomDownloadManagerDelegate::GetNextId( void AtomDownloadManagerDelegate::GetNextId(
const content::DownloadIdCallback& callback) { const content::DownloadIdCallback& callback) {
static uint32_t next_id = content::DownloadItem::kInvalidId + 1; static uint32_t next_id = download::DownloadItem::kInvalidId + 1;
callback.Run(next_id++); callback.Run(next_id++);
} }

View file

@ -31,16 +31,16 @@ class AtomDownloadManagerDelegate : public content::DownloadManagerDelegate {
// content::DownloadManagerDelegate: // content::DownloadManagerDelegate:
void Shutdown() override; void Shutdown() override;
bool DetermineDownloadTarget( bool DetermineDownloadTarget(
content::DownloadItem* download, download::DownloadItem* download,
const content::DownloadTargetCallback& callback) override; const content::DownloadTargetCallback& callback) override;
bool ShouldOpenDownload( bool ShouldOpenDownload(
content::DownloadItem* download, download::DownloadItem* download,
const content::DownloadOpenDelayedCallback& callback) override; const content::DownloadOpenDelayedCallback& callback) override;
void GetNextId(const content::DownloadIdCallback& callback) override; void GetNextId(const content::DownloadIdCallback& callback) override;
private: private:
// Get the save path set on the associated api::DownloadItem object // Get the save path set on the associated api::DownloadItem object
void GetItemSavePath(content::DownloadItem* item, base::FilePath* path); void GetItemSavePath(download::DownloadItem* item, base::FilePath* path);
content::DownloadManager* download_manager_; content::DownloadManager* download_manager_;
base::WeakPtrFactory<AtomDownloadManagerDelegate> weak_ptr_factory_; base::WeakPtrFactory<AtomDownloadManagerDelegate> weak_ptr_factory_;

View file

@ -33,12 +33,13 @@ AtomJavaScriptDialogManager::~AtomJavaScriptDialogManager() = default;
void AtomJavaScriptDialogManager::RunJavaScriptDialog( void AtomJavaScriptDialogManager::RunJavaScriptDialog(
content::WebContents* web_contents, content::WebContents* web_contents,
const GURL& origin_url, content::RenderFrameHost* rfh,
JavaScriptDialogType dialog_type, JavaScriptDialogType dialog_type,
const base::string16& message_text, const base::string16& message_text,
const base::string16& default_prompt_text, const base::string16& default_prompt_text,
DialogClosedCallback callback, DialogClosedCallback callback,
bool* did_suppress_message) { bool* did_suppress_message) {
auto origin_url = rfh->GetLastCommittedURL();
const std::string& origin = origin_url.GetOrigin().spec(); const std::string& origin = origin_url.GetOrigin().spec();
if (origin_counts_[origin] == kUserWantsNoMoreDialogs) { if (origin_counts_[origin] == kUserWantsNoMoreDialogs) {
return std::move(callback).Run(false, base::string16()); return std::move(callback).Run(false, base::string16());
@ -84,6 +85,7 @@ void AtomJavaScriptDialogManager::RunJavaScriptDialog(
void AtomJavaScriptDialogManager::RunBeforeUnloadDialog( void AtomJavaScriptDialogManager::RunBeforeUnloadDialog(
content::WebContents* web_contents, content::WebContents* web_contents,
content::RenderFrameHost* rfh,
bool is_reload, bool is_reload,
DialogClosedCallback callback) { DialogClosedCallback callback) {
bool default_prevented = api_web_contents_->Emit("will-prevent-unload"); bool default_prevented = api_web_contents_->Emit("will-prevent-unload");

View file

@ -23,13 +23,14 @@ class AtomJavaScriptDialogManager : public content::JavaScriptDialogManager {
// content::JavaScriptDialogManager implementations. // content::JavaScriptDialogManager implementations.
void RunJavaScriptDialog(content::WebContents* web_contents, void RunJavaScriptDialog(content::WebContents* web_contents,
const GURL& origin_url, content::RenderFrameHost* rfh,
content::JavaScriptDialogType dialog_type, content::JavaScriptDialogType dialog_type,
const base::string16& message_text, const base::string16& message_text,
const base::string16& default_prompt_text, const base::string16& default_prompt_text,
DialogClosedCallback callback, DialogClosedCallback callback,
bool* did_suppress_message) override; bool* did_suppress_message) override;
void RunBeforeUnloadDialog(content::WebContents* web_contents, void RunBeforeUnloadDialog(content::WebContents* web_contents,
content::RenderFrameHost* rfh,
bool is_reload, bool is_reload,
DialogClosedCallback callback) override; DialogClosedCallback callback) override;
void CancelDialogs(content::WebContents* web_contents, void CancelDialogs(content::WebContents* web_contents,

View file

@ -186,15 +186,6 @@ void AtomPermissionManager::OnPermissionResponse(
} }
} }
void AtomPermissionManager::CancelPermissionRequest(int request_id) {
auto* pending_request = pending_requests_.Lookup(request_id);
if (!pending_request)
return;
if (!WebContentsDestroyed(pending_request->render_process_id()))
pending_request->RunCallback();
pending_requests_.Remove(request_id);
}
void AtomPermissionManager::ResetPermission(content::PermissionType permission, void AtomPermissionManager::ResetPermission(content::PermissionType permission,
const GURL& requesting_origin, const GURL& requesting_origin,

View file

@ -73,7 +73,6 @@ class AtomPermissionManager : public content::PermissionManager {
blink::mojom::PermissionStatus status); blink::mojom::PermissionStatus status);
// content::PermissionManager: // content::PermissionManager:
void CancelPermissionRequest(int request_id) override;
void ResetPermission(content::PermissionType permission, void ResetPermission(content::PermissionType permission,
const GURL& requesting_origin, const GURL& requesting_origin,
const GURL& embedding_origin) override; const GURL& embedding_origin) override;

View file

@ -4,8 +4,6 @@
#include "atom/browser/atom_quota_permission_context.h" #include "atom/browser/atom_quota_permission_context.h"
#include "storage/common/quota/quota_types.h"
namespace atom { namespace atom {
AtomQuotaPermissionContext::AtomQuotaPermissionContext() {} AtomQuotaPermissionContext::AtomQuotaPermissionContext() {}

View file

@ -6,6 +6,7 @@
#define ATOM_BROWSER_ATOM_QUOTA_PERMISSION_CONTEXT_H_ #define ATOM_BROWSER_ATOM_QUOTA_PERMISSION_CONTEXT_H_
#include "content/public/browser/quota_permission_context.h" #include "content/public/browser/quota_permission_context.h"
#include "content/public/common/storage_quota_params.h"
namespace atom { namespace atom {

View file

@ -5,7 +5,6 @@
#include "atom/browser/atom_resource_dispatcher_host_delegate.h" #include "atom/browser/atom_resource_dispatcher_host_delegate.h"
#include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_context.h"
#include "atom/browser/login_handler.h"
#include "atom/browser/web_contents_permission_helper.h" #include "atom/browser/web_contents_permission_helper.h"
#include "atom/browser/web_contents_preferences.h" #include "atom/browser/web_contents_preferences.h"
#include "atom/common/platform_util.h" #include "atom/common/platform_util.h"
@ -14,17 +13,8 @@
#include "content/public/browser/download_manager.h" #include "content/public/browser/download_manager.h"
#include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_frame_host.h"
#include "net/base/escape.h" #include "net/base/escape.h"
#include "net/ssl/client_cert_store.h"
#include "url/gurl.h" #include "url/gurl.h"
#if defined(USE_NSS_CERTS)
#include "net/ssl/client_cert_store_nss.h"
#elif defined(OS_WIN)
#include "net/ssl/client_cert_store_win.h"
#elif defined(OS_MACOSX)
#include "net/ssl/client_cert_store_mac.h"
#endif
#if defined(ENABLE_PDF_VIEWER) #if defined(ENABLE_PDF_VIEWER)
#include "atom/common/atom_constants.h" #include "atom/common/atom_constants.h"
#include "base/strings/stringprintf.h" #include "base/strings/stringprintf.h"
@ -123,31 +113,8 @@ bool AtomResourceDispatcherHostDelegate::HandleExternalProtocol(
return true; return true;
} }
content::ResourceDispatcherHostLoginDelegate*
AtomResourceDispatcherHostDelegate::CreateLoginDelegate(
net::AuthChallengeInfo* auth_info,
net::URLRequest* request) {
return new LoginHandler(auth_info, request);
}
std::unique_ptr<net::ClientCertStore>
AtomResourceDispatcherHostDelegate::CreateClientCertStore(
content::ResourceContext* resource_context) {
#if defined(USE_NSS_CERTS)
return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreNSS(
net::ClientCertStoreNSS::PasswordDelegateFactory()));
#elif defined(OS_WIN)
return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreWin());
#elif defined(OS_MACOSX)
return std::unique_ptr<net::ClientCertStore>(new net::ClientCertStoreMac());
#elif defined(USE_OPENSSL)
return std::unique_ptr<net::ClientCertStore>();
#endif
}
bool AtomResourceDispatcherHostDelegate::ShouldInterceptResourceAsStream( bool AtomResourceDispatcherHostDelegate::ShouldInterceptResourceAsStream(
net::URLRequest* request, net::URLRequest* request,
const base::FilePath& plugin_path,
const std::string& mime_type, const std::string& mime_type,
GURL* origin, GURL* origin,
std::string* payload) { std::string* payload) {

View file

@ -19,13 +19,7 @@ class AtomResourceDispatcherHostDelegate
// content::ResourceDispatcherHostDelegate: // content::ResourceDispatcherHostDelegate:
bool HandleExternalProtocol(const GURL& url, bool HandleExternalProtocol(const GURL& url,
content::ResourceRequestInfo* info) override; content::ResourceRequestInfo* info) override;
content::ResourceDispatcherHostLoginDelegate* CreateLoginDelegate(
net::AuthChallengeInfo* auth_info,
net::URLRequest* request) override;
std::unique_ptr<net::ClientCertStore> CreateClientCertStore(
content::ResourceContext* resource_context) override;
bool ShouldInterceptResourceAsStream(net::URLRequest* request, bool ShouldInterceptResourceAsStream(net::URLRequest* request,
const base::FilePath& plugin_path,
const std::string& mime_type, const std::string& mime_type,
GURL* origin, GURL* origin,
std::string* payload) override; std::string* payload) override;

View file

@ -18,6 +18,7 @@
#include "native_mate/arguments.h" #include "native_mate/arguments.h"
#if defined(OS_WIN) #if defined(OS_WIN)
#include <windows.h>
#include "base/files/file_path.h" #include "base/files/file_path.h"
#endif #endif

View file

@ -16,6 +16,8 @@
#include "atom/common/atom_constants.h" #include "atom/common/atom_constants.h"
#include "atom/common/options_switches.h" #include "atom/common/options_switches.h"
#include "base/files/file_util.h" #include "base/files/file_util.h"
#include "base/task_scheduler/post_task.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "chrome/browser/printing/print_preview_message_handler.h" #include "chrome/browser/printing/print_preview_message_handler.h"
#include "chrome/browser/printing/print_view_manager_basic.h" #include "chrome/browser/printing/print_view_manager_basic.h"
#include "chrome/browser/ssl/security_state_tab_helper.h" #include "chrome/browser/ssl/security_state_tab_helper.h"
@ -100,14 +102,14 @@ std::unique_ptr<base::DictionaryValue> CreateFileSystemValue(
} }
void WriteToFile(const base::FilePath& path, const std::string& content) { void WriteToFile(const base::FilePath& path, const std::string& content) {
DCHECK_CURRENTLY_ON(BrowserThread::FILE); base::AssertBlockingAllowed();
DCHECK(!path.empty()); DCHECK(!path.empty());
base::WriteFile(path, content.data(), content.size()); base::WriteFile(path, content.data(), content.size());
} }
void AppendToFile(const base::FilePath& path, const std::string& content) { void AppendToFile(const base::FilePath& path, const std::string& content) {
DCHECK_CURRENTLY_ON(BrowserThread::FILE); base::AssertBlockingAllowed();
DCHECK(!path.empty()); DCHECK(!path.empty());
base::AppendToFile(path, content.data(), content.size()); base::AppendToFile(path, content.data(), content.size());
@ -142,7 +144,9 @@ bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
} // namespace } // namespace
CommonWebContentsDelegate::CommonWebContentsDelegate() CommonWebContentsDelegate::CommonWebContentsDelegate()
: devtools_file_system_indexer_(new DevToolsFileSystemIndexer) {} : devtools_file_system_indexer_(new DevToolsFileSystemIndexer),
file_task_runner_(
base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})) {}
CommonWebContentsDelegate::~CommonWebContentsDelegate() {} CommonWebContentsDelegate::~CommonWebContentsDelegate() {}
@ -231,7 +235,7 @@ bool CommonWebContentsDelegate::CanOverscrollContent() const {
content::ColorChooser* CommonWebContentsDelegate::OpenColorChooser( content::ColorChooser* CommonWebContentsDelegate::OpenColorChooser(
content::WebContents* web_contents, content::WebContents* web_contents,
SkColor color, SkColor color,
const std::vector<content::ColorSuggestion>& suggestions) { const std::vector<blink::mojom::ColorSuggestionPtr>& suggestions) {
return chrome::ShowColorChooser(web_contents, color); return chrome::ShowColorChooser(web_contents, color);
} }
@ -309,11 +313,13 @@ void CommonWebContentsDelegate::DevToolsSaveToFile(const std::string& url,
} }
saved_files_[url] = path; saved_files_[url] = path;
BrowserThread::PostTaskAndReply( // Notify DevTools.
BrowserThread::FILE, FROM_HERE, base::Value url_value(url);
base::BindOnce(&WriteToFile, path, content), base::Value file_system_path_value(path.AsUTF8Unsafe());
base::BindOnce(&CommonWebContentsDelegate::OnDevToolsSaveToFile, web_contents_->CallClientFunction("DevToolsAPI.savedURL", &url_value,
base::Unretained(this), url)); &file_system_path_value, nullptr);
file_task_runner_->PostTask(FROM_HERE,
base::BindOnce(&WriteToFile, path, content));
} }
void CommonWebContentsDelegate::DevToolsAppendToFile( void CommonWebContentsDelegate::DevToolsAppendToFile(
@ -323,11 +329,12 @@ void CommonWebContentsDelegate::DevToolsAppendToFile(
if (it == saved_files_.end()) if (it == saved_files_.end())
return; return;
BrowserThread::PostTaskAndReply( // Notify DevTools.
BrowserThread::FILE, FROM_HERE, base::Value url_value(url);
base::BindOnce(&AppendToFile, it->second, content), web_contents_->CallClientFunction("DevToolsAPI.appendedToURL", &url_value,
base::BindOnce(&CommonWebContentsDelegate::OnDevToolsAppendToFile, nullptr, nullptr);
base::Unretained(this), url)); file_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&AppendToFile, it->second, content));
} }
void CommonWebContentsDelegate::DevToolsRequestFileSystems() { void CommonWebContentsDelegate::DevToolsRequestFileSystems() {
@ -455,20 +462,6 @@ void CommonWebContentsDelegate::DevToolsSearchInPath(
base::Unretained(this), request_id, file_system_path)); base::Unretained(this), request_id, file_system_path));
} }
void CommonWebContentsDelegate::OnDevToolsSaveToFile(const std::string& url) {
// Notify DevTools.
base::Value url_value(url);
web_contents_->CallClientFunction("DevToolsAPI.savedURL", &url_value, nullptr,
nullptr);
}
void CommonWebContentsDelegate::OnDevToolsAppendToFile(const std::string& url) {
// Notify DevTools.
base::Value url_value(url);
web_contents_->CallClientFunction("DevToolsAPI.appendedToURL", &url_value,
nullptr, nullptr);
}
void CommonWebContentsDelegate::OnDevToolsIndexingWorkCalculated( void CommonWebContentsDelegate::OnDevToolsIndexingWorkCalculated(
int request_id, int request_id,
const std::string& file_system_path, const std::string& file_system_path,

View file

@ -21,6 +21,10 @@
using brightray::DevToolsFileSystemIndexer; using brightray::DevToolsFileSystemIndexer;
namespace base {
class SequencedTaskRunner;
}
namespace atom { namespace atom {
class AtomBrowserContext; class AtomBrowserContext;
@ -72,7 +76,8 @@ class CommonWebContentsDelegate
content::ColorChooser* OpenColorChooser( content::ColorChooser* OpenColorChooser(
content::WebContents* web_contents, content::WebContents* web_contents,
SkColor color, SkColor color,
const std::vector<content::ColorSuggestion>& suggestions) override; const std::vector<blink::mojom::ColorSuggestionPtr>& suggestions)
override;
void RunFileChooser(content::RenderFrameHost* render_frame_host, void RunFileChooser(content::RenderFrameHost* render_frame_host,
const content::FileChooserParams& params) override; const content::FileChooserParams& params) override;
void EnumerateDirectory(content::WebContents* web_contents, void EnumerateDirectory(content::WebContents* web_contents,
@ -92,8 +97,9 @@ class CommonWebContentsDelegate
// Autofill related events. // Autofill related events.
#if defined(TOOLKIT_VIEWS) && !defined(OS_MACOSX) #if defined(TOOLKIT_VIEWS) && !defined(OS_MACOSX)
void ShowAutofillPopup(bool offscreen, void ShowAutofillPopup(content::RenderFrameHost* frame_host,
content::RenderFrameHost* frame_host, content::RenderFrameHost* embedder_frame_host,
bool offscreen,
const gfx::RectF& bounds, const gfx::RectF& bounds,
const std::vector<base::string16>& values, const std::vector<base::string16>& values,
const std::vector<base::string16>& labels); const std::vector<base::string16>& labels);
@ -130,12 +136,6 @@ class CommonWebContentsDelegate
void ResetManagedWebContents(bool async); void ResetManagedWebContents(bool async);
private: private:
// Callback for when DevToolsSaveToFile has completed.
void OnDevToolsSaveToFile(const std::string& url);
// Callback for when DevToolsAppendToFile has completed.
void OnDevToolsAppendToFile(const std::string& url);
// DevTools index event callbacks. // DevTools index event callbacks.
void OnDevToolsIndexingWorkCalculated(int request_id, void OnDevToolsIndexingWorkCalculated(int request_id,
const std::string& file_system_path, const std::string& file_system_path,
@ -191,6 +191,8 @@ class CommonWebContentsDelegate
DevToolsIndexingJobsMap; DevToolsIndexingJobsMap;
DevToolsIndexingJobsMap devtools_indexing_jobs_; DevToolsIndexingJobsMap devtools_indexing_jobs_;
scoped_refptr<base::SequencedTaskRunner> file_task_runner_;
DISALLOW_COPY_AND_ASSIGN(CommonWebContentsDelegate); DISALLOW_COPY_AND_ASSIGN(CommonWebContentsDelegate);
}; };

View file

@ -4,6 +4,7 @@
#include "atom/browser/common_web_contents_delegate.h" #include "atom/browser/common_web_contents_delegate.h"
#include "atom/browser/api/atom_api_web_contents_view.h"
#include "atom/browser/native_window_views.h" #include "atom/browser/native_window_views.h"
#include "base/strings/string_util.h" #include "base/strings/string_util.h"
#include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/native_web_keyboard_event.h"
@ -28,8 +29,9 @@ void CommonWebContentsDelegate::HandleKeyboardEvent(
} }
void CommonWebContentsDelegate::ShowAutofillPopup( void CommonWebContentsDelegate::ShowAutofillPopup(
bool offscreen,
content::RenderFrameHost* frame_host, content::RenderFrameHost* frame_host,
content::RenderFrameHost* embedder_frame_host,
bool offscreen,
const gfx::RectF& bounds, const gfx::RectF& bounds,
const std::vector<base::string16>& values, const std::vector<base::string16>& values,
const std::vector<base::string16>& labels) { const std::vector<base::string16>& labels) {
@ -37,8 +39,8 @@ void CommonWebContentsDelegate::ShowAutofillPopup(
return; return;
auto* window = static_cast<NativeWindowViews*>(owner_window()); auto* window = static_cast<NativeWindowViews*>(owner_window());
autofill_popup_->CreateView(frame_host, offscreen, window->content_view(), autofill_popup_->CreateView(frame_host, embedder_frame_host, offscreen,
bounds); window->content_view(), bounds);
autofill_popup_->SetItems(values, labels); autofill_popup_->SetItems(values, labels);
} }

View file

@ -56,7 +56,8 @@ bool JavascriptEnvironment::Initialize() {
new v8::TracingController()); new v8::TracingController());
gin::IsolateHolder::Initialize( gin::IsolateHolder::Initialize(
gin::IsolateHolder::kNonStrictMode, gin::IsolateHolder::kStableV8Extras, gin::IsolateHolder::kNonStrictMode, gin::IsolateHolder::kStableV8Extras,
gin::ArrayBufferAllocator::SharedInstance(), false); gin::ArrayBufferAllocator::SharedInstance(),
nullptr /* external_reference_table */, false /* create_v8_platform */);
return true; return true;
} }

View file

@ -16,7 +16,7 @@ LayeredResourceHandler::LayeredResourceHandler(
LayeredResourceHandler::~LayeredResourceHandler() {} LayeredResourceHandler::~LayeredResourceHandler() {}
void LayeredResourceHandler::OnResponseStarted( void LayeredResourceHandler::OnResponseStarted(
content::ResourceResponse* response, network::ResourceResponse* response,
std::unique_ptr<content::ResourceController> controller) { std::unique_ptr<content::ResourceController> controller) {
if (delegate_) if (delegate_)
delegate_->OnResponseStarted(response); delegate_->OnResponseStarted(response);

View file

@ -6,6 +6,7 @@
#define ATOM_BROWSER_LOADER_LAYERED_RESOURCE_HANDLER_H_ #define ATOM_BROWSER_LOADER_LAYERED_RESOURCE_HANDLER_H_
#include "content/browser/loader/layered_resource_handler.h" #include "content/browser/loader/layered_resource_handler.h"
#include "services/network/public/cpp/resource_response.h"
namespace atom { namespace atom {
@ -17,7 +18,7 @@ class LayeredResourceHandler : public content::LayeredResourceHandler {
Delegate() {} Delegate() {}
virtual ~Delegate() {} virtual ~Delegate() {}
virtual void OnResponseStarted(content::ResourceResponse* response) = 0; virtual void OnResponseStarted(network::ResourceResponse* response) = 0;
}; };
LayeredResourceHandler(net::URLRequest* request, LayeredResourceHandler(net::URLRequest* request,
@ -27,7 +28,7 @@ class LayeredResourceHandler : public content::LayeredResourceHandler {
// content::LayeredResourceHandler: // content::LayeredResourceHandler:
void OnResponseStarted( void OnResponseStarted(
content::ResourceResponse* response, network::ResourceResponse* response,
std::unique_ptr<content::ResourceController> controller) override; std::unique_ptr<content::ResourceController> controller) override;
private: private:

View file

@ -5,41 +5,30 @@
#include "atom/browser/login_handler.h" #include "atom/browser/login_handler.h"
#include "atom/browser/browser.h" #include "atom/browser/browser.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "base/values.h" #include "base/values.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/resource_dispatcher_host.h"
#include "content/public/browser/resource_request_info.h"
#include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents.h"
#include "net/base/auth.h" #include "net/base/auth.h"
#include "net/url_request/url_request.h"
using content::BrowserThread; using content::BrowserThread;
namespace atom { namespace atom {
namespace { LoginHandler::LoginHandler(
net::AuthChallengeInfo* auth_info,
// Helper to remove the ref from an net::URLRequest to the LoginHandler. content::ResourceRequestInfo::WebContentsGetter web_contents_getter,
// Should only be called from the IO thread, since it accesses an const GURL& url,
// net::URLRequest. const base::Callback<void(const base::Optional<net::AuthCredentials>&)>&
void ResetLoginHandlerForRequest(net::URLRequest* request) { auth_required_callback)
content::ResourceDispatcherHost::Get()->ClearLoginDelegateForRequest(request); : auth_info_(auth_info),
} web_contents_getter_(web_contents_getter),
auth_required_callback_(auth_required_callback) {
} // namespace
LoginHandler::LoginHandler(net::AuthChallengeInfo* auth_info,
net::URLRequest* request)
: auth_info_(auth_info), request_(request) {
content::ResourceRequestInfo::ForRequest(request_)->GetAssociatedRenderFrame(
&render_process_host_id_, &render_frame_id_);
// Fill request details on IO thread. // Fill request details on IO thread.
// TODO(deepak1556): Fill in method and referrer details to
// avoid breaking the app login event.
std::unique_ptr<base::DictionaryValue> request_details( std::unique_ptr<base::DictionaryValue> request_details(
new base::DictionaryValue); new base::DictionaryValue);
FillRequestDetails(request_details.get(), request_); request_details->SetKey("url", base::Value(url.spec()));
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, BrowserThread::UI, FROM_HERE,
@ -52,10 +41,7 @@ LoginHandler::~LoginHandler() {}
content::WebContents* LoginHandler::GetWebContents() const { content::WebContents* LoginHandler::GetWebContents() const {
DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_CURRENTLY_ON(BrowserThread::UI);
return web_contents_getter_.Run();
content::RenderFrameHost* rfh = content::RenderFrameHost::FromID(
render_process_host_id_, render_frame_id_);
return content::WebContents::FromRenderFrameHost(rfh);
} }
void LoginHandler::Login(const base::string16& username, void LoginHandler::Login(const base::string16& username,
@ -78,7 +64,7 @@ void LoginHandler::CancelAuth() {
void LoginHandler::OnRequestCancelled() { void LoginHandler::OnRequestCancelled() {
TestAndSetAuthHandled(); TestAndSetAuthHandled();
request_ = nullptr; auth_required_callback_.Reset();
} }
// Marks authentication as handled and returns the previous handled state. // Marks authentication as handled and returns the previous handled state.
@ -91,22 +77,16 @@ bool LoginHandler::TestAndSetAuthHandled() {
void LoginHandler::DoCancelAuth() { void LoginHandler::DoCancelAuth() {
DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!auth_required_callback_.is_null())
if (request_) { std::move(auth_required_callback_).Run(base::nullopt);
request_->CancelAuth();
// Verify that CancelAuth doesn't destroy the request via our delegate.
DCHECK(request_ != nullptr);
ResetLoginHandlerForRequest(request_);
}
} }
void LoginHandler::DoLogin(const base::string16& username, void LoginHandler::DoLogin(const base::string16& username,
const base::string16& password) { const base::string16& password) {
DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!auth_required_callback_.is_null()) {
if (request_) { std::move(auth_required_callback_)
request_->SetAuth(net::AuthCredentials(username, password)); .Run(net::AuthCredentials(username, password));
ResetLoginHandlerForRequest(request_);
} }
} }

View file

@ -5,9 +5,12 @@
#ifndef ATOM_BROWSER_LOGIN_HANDLER_H_ #ifndef ATOM_BROWSER_LOGIN_HANDLER_H_
#define ATOM_BROWSER_LOGIN_HANDLER_H_ #define ATOM_BROWSER_LOGIN_HANDLER_H_
#include "base/callback.h"
#include "base/optional.h"
#include "base/strings/string16.h" #include "base/strings/string16.h"
#include "base/synchronization/lock.h" #include "base/synchronization/lock.h"
#include "content/public/browser/resource_dispatcher_host_login_delegate.h" #include "content/public/browser/resource_dispatcher_host_login_delegate.h"
#include "content/public/browser/resource_request_info.h"
namespace content { namespace content {
class WebContents; class WebContents;
@ -15,7 +18,7 @@ class WebContents;
namespace net { namespace net {
class AuthChallengeInfo; class AuthChallengeInfo;
class URLRequest; class AuthCredentials;
} // namespace net } // namespace net
namespace atom { namespace atom {
@ -23,7 +26,12 @@ namespace atom {
// Handles the HTTP basic auth, must be created on IO thread. // Handles the HTTP basic auth, must be created on IO thread.
class LoginHandler : public content::ResourceDispatcherHostLoginDelegate { class LoginHandler : public content::ResourceDispatcherHostLoginDelegate {
public: public:
LoginHandler(net::AuthChallengeInfo* auth_info, net::URLRequest* request); 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);
// Returns the WebContents associated with the request, must be called on UI // Returns the WebContents associated with the request, must be called on UI
// thread. // thread.
@ -59,13 +67,11 @@ class LoginHandler : public content::ResourceDispatcherHostLoginDelegate {
// Who/where/what asked for the authentication. // Who/where/what asked for the authentication.
scoped_refptr<net::AuthChallengeInfo> auth_info_; scoped_refptr<net::AuthChallengeInfo> auth_info_;
// The request that wants login data. // WebContents associated with the login request.
// This should only be accessed on the IO loop. content::ResourceRequestInfo::WebContentsGetter web_contents_getter_;
net::URLRequest* request_ = nullptr;
// Cached from the net::URLRequest, in case it goes NULL on us. base::Callback<void(const base::Optional<net::AuthCredentials>&)>
int render_process_host_id_ = 0; auth_required_callback_;
int render_frame_id_ = 0;
DISALLOW_COPY_AND_ASSIGN(LoginHandler); DISALLOW_COPY_AND_ASSIGN(LoginHandler);
}; };

View file

@ -8,7 +8,7 @@
#import "atom/browser/mac/atom_application.h" #import "atom/browser/mac/atom_application.h"
#include "atom/browser/mac/dict_util.h" #include "atom/browser/mac/dict_util.h"
#include "base/allocator/allocator_shim.h" #include "base/allocator/allocator_shim.h"
#include "base/allocator/features.h" #include "base/allocator/buildflags.h"
#include "base/mac/mac_util.h" #include "base/mac/mac_util.h"
#include "base/mac/scoped_objc_class_swizzler.h" #include "base/mac/scoped_objc_class_swizzler.h"
#include "base/strings/sys_string_conversions.h" #include "base/strings/sys_string_conversions.h"
@ -62,9 +62,7 @@ static base::mac::ScopedObjCClassSwizzler* g_swizzle_imk_input_session;
atom::NSDictionaryToDictionaryValue(user_notification.userInfo); atom::NSDictionaryToDictionaryValue(user_notification.userInfo);
atom::Browser::Get()->DidFinishLaunching(*launch_info); atom::Browser::Get()->DidFinishLaunching(*launch_info);
} else { } else {
std::unique_ptr<base::DictionaryValue> empty_info( atom::Browser::Get()->DidFinishLaunching(base::DictionaryValue());
new base::DictionaryValue);
atom::Browser::Get()->DidFinishLaunching(*empty_info);
} }
#if BUILDFLAG(USE_ALLOCATOR_SHIM) #if BUILDFLAG(USE_ALLOCATOR_SHIM)

View file

@ -26,7 +26,7 @@ std::unique_ptr<base::ListValue> NSArrayToListValue(NSArray* arr) {
if (!arr) if (!arr)
return nullptr; return nullptr;
std::unique_ptr<base::ListValue> result(new base::ListValue); auto result = std::make_unique<base::ListValue>();
for (id value in arr) { for (id value in arr) {
if ([value isKindOfClass:[NSString class]]) { if ([value isKindOfClass:[NSString class]]) {
result->AppendString(base::SysNSStringToUTF8(value)); result->AppendString(base::SysNSStringToUTF8(value));
@ -79,7 +79,7 @@ std::unique_ptr<base::DictionaryValue> NSDictionaryToDictionaryValue(
if (!dict) if (!dict)
return nullptr; return nullptr;
std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue); auto result = std::make_unique<base::DictionaryValue>();
for (id key in dict) { for (id key in dict) {
std::string str_key = base::SysNSStringToUTF8( std::string str_key = base::SysNSStringToUTF8(
[key isKindOfClass:[NSString class]] ? key : [key description]); [key isKindOfClass:[NSString class]] ? key : [key description]);

View file

@ -1079,7 +1079,7 @@ gfx::NativeWindow NativeWindowMac::GetNativeWindow() const {
} }
gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const {
return [window_ contentView]; return gfx::kNullAcceleratedWidget;
} }
void NativeWindowMac::SetProgressBar(double progress, void NativeWindowMac::SetProgressBar(double progress,

View file

@ -6,6 +6,7 @@
#if defined(OS_WIN) #if defined(OS_WIN)
#include <objbase.h> #include <objbase.h>
#include <wrl/client.h>
#endif #endif
#include <vector> #include <vector>
@ -192,8 +193,8 @@ NativeWindowViews::NativeWindowViews(const mate::Dictionary& options,
if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) {
XDisplay* xdisplay = gfx::GetXDisplay(); XDisplay* xdisplay = gfx::GetXDisplay();
XChangeProperty(xdisplay, GetAcceleratedWidget(), XChangeProperty(xdisplay, GetAcceleratedWidget(),
XInternAtom(xdisplay, "_GTK_THEME_VARIANT", False), XInternAtom(xdisplay, "_GTK_THEME_VARIANT", x11::False),
XInternAtom(xdisplay, "UTF8_STRING", False), 8, XInternAtom(xdisplay, "UTF8_STRING", x11::False), 8,
PropModeReplace, PropModeReplace,
reinterpret_cast<const unsigned char*>("dark"), 4); reinterpret_cast<const unsigned char*>("dark"), 4);
} }
@ -741,7 +742,7 @@ void NativeWindowViews::FlashFrame(bool flash) {
void NativeWindowViews::SetSkipTaskbar(bool skip) { void NativeWindowViews::SetSkipTaskbar(bool skip) {
#if defined(OS_WIN) #if defined(OS_WIN)
base::win::ScopedComPtr<ITaskbarList> taskbar; Microsoft::WRL::ComPtr<ITaskbarList> taskbar;
if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr,
CLSCTX_INPROC_SERVER, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&taskbar))) || IID_PPV_ARGS(&taskbar))) ||
@ -791,14 +792,14 @@ void NativeWindowViews::SetBackgroundColor(SkColor background_color) {
} }
void NativeWindowViews::SetHasShadow(bool has_shadow) { void NativeWindowViews::SetHasShadow(bool has_shadow) {
wm::SetShadowElevation(GetNativeWindow(), has_shadow wm::SetShadowElevation(GetNativeWindow(),
? wm::ShadowElevation::MEDIUM has_shadow ? wm::kShadowElevationInactiveWindow
: wm::ShadowElevation::NONE); : wm::kShadowElevationNone);
} }
bool NativeWindowViews::HasShadow() { bool NativeWindowViews::HasShadow() {
return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) !=
wm::ShadowElevation::NONE; wm::kShadowElevationNone;
} }
void NativeWindowViews::SetOpacity(const double opacity) { void NativeWindowViews::SetOpacity(const double opacity) {
@ -843,7 +844,7 @@ void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) {
ShapeInput, 0, 0, &r, 1, ShapeSet, YXBanded); ShapeInput, 0, 0, &r, 1, ShapeSet, YXBanded);
} else { } else {
XShapeCombineMask(gfx::GetXDisplay(), GetAcceleratedWidget(), ShapeInput, 0, XShapeCombineMask(gfx::GetXDisplay(), GetAcceleratedWidget(), ShapeInput, 0,
0, None, ShapeSet); 0, x11::None, ShapeSet);
} }
#endif #endif
} }
@ -1186,10 +1187,6 @@ base::string16 NativeWindowViews::GetWindowTitle() const {
return base::UTF8ToUTF16(title_); return base::UTF8ToUTF16(title_);
} }
bool NativeWindowViews::ShouldHandleSystemCommands() const {
return true;
}
views::View* NativeWindowViews::GetContentsView() { views::View* NativeWindowViews::GetContentsView() {
return root_view_.get(); return root_view_.get();
} }

View file

@ -154,7 +154,6 @@ class NativeWindowViews : public NativeWindow,
bool CanMaximize() const override; bool CanMaximize() const override;
bool CanMinimize() const override; bool CanMinimize() const override;
base::string16 GetWindowTitle() const override; base::string16 GetWindowTitle() const override;
bool ShouldHandleSystemCommands() const override;
views::View* GetContentsView() override; views::View* GetContentsView() override;
bool ShouldDescendIntoChildForEventHandling( bool ShouldDescendIntoChildForEventHandling(
gfx::NativeView child, gfx::NativeView child,

View file

@ -88,7 +88,7 @@ class CertVerifierRequest : public AtomCertVerifier::Request {
void OnDefaultVerificationDone(int error) { void OnDefaultVerificationDone(int error) {
error_ = error; error_ = error;
std::unique_ptr<VerifyRequestParams> request(new VerifyRequestParams()); auto request = std::make_unique<VerifyRequestParams>();
request->hostname = params_.hostname(); request->hostname = params_.hostname();
request->default_result = net::ErrorToString(error); request->default_result = net::ErrorToString(error);
request->error_code = error; request->error_code = error;
@ -174,8 +174,7 @@ int AtomCertVerifier::Verify(const RequestParams& params,
CertVerifierRequest* request = FindRequest(params); CertVerifierRequest* request = FindRequest(params);
if (!request) { if (!request) {
out_req->reset(); out_req->reset();
std::unique_ptr<CertVerifierRequest> new_request = auto new_request = std::make_unique<CertVerifierRequest>(params, this);
std::make_unique<CertVerifierRequest>(params, this);
new_request->Start(crl_set, net_log); new_request->Start(crl_set, net_log);
request = new_request.get(); request = new_request.get();
*out_req = std::move(new_request); *out_req = std::move(new_request);

View file

@ -10,13 +10,13 @@
#include "atom/common/native_mate_converters/net_converter.h" #include "atom/common/native_mate_converters/net_converter.h"
#include "base/stl_util.h" #include "base/stl_util.h"
#include "base/strings/string_util.h" #include "base/strings/string_util.h"
#include "content/common/devtools/devtools_network_transaction.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_frame_host.h"
#include "net/url_request/url_request.h" #include "net/url_request/url_request.h"
#include "services/network/throttling/throttling_network_transaction.h"
using content::BrowserThread; using content::BrowserThread;
using content::DevToolsNetworkTransaction; using network::ThrottlingNetworkTransaction;
namespace atom { namespace atom {
@ -105,7 +105,7 @@ void ToDictionary(base::DictionaryValue* details, net::URLRequest* request) {
void ToDictionary(base::DictionaryValue* details, void ToDictionary(base::DictionaryValue* details,
const net::HttpRequestHeaders& headers) { const net::HttpRequestHeaders& headers) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue); auto dict = std::make_unique<base::DictionaryValue>();
net::HttpRequestHeaders::Iterator it(headers); net::HttpRequestHeaders::Iterator it(headers);
while (it.GetNext()) while (it.GetNext())
dict->SetKey(it.name(), base::Value(it.value())); dict->SetKey(it.name(), base::Value(it.value()));
@ -117,7 +117,7 @@ void ToDictionary(base::DictionaryValue* details,
if (!headers) if (!headers)
return; return;
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue); auto dict = std::make_unique<base::DictionaryValue>();
size_t iter = 0; size_t iter = 0;
std::string key; std::string key;
std::string value; std::string value;
@ -127,7 +127,7 @@ void ToDictionary(base::DictionaryValue* details,
if (dict->GetList(key, &values)) if (dict->GetList(key, &values))
values->AppendString(value); values->AppendString(value);
} else { } else {
std::unique_ptr<base::ListValue> values(new base::ListValue); auto values = std::make_unique<base::ListValue>();
values->AppendString(value); values->AppendString(value);
dict->Set(key, std::move(values)); dict->Set(key, std::move(values));
} }
@ -274,7 +274,7 @@ int AtomNetworkDelegate::OnBeforeStartTransaction(
const net::CompletionCallback& callback, const net::CompletionCallback& callback,
net::HttpRequestHeaders* headers) { net::HttpRequestHeaders* headers) {
if (!client_id_.empty()) if (!client_id_.empty())
headers->SetHeader(content::DevToolsNetworkTransaction:: headers->SetHeader(network::ThrottlingNetworkTransaction::
kDevToolsEmulateNetworkConditionsClientId, kDevToolsEmulateNetworkConditionsClientId,
client_id_); client_id_);
if (!base::ContainsKey(response_listeners_, kOnBeforeSendHeaders)) if (!base::ContainsKey(response_listeners_, kOnBeforeSendHeaders))
@ -323,9 +323,10 @@ void AtomNetworkDelegate::OnBeforeRedirect(net::URLRequest* request,
request->was_cached()); request->was_cached());
} }
void AtomNetworkDelegate::OnResponseStarted(net::URLRequest* request) { void AtomNetworkDelegate::OnResponseStarted(net::URLRequest* request,
int net_error) {
if (!base::ContainsKey(simple_listeners_, kOnResponseStarted)) { if (!base::ContainsKey(simple_listeners_, kOnResponseStarted)) {
brightray::NetworkDelegate::OnResponseStarted(request); brightray::NetworkDelegate::OnResponseStarted(request, net_error);
return; return;
} }
@ -388,7 +389,7 @@ int AtomNetworkDelegate::HandleResponseEvent(
if (!MatchesFilterCondition(request, info.url_patterns)) if (!MatchesFilterCondition(request, info.url_patterns))
return net::OK; return net::OK;
std::unique_ptr<base::DictionaryValue> details(new base::DictionaryValue); auto details = std::make_unique<base::DictionaryValue>();
FillDetailsObject(details.get(), request, args...); FillDetailsObject(details.get(), request, args...);
int render_process_id, render_frame_id; int render_process_id, render_frame_id;
@ -416,7 +417,7 @@ void AtomNetworkDelegate::HandleSimpleEvent(SimpleEvent type,
if (!MatchesFilterCondition(request, info.url_patterns)) if (!MatchesFilterCondition(request, info.url_patterns))
return; return;
std::unique_ptr<base::DictionaryValue> details(new base::DictionaryValue); auto details = std::make_unique<base::DictionaryValue>();
FillDetailsObject(details.get(), request, args...); FillDetailsObject(details.get(), request, args...);
int render_process_id, render_frame_id; int render_process_id, render_frame_id;

View file

@ -96,7 +96,7 @@ class AtomNetworkDelegate : public brightray::NetworkDelegate {
GURL* allowed_unsafe_redirect_url) override; GURL* allowed_unsafe_redirect_url) override;
void OnBeforeRedirect(net::URLRequest* request, void OnBeforeRedirect(net::URLRequest* request,
const GURL& new_location) override; const GURL& new_location) override;
void OnResponseStarted(net::URLRequest* request) override; void OnResponseStarted(net::URLRequest* request, int net_error) override;
void OnCompleted(net::URLRequest* request, bool started) override; void OnCompleted(net::URLRequest* request, bool started) override;
void OnURLRequestDestroyed(net::URLRequest* request) override; void OnURLRequestDestroyed(net::URLRequest* request) override;

View file

@ -354,7 +354,8 @@ void AtomURLRequest::OnAuthRequired(net::URLRequest* request,
this, scoped_refptr<net::AuthChallengeInfo>(auth_info))); this, scoped_refptr<net::AuthChallengeInfo>(auth_info)));
} }
void AtomURLRequest::OnResponseStarted(net::URLRequest* request) { void AtomURLRequest::OnResponseStarted(net::URLRequest* request,
int net_error) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (!request_) { if (!request_) {
return; return;
@ -373,7 +374,7 @@ void AtomURLRequest::OnResponseStarted(net::URLRequest* request) {
ReadResponse(); ReadResponse();
} else if (status.status() == net::URLRequestStatus::Status::FAILED) { } else if (status.status() == net::URLRequestStatus::Status::FAILED) {
// Report error on Start. // Report error on Start.
DoCancelWithError(net::ErrorToString(status.ToNetError()), true); DoCancelWithError(net::ErrorToString(net_error), true);
} }
// We don't report an error is the request is canceled. // We don't report an error is the request is canceled.
} }

View file

@ -51,7 +51,7 @@ class AtomURLRequest : public base::RefCountedThreadSafe<AtomURLRequest>,
bool* defer_redirect) override; bool* defer_redirect) override;
void OnAuthRequired(net::URLRequest* request, void OnAuthRequired(net::URLRequest* request,
net::AuthChallengeInfo* auth_info) override; net::AuthChallengeInfo* auth_info) override;
void OnResponseStarted(net::URLRequest* request) override; void OnResponseStarted(net::URLRequest* request, int net_error) override;
void OnReadCompleted(net::URLRequest* request, int bytes_read) override; void OnReadCompleted(net::URLRequest* request, int bytes_read) override;
// Overrides of net::URLRequestContextGetterObserver // Overrides of net::URLRequestContextGetterObserver

View file

@ -6,7 +6,7 @@
#define ATOM_BROWSER_NET_COOKIE_DETAILS_H_ #define ATOM_BROWSER_NET_COOKIE_DETAILS_H_
#include "base/macros.h" #include "base/macros.h"
#include "net/cookies/cookie_store.h" #include "net/cookies/cookie_change_dispatcher.h"
namespace atom { namespace atom {
@ -14,12 +14,12 @@ struct CookieDetails {
public: public:
CookieDetails(const net::CanonicalCookie* cookie_copy, CookieDetails(const net::CanonicalCookie* cookie_copy,
bool is_removed, bool is_removed,
net::CookieStore::ChangeCause cause) net::CookieChangeCause cause)
: cookie(cookie_copy), removed(is_removed), cause(cause) {} : cookie(cookie_copy), removed(is_removed), cause(cause) {}
const net::CanonicalCookie* cookie; const net::CanonicalCookie* cookie;
bool removed; bool removed;
net::CookieStore::ChangeCause cause; net::CookieChangeCause cause;
}; };
} // namespace atom } // namespace atom

View file

@ -57,11 +57,11 @@ void AskForOptions(v8::Isolate* isolate,
} }
bool IsErrorOptions(base::Value* value, int* error) { bool IsErrorOptions(base::Value* value, int* error) {
if (value->IsType(base::Value::Type::DICTIONARY)) { if (value->is_dict()) {
base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(value); base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(value);
if (dict->GetInteger("error", error)) if (dict->GetInteger("error", error))
return true; return true;
} else if (value->IsType(base::Value::Type::INTEGER)) { } else if (value->is_int()) {
if (value->GetAsInteger(error)) if (value->GetAsInteger(error))
return true; return true;
} }

View file

@ -68,8 +68,7 @@ class JsAsker : public RequestJob {
private: private:
// RequestJob: // RequestJob:
void Start() override { void Start() override {
std::unique_ptr<base::DictionaryValue> request_details( auto request_details = std::make_unique<base::DictionaryValue>();
new base::DictionaryValue);
request_start_time_ = base::TimeTicks::Now(); request_start_time_ = base::TimeTicks::Now();
FillRequestDetails(request_details.get(), RequestJob::request()); FillRequestDetails(request_details.get(), RequestJob::request());
content::BrowserThread::PostTask( content::BrowserThread::PostTask(

View file

@ -18,10 +18,10 @@ URLRequestAsyncAsarJob::URLRequestAsyncAsarJob(
void URLRequestAsyncAsarJob::StartAsync(std::unique_ptr<base::Value> options) { void URLRequestAsyncAsarJob::StartAsync(std::unique_ptr<base::Value> options) {
base::FilePath::StringType file_path; base::FilePath::StringType file_path;
if (options->IsType(base::Value::Type::DICTIONARY)) { if (options->is_dict()) {
static_cast<base::DictionaryValue*>(options.get()) static_cast<base::DictionaryValue*>(options.get())
->GetString("path", &file_path); ->GetString("path", &file_path);
} else if (options->IsType(base::Value::Type::STRING)) { } else if (options->is_string()) {
options->GetAsString(&file_path); options->GetAsString(&file_path);
} }

View file

@ -35,13 +35,13 @@ URLRequestBufferJob::~URLRequestBufferJob() = default;
void URLRequestBufferJob::StartAsync(std::unique_ptr<base::Value> options) { void URLRequestBufferJob::StartAsync(std::unique_ptr<base::Value> options) {
const base::Value* binary = nullptr; const base::Value* binary = nullptr;
if (options->IsType(base::Value::Type::DICTIONARY)) { if (options->is_dict()) {
base::DictionaryValue* dict = base::DictionaryValue* dict =
static_cast<base::DictionaryValue*>(options.get()); static_cast<base::DictionaryValue*>(options.get());
dict->GetString("mimeType", &mime_type_); dict->GetString("mimeType", &mime_type_);
dict->GetString("charset", &charset_); dict->GetString("charset", &charset_);
dict->GetBinary("data", &binary); dict->GetBinary("data", &binary);
} else if (options->IsType(base::Value::Type::BINARY)) { } else if (options->is_blob()) {
binary = options.get(); binary = options.get();
} }

View file

@ -109,7 +109,7 @@ void URLRequestFetchJob::BeforeStartInUI(v8::Isolate* isolate,
} }
void URLRequestFetchJob::StartAsync(std::unique_ptr<base::Value> options) { void URLRequestFetchJob::StartAsync(std::unique_ptr<base::Value> options) {
if (!options->IsType(base::Value::Type::DICTIONARY)) { if (!options->is_dict()) {
NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED, NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED,
net::ERR_NOT_IMPLEMENTED)); net::ERR_NOT_IMPLEMENTED));
return; return;

View file

@ -18,13 +18,13 @@ URLRequestStringJob::URLRequestStringJob(net::URLRequest* request,
URLRequestStringJob::~URLRequestStringJob() = default; URLRequestStringJob::~URLRequestStringJob() = default;
void URLRequestStringJob::StartAsync(std::unique_ptr<base::Value> options) { void URLRequestStringJob::StartAsync(std::unique_ptr<base::Value> options) {
if (options->IsType(base::Value::Type::DICTIONARY)) { if (options->is_dict()) {
base::DictionaryValue* dict = base::DictionaryValue* dict =
static_cast<base::DictionaryValue*>(options.get()); static_cast<base::DictionaryValue*>(options.get());
dict->GetString("mimeType", &mime_type_); dict->GetString("mimeType", &mime_type_);
dict->GetString("charset", &charset_); dict->GetString("charset", &charset_);
dict->GetString("data", &data_); dict->GetString("data", &data_);
} else if (options->IsType(base::Value::Type::STRING)) { } else if (options->is_string()) {
options->GetAsString(&data_); options->GetAsString(&data_);
} }
net::URLRequestSimpleJob::Start(); net::URLRequestSimpleJob::Start();

View file

@ -14,6 +14,7 @@
#include "base/memory/ptr_util.h" #include "base/memory/ptr_util.h"
#include "base/single_thread_task_runner.h" #include "base/single_thread_task_runner.h"
#include "base/time/time.h" #include "base/time/time.h"
#include "components/viz/common/features.h"
#include "components/viz/common/frame_sinks/copy_output_request.h" #include "components/viz/common/frame_sinks/copy_output_request.h"
#include "components/viz/common/frame_sinks/delay_based_time_source.h" #include "components/viz/common/frame_sinks/delay_based_time_source.h"
#include "components/viz/common/gl_helper.h" #include "components/viz/common/gl_helper.h"
@ -21,10 +22,10 @@
#include "content/browser/renderer_host/compositor_resize_lock.h" #include "content/browser/renderer_host/compositor_resize_lock.h"
#include "content/browser/renderer_host/render_widget_host_delegate.h" #include "content/browser/renderer_host/render_widget_host_delegate.h"
#include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_frame_subscriber.h"
#include "content/common/view_messages.h" #include "content/common/view_messages.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "content/public/browser/context_factory.h" #include "content/public/browser/context_factory.h"
#include "content/public/browser/render_process_host.h"
#include "media/base/video_frame.h" #include "media/base/video_frame.h"
#include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebInputEvent.h"
#include "ui/compositor/compositor.h" #include "ui/compositor/compositor.h"
@ -133,7 +134,7 @@ class AtomCopyFrameGenerator {
&AtomCopyFrameGenerator::CopyFromCompositingSurfaceHasResult, &AtomCopyFrameGenerator::CopyFromCompositingSurfaceHasResult,
weak_ptr_factory_.GetWeakPtr(), damage_rect)); weak_ptr_factory_.GetWeakPtr(), damage_rect));
request->set_area(gfx::Rect(view_->GetPhysicalBackingSize())); request->set_area(gfx::Rect(view_->GetCompositorViewportPixelSize()));
view_->GetRootLayer()->RequestCopyOfOutput(std::move(request)); view_->GetRootLayer()->RequestCopyOfOutput(std::move(request));
} }
@ -269,13 +270,18 @@ OffScreenRenderWidgetHostView::OffScreenRenderWidgetHostView(
#if !defined(OS_MACOSX) #if !defined(OS_MACOSX)
delegated_frame_host_ = std::make_unique<content::DelegatedFrameHost>( delegated_frame_host_ = std::make_unique<content::DelegatedFrameHost>(
AllocateFrameSinkId(is_guest_view_hack), this, AllocateFrameSinkId(is_guest_view_hack), this,
false /* enable_surface_synchronization */); features::IsSurfaceSynchronizationEnabled(),
base::FeatureList::IsEnabled(features::kVizDisplayCompositor),
true /* should_register_frame_sink_id */);
root_layer_.reset(new ui::Layer(ui::LAYER_SOLID_COLOR)); root_layer_.reset(new ui::Layer(ui::LAYER_SOLID_COLOR));
#endif #endif
local_surface_id_ = local_surface_id_allocator_.GenerateId(); local_surface_id_ = local_surface_id_allocator_.GenerateId();
// Surface synchronization is not supported with OSR.
DCHECK(!features::IsSurfaceSynchronizationEnabled());
#if defined(OS_MACOSX) #if defined(OS_MACOSX)
CreatePlatformWidget(is_guest_view_hack); CreatePlatformWidget(is_guest_view_hack);
#else #else
@ -288,7 +294,7 @@ OffScreenRenderWidgetHostView::OffScreenRenderWidgetHostView(
new ui::Compositor(context_factory_private->AllocateFrameSinkId(), new ui::Compositor(context_factory_private->AllocateFrameSinkId(),
content::GetContextFactory(), context_factory_private, content::GetContextFactory(), context_factory_private,
base::ThreadTaskRunnerHandle::Get(), base::ThreadTaskRunnerHandle::Get(),
false /* enable_surface_synchronization */, features::IsSurfaceSynchronizationEnabled(),
false /* enable_pixel_canvas */)); false /* enable_pixel_canvas */));
compositor_->SetAcceleratedWidget(gfx::kNullAcceleratedWidget); compositor_->SetAcceleratedWidget(gfx::kNullAcceleratedWidget);
compositor_->SetRootLayer(root_layer_.get()); compositor_->SetRootLayer(root_layer_.get());
@ -369,19 +375,6 @@ void OffScreenRenderWidgetHostView::SendBeginFrame(
renderer_compositor_frame_sink_->OnBeginFrame(begin_frame_args); renderer_compositor_frame_sink_->OnBeginFrame(begin_frame_args);
} }
bool OffScreenRenderWidgetHostView::OnMessageReceived(
const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(OffScreenRenderWidgetHostView, message)
IPC_MESSAGE_HANDLER(ViewHostMsg_SetNeedsBeginFrames, SetNeedsBeginFrames)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (!handled)
return content::RenderWidgetHostViewBase::OnMessageReceived(message);
return handled;
}
void OffScreenRenderWidgetHostView::InitAsChild(gfx::NativeView) { void OffScreenRenderWidgetHostView::InitAsChild(gfx::NativeView) {
DCHECK(parent_host_view_); DCHECK(parent_host_view_);
@ -396,11 +389,6 @@ void OffScreenRenderWidgetHostView::InitAsChild(gfx::NativeView) {
Show(); Show();
} }
content::RenderWidgetHost* OffScreenRenderWidgetHostView::GetRenderWidgetHost()
const {
return render_widget_host_;
}
void OffScreenRenderWidgetHostView::SetSize(const gfx::Size& size) { void OffScreenRenderWidgetHostView::SetSize(const gfx::Size& size) {
size_ = size; size_ = size;
WasResized(); WasResized();
@ -447,7 +435,8 @@ void OffScreenRenderWidgetHostView::Show() {
browser_compositor_->SetRenderWidgetHostIsHidden(false); browser_compositor_->SetRenderWidgetHostIsHidden(false);
#else #else
delegated_frame_host_->SetCompositor(compositor_.get()); delegated_frame_host_->SetCompositor(compositor_.get());
delegated_frame_host_->WasShown(ui::LatencyInfo()); delegated_frame_host_->WasShown(
GetLocalSurfaceId(), GetRootLayer()->bounds().size(), ui::LatencyInfo());
#endif #endif
if (render_widget_host_) if (render_widget_host_)
@ -520,7 +509,8 @@ void OffScreenRenderWidgetHostView::DidCreateNewRendererCompositorFrameSink(
void OffScreenRenderWidgetHostView::SubmitCompositorFrame( void OffScreenRenderWidgetHostView::SubmitCompositorFrame(
const viz::LocalSurfaceId& local_surface_id, const viz::LocalSurfaceId& local_surface_id,
viz::CompositorFrame frame) { viz::CompositorFrame frame,
viz::mojom::HitTestRegionListPtr hit_test_region_list) {
TRACE_EVENT0("electron", TRACE_EVENT0("electron",
"OffScreenRenderWidgetHostView::SubmitCompositorFrame"); "OffScreenRenderWidgetHostView::SubmitCompositorFrame");
@ -539,8 +529,8 @@ void OffScreenRenderWidgetHostView::SubmitCompositorFrame(
// We would normally call BrowserCompositorMac::SubmitCompositorFrame on // We would normally call BrowserCompositorMac::SubmitCompositorFrame on
// macOS, however it contains compositor resize logic that we don't want. // macOS, however it contains compositor resize logic that we don't want.
// Consequently we instead call the SubmitCompositorFrame method directly. // Consequently we instead call the SubmitCompositorFrame method directly.
GetDelegatedFrameHost()->SubmitCompositorFrame(local_surface_id, GetDelegatedFrameHost()->SubmitCompositorFrame(
std::move(frame)); local_surface_id, std::move(frame), std::move(hit_test_region_list));
} else { } else {
if (!copy_frame_generator_.get()) { if (!copy_frame_generator_.get()) {
copy_frame_generator_.reset( copy_frame_generator_.reset(
@ -558,8 +548,8 @@ void OffScreenRenderWidgetHostView::SubmitCompositorFrame(
// We would normally call BrowserCompositorMac::SubmitCompositorFrame on // We would normally call BrowserCompositorMac::SubmitCompositorFrame on
// macOS, however it contains compositor resize logic that we don't want. // macOS, however it contains compositor resize logic that we don't want.
// Consequently we instead call the SubmitCompositorFrame method directly. // Consequently we instead call the SubmitCompositorFrame method directly.
GetDelegatedFrameHost()->SubmitCompositorFrame(local_surface_id, GetDelegatedFrameHost()->SubmitCompositorFrame(
std::move(frame)); local_surface_id, std::move(frame), std::move(hit_test_region_list));
// Request a copy of the last compositor frame which will eventually call // Request a copy of the last compositor frame which will eventually call
// OnPaint asynchronously. // OnPaint asynchronously.
@ -645,29 +635,23 @@ void OffScreenRenderWidgetHostView::SelectionBoundsChanged(
const ViewHostMsg_SelectionBounds_Params&) {} const ViewHostMsg_SelectionBounds_Params&) {}
void OffScreenRenderWidgetHostView::CopyFromSurface( void OffScreenRenderWidgetHostView::CopyFromSurface(
const gfx::Rect& src_subrect, const gfx::Rect& src_rect,
const gfx::Size& dst_size, const gfx::Size& output_size,
const content::ReadbackRequestCallback& callback, base::OnceCallback<void(const SkBitmap&)> callback) {
const SkColorType preferred_color_type) { GetDelegatedFrameHost()->CopyFromCompositingSurface(src_rect, output_size,
GetDelegatedFrameHost()->CopyFromCompositingSurface( std::move(callback));
src_subrect, dst_size, callback, preferred_color_type);
} }
void OffScreenRenderWidgetHostView::CopyFromSurfaceToVideoFrame( void OffScreenRenderWidgetHostView::GetScreenInfo(
const gfx::Rect& src_subrect, content::ScreenInfo* screen_info) const {
scoped_refptr<media::VideoFrame> target, screen_info->depth = 24;
const base::Callback<void(const gfx::Rect&, bool)>& callback) { screen_info->depth_per_component = 8;
GetDelegatedFrameHost()->CopyFromCompositingSurfaceToVideoFrame( screen_info->orientation_angle = 0;
src_subrect, target, callback); screen_info->device_scale_factor = 1.0;
} screen_info->orientation_type =
content::SCREEN_ORIENTATION_VALUES_LANDSCAPE_PRIMARY;
void OffScreenRenderWidgetHostView::BeginFrameSubscription( screen_info->rect = gfx::Rect(size_);
std::unique_ptr<content::RenderWidgetHostViewFrameSubscriber> subscriber) { screen_info->available_rect = gfx::Rect(size_);
GetDelegatedFrameHost()->BeginFrameSubscription(std::move(subscriber));
}
void OffScreenRenderWidgetHostView::EndFrameSubscription() {
GetDelegatedFrameHost()->EndFrameSubscription();
} }
void OffScreenRenderWidgetHostView::InitAsGuest( void OffScreenRenderWidgetHostView::InitAsGuest(
@ -677,19 +661,31 @@ void OffScreenRenderWidgetHostView::InitAsGuest(
parent_host_view_->RegisterGuestViewFrameSwappedCallback(guest_view); parent_host_view_->RegisterGuestViewFrameSwappedCallback(guest_view);
} }
bool OffScreenRenderWidgetHostView::HasAcceleratedSurface(const gfx::Size&) { gfx::Vector2d OffScreenRenderWidgetHostView::GetOffsetFromRootSurface() {
return false; return gfx::Vector2d();
} }
gfx::Rect OffScreenRenderWidgetHostView::GetBoundsInRootWindow() { gfx::Rect OffScreenRenderWidgetHostView::GetBoundsInRootWindow() {
return gfx::Rect(size_); return gfx::Rect(size_);
} }
content::RenderWidgetHostImpl*
OffScreenRenderWidgetHostView::GetRenderWidgetHostImpl() const {
return render_widget_host_;
}
viz::SurfaceId OffScreenRenderWidgetHostView::GetCurrentSurfaceId() const {
return GetDelegatedFrameHost()
? GetDelegatedFrameHost()->GetCurrentSurfaceId()
: viz::SurfaceId();
}
void OffScreenRenderWidgetHostView::ImeCompositionRangeChanged( void OffScreenRenderWidgetHostView::ImeCompositionRangeChanged(
const gfx::Range&, const gfx::Range&,
const std::vector<gfx::Rect>&) {} const std::vector<gfx::Rect>&) {}
gfx::Size OffScreenRenderWidgetHostView::GetPhysicalBackingSize() const { gfx::Size OffScreenRenderWidgetHostView::GetCompositorViewportPixelSize()
const {
return gfx::ScaleToCeiledSize(GetRequestedRendererSize(), scale_factor_); return gfx::ScaleToCeiledSize(GetRequestedRendererSize(), scale_factor_);
} }
@ -727,18 +723,13 @@ bool OffScreenRenderWidgetHostView::DelegatedFrameHostIsVisible() const {
return !render_widget_host_->is_hidden(); return !render_widget_host_->is_hidden();
} }
SkColor OffScreenRenderWidgetHostView::DelegatedFrameHostGetGutterColor( SkColor OffScreenRenderWidgetHostView::DelegatedFrameHostGetGutterColor()
SkColor color) const { const {
if (render_widget_host_->delegate() && if (render_widget_host_->delegate() &&
render_widget_host_->delegate()->IsFullscreenForCurrentTab()) { render_widget_host_->delegate()->IsFullscreenForCurrentTab()) {
return SK_ColorWHITE; return SK_ColorWHITE;
} }
return color; return background_color_;
}
gfx::Size OffScreenRenderWidgetHostView::DelegatedFrameHostDesiredSizeInDIP()
const {
return GetRootLayer()->bounds().size();
} }
bool OffScreenRenderWidgetHostView::DelegatedFrameCanCreateResizeLock() const { bool OffScreenRenderWidgetHostView::DelegatedFrameCanCreateResizeLock() const {
@ -756,7 +747,18 @@ viz::LocalSurfaceId OffScreenRenderWidgetHostView::GetLocalSurfaceId() const {
return local_surface_id_; return local_surface_id_;
} }
void OffScreenRenderWidgetHostView::OnBeginFrame() {} void OffScreenRenderWidgetHostView::OnFirstSurfaceActivation(
const viz::SurfaceInfo& surface_info) {}
void OffScreenRenderWidgetHostView::OnBeginFrame(base::TimeTicks frame_time) {}
void OffScreenRenderWidgetHostView::OnFrameTokenChanged(uint32_t frame_token) {
render_widget_host_->DidProcessFrame(frame_token);
}
void OffScreenRenderWidgetHostView::DidReceiveFirstFrameAfterNavigation() {
render_widget_host_->DidReceiveFirstFrameAfterNavigation();
}
std::unique_ptr<ui::CompositorLock> std::unique_ptr<ui::CompositorLock>
OffScreenRenderWidgetHostView::GetCompositorLock( OffScreenRenderWidgetHostView::GetCompositorLock(
@ -775,12 +777,12 @@ bool OffScreenRenderWidgetHostView::IsAutoResizeEnabled() const {
#endif // !defined(OS_MACOSX) #endif // !defined(OS_MACOSX)
bool OffScreenRenderWidgetHostView::TransformPointToLocalCoordSpace( bool OffScreenRenderWidgetHostView::TransformPointToLocalCoordSpace(
const gfx::Point& point, const gfx::PointF& point,
const viz::SurfaceId& original_surface, const viz::SurfaceId& original_surface,
gfx::Point* transformed_point) { gfx::PointF* transformed_point) {
// Transformations use physical pixels rather than DIP, so conversion // Transformations use physical pixels rather than DIP, so conversion
// is necessary. // is necessary.
gfx::Point point_in_pixels = gfx::ConvertPointToPixel(scale_factor_, point); gfx::PointF point_in_pixels = gfx::ConvertPointToPixel(scale_factor_, point);
if (!GetDelegatedFrameHost()->TransformPointToLocalCoordSpace( if (!GetDelegatedFrameHost()->TransformPointToLocalCoordSpace(
point_in_pixels, original_surface, transformed_point)) { point_in_pixels, original_surface, transformed_point)) {
return false; return false;
@ -792,9 +794,9 @@ bool OffScreenRenderWidgetHostView::TransformPointToLocalCoordSpace(
} }
bool OffScreenRenderWidgetHostView::TransformPointToCoordSpaceForView( bool OffScreenRenderWidgetHostView::TransformPointToCoordSpaceForView(
const gfx::Point& point, const gfx::PointF& point,
RenderWidgetHostViewBase* target_view, RenderWidgetHostViewBase* target_view,
gfx::Point* transformed_point) { gfx::PointF* transformed_point) {
if (target_view == this) { if (target_view == this) {
*transformed_point = point; *transformed_point = point;
return true; return true;
@ -860,10 +862,9 @@ void OffScreenRenderWidgetHostView::ProxyViewDestroyed(
void OffScreenRenderWidgetHostView::RegisterGuestViewFrameSwappedCallback( void OffScreenRenderWidgetHostView::RegisterGuestViewFrameSwappedCallback(
content::RenderWidgetHostViewGuest* guest_host_view) { content::RenderWidgetHostViewGuest* guest_host_view) {
guest_host_view->RegisterFrameSwappedCallback( guest_host_view->RegisterFrameSwappedCallback(base::BindOnce(
std::make_unique<base::Closure>(base::Bind( &OffScreenRenderWidgetHostView::OnGuestViewFrameSwapped,
&OffScreenRenderWidgetHostView::OnGuestViewFrameSwapped, weak_ptr_factory_.GetWeakPtr(), base::Unretained(guest_host_view)));
weak_ptr_factory_.GetWeakPtr(), base::Unretained(guest_host_view))));
} }
void OffScreenRenderWidgetHostView::OnGuestViewFrameSwapped( void OffScreenRenderWidgetHostView::OnGuestViewFrameSwapped(
@ -913,6 +914,12 @@ void OffScreenRenderWidgetHostView::SetNeedsBeginFrames(
} }
} }
void OffScreenRenderWidgetHostView::SetWantsAnimateOnlyBeginFrames() {
if (GetDelegatedFrameHost()) {
GetDelegatedFrameHost()->SetWantsAnimateOnlyBeginFrames();
}
}
void CopyBitmapTo(const SkBitmap& destination, void CopyBitmapTo(const SkBitmap& destination,
const SkBitmap& source, const SkBitmap& source,
const gfx::Rect& pos) { const gfx::Rect& pos) {
@ -1030,20 +1037,12 @@ void OffScreenRenderWidgetHostView::WasResized() {
ResizeRootLayer(); ResizeRootLayer();
if (render_widget_host_) if (render_widget_host_)
render_widget_host_->WasResized(); render_widget_host_->WasResized();
GetDelegatedFrameHost()->WasResized(); GetDelegatedFrameHost()->WasResized(local_surface_id_, size_,
cc::DeadlinePolicy::UseDefaultDeadline());
} }
void OffScreenRenderWidgetHostView::ProcessKeyboardEvent( void OffScreenRenderWidgetHostView::SendMouseEvent(
const content::NativeWebKeyboardEvent& event, const blink::WebMouseEvent& event) {
const ui::LatencyInfo& latency) {
if (!render_widget_host_)
return;
render_widget_host_->ForwardKeyboardEventWithLatencyInfo(event, latency);
}
void OffScreenRenderWidgetHostView::ProcessMouseEvent(
const blink::WebMouseEvent& event,
const ui::LatencyInfo& latency) {
for (auto* proxy_view : proxy_views_) { for (auto* proxy_view : proxy_views_) {
gfx::Rect bounds = proxy_view->GetBounds(); gfx::Rect bounds = proxy_view->GetBounds();
if (bounds.Contains(event.PositionInWidget().x, if (bounds.Contains(event.PositionInWidget().x,
@ -1070,7 +1069,7 @@ void OffScreenRenderWidgetHostView::ProcessMouseEvent(
popup_event.PositionInWidget().y - popup_event.PositionInWidget().y -
popup_host_view_->popup_position_.y()); popup_host_view_->popup_position_.y());
popup_host_view_->ProcessMouseEvent(popup_event, latency); popup_host_view_->ProcessMouseEvent(popup_event, ui::LatencyInfo());
return; return;
} }
} }
@ -1080,9 +1079,8 @@ void OffScreenRenderWidgetHostView::ProcessMouseEvent(
render_widget_host_->ForwardMouseEvent(event); render_widget_host_->ForwardMouseEvent(event);
} }
void OffScreenRenderWidgetHostView::ProcessMouseWheelEvent( void OffScreenRenderWidgetHostView::SendMouseWheelEvent(
const blink::WebMouseWheelEvent& event, const blink::WebMouseWheelEvent& event) {
const ui::LatencyInfo& latency) {
for (auto* proxy_view : proxy_views_) { for (auto* proxy_view : proxy_views_) {
gfx::Rect bounds = proxy_view->GetBounds(); gfx::Rect bounds = proxy_view->GetBounds();
if (bounds.Contains(event.PositionInWidget().x, if (bounds.Contains(event.PositionInWidget().x,
@ -1108,7 +1106,8 @@ void OffScreenRenderWidgetHostView::ProcessMouseWheelEvent(
popup_host_view_->popup_position_.x(), popup_host_view_->popup_position_.x(),
popup_event.PositionInWidget().y - popup_event.PositionInWidget().y -
popup_host_view_->popup_position_.y()); popup_host_view_->popup_position_.y());
popup_host_view_->ProcessMouseWheelEvent(popup_event, latency); popup_host_view_->ProcessMouseWheelEvent(popup_event,
ui::LatencyInfo());
return; return;
} else { } else {
// Scrolling outside of the popup widget so destroy it. // Scrolling outside of the popup widget so destroy it.
@ -1235,7 +1234,21 @@ void OffScreenRenderWidgetHostView::ResizeRootLayer() {
local_surface_id_ = local_surface_id_allocator_.GenerateId(); local_surface_id_ = local_surface_id_allocator_.GenerateId();
GetRootLayer()->SetBounds(gfx::Rect(size)); GetRootLayer()->SetBounds(gfx::Rect(size));
GetCompositor()->SetScaleAndSize(scale_factor_, size_in_pixels); GetCompositor()->SetScaleAndSize(scale_factor_, size_in_pixels,
local_surface_id_);
#if defined(OS_MACOSX)
bool resized = browser_compositor_->UpdateNSViewAndDisplay();
#else
bool resized = true;
GetDelegatedFrameHost()->WasResized(local_surface_id_, size,
cc::DeadlinePolicy::UseDefaultDeadline());
#endif
// Note that |render_widget_host_| will retrieve resize parameters from the
// DelegatedFrameHost, so it must have WasResized called after.
if (resized && render_widget_host_)
render_widget_host_->WasResized();
} }
viz::FrameSinkId OffScreenRenderWidgetHostView::AllocateFrameSinkId( viz::FrameSinkId OffScreenRenderWidgetHostView::AllocateFrameSinkId(

View file

@ -23,7 +23,7 @@
#include "components/viz/common/frame_sinks/begin_frame_args.h" #include "components/viz/common/frame_sinks/begin_frame_args.h"
#include "components/viz/common/frame_sinks/begin_frame_source.h" #include "components/viz/common/frame_sinks/begin_frame_source.h"
#include "components/viz/common/quads/compositor_frame.h" #include "components/viz/common/quads/compositor_frame.h"
#include "components/viz/common/surfaces/local_surface_id_allocator.h" #include "components/viz/common/surfaces/parent_local_surface_id_allocator.h"
#include "content/browser/frame_host/render_widget_host_view_guest.h" #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/compositor_resize_lock.h"
#include "content/browser/renderer_host/delegated_frame_host.h" #include "content/browser/renderer_host/delegated_frame_host.h"
@ -85,9 +85,7 @@ class OffScreenRenderWidgetHostView
~OffScreenRenderWidgetHostView() override; ~OffScreenRenderWidgetHostView() override;
// content::RenderWidgetHostView: // content::RenderWidgetHostView:
bool OnMessageReceived(const IPC::Message&) override;
void InitAsChild(gfx::NativeView) override; void InitAsChild(gfx::NativeView) override;
content::RenderWidgetHost* GetRenderWidgetHost(void) const override;
void SetSize(const gfx::Size&) override; void SetSize(const gfx::Size&) override;
void SetBounds(const gfx::Rect&) override; void SetBounds(const gfx::Rect&) override;
gfx::Vector2dF GetLastScrollOffset(void) const override; gfx::Vector2dF GetLastScrollOffset(void) const override;
@ -108,6 +106,7 @@ class OffScreenRenderWidgetHostView
bool LockMouse(void) override; bool LockMouse(void) override;
void UnlockMouse(void) override; void UnlockMouse(void) override;
void SetNeedsBeginFrames(bool needs_begin_frames) override; void SetNeedsBeginFrames(bool needs_begin_frames) override;
void SetWantsAnimateOnlyBeginFrames() override;
#if defined(OS_MACOSX) #if defined(OS_MACOSX)
ui::AcceleratedWidgetMac* GetAcceleratedWidgetMac() const override; ui::AcceleratedWidgetMac* GetAcceleratedWidgetMac() const override;
void SetActive(bool active) override; void SetActive(bool active) override;
@ -122,8 +121,10 @@ class OffScreenRenderWidgetHostView
void DidCreateNewRendererCompositorFrameSink( void DidCreateNewRendererCompositorFrameSink(
viz::mojom::CompositorFrameSinkClient* renderer_compositor_frame_sink) viz::mojom::CompositorFrameSinkClient* renderer_compositor_frame_sink)
override; override;
void SubmitCompositorFrame(const viz::LocalSurfaceId& local_surface_id, void SubmitCompositorFrame(
viz::CompositorFrame frame) override; const viz::LocalSurfaceId& local_surface_id,
viz::CompositorFrame frame,
viz::mojom::HitTestRegionListPtr hit_test_region_list) override;
void ClearCompositorFrame(void) override; void ClearCompositorFrame(void) override;
void InitAsPopup(content::RenderWidgetHostView* rwhv, void InitAsPopup(content::RenderWidgetHostView* rwhv,
@ -136,31 +137,22 @@ class OffScreenRenderWidgetHostView
void RenderProcessGone(base::TerminationStatus, int) override; void RenderProcessGone(base::TerminationStatus, int) override;
void Destroy(void) override; void Destroy(void) override;
void SetTooltipText(const base::string16&) override; void SetTooltipText(const base::string16&) override;
#if defined(OS_MACOSX)
void SelectionChanged(const base::string16& text,
size_t offset,
const gfx::Range& range) override;
#endif
void SelectionBoundsChanged( void SelectionBoundsChanged(
const ViewHostMsg_SelectionBounds_Params&) override; const ViewHostMsg_SelectionBounds_Params&) override;
void CopyFromSurface(const gfx::Rect& src_subrect, void CopyFromSurface(
const gfx::Size& dst_size, const gfx::Rect& src_rect,
const content::ReadbackRequestCallback& callback, const gfx::Size& output_size,
const SkColorType color_type) override; base::OnceCallback<void(const SkBitmap&)> callback) override;
void CopyFromSurfaceToVideoFrame( void GetScreenInfo(content::ScreenInfo* results) const override;
const gfx::Rect& src_subrect,
scoped_refptr<media::VideoFrame> target,
const base::Callback<void(const gfx::Rect&, bool)>& callback) override;
void BeginFrameSubscription(
std::unique_ptr<content::RenderWidgetHostViewFrameSubscriber>) override;
void EndFrameSubscription() override;
void InitAsGuest(content::RenderWidgetHostView*, void InitAsGuest(content::RenderWidgetHostView*,
content::RenderWidgetHostViewGuest*) override; content::RenderWidgetHostViewGuest*) override;
bool HasAcceleratedSurface(const gfx::Size&) override; gfx::Vector2d GetOffsetFromRootSurface() override;
gfx::Rect GetBoundsInRootWindow(void) override; gfx::Rect GetBoundsInRootWindow(void) override;
content::RenderWidgetHostImpl* GetRenderWidgetHostImpl() const override;
viz::SurfaceId GetCurrentSurfaceId() const override;
void ImeCompositionRangeChanged(const gfx::Range&, void ImeCompositionRangeChanged(const gfx::Range&,
const std::vector<gfx::Rect>&) override; const std::vector<gfx::Rect>&) override;
gfx::Size GetPhysicalBackingSize() const override; gfx::Size GetCompositorViewportPixelSize() const override;
gfx::Size GetRequestedRendererSize() const override; gfx::Size GetRequestedRendererSize() const override;
content::RenderWidgetHostViewBase* CreateViewForWidget( content::RenderWidgetHostViewBase* CreateViewForWidget(
@ -173,13 +165,15 @@ class OffScreenRenderWidgetHostView
int DelegatedFrameHostGetGpuMemoryBufferClientId(void) const; int DelegatedFrameHostGetGpuMemoryBufferClientId(void) const;
ui::Layer* DelegatedFrameHostGetLayer(void) const override; ui::Layer* DelegatedFrameHostGetLayer(void) const override;
bool DelegatedFrameHostIsVisible(void) const override; bool DelegatedFrameHostIsVisible(void) const override;
SkColor DelegatedFrameHostGetGutterColor(SkColor) const override; SkColor DelegatedFrameHostGetGutterColor() const override;
gfx::Size DelegatedFrameHostDesiredSizeInDIP(void) const override;
bool DelegatedFrameCanCreateResizeLock() const override; bool DelegatedFrameCanCreateResizeLock() const override;
std::unique_ptr<content::CompositorResizeLock> std::unique_ptr<content::CompositorResizeLock>
DelegatedFrameHostCreateResizeLock() override; DelegatedFrameHostCreateResizeLock() override;
viz::LocalSurfaceId GetLocalSurfaceId() const override; viz::LocalSurfaceId GetLocalSurfaceId() const override;
void OnBeginFrame() override; void OnFirstSurfaceActivation(const viz::SurfaceInfo& surface_info) override;
void OnBeginFrame(base::TimeTicks frame_time) override;
void OnFrameTokenChanged(uint32_t frame_token) override;
void DidReceiveFirstFrameAfterNavigation() override;
// CompositorResizeLockClient implementation. // CompositorResizeLockClient implementation.
std::unique_ptr<ui::CompositorLock> GetCompositorLock( std::unique_ptr<ui::CompositorLock> GetCompositorLock(
ui::CompositorLockClient* client) override; ui::CompositorLockClient* client) override;
@ -187,13 +181,13 @@ class OffScreenRenderWidgetHostView
bool IsAutoResizeEnabled() const override; bool IsAutoResizeEnabled() const override;
#endif // !defined(OS_MACOSX) #endif // !defined(OS_MACOSX)
bool TransformPointToLocalCoordSpace(const gfx::Point& point, bool TransformPointToLocalCoordSpace(const gfx::PointF& point,
const viz::SurfaceId& original_surface, const viz::SurfaceId& original_surface,
gfx::Point* transformed_point) override; gfx::PointF* transformed_point) override;
bool TransformPointToCoordSpaceForView( bool TransformPointToCoordSpaceForView(
const gfx::Point& point, const gfx::PointF& point,
RenderWidgetHostViewBase* target_view, RenderWidgetHostViewBase* target_view,
gfx::Point* transformed_point) override; gfx::PointF* transformed_point) override;
// ui::CompositorDelegate: // ui::CompositorDelegate:
std::unique_ptr<viz::SoftwareOutputDevice> CreateSoftwareOutputDevice( std::unique_ptr<viz::SoftwareOutputDevice> CreateSoftwareOutputDevice(
@ -235,12 +229,8 @@ class OffScreenRenderWidgetHostView
void ReleaseResize(); void ReleaseResize();
void WasResized(); void WasResized();
void ProcessKeyboardEvent(const content::NativeWebKeyboardEvent& event, void SendMouseEvent(const blink::WebMouseEvent& event);
const ui::LatencyInfo& latency) override; void SendMouseWheelEvent(const blink::WebMouseWheelEvent& event);
void ProcessMouseEvent(const blink::WebMouseEvent& event,
const ui::LatencyInfo& latency) override;
void ProcessMouseWheelEvent(const blink::WebMouseWheelEvent& event,
const ui::LatencyInfo& latency) override;
void SetPainting(bool painting); void SetPainting(bool painting);
bool IsPainting() const; bool IsPainting() const;
@ -319,7 +309,7 @@ class OffScreenRenderWidgetHostView
bool paint_callback_running_ = false; bool paint_callback_running_ = false;
viz::LocalSurfaceId local_surface_id_; viz::LocalSurfaceId local_surface_id_;
viz::LocalSurfaceIdAllocator local_surface_id_allocator_; viz::ParentLocalSurfaceIdAllocator local_surface_id_allocator_;
std::unique_ptr<ui::Layer> root_layer_; std::unique_ptr<ui::Layer> root_layer_;
std::unique_ptr<ui::Compositor> compositor_; std::unique_ptr<ui::Compositor> compositor_;
@ -333,7 +323,6 @@ class OffScreenRenderWidgetHostView
uint64_t begin_frame_number_ = viz::BeginFrameArgs::kStartingFrameNumber; uint64_t begin_frame_number_ = viz::BeginFrameArgs::kStartingFrameNumber;
#if defined(OS_MACOSX) #if defined(OS_MACOSX)
CALayer* background_layer_;
std::unique_ptr<content::BrowserCompositorMac> browser_compositor_; std::unique_ptr<content::BrowserCompositorMac> browser_compositor_;
// Can not be managed by smart pointer because its header can not be included // Can not be managed by smart pointer because its header can not be included

View file

@ -22,13 +22,6 @@ class MacHelper : public content::BrowserCompositorMacClient,
virtual ~MacHelper() {} virtual ~MacHelper() {}
// content::BrowserCompositorMacClient: // content::BrowserCompositorMacClient:
NSView* BrowserCompositorMacGetNSView() const override {
// Intentionally return nil so that
// BrowserCompositorMac::DelegatedFrameHostDesiredSizeInDIP uses the layer
// size instead of the NSView size.
return nil;
}
SkColor BrowserCompositorMacGetGutterColor(SkColor color) const override { SkColor BrowserCompositorMacGetGutterColor(SkColor color) const override {
// When making an element on the page fullscreen the element's background // 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 // may not match the page's, so use black as the gutter color to avoid
@ -42,8 +35,8 @@ class MacHelper : public content::BrowserCompositorMacClient,
void BrowserCompositorMacOnBeginFrame() override {} void BrowserCompositorMacOnBeginFrame() override {}
viz::LocalSurfaceId GetLocalSurfaceId() const override { void OnFrameTokenChanged(uint32_t frame_token) override {
return view_->local_surface_id(); view_->render_widget_host()->DidProcessFrame(frame_token);
} }
// ui::AcceleratedWidgetMacNSView: // ui::AcceleratedWidgetMacNSView:
@ -60,19 +53,18 @@ class MacHelper : public content::BrowserCompositorMacClient,
void AcceleratedWidgetSwapCompleted() override {} void AcceleratedWidgetSwapCompleted() override {}
void DidReceiveFirstFrameAfterNavigation() override {
view_->render_widget_host()->DidReceiveFirstFrameAfterNavigation();
}
void DestroyCompositorForShutdown() override {}
private: private:
OffScreenRenderWidgetHostView* view_; OffScreenRenderWidgetHostView* view_;
DISALLOW_COPY_AND_ASSIGN(MacHelper); DISALLOW_COPY_AND_ASSIGN(MacHelper);
}; };
ui::AcceleratedWidgetMac*
OffScreenRenderWidgetHostView::GetAcceleratedWidgetMac() const {
if (browser_compositor_)
return browser_compositor_->GetAcceleratedWidgetMac();
return nullptr;
}
void OffScreenRenderWidgetHostView::SetActive(bool active) {} void OffScreenRenderWidgetHostView::SetActive(bool active) {}
void OffScreenRenderWidgetHostView::ShowDefinitionForSelection() {} void OffScreenRenderWidgetHostView::ShowDefinitionForSelection() {}
@ -89,24 +81,8 @@ bool OffScreenRenderWidgetHostView::IsSpeaking() const {
void OffScreenRenderWidgetHostView::StopSpeaking() {} void OffScreenRenderWidgetHostView::StopSpeaking() {}
void OffScreenRenderWidgetHostView::SelectionChanged(const base::string16& text, bool CefRenderWidgetHostViewOSR::ShouldContinueToPauseForFrame() {
size_t offset, return browser_compositor_->ShouldContinueToPauseForFrame();
const gfx::Range& range) {
if (range.is_empty() || text.empty()) {
selected_text_.clear();
} else {
size_t pos = range.GetMin() - offset;
size_t n = range.length();
DCHECK(pos + n <= text.length()) << "The text can not fully cover range.";
if (pos >= text.length()) {
DCHECK(false) << "The text can not cover range.";
return;
}
selected_text_ = base::UTF16ToUTF8(text.substr(pos, n));
}
RenderWidgetHostViewBase::SelectionChanged(text, offset, range);
} }
void OffScreenRenderWidgetHostView::CreatePlatformWidget( void OffScreenRenderWidgetHostView::CreatePlatformWidget(

View file

@ -80,6 +80,8 @@ void OffScreenWebContentsView::StoreFocus() {}
void OffScreenWebContentsView::RestoreFocus() {} void OffScreenWebContentsView::RestoreFocus() {}
void OffScreenWebContentsView::FocusThroughTabTraversal(bool reverse) {}
content::DropData* OffScreenWebContentsView::GetDropData() const { content::DropData* OffScreenWebContentsView::GetDropData() const {
return nullptr; return nullptr;
} }
@ -143,26 +145,6 @@ void OffScreenWebContentsView::RenderViewSwappedIn(
void OffScreenWebContentsView::SetOverscrollControllerEnabled(bool enabled) {} void OffScreenWebContentsView::SetOverscrollControllerEnabled(bool enabled) {}
void OffScreenWebContentsView::GetScreenInfo(
content::ScreenInfo* screen_info) const {
screen_info->depth = 24;
screen_info->depth_per_component = 8;
screen_info->orientation_angle = 0;
screen_info->device_scale_factor = 1.0;
screen_info->orientation_type =
content::SCREEN_ORIENTATION_VALUES_LANDSCAPE_PRIMARY;
if (GetView()) {
screen_info->rect = gfx::Rect(GetView()->size());
screen_info->available_rect = gfx::Rect(GetView()->size());
} else {
const display::Display display =
display::Screen::GetScreen()->GetPrimaryDisplay();
screen_info->rect = display.bounds();
screen_info->available_rect = display.work_area();
}
}
#if defined(OS_MACOSX) #if defined(OS_MACOSX)
void OffScreenWebContentsView::SetAllowOtherViews(bool allow) {} void OffScreenWebContentsView::SetAllowOtherViews(bool allow) {}

View file

@ -38,6 +38,7 @@ class OffScreenWebContentsView : public content::WebContentsView,
void SetInitialFocus() override; void SetInitialFocus() override;
void StoreFocus() override; void StoreFocus() override;
void RestoreFocus() override; void RestoreFocus() override;
void FocusThroughTabTraversal(bool reverse) override;
content::DropData* GetDropData() const override; content::DropData* GetDropData() const override;
gfx::Rect GetViewBounds() const override; gfx::Rect GetViewBounds() const override;
void CreateView(const gfx::Size& initial_size, void CreateView(const gfx::Size& initial_size,
@ -51,7 +52,6 @@ class OffScreenWebContentsView : public content::WebContentsView,
void RenderViewCreated(content::RenderViewHost* host) override; void RenderViewCreated(content::RenderViewHost* host) override;
void RenderViewSwappedIn(content::RenderViewHost* host) override; void RenderViewSwappedIn(content::RenderViewHost* host) override;
void SetOverscrollControllerEnabled(bool enabled) override; void SetOverscrollControllerEnabled(bool enabled) override;
void GetScreenInfo(content::ScreenInfo* screen_info) const override;
#if defined(OS_MACOSX) #if defined(OS_MACOSX)
void SetAllowOtherViews(bool allow) override; void SetAllowOtherViews(bool allow) override;

View file

@ -23,7 +23,7 @@
<key>LSApplicationCategoryType</key> <key>LSApplicationCategoryType</key>
<string>public.app-category.developer-tools</string> <string>public.app-category.developer-tools</string>
<key>LSMinimumSystemVersion</key> <key>LSMinimumSystemVersion</key>
<string>10.9.0</string> <string>10.10.0</string>
<key>NSMainNibFile</key> <key>NSMainNibFile</key>
<string>MainMenu</string> <string>MainMenu</string>
<key>NSPrincipalClass</key> <key>NSPrincipalClass</key>

View file

@ -115,6 +115,7 @@ AutofillPopup::~AutofillPopup() {
} }
void AutofillPopup::CreateView(content::RenderFrameHost* frame_host, void AutofillPopup::CreateView(content::RenderFrameHost* frame_host,
content::RenderFrameHost* embedder_frame_host,
bool offscreen, bool offscreen,
views::View* parent, views::View* parent,
const gfx::RectF& r) { const gfx::RectF& r) {
@ -123,6 +124,11 @@ void AutofillPopup::CreateView(content::RenderFrameHost* frame_host,
frame_host_ = frame_host; frame_host_ = frame_host;
element_bounds_ = gfx::ToEnclosedRect(r); element_bounds_ = gfx::ToEnclosedRect(r);
gfx::Vector2d height_offset(0, element_bounds_.height());
gfx::Point menu_position(element_bounds_.origin() + height_offset);
views::View::ConvertPointToScreen(parent, &menu_position);
popup_bounds_ = gfx::Rect(menu_position, element_bounds_.size());
parent_ = parent; parent_ = parent;
parent_->AddObserver(this); parent_->AddObserver(this);
@ -131,8 +137,12 @@ void AutofillPopup::CreateView(content::RenderFrameHost* frame_host,
#if defined(ENABLE_OSR) #if defined(ENABLE_OSR)
if (offscreen) { if (offscreen) {
auto* osr_rwhv = auto* rwhv = frame_host->GetView();
static_cast<OffScreenRenderWidgetHostView*>(frame_host_->GetView()); if (embedder_frame_host != nullptr) {
rwhv = embedder_frame_host->GetView();
}
auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(rwhv);
view_->view_proxy_.reset(new OffscreenViewProxy(view_)); view_->view_proxy_.reset(new OffscreenViewProxy(view_));
osr_rwhv->AddViewProxy(view_->view_proxy_.get()); osr_rwhv->AddViewProxy(view_->view_proxy_.get());
} }
@ -198,9 +208,13 @@ void AutofillPopup::UpdatePopupBounds() {
popup_bounds_ = popup_bounds_ =
gfx::Rect(popup_x_and_width.first, popup_y_and_height.first, gfx::Rect(popup_x_and_width.first, popup_y_and_height.first,
popup_x_and_width.second, popup_y_and_height.second); popup_x_and_width.second, popup_y_and_height.second);
popup_bounds_in_view_ = }
gfx::Rect(popup_bounds_in_view_.origin(),
gfx::Size(popup_x_and_width.second, popup_y_and_height.second)); gfx::Rect AutofillPopup::popup_bounds_in_view() {
gfx::Point origin(popup_bounds_.origin());
views::View::ConvertPointFromScreen(parent_, &origin);
return gfx::Rect(origin, popup_bounds_.size());
} }
void AutofillPopup::OnViewBoundsChanged(views::View* view) { void AutofillPopup::OnViewBoundsChanged(views::View* view) {

View file

@ -24,6 +24,7 @@ class AutofillPopup : public views::ViewObserver {
~AutofillPopup() override; ~AutofillPopup() override;
void CreateView(content::RenderFrameHost* render_frame, void CreateView(content::RenderFrameHost* render_frame,
content::RenderFrameHost* embedder_frame,
bool offscreen, bool offscreen,
views::View* parent, views::View* parent,
const gfx::RectF& bounds); const gfx::RectF& bounds);
@ -33,6 +34,8 @@ class AutofillPopup : public views::ViewObserver {
const std::vector<base::string16>& labels); const std::vector<base::string16>& labels);
void UpdatePopupBounds(); void UpdatePopupBounds();
gfx::Rect popup_bounds_in_view();
private: private:
friend class AutofillPopupView; friend class AutofillPopupView;
@ -58,7 +61,6 @@ class AutofillPopup : public views::ViewObserver {
// Popup location // Popup location
gfx::Rect popup_bounds_; gfx::Rect popup_bounds_;
gfx::Rect popup_bounds_in_view_;
// Bounds of the autofilled element // Bounds of the autofilled element
gfx::Rect element_bounds_; gfx::Rect element_bounds_;

View file

@ -4,8 +4,9 @@
#include "atom/browser/ui/certificate_trust.h" #include "atom/browser/ui/certificate_trust.h"
#include <windows.h> // windows.h must be included first
#include <wincrypt.h> #include <wincrypt.h>
#include <windows.h>
#include "base/callback.h" #include "base/callback.h"
#include "net/cert/cert_database.h" #include "net/cert/cert_database.h"

View file

@ -187,8 +187,8 @@ void FileChooserDialog::AddFilters(const Filters& filters) {
GtkFileFilter* gtk_filter = gtk_file_filter_new(); GtkFileFilter* gtk_filter = gtk_file_filter_new();
for (size_t j = 0; j < filter.second.size(); ++j) { for (size_t j = 0; j < filter.second.size(); ++j) {
std::unique_ptr<std::string> file_extension( auto file_extension =
new std::string("." + filter.second[j])); std::make_unique<std::string>("." + filter.second[j]);
gtk_file_filter_add_custom( gtk_file_filter_add_custom(
gtk_filter, GTK_FILE_FILTER_FILENAME, gtk_filter, GTK_FILE_FILTER_FILENAME,
reinterpret_cast<GtkFileFilterFunc>(FileFilterCaseInsensitive), reinterpret_cast<GtkFileFilterFunc>(FileFilterCaseInsensitive),

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