This commit is contained in:
Charlie Hess 2016-04-29 13:12:56 -07:00
commit e9514bf35d
347 changed files with 5061 additions and 1714 deletions

8
.gitmodules vendored
View file

@ -1,21 +1,21 @@
[submodule "vendor/brightray"]
path = vendor/brightray
url = https://github.com/atom/brightray.git
url = https://github.com/electron/brightray.git
[submodule "vendor/node"]
path = vendor/node
url = https://github.com/atom/node.git
url = https://github.com/electron/node.git
[submodule "vendor/depot_tools"]
path = vendor/depot_tools
url = https://chromium.googlesource.com/chromium/tools/depot_tools.git
[submodule "vendor/breakpad"]
path = vendor/breakpad
url = https://github.com/atom/chromium-breakpad.git
url = https://github.com/electron/chromium-breakpad.git
[submodule "vendor/native_mate"]
path = vendor/native_mate
url = https://github.com/zcbenz/native-mate.git
[submodule "vendor/crashpad"]
path = vendor/crashpad
url = https://github.com/atom/crashpad.git
url = https://github.com/electron/crashpad.git
[submodule "vendor/requests"]
path = vendor/requests
url = https://github.com/kennethreitz/requests

View file

@ -1 +1 @@
v5.1.1
v5.10.0

View file

@ -1,10 +1,10 @@
# Electron에 기여하기
:+1::tada: 먼저, 이 프로젝트에 기여해주셔서 감사합니다! :tada::+1:
:+1::tada: 먼저, 기여에 관심을 가져주셔서 감사합니다! :tada::+1:
이 프로젝트는 기여자 규약 [행동강령](CODE_OF_CONDUCT.md)을 준수합니다. 따라서 이
이 프로젝트는 기여자 규약 [행동강령](CODE_OF_CONDUCT.md)을 준수합니다. 따라서 이
프로젝트의 개발에 참여하려면 이 규약을 지켜야 합니다. 받아들일 수 없는 행위를 발견했을
경우 atom@github.com로 보고 하십시오.
경우 atom@github.com로 보고하세요.
다음 항목들은 Electron에 기여하는 가이드라인을 제시합니다.
참고로 이 항목들은 그저 가이드라인에 불과하며 규칙이 아닙니다. 따라서 스스로의 적절한
@ -12,7 +12,7 @@
## 이슈 제출
* [여기](https://github.com/atom/electron/issues/new)에서 새로운 이슈를 만들 수
* [여기](https://github.com/electron/electron/issues/new)에서 새로운 이슈를 만들 수
있습니다. 하지만 이슈를 작성하기 전에 아래의 항목들을 숙지하고 가능한한 이슈 보고에
대해 최대한 많은 정보와 자세한 설명을 포함해야 합니다. 가능하다면 다음 항목을 포함해야
합니다:
@ -23,14 +23,14 @@
* 추가로 다음 사항을 준수하면 이슈를 해결하는데 큰 도움이 됩니다:
* 스크린샷 또는 GIF 애니메이션 이미지들
* 터미널에 출력된 에러의 내용 또는 개발자 도구, 알림창에 뜬 내용
* [Cursory search](https://github.com/atom/electron/issues?utf8=✓&q=is%3Aissue+)를
* [Cursory search](https://github.com/electron/electron/issues?utf8=✓&q=is%3Aissue+)를
통해 이미 비슷한 내용의 이슈가 등록되어있는지 확인
## Pull Request 하기
* 가능한한 스크린샷과 GIF 애니메이션 이미지를 pull request에 추가
* CoffeeScript, JavaScript, C++과 Python등
[참조문서에 정의된 코딩스타일](/docs-translations/ko-KR/development/coding-style.md)을
* JavaScript, C++과 Python등
[참조 문서에 정의된 코딩스타일](/docs-translations/ko-KR/development/coding-style.md)을
준수
* [문서 스타일 가이드](/docs-translations/ko-KR/styleguide.md)에 따라 문서를
[Markdown](https://daringfireball.net/projects/markdown) 형식으로 작성.

View file

@ -12,7 +12,7 @@ propose changes to this document in a pull request.
## Submitting Issues
* You can create an issue [here](https://github.com/atom/electron/issues/new),
* You can create an issue [here](https://github.com/electron/electron/issues/new),
but before doing that please read the notes below and include as many details as
possible with your report. If you can, please include:
* The version of Electron you are using
@ -22,7 +22,7 @@ possible with your report. If you can, please include:
* Other things that will help resolve your issue:
* Screenshots and animated GIFs
* Error output that appears in your terminal, dev tools or as an alert
* Perform a [cursory search](https://github.com/atom/electron/issues?utf8=✓&q=is%3Aissue+)
* Perform a [cursory search](https://github.com/electron/electron/issues?utf8=✓&q=is%3Aissue+)
to see if a similar issue has already been submitted
## Submitting Pull Requests

View file

@ -1,11 +1,11 @@
[![Electron Logo](http://electron.atom.io/images/electron-logo.svg)](http://electron.atom.io/)
[![Build Status](https://travis-ci.org/atom/electron.svg?branch=master)](https://travis-ci.org/atom/electron)
[![Travis Build Status](https://travis-ci.org/electron/electron.svg?branch=master)](https://travis-ci.org/electron/electron)
[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/qtmod45u0cc1ouov/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/electron)
[![devDependency Status](https://david-dm.org/atom/electron/dev-status.svg)](https://david-dm.org/atom/electron#info=devDependencies)
[![devDependency Status](https://david-dm.org/electron/electron/dev-status.svg)](https://david-dm.org/electron/electron#info=devDependencies)
[![Join the Electron Community on Slack](http://atom-slack.herokuapp.com/badge.svg)](http://atom-slack.herokuapp.com/)
### [Electron](https://github.com/atom/electron/) 한국어 참조문서
### [Electron](https://github.com/electron/electron/) 한국어 참조문서
:zap: *프레임워크 이름이 Atom Shell에서 Electron으로 변경되었습니다* :zap:
@ -17,15 +17,15 @@ Cross-Platform 데스크톱 어플리케이션을 개발할 수 있도록 해주
Electron에 대한 중요한 알림을 받고 싶다면 Twitter에서
[@ElectronJS](https://twitter.com/electronjs)를 팔로우 하세요.
이 프로젝트는 기여자 규약 [행동강령](CODE_OF_CONDUCT.md)을 준수합니다. 따라서 이
이 프로젝트는 기여자 규약 [행동강령](CODE_OF_CONDUCT.md)을 준수합니다. 따라서 이
프로젝트의 개발에 참여하려면 이 규약을 지켜야 합니다. 받아들일 수 없는 행위를 발견했을
경우 atom@github.com로 보고 하십시오.
경우 atom@github.com로 보고하세요.
## 다운로드
Linux, Windows, OS X 용으로 미리 빌드된 Electron 바이너리와 디버그 심볼이 준비되어
있습니다. [releases](https://github.com/atom/electron/releases) 페이지에서 받아 볼
수 있습니다.
있습니다. [releases](https://github.com/electron/electron/releases) 페이지에서
받아 볼 수 있습니다.
또한 [`npm`](https://docs.npmjs.com/)을 통해 미리 빌드된 Electron 바이너리를 설치할
수도 있습니다:
@ -44,25 +44,26 @@ npm install electron-prebuilt --save-dev
## 참조 문서
[Docs](https://github.com/atom/electron/tree/master/docs/README.md)에 개발 지침과
API 레퍼런스가 있습니다. Electron을 빌드 하는 방법과 프로젝트에 기여하는법 또한 문서에
포함되어 있으니 참고하시기 바랍니다.
[Docs](https://github.com/electron/electron/tree/master/docs-translations/ko-KR/README.md)에
개발 지침과 API 레퍼런스가 있습니다. Electron을 빌드 하는 방법과 프로젝트에 기여하는법
또한 문서에 포함되어 있으니 참고하시기 바랍니다.
## 참조 문서 (번역)
- [브라질 포르투갈어](https://github.com/atom/electron/tree/master/docs-translations/pt-BR)
- [한국어](https://github.com/atom/electron/tree/master/docs-translations/ko-KR)
- [일본어](https://github.com/atom/electron/tree/master/docs-translations/jp)
- [스페인어](https://github.com/atom/electron/tree/master/docs-translations/es)
- [중국어 간체](https://github.com/atom/electron/tree/master/docs-translations/zh-CN)
- [중국어 번체](https://github.com/atom/electron/tree/master/docs-translations/zh-TW)
- [우크라이나어](https://github.com/atom/electron/tree/master/docs-translations/uk-UA)
- [러시아어](https://github.com/atom/electron/tree/master/docs-translations/ru-RU)
- [프랑스어](https://github.com/atom/electron/tree/master/docs-translations/fr-FR)
- [브라질 포르투갈어](https://github.com/electron/electron/tree/master/docs-translations/pt-BR)
- [한국어](https://github.com/electron/electron/tree/master/docs-translations/ko-KR)
- [일본어](https://github.com/electron/electron/tree/master/docs-translations/jp)
- [스페인어](https://github.com/electron/electron/tree/master/docs-translations/es)
- [중국어 간체](https://github.com/electron/electron/tree/master/docs-translations/zh-CN)
- [중국어 번체](https://github.com/electron/electron/tree/master/docs-translations/zh-TW)
- [터키의](https://github.com/electron/electron/tree/master/docs-translations/tr-TR)
- [우크라이나어](https://github.com/electron/electron/tree/master/docs-translations/uk-UA)
- [러시아어](https://github.com/electron/electron/tree/master/docs-translations/ru-RU)
- [프랑스어](https://github.com/electron/electron/tree/master/docs-translations/fr-FR)
## 시작하기
[`atom/electron-quick-start`](https://github.com/atom/electron-quick-start)
[`electron/electron-quick-start`](https://github.com/electron/electron-quick-start)
저장소를 클론하여 Electron을 간단히 접해볼 수 있습니다.
## 커뮤니티

View file

@ -1,8 +1,8 @@
[![Electron Logo](http://electron.atom.io/images/electron-logo.svg)](http://electron.atom.io/)
[![Travis Build Status](https://travis-ci.org/atom/electron.svg?branch=master)](https://travis-ci.org/atom/electron)
[![Travis Build Status](https://travis-ci.org/electron/electron.svg?branch=master)](https://travis-ci.org/electron/electron)
[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/qtmod45u0cc1ouov/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/electron)
[![devDependency Status](https://david-dm.org/atom/electron/dev-status.svg)](https://david-dm.org/atom/electron#info=devDependencies)
[![devDependency Status](https://david-dm.org/electron/electron/dev-status.svg)](https://david-dm.org/electron/electron#info=devDependencies)
[![Join the Electron Community on Slack](http://atom-slack.herokuapp.com/badge.svg)](http://atom-slack.herokuapp.com/)
:zap: *Formerly known as Atom Shell* :zap:
@ -22,7 +22,7 @@ behavior to atom@github.com.
## Downloads
Prebuilt binaries and debug symbols of Electron for Linux, Windows and OS X can
be found on the [releases](https://github.com/atom/electron/releases) page.
be found on the [releases](https://github.com/electron/electron/releases) page.
You can also use [`npm`](https://docs.npmjs.com/) to install prebuilt electron
binaries:
@ -42,24 +42,25 @@ npm install electron-prebuilt --save-dev
## Documentation
Guides and the API reference are located in the
[docs](https://github.com/atom/electron/tree/master/docs) directory. It also
[docs](https://github.com/electron/electron/tree/master/docs) directory. It also
contains documents describing how to build and contribute to Electron.
## Documentation Translations
- [Brazilian Portuguese](https://github.com/atom/electron/tree/master/docs-translations/pt-BR)
- [Korean](https://github.com/atom/electron/tree/master/docs-translations/ko-KR)
- [Japanese](https://github.com/atom/electron/tree/master/docs-translations/jp)
- [Spanish](https://github.com/atom/electron/tree/master/docs-translations/es)
- [Simplified Chinese](https://github.com/atom/electron/tree/master/docs-translations/zh-CN)
- [Traditional Chinese](https://github.com/atom/electron/tree/master/docs-translations/zh-TW)
- [Ukrainian](https://github.com/atom/electron/tree/master/docs-translations/uk-UA)
- [Russian](https://github.com/atom/electron/tree/master/docs-translations/ru-RU)
- [French](https://github.com/atom/electron/tree/master/docs-translations/fr-FR)
- [Brazilian Portuguese](https://github.com/electron/electron/tree/master/docs-translations/pt-BR)
- [Korean](https://github.com/electron/electron/tree/master/docs-translations/ko-KR)
- [Japanese](https://github.com/electron/electron/tree/master/docs-translations/jp)
- [Spanish](https://github.com/electron/electron/tree/master/docs-translations/es)
- [Simplified Chinese](https://github.com/electron/electron/tree/master/docs-translations/zh-CN)
- [Traditional Chinese](https://github.com/electron/electron/tree/master/docs-translations/zh-TW)
- [Turkish](https://github.com/electron/electron/tree/master/docs-translations/tr-TR)
- [Ukrainian](https://github.com/electron/electron/tree/master/docs-translations/uk-UA)
- [Russian](https://github.com/electron/electron/tree/master/docs-translations/ru-RU)
- [French](https://github.com/electron/electron/tree/master/docs-translations/fr-FR)
## Quick Start
Clone and run the [`atom/electron-quick-start`](https://github.com/atom/electron-quick-start)
Clone and run the [`electron/electron-quick-start`](https://github.com/electron/electron-quick-start)
repository to see a minimal Electron app in action.
## Community

View file

@ -98,10 +98,6 @@ void AtomMainDelegate::PreSandboxStartup() {
std::string process_type = command_line->GetSwitchValueASCII(
switches::kProcessType);
if (process_type == switches::kUtilityProcess) {
AtomContentUtilityClient::PreSandboxStartup();
}
// Only append arguments for browser process.
if (!IsBrowserProcess(command_line))
return;

View file

@ -15,15 +15,17 @@
#include "atom/browser/browser.h"
#include "atom/browser/login_handler.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/native_mate_converters/file_path_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/net_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/path_service.h"
#include "brightray/browser/brightray_paths.h"
#include "chrome/common/chrome_paths.h"
@ -39,7 +41,6 @@
#if defined(OS_WIN)
#include "base/strings/utf_string_conversions.h"
#include "ui/base/win/shell.h"
#endif
using atom::Browser;
@ -157,12 +158,46 @@ void PassLoginInformation(scoped_refptr<LoginHandler> login_handler,
login_handler->CancelAuth();
}
#if defined(USE_NSS_CERTS)
int ImportIntoCertStore(
CertificateManagerModel* model,
const base::DictionaryValue& options) {
std::string file_data, cert_path;
base::string16 password;
net::CertificateList imported_certs;
int rv = -1;
options.GetString("certificate", &cert_path);
options.GetString("password", &password);
if (!cert_path.empty()) {
if (base::ReadFileToString(base::FilePath(cert_path), &file_data)) {
auto module = model->cert_db()->GetPublicModule();
rv = model->ImportFromPKCS12(module,
file_data,
password,
true,
&imported_certs);
if (imported_certs.size() > 1) {
auto it = imported_certs.begin();
++it; // skip first which would be the client certificate.
for (; it != imported_certs.end(); ++it)
rv &= model->SetCertTrust(it->get(),
net::CA_CERT,
net::NSSCertDatabase::TRUSTED_SSL);
}
}
}
return rv;
}
#endif
} // namespace
App::App() {
App::App(v8::Isolate* isolate) {
static_cast<AtomBrowserClient*>(AtomBrowserClient::Get())->set_delegate(this);
Browser::Get()->AddObserver(this);
content::GpuDataManager::GetInstance()->AddObserver(this);
Init(isolate);
}
App::~App() {
@ -296,12 +331,6 @@ void App::OnGpuProcessCrashed(base::TerminationStatus exit_code) {
Emit("gpu-process-crashed");
}
#if defined(OS_MACOSX)
void App::OnPlatformThemeChanged() {
Emit("platform-theme-changed");
}
#endif
base::FilePath App::GetPath(mate::Arguments* args, const std::string& name) {
bool succeed = false;
base::FilePath path;
@ -316,10 +345,15 @@ base::FilePath App::GetPath(mate::Arguments* args, const std::string& name) {
void App::SetPath(mate::Arguments* args,
const std::string& name,
const base::FilePath& path) {
if (!path.IsAbsolute()) {
args->ThrowError("path must be absolute");
return;
}
bool succeed = false;
int key = GetPathConstant(name);
if (key >= 0)
succeed = PathService::Override(key, path);
succeed = PathService::OverrideAndCreateIfNeeded(key, path, true, false);
if (!succeed)
args->ThrowError("Failed to set path");
}
@ -341,12 +375,6 @@ std::string App::GetLocale() {
return l10n_util::GetApplicationLocale("");
}
#if defined(OS_WIN)
bool App::IsAeroGlassEnabled() {
return ui::win::IsAeroGlassEnabled();
}
#endif
bool App::MakeSingleInstance(
const ProcessSingleton::NotificationCallback& callback) {
if (process_singleton_.get())
@ -369,10 +397,46 @@ bool App::MakeSingleInstance(
}
}
mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
#if defined(USE_NSS_CERTS)
void App::ImportCertificate(
const base::DictionaryValue& options,
const net::CompletionCallback& callback) {
auto browser_context = AtomBrowserMainParts::Get()->browser_context();
if (!certificate_manager_model_) {
scoped_ptr<base::DictionaryValue> copy = options.CreateDeepCopy();
CertificateManagerModel::Create(browser_context,
base::Bind(&App::OnCertificateManagerModelCreated,
base::Unretained(this),
base::Passed(&copy),
callback));
return;
}
int rv = ImportIntoCertStore(certificate_manager_model_.get(), options);
callback.Run(rv);
}
void App::OnCertificateManagerModelCreated(
scoped_ptr<base::DictionaryValue> options,
const net::CompletionCallback& callback,
scoped_ptr<CertificateManagerModel> model) {
certificate_manager_model_ = std::move(model);
int rv = ImportIntoCertStore(certificate_manager_model_.get(),
*(options.get()));
callback.Run(rv);
}
#endif
// static
mate::Handle<App> App::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new App(isolate));
}
// static
void App::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
auto browser = base::Unretained(Browser::Get());
return mate::ObjectTemplateBuilder(isolate)
mate::ObjectTemplateBuilder(isolate, prototype)
.SetMethod("quit", base::Bind(&Browser::Quit, browser))
.SetMethod("exit", base::Bind(&Browser::Exit, browser))
.SetMethod("focus", base::Bind(&Browser::Focus, browser))
@ -387,6 +451,8 @@ mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder(
base::Bind(&Browser::ClearRecentDocuments, browser))
.SetMethod("setAppUserModelId",
base::Bind(&Browser::SetAppUserModelID, browser))
.SetMethod("isDefaultProtocolClient",
base::Bind(&Browser::IsDefaultProtocolClient, browser))
.SetMethod("setAsDefaultProtocolClient",
base::Bind(&Browser::SetAsDefaultProtocolClient, browser))
.SetMethod("removeAsDefaultProtocolClient",
@ -394,13 +460,10 @@ mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder(
#if defined(OS_MACOSX)
.SetMethod("hide", base::Bind(&Browser::Hide, browser))
.SetMethod("show", base::Bind(&Browser::Show, browser))
.SetMethod("isDarkMode",
base::Bind(&Browser::IsDarkMode, browser))
#endif
#if defined(OS_WIN)
.SetMethod("setUserTasks",
base::Bind(&Browser::SetUserTasks, browser))
.SetMethod("isAeroGlassEnabled", &App::IsAeroGlassEnabled)
#endif
.SetMethod("setPath", &App::SetPath)
.SetMethod("getPath", &App::GetPath)
@ -408,14 +471,12 @@ mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder(
.SetMethod("allowNTLMCredentialsForAllDomains",
&App::AllowNTLMCredentialsForAllDomains)
.SetMethod("getLocale", &App::GetLocale)
#if defined(USE_NSS_CERTS)
.SetMethod("importCertificate", &App::ImportCertificate)
#endif
.SetMethod("makeSingleInstance", &App::MakeSingleInstance);
}
// static
mate::Handle<App> App::Create(v8::Isolate* isolate) {
return CreateHandle(isolate, new App);
}
} // namespace api
} // namespace atom
@ -427,7 +488,6 @@ void AppendSwitch(const std::string& switch_string, mate::Arguments* args) {
auto command_line = base::CommandLine::ForCurrentProcess();
if (switch_string == atom::switches::kPpapiFlashPath ||
switch_string == atom::switches::kClientCertificate ||
switch_string == switches::kLogNetLog) {
base::FilePath path;
args->GetNext(&path);

View file

@ -14,6 +14,11 @@
#include "chrome/browser/process_singleton.h"
#include "content/public/browser/gpu_data_manager_observer.h"
#include "native_mate/handle.h"
#include "net/base/completion_callback.h"
#if defined(USE_NSS_CERTS)
#include "chrome/browser/certificate_manager_model.h"
#endif
namespace base {
class FilePath;
@ -28,12 +33,15 @@ namespace atom {
namespace api {
class App : public AtomBrowserClient::Delegate,
public mate::EventEmitter,
public mate::EventEmitter<App>,
public BrowserObserver,
public content::GpuDataManagerObserver {
public:
static mate::Handle<App> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
// Called when window with disposition needs to be created.
void OnCreateWindow(const GURL& target_url,
const std::string& frame_name,
@ -41,9 +49,16 @@ class App : public AtomBrowserClient::Delegate,
int render_process_id,
int render_frame_id);
#if defined(USE_NSS_CERTS)
void OnCertificateManagerModelCreated(
scoped_ptr<base::DictionaryValue> options,
const net::CompletionCallback& callback,
scoped_ptr<CertificateManagerModel> model);
#endif
protected:
App();
virtual ~App();
explicit App(v8::Isolate* isolate);
~App() override;
// BrowserObserver:
void OnBeforeQuit(bool* prevent_default) override;
@ -77,14 +92,6 @@ class App : public AtomBrowserClient::Delegate,
// content::GpuDataManagerObserver:
void OnGpuProcessCrashed(base::TerminationStatus exit_code) override;
#if defined(OS_MACOSX)
void OnPlatformThemeChanged() override;
#endif
// mate::Wrappable:
mate::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
private:
// Get/Set the pre-defined path in PathService.
base::FilePath GetPath(mate::Arguments* args, const std::string& name);
@ -98,12 +105,17 @@ class App : public AtomBrowserClient::Delegate,
const ProcessSingleton::NotificationCallback& callback);
std::string GetLocale();
#if defined(OS_WIN)
bool IsAeroGlassEnabled();
#if defined(USE_NSS_CERTS)
void ImportCertificate(const base::DictionaryValue& options,
const net::CompletionCallback& callback);
#endif
scoped_ptr<ProcessSingleton> process_singleton_;
#if defined(USE_NSS_CERTS)
scoped_ptr<CertificateManagerModel> certificate_manager_model_;
#endif
DISALLOW_COPY_AND_ASSIGN(App);
};

View file

@ -34,8 +34,9 @@ namespace atom {
namespace api {
AutoUpdater::AutoUpdater() {
AutoUpdater::AutoUpdater(v8::Isolate* isolate) {
auto_updater::AutoUpdater::SetDelegate(this);
Init(isolate);
}
AutoUpdater::~AutoUpdater() {
@ -78,14 +79,6 @@ void AutoUpdater::OnWindowAllClosed() {
QuitAndInstall();
}
mate::ObjectTemplateBuilder AutoUpdater::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return mate::ObjectTemplateBuilder(isolate)
.SetMethod("setFeedURL", &auto_updater::AutoUpdater::SetFeedURL)
.SetMethod("checkForUpdates", &auto_updater::AutoUpdater::CheckForUpdates)
.SetMethod("quitAndInstall", &AutoUpdater::QuitAndInstall);
}
void AutoUpdater::QuitAndInstall() {
// If we don't have any window then quitAndInstall immediately.
WindowList* window_list = WindowList::GetInstance();
@ -102,7 +95,16 @@ void AutoUpdater::QuitAndInstall() {
// static
mate::Handle<AutoUpdater> AutoUpdater::Create(v8::Isolate* isolate) {
return CreateHandle(isolate, new AutoUpdater);
return mate::CreateHandle(isolate, new AutoUpdater(isolate));
}
// static
void AutoUpdater::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
mate::ObjectTemplateBuilder(isolate, prototype)
.SetMethod("setFeedURL", &auto_updater::AutoUpdater::SetFeedURL)
.SetMethod("checkForUpdates", &auto_updater::AutoUpdater::CheckForUpdates)
.SetMethod("quitAndInstall", &AutoUpdater::QuitAndInstall);
}
} // namespace api

View file

@ -16,15 +16,18 @@ namespace atom {
namespace api {
class AutoUpdater : public mate::EventEmitter,
class AutoUpdater : public mate::EventEmitter<AutoUpdater>,
public auto_updater::Delegate,
public WindowListObserver {
public:
static mate::Handle<AutoUpdater> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
protected:
AutoUpdater();
virtual ~AutoUpdater();
explicit AutoUpdater(v8::Isolate* isolate);
~AutoUpdater() override;
// Delegate implementations.
void OnError(const std::string& error) override;
@ -39,10 +42,6 @@ class AutoUpdater : public mate::EventEmitter,
// WindowListObserver:
void OnWindowAllClosed() override;
// mate::Wrappable implementations:
mate::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
private:
void QuitAndInstall();

View file

@ -186,8 +186,10 @@ void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter,
} // namespace
Cookies::Cookies(content::BrowserContext* browser_context)
: request_context_getter_(browser_context->GetRequestContext()) {
Cookies::Cookies(v8::Isolate* isolate,
content::BrowserContext* browser_context)
: request_context_getter_(browser_context->GetRequestContext()) {
Init(isolate);
}
Cookies::~Cookies() {
@ -223,7 +225,7 @@ void Cookies::Set(const base::DictionaryValue& details,
mate::Handle<Cookies> Cookies::Create(
v8::Isolate* isolate,
content::BrowserContext* browser_context) {
return mate::CreateHandle(isolate, new Cookies(browser_context));
return mate::CreateHandle(isolate, new Cookies(isolate, browser_context));
}
// static

View file

@ -46,8 +46,8 @@ class Cookies : public mate::TrackableObject<Cookies> {
v8::Local<v8::ObjectTemplate> prototype);
protected:
explicit Cookies(content::BrowserContext* browser_context);
~Cookies();
Cookies(v8::Isolate* isolate, content::BrowserContext* browser_context);
~Cookies() override;
void Get(const base::DictionaryValue& filter, const GetCallback& callback);
void Remove(const GURL& url, const std::string& name,

View file

@ -31,9 +31,10 @@ WrapDebuggerCallback g_wrap_debugger;
} // namespace
Debugger::Debugger(content::WebContents* web_contents)
Debugger::Debugger(v8::Isolate* isolate, content::WebContents* web_contents)
: web_contents_(web_contents),
previous_request_id_(0) {
Init(isolate);
}
Debugger::~Debugger() {
@ -150,7 +151,8 @@ void Debugger::SendCommand(mate::Arguments* args) {
mate::Handle<Debugger> Debugger::Create(
v8::Isolate* isolate,
content::WebContents* web_contents) {
auto handle = mate::CreateHandle(isolate, new Debugger(web_contents));
auto handle = mate::CreateHandle(
isolate, new Debugger(isolate, web_contents));
g_wrap_debugger.Run(handle.ToV8());
return handle;
}
@ -165,16 +167,8 @@ void Debugger::BuildPrototype(v8::Isolate* isolate,
.SetMethod("sendCommand", &Debugger::SendCommand);
}
void ClearWrapDebugger() {
g_wrap_debugger.Reset();
}
void SetWrapDebugger(const WrapDebuggerCallback& callback) {
g_wrap_debugger = callback;
// Cleanup the wrapper on exit.
atom::AtomBrowserMainParts::Get()->RegisterDestructionCallback(
base::Bind(ClearWrapDebugger));
}
} // namespace api

View file

@ -42,8 +42,8 @@ class Debugger: public mate::TrackableObject<Debugger>,
v8::Local<v8::ObjectTemplate> prototype);
protected:
explicit Debugger(content::WebContents* web_contents);
~Debugger();
Debugger(v8::Isolate* isolate, content::WebContents* web_contents);
~Debugger() override;
// content::DevToolsAgentHostClient:
void AgentHostClosed(content::DevToolsAgentHost* agent_host,

View file

@ -38,7 +38,8 @@ namespace atom {
namespace api {
DesktopCapturer::DesktopCapturer() {
DesktopCapturer::DesktopCapturer(v8::Isolate* isolate) {
Init(isolate);
}
DesktopCapturer::~DesktopCapturer() {
@ -88,19 +89,19 @@ void DesktopCapturer::OnSourceThumbnailChanged(int index) {
bool DesktopCapturer::OnRefreshFinished() {
Emit("finished", media_list_->GetSources());
media_list_.reset();
return false;
}
mate::ObjectTemplateBuilder DesktopCapturer::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return mate::ObjectTemplateBuilder(isolate)
.SetMethod("startHandling", &DesktopCapturer::StartHandling);
}
// static
mate::Handle<DesktopCapturer> DesktopCapturer::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new DesktopCapturer);
return mate::CreateHandle(isolate, new DesktopCapturer(isolate));
}
// static
void DesktopCapturer::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
mate::ObjectTemplateBuilder(isolate, prototype)
.SetMethod("startHandling", &DesktopCapturer::StartHandling);
}
} // namespace api

View file

@ -14,18 +14,21 @@ namespace atom {
namespace api {
class DesktopCapturer: public mate::EventEmitter,
class DesktopCapturer: public mate::EventEmitter<DesktopCapturer>,
public DesktopMediaListObserver {
public:
static mate::Handle<DesktopCapturer> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
void StartHandling(bool capture_window,
bool capture_screen,
const gfx::Size& thumbnail_size);
protected:
DesktopCapturer();
~DesktopCapturer();
explicit DesktopCapturer(v8::Isolate* isolate);
~DesktopCapturer() override;
// DesktopMediaListObserver overrides.
void OnSourceAdded(int index) override;
@ -36,10 +39,6 @@ class DesktopCapturer: public mate::EventEmitter,
bool OnRefreshFinished() override;
private:
// mate::Wrappable:
mate::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
scoped_ptr<DesktopMediaList> media_list_;
DISALLOW_COPY_AND_ASSIGN(DesktopCapturer);

View file

@ -57,9 +57,11 @@ std::map<uint32_t, linked_ptr<v8::Global<v8::Value>>> g_download_item_objects;
} // namespace
DownloadItem::DownloadItem(content::DownloadItem* download_item)
DownloadItem::DownloadItem(v8::Isolate* isolate,
content::DownloadItem* download_item)
: download_item_(download_item) {
download_item_->AddObserver(this);
Init(isolate);
AttachAsUserData(download_item);
}
@ -173,7 +175,7 @@ mate::Handle<DownloadItem> DownloadItem::Create(
if (existing)
return mate::CreateHandle(isolate, static_cast<DownloadItem*>(existing));
auto handle = mate::CreateHandle(isolate, new DownloadItem(item));
auto handle = mate::CreateHandle(isolate, new DownloadItem(isolate, item));
g_wrap_download_item.Run(handle.ToV8());
// Reference this object in case it got garbage collected.
@ -182,16 +184,8 @@ mate::Handle<DownloadItem> DownloadItem::Create(
return handle;
}
void ClearWrapDownloadItem() {
g_wrap_download_item.Reset();
}
void SetWrapDownloadItem(const WrapDownloadItemCallback& callback) {
g_wrap_download_item = callback;
// Cleanup the wrapper on exit.
atom::AtomBrowserMainParts::Get()->RegisterDestructionCallback(
base::Bind(ClearWrapDownloadItem));
}
} // namespace api

View file

@ -23,7 +23,6 @@ class DownloadItem : public mate::TrackableObject<DownloadItem>,
static mate::Handle<DownloadItem> Create(v8::Isolate* isolate,
content::DownloadItem* item);
// mate::TrackableObject:
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
@ -41,7 +40,7 @@ class DownloadItem : public mate::TrackableObject<DownloadItem>,
base::FilePath GetSavePath() const;
protected:
explicit DownloadItem(content::DownloadItem* download_item);
DownloadItem(v8::Isolate* isolate, content::DownloadItem* download_item);
~DownloadItem();
// Override content::DownloadItem::Observer methods

View file

@ -19,7 +19,8 @@ namespace atom {
namespace api {
GlobalShortcut::GlobalShortcut() {
GlobalShortcut::GlobalShortcut(v8::Isolate* isolate) {
Init(isolate);
}
GlobalShortcut::~GlobalShortcut() {
@ -66,20 +67,21 @@ void GlobalShortcut::UnregisterAll() {
GlobalShortcutListener::GetInstance()->UnregisterAccelerators(this);
}
mate::ObjectTemplateBuilder GlobalShortcut::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return mate::ObjectTemplateBuilder(isolate)
// static
mate::Handle<GlobalShortcut> GlobalShortcut::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new GlobalShortcut(isolate));
}
// static
void GlobalShortcut::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
mate::ObjectTemplateBuilder(isolate, prototype)
.SetMethod("register", &GlobalShortcut::Register)
.SetMethod("isRegistered", &GlobalShortcut::IsRegistered)
.SetMethod("unregister", &GlobalShortcut::Unregister)
.SetMethod("unregisterAll", &GlobalShortcut::UnregisterAll);
}
// static
mate::Handle<GlobalShortcut> GlobalShortcut::Create(v8::Isolate* isolate) {
return CreateHandle(isolate, new GlobalShortcut);
}
} // namespace api
} // namespace atom

View file

@ -23,13 +23,12 @@ class GlobalShortcut : public extensions::GlobalShortcutListener::Observer,
public:
static mate::Handle<GlobalShortcut> Create(v8::Isolate* isolate);
protected:
GlobalShortcut();
~GlobalShortcut() override;
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
// mate::Wrappable implementations:
mate::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
protected:
explicit GlobalShortcut(v8::Isolate* isolate);
~GlobalShortcut() override;
private:
typedef std::map<ui::Accelerator, base::Closure> AcceleratorCallbackMap;

View file

@ -19,7 +19,7 @@ namespace atom {
namespace api {
Menu::Menu()
Menu::Menu(v8::Isolate* isolate)
: model_(new AtomMenuModel(this)),
parent_(NULL) {
}
@ -28,7 +28,7 @@ Menu::~Menu() {
}
void Menu::AfterInit(v8::Isolate* isolate) {
mate::Dictionary wrappable(isolate, GetWrapper(isolate));
mate::Dictionary wrappable(isolate, GetWrapper());
mate::Dictionary delegate;
if (!wrappable.Get("delegate", &delegate))
return;

View file

@ -20,7 +20,7 @@ namespace api {
class Menu : public mate::TrackableObject<Menu>,
public AtomMenuModel::Delegate {
public:
static mate::Wrappable* Create();
static mate::WrappableBase* Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
@ -36,7 +36,7 @@ class Menu : public mate::TrackableObject<Menu>,
AtomMenuModel* model() const { return model_.get(); }
protected:
Menu();
explicit Menu(v8::Isolate* isolate);
~Menu() override;
// mate::Wrappable:

View file

@ -17,7 +17,7 @@ namespace api {
class MenuMac : public Menu {
protected:
MenuMac();
explicit MenuMac(v8::Isolate* isolate);
void PopupAt(Window* window, int x, int y, int positioning_item = 0) override;

View file

@ -15,7 +15,7 @@ namespace atom {
namespace api {
MenuMac::MenuMac() {
MenuMac::MenuMac(v8::Isolate* isolate) : Menu(isolate) {
}
void MenuMac::PopupAt(Window* window, int x, int y, int positioning_item) {
@ -68,8 +68,8 @@ void Menu::SendActionToFirstResponder(const std::string& action) {
}
// static
mate::Wrappable* Menu::Create() {
return new MenuMac();
mate::WrappableBase* Menu::Create(v8::Isolate* isolate) {
return new MenuMac(isolate);
}
} // namespace api

View file

@ -13,7 +13,7 @@ namespace atom {
namespace api {
MenuViews::MenuViews() {
MenuViews::MenuViews(v8::Isolate* isolate) : Menu(isolate) {
}
void MenuViews::PopupAt(Window* window, int x, int y, int positioning_item) {
@ -49,8 +49,8 @@ void MenuViews::PopupAt(Window* window, int x, int y, int positioning_item) {
}
// static
mate::Wrappable* Menu::Create() {
return new MenuViews();
mate::WrappableBase* Menu::Create(v8::Isolate* isolate) {
return new MenuViews(isolate);
}
} // namespace api

View file

@ -14,7 +14,7 @@ namespace api {
class MenuViews : public Menu {
public:
MenuViews();
explicit MenuViews(v8::Isolate* isolate);
protected:
void PopupAt(Window* window, int x, int y, int positioning_item = 0) override;

View file

@ -14,8 +14,9 @@ namespace atom {
namespace api {
PowerMonitor::PowerMonitor() {
PowerMonitor::PowerMonitor(v8::Isolate* isolate) {
base::PowerMonitor::Get()->AddObserver(this);
Init(isolate);
}
PowerMonitor::~PowerMonitor() {
@ -46,7 +47,13 @@ v8::Local<v8::Value> PowerMonitor::Create(v8::Isolate* isolate) {
return v8::Null(isolate);
}
return CreateHandle(isolate, new PowerMonitor).ToV8();
return mate::CreateHandle(isolate, new PowerMonitor(isolate)).ToV8();
}
// static
void PowerMonitor::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
mate::ObjectTemplateBuilder(isolate, prototype);
}
} // namespace api

View file

@ -19,8 +19,11 @@ class PowerMonitor : public mate::TrackableObject<PowerMonitor>,
public:
static v8::Local<v8::Value> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
protected:
PowerMonitor();
explicit PowerMonitor(v8::Isolate* isolate);
~PowerMonitor() override;
// base::PowerObserver implementations:

View file

@ -37,9 +37,10 @@ namespace atom {
namespace api {
PowerSaveBlocker::PowerSaveBlocker()
PowerSaveBlocker::PowerSaveBlocker(v8::Isolate* isolate)
: current_blocker_type_(
content::PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension) {
content::PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension) {
Init(isolate);
}
PowerSaveBlocker::~PowerSaveBlocker() {
@ -97,17 +98,18 @@ bool PowerSaveBlocker::IsStarted(int id) {
return power_save_blocker_types_.find(id) != power_save_blocker_types_.end();
}
mate::ObjectTemplateBuilder PowerSaveBlocker::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return mate::ObjectTemplateBuilder(isolate)
.SetMethod("start", &PowerSaveBlocker::Start)
.SetMethod("stop", &PowerSaveBlocker::Stop)
.SetMethod("isStarted", &PowerSaveBlocker::IsStarted);
// static
mate::Handle<PowerSaveBlocker> PowerSaveBlocker::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new PowerSaveBlocker(isolate));
}
// static
mate::Handle<PowerSaveBlocker> PowerSaveBlocker::Create(v8::Isolate* isolate) {
return CreateHandle(isolate, new PowerSaveBlocker);
void PowerSaveBlocker::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
mate::ObjectTemplateBuilder(isolate, prototype)
.SetMethod("start", &PowerSaveBlocker::Start)
.SetMethod("stop", &PowerSaveBlocker::Stop)
.SetMethod("isStarted", &PowerSaveBlocker::IsStarted);
}
} // namespace api

View file

@ -24,13 +24,12 @@ class PowerSaveBlocker : public mate::TrackableObject<PowerSaveBlocker> {
public:
static mate::Handle<PowerSaveBlocker> Create(v8::Isolate* isolate);
protected:
PowerSaveBlocker();
~PowerSaveBlocker() override;
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
// mate::Wrappable implementations:
mate::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
protected:
explicit PowerSaveBlocker(v8::Isolate* isolate);
~PowerSaveBlocker() override;
private:
void UpdatePowerSaveBlocker();

View file

@ -22,37 +22,11 @@ namespace atom {
namespace api {
Protocol::Protocol(AtomBrowserContext* browser_context)
Protocol::Protocol(v8::Isolate* isolate, AtomBrowserContext* browser_context)
: request_context_getter_(browser_context->GetRequestContext()),
job_factory_(browser_context->job_factory()) {
CHECK(job_factory_);
}
mate::ObjectTemplateBuilder Protocol::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return mate::ObjectTemplateBuilder(isolate)
.SetMethod("registerStandardSchemes", &Protocol::RegisterStandardSchemes)
.SetMethod("registerServiceWorkerSchemes",
&Protocol::RegisterServiceWorkerSchemes)
.SetMethod("registerStringProtocol",
&Protocol::RegisterProtocol<URLRequestStringJob>)
.SetMethod("registerBufferProtocol",
&Protocol::RegisterProtocol<URLRequestBufferJob>)
.SetMethod("registerFileProtocol",
&Protocol::RegisterProtocol<URLRequestAsyncAsarJob>)
.SetMethod("registerHttpProtocol",
&Protocol::RegisterProtocol<URLRequestFetchJob>)
.SetMethod("unregisterProtocol", &Protocol::UnregisterProtocol)
.SetMethod("isProtocolHandled", &Protocol::IsProtocolHandled)
.SetMethod("interceptStringProtocol",
&Protocol::InterceptProtocol<URLRequestStringJob>)
.SetMethod("interceptBufferProtocol",
&Protocol::InterceptProtocol<URLRequestBufferJob>)
.SetMethod("interceptFileProtocol",
&Protocol::InterceptProtocol<URLRequestAsyncAsarJob>)
.SetMethod("interceptHttpProtocol",
&Protocol::InterceptProtocol<URLRequestFetchJob>)
.SetMethod("uninterceptProtocol", &Protocol::UninterceptProtocol);
Init(isolate);
}
void Protocol::RegisterStandardSchemes(
@ -150,7 +124,35 @@ std::string Protocol::ErrorCodeToString(ProtocolError error) {
// static
mate::Handle<Protocol> Protocol::Create(
v8::Isolate* isolate, AtomBrowserContext* browser_context) {
return mate::CreateHandle(isolate, new Protocol(browser_context));
return mate::CreateHandle(isolate, new Protocol(isolate, browser_context));
}
// static
void Protocol::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
mate::ObjectTemplateBuilder(isolate, prototype)
.SetMethod("registerStandardSchemes", &Protocol::RegisterStandardSchemes)
.SetMethod("registerServiceWorkerSchemes",
&Protocol::RegisterServiceWorkerSchemes)
.SetMethod("registerStringProtocol",
&Protocol::RegisterProtocol<URLRequestStringJob>)
.SetMethod("registerBufferProtocol",
&Protocol::RegisterProtocol<URLRequestBufferJob>)
.SetMethod("registerFileProtocol",
&Protocol::RegisterProtocol<URLRequestAsyncAsarJob>)
.SetMethod("registerHttpProtocol",
&Protocol::RegisterProtocol<URLRequestFetchJob>)
.SetMethod("unregisterProtocol", &Protocol::UnregisterProtocol)
.SetMethod("isProtocolHandled", &Protocol::IsProtocolHandled)
.SetMethod("interceptStringProtocol",
&Protocol::InterceptProtocol<URLRequestStringJob>)
.SetMethod("interceptBufferProtocol",
&Protocol::InterceptProtocol<URLRequestBufferJob>)
.SetMethod("interceptFileProtocol",
&Protocol::InterceptProtocol<URLRequestAsyncAsarJob>)
.SetMethod("interceptHttpProtocol",
&Protocol::InterceptProtocol<URLRequestFetchJob>)
.SetMethod("uninterceptProtocol", &Protocol::UninterceptProtocol);
}
} // namespace api

View file

@ -30,7 +30,7 @@ class AtomURLRequestJobFactory;
namespace api {
class Protocol : public mate::Wrappable {
class Protocol : public mate::Wrappable<Protocol> {
public:
using Handler =
base::Callback<void(const net::URLRequest*, v8::Local<v8::Value>)>;
@ -40,12 +40,11 @@ class Protocol : public mate::Wrappable {
static mate::Handle<Protocol> Create(
v8::Isolate* isolate, AtomBrowserContext* browser_context);
protected:
explicit Protocol(AtomBrowserContext* browser_context);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
// mate::Wrappable implementations:
virtual mate::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate);
protected:
Protocol(v8::Isolate* isolate, AtomBrowserContext* browser_context);
private:
// Possible errors.

View file

@ -47,9 +47,10 @@ std::vector<std::string> MetricsToArray(uint32_t metrics) {
} // namespace
Screen::Screen(gfx::Screen* screen) : screen_(screen) {
displays_ = screen_->GetAllDisplays();
Screen::Screen(v8::Isolate* isolate, gfx::Screen* screen)
: screen_(screen) {
screen_->AddObserver(this);
Init(isolate);
}
Screen::~Screen() {
@ -65,7 +66,7 @@ gfx::Display Screen::GetPrimaryDisplay() {
}
std::vector<gfx::Display> Screen::GetAllDisplays() {
return displays_;
return screen_->GetAllDisplays();
}
gfx::Display Screen::GetDisplayNearestPoint(const gfx::Point& point) {
@ -77,39 +78,18 @@ gfx::Display Screen::GetDisplayMatching(const gfx::Rect& match_rect) {
}
void Screen::OnDisplayAdded(const gfx::Display& new_display) {
displays_.push_back(new_display);
Emit("display-added", new_display);
}
void Screen::OnDisplayRemoved(const gfx::Display& old_display) {
auto iter = FindById(&displays_, old_display.id());
if (iter == displays_.end())
return;
displays_.erase(iter);
Emit("display-removed", old_display);
}
void Screen::OnDisplayMetricsChanged(const gfx::Display& display,
uint32_t changed_metrics) {
auto iter = FindById(&displays_, display.id());
if (iter == displays_.end())
return;
*iter = display;
Emit("display-metrics-changed", display, MetricsToArray(changed_metrics));
}
mate::ObjectTemplateBuilder Screen::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return mate::ObjectTemplateBuilder(isolate)
.SetMethod("getCursorScreenPoint", &Screen::GetCursorScreenPoint)
.SetMethod("getPrimaryDisplay", &Screen::GetPrimaryDisplay)
.SetMethod("getAllDisplays", &Screen::GetAllDisplays)
.SetMethod("getDisplayNearestPoint", &Screen::GetDisplayNearestPoint)
.SetMethod("getDisplayMatching", &Screen::GetDisplayMatching);
}
// static
v8::Local<v8::Value> Screen::Create(v8::Isolate* isolate) {
if (!Browser::Get()->is_ready()) {
@ -126,7 +106,18 @@ v8::Local<v8::Value> Screen::Create(v8::Isolate* isolate) {
return v8::Null(isolate);
}
return mate::CreateHandle(isolate, new Screen(screen)).ToV8();
return mate::CreateHandle(isolate, new Screen(isolate, screen)).ToV8();
}
// static
void Screen::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
mate::ObjectTemplateBuilder(isolate, prototype)
.SetMethod("getCursorScreenPoint", &Screen::GetCursorScreenPoint)
.SetMethod("getPrimaryDisplay", &Screen::GetPrimaryDisplay)
.SetMethod("getAllDisplays", &Screen::GetAllDisplays)
.SetMethod("getDisplayNearestPoint", &Screen::GetDisplayNearestPoint)
.SetMethod("getDisplayMatching", &Screen::GetDisplayMatching);
}
} // namespace api

View file

@ -21,14 +21,17 @@ namespace atom {
namespace api {
class Screen : public mate::EventEmitter,
class Screen : public mate::EventEmitter<Screen>,
public gfx::DisplayObserver {
public:
static v8::Local<v8::Value> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
protected:
explicit Screen(gfx::Screen* screen);
virtual ~Screen();
Screen(v8::Isolate* isolate, gfx::Screen* screen);
~Screen() override;
gfx::Point GetCursorScreenPoint();
gfx::Display GetPrimaryDisplay();
@ -42,13 +45,8 @@ class Screen : public mate::EventEmitter,
void OnDisplayMetricsChanged(const gfx::Display& display,
uint32_t changed_metrics) override;
// mate::Wrappable:
mate::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
private:
gfx::Screen* screen_;
std::vector<gfx::Display> displays_;
DISALLOW_COPY_AND_ASSIGN(Screen);
};

View file

@ -9,9 +9,7 @@
#include "atom/browser/api/atom_api_cookies.h"
#include "atom/browser/api/atom_api_download_item.h"
#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/api/atom_api_web_request.h"
#include "atom/browser/api/save_page_handler.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/atom_permission_manager.h"
@ -23,12 +21,13 @@
#include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/node_includes.h"
#include "base/files/file_path.h"
#include "base/guid.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/thread_task_runner_handle.h"
#include "brightray/browser/net/devtools_network_conditions.h"
#include "brightray/browser/net/devtools_network_controller.h"
#include "brightray/browser/net/devtools_network_controller_handle.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/storage_partition.h"
@ -287,13 +286,15 @@ void ClearHostResolverCacheInIO(
} // namespace
Session::Session(AtomBrowserContext* browser_context)
: browser_context_(browser_context) {
AttachAsUserData(browser_context);
Session::Session(v8::Isolate* isolate, AtomBrowserContext* browser_context)
: devtools_network_emulation_client_id_(base::GenerateGUID()),
browser_context_(browser_context) {
// Observe DownloadManger to get download notifications.
content::BrowserContext::GetDownloadManager(browser_context)->
AddObserver(this);
Init(isolate);
AttachAsUserData(browser_context);
}
Session::~Session() {
@ -303,13 +304,15 @@ Session::~Session() {
void Session::OnDownloadCreated(content::DownloadManager* manager,
content::DownloadItem* item) {
auto web_contents = item->GetWebContents();
if (SavePageHandler::IsSavePageTypes(item->GetMimeType()))
if (item->IsSavePackageDownload())
return;
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
bool prevent_default = Emit(
"will-download",
DownloadItem::Create(isolate(), item),
api::WebContents::CreateFrom(isolate(), web_contents));
item->GetWebContents());
if (prevent_default) {
item->Cancel(true);
item->Remove();
@ -381,25 +384,19 @@ void Session::EnableNetworkEmulation(const mate::Dictionary& options) {
download_throughput,
upload_throughput));
}
auto controller = browser_context_->GetDevToolsNetworkController();
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(&brightray::DevToolsNetworkController::SetNetworkState,
base::Unretained(controller),
std::string(),
base::Passed(&conditions)));
browser_context_->network_controller_handle()->SetNetworkState(
devtools_network_emulation_client_id_, std::move(conditions));
browser_context_->network_delegate()->SetDevToolsNetworkEmulationClientId(
devtools_network_emulation_client_id_);
}
void Session::DisableNetworkEmulation() {
scoped_ptr<brightray::DevToolsNetworkConditions> conditions(
new brightray::DevToolsNetworkConditions(false));
auto controller = browser_context_->GetDevToolsNetworkController();
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(&brightray::DevToolsNetworkController::SetNetworkState,
base::Unretained(controller),
std::string(),
base::Passed(&conditions)));
scoped_ptr<brightray::DevToolsNetworkConditions> conditions;
browser_context_->network_controller_handle()->SetNetworkState(
devtools_network_emulation_client_id_, std::move(conditions));
browser_context_->network_delegate()->SetDevToolsNetworkEmulationClientId(
std::string());
}
void Session::SetCertVerifyProc(v8::Local<v8::Value> val,
@ -458,7 +455,8 @@ mate::Handle<Session> Session::CreateFrom(
if (existing)
return mate::CreateHandle(isolate, static_cast<Session*>(existing));
auto handle = mate::CreateHandle(isolate, new Session(browser_context));
auto handle = mate::CreateHandle(
isolate, new Session(isolate, browser_context));
g_wrap_session.Run(handle.ToV8());
return handle;
}
@ -493,16 +491,8 @@ void Session::BuildPrototype(v8::Isolate* isolate,
.SetProperty("webRequest", &Session::WebRequest);
}
void ClearWrapSession() {
g_wrap_session.Reset();
}
void SetWrapSession(const WrapSessionCallback& callback) {
g_wrap_session = callback;
// Cleanup the wrapper on exit.
atom::AtomBrowserMainParts::Get()->RegisterDestructionCallback(
base::Bind(ClearWrapSession));
}
} // namespace api

View file

@ -58,7 +58,7 @@ class Session: public mate::TrackableObject<Session>,
v8::Local<v8::ObjectTemplate> prototype);
protected:
explicit Session(AtomBrowserContext* browser_context);
Session(v8::Isolate* isolate, AtomBrowserContext* browser_context);
~Session();
// content::DownloadManager::Observer:
@ -86,6 +86,9 @@ class Session: public mate::TrackableObject<Session>,
v8::Global<v8::Value> cookies_;
v8::Global<v8::Value> web_request_;
// The X-DevTools-Emulate-Network-Conditions-Client-Id.
std::string devtools_network_emulation_client_id_;
scoped_refptr<AtomBrowserContext> browser_context_;
DISALLOW_COPY_AND_ASSIGN(Session);

View file

@ -0,0 +1,75 @@
// Copyright (c) 2016 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_system_preferences.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
#if defined(OS_WIN)
#include "ui/base/win/shell.h"
#endif
namespace atom {
namespace api {
SystemPreferences::SystemPreferences(v8::Isolate* isolate) {
Init(isolate);
}
SystemPreferences::~SystemPreferences() {
}
#if defined(OS_WIN)
bool SystemPreferences::IsAeroGlassEnabled() {
return ui::win::IsAeroGlassEnabled();
}
#endif
#if !defined(OS_MACOSX)
bool SystemPreferences::IsDarkMode() {
return false;
}
#endif
// static
mate::Handle<SystemPreferences> SystemPreferences::Create(
v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new SystemPreferences(isolate));
}
// static
void SystemPreferences::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
mate::ObjectTemplateBuilder(isolate, prototype)
#if defined(OS_WIN)
.SetMethod("isAeroGlassEnabled", &SystemPreferences::IsAeroGlassEnabled)
#elif defined(OS_MACOSX)
.SetMethod("subscribeNotification",
&SystemPreferences::SubscribeNotification)
.SetMethod("unsubscribeNotification",
&SystemPreferences::UnsubscribeNotification)
.SetMethod("getUserDefault", &SystemPreferences::GetUserDefault)
#endif
.SetMethod("isDarkMode", &SystemPreferences::IsDarkMode);
}
} // namespace api
} // namespace atom
namespace {
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("systemPreferences", atom::api::SystemPreferences::Create(isolate));
}
} // namespace
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_system_preferences, Initialize);

View file

@ -0,0 +1,48 @@
// Copyright (c) 2016 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_SYSTEM_PREFERENCES_H_
#define ATOM_BROWSER_API_ATOM_API_SYSTEM_PREFERENCES_H_
#include <string>
#include "atom/browser/api/event_emitter.h"
#include "base/callback.h"
#include "native_mate/handle.h"
namespace atom {
namespace api {
class SystemPreferences : public mate::EventEmitter<SystemPreferences> {
public:
static mate::Handle<SystemPreferences> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
#if defined(OS_WIN)
bool IsAeroGlassEnabled();
#elif defined(OS_MACOSX)
int SubscribeNotification(const std::string& name,
const base::Closure& callback);
void UnsubscribeNotification(int id);
v8::Local<v8::Value> GetUserDefault(const std::string& name,
const std::string& type);
#endif
bool IsDarkMode();
protected:
explicit SystemPreferences(v8::Isolate* isolate);
~SystemPreferences() override;
private:
DISALLOW_COPY_AND_ASSIGN(SystemPreferences);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_SYSTEM_PREFERENCES_H_

View file

@ -0,0 +1,83 @@
// Copyright (c) 2016 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_system_preferences.h"
#include <map>
#import <Cocoa/Cocoa.h>
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "base/strings/sys_string_conversions.h"
#include "net/base/mac/url_conversions.h"
namespace atom {
namespace api {
namespace {
int g_next_id = 0;
// The map to convert |id| to |int|.
std::map<int, id> g_id_map;
} // namespace
int SystemPreferences::SubscribeNotification(const std::string& name,
const base::Closure& callback) {
int request_id = g_next_id++;
__block base::Closure copied_callback = callback;
g_id_map[request_id] = [[NSDistributedNotificationCenter defaultCenter]
addObserverForName:base::SysUTF8ToNSString(name)
object:nil
queue:nil
usingBlock:^(NSNotification* notification) {
copied_callback.Run();
}
];
return request_id;
}
void SystemPreferences::UnsubscribeNotification(int request_id) {
auto iter = g_id_map.find(request_id);
if (iter != g_id_map.end()) {
id observer = iter->second;
[[NSDistributedNotificationCenter defaultCenter] removeObserver:observer];
g_id_map.erase(iter);
}
}
v8::Local<v8::Value> SystemPreferences::GetUserDefault(
const std::string& name, const std::string& type) {
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* key = base::SysUTF8ToNSString(name);
if (type == "string") {
return mate::StringToV8(
isolate(), base::SysNSStringToUTF8([defaults stringForKey:key]));
} else if (type == "boolean") {
return v8::Boolean::New(isolate(), [defaults boolForKey:key]);
} else if (type == "float") {
return v8::Number::New(isolate(), [defaults floatForKey:key]);
} else if (type == "integer") {
return v8::Integer::New(isolate(), [defaults integerForKey:key]);
} else if (type == "double") {
return v8::Number::New(isolate(), [defaults doubleForKey:key]);
} else if (type == "url") {
return mate::ConvertToV8(
isolate(), net::GURLWithNSURL([defaults URLForKey:key]));
} else {
return v8::Undefined(isolate());
}
}
bool SystemPreferences::IsDarkMode() {
NSString* mode = [[NSUserDefaults standardUserDefaults]
stringForKey:@"AppleInterfaceStyle"];
return [mode isEqualToString:@"Dark"];
}
} // namespace api
} // namespace atom

View file

@ -22,7 +22,7 @@ namespace atom {
namespace api {
Tray::Tray(const gfx::Image& image)
Tray::Tray(v8::Isolate* isolate, const gfx::Image& image)
: tray_icon_(TrayIcon::Create()) {
tray_icon_->SetImage(image);
tray_icon_->AddObserver(this);
@ -32,13 +32,13 @@ Tray::~Tray() {
}
// static
mate::Wrappable* Tray::New(v8::Isolate* isolate, const gfx::Image& image) {
mate::WrappableBase* Tray::New(v8::Isolate* isolate, const gfx::Image& image) {
if (!Browser::Get()->is_ready()) {
isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate, "Cannot create Tray before app is ready")));
return nullptr;
}
return new Tray(image);
return new Tray(isolate, image);
}
void Tray::OnClicked(const gfx::Rect& bounds, int modifiers) {

View file

@ -32,13 +32,14 @@ class Menu;
class Tray : public mate::TrackableObject<Tray>,
public TrayIconObserver {
public:
static mate::Wrappable* New(v8::Isolate* isolate, const gfx::Image& image);
static mate::WrappableBase* New(
v8::Isolate* isolate, const gfx::Image& image);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
protected:
explicit Tray(const gfx::Image& image);
Tray(v8::Isolate* isolate, const gfx::Image& image);
~Tray() override;
// TrayIconObserver:

View file

@ -13,12 +13,16 @@
#include "atom/browser/atom_browser_client.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/atom_security_state_model_client.h"
#include "atom/browser/native_window.h"
#include "atom/browser/net/atom_network_delegate.h"
#include "atom/browser/web_contents_permission_helper.h"
#include "atom/browser/web_contents_preferences.h"
#include "atom/browser/web_view_guest_delegate.h"
#include "atom/common/api/api_messages.h"
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/color_util.h"
#include "atom/common/mouse_util.h"
#include "atom/common/native_mate_converters/blink_converter.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/content_converter.h"
@ -28,13 +32,14 @@
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/mouse_util.h"
#include "atom/common/options_switches.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "brightray/browser/inspectable_web_contents.h"
#include "brightray/browser/inspectable_web_contents_view.h"
#include "chrome/browser/printing/print_view_manager_basic.h"
#include "chrome/browser/printing/print_preview_message_handler.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/common/view_messages.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/native_web_keyboard_event.h"
@ -210,17 +215,27 @@ content::ServiceWorkerContext* GetServiceWorkerContext(
} // namespace
WebContents::WebContents(content::WebContents* web_contents)
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
type_(REMOTE) {
AttachAsUserData(web_contents);
embedder_(nullptr),
type_(REMOTE),
request_id_(0),
background_throttling_(true) {
web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
Init(isolate);
AttachAsUserData(web_contents);
}
WebContents::WebContents(v8::Isolate* isolate,
const mate::Dictionary& options)
: embedder_(nullptr),
request_id_(0) {
request_id_(0),
background_throttling_(true) {
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
// Whether it is a guest WebContents.
bool is_guest = false;
options.Get("isGuest", &is_guest);
@ -258,7 +273,6 @@ WebContents::WebContents(v8::Isolate* isolate,
}
Observe(web_contents);
AttachAsUserData(web_contents);
InitWithWebContents(web_contents);
managed_web_contents()->GetView()->SetDelegate(this);
@ -268,6 +282,8 @@ WebContents::WebContents(v8::Isolate* isolate,
// Intialize permission helper.
WebContentsPermissionHelper::CreateForWebContents(web_contents);
// Intialize security state client.
AtomSecurityStateModelClient::CreateForWebContents(web_contents);
web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
@ -285,6 +301,9 @@ WebContents::WebContents(v8::Isolate* isolate,
if (owner_window)
SetOwnerWindow(owner_window);
}
Init(isolate);
AttachAsUserData(web_contents);
}
WebContents::~WebContents() {
@ -538,18 +557,21 @@ void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
void WebContents::DidFailProvisionalLoad(
content::RenderFrameHost* render_frame_host,
const GURL& url,
int error_code,
const base::string16& error_description,
int code,
const base::string16& description,
bool was_ignored_by_handler) {
Emit("did-fail-provisional-load", error_code, error_description, url);
bool is_main_frame = !render_frame_host->GetParent();
Emit("did-fail-provisional-load", code, description, url, is_main_frame);
Emit("did-fail-load", code, description, url, is_main_frame);
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url,
const GURL& url,
int error_code,
const base::string16& error_description,
bool was_ignored_by_handler) {
Emit("did-fail-load", error_code, error_description, validated_url);
bool is_main_frame = !render_frame_host->GetParent();
Emit("did-fail-load", error_code, error_description, url, is_main_frame);
}
void WebContents::DidStartLoading() {
@ -569,7 +591,8 @@ void WebContents::DidGetResourceResponseStart(
details.http_response_code,
details.method,
details.referrer,
details.headers.get());
details.headers.get(),
ResourceTypeToString(details.resource_type));
}
void WebContents::DidGetRedirectForResourceRequest(
@ -615,6 +638,10 @@ void WebContents::DidUpdateFaviconURL(
Emit("page-favicon-updated", unique_urls);
}
void WebContents::DevToolsReloadPage() {
Emit("devtools-reload-page");
}
void WebContents::DevToolsFocused() {
Emit("devtools-focused");
}
@ -705,7 +732,8 @@ void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) {
Emit("did-fail-load",
static_cast<int>(net::ERR_INVALID_URL),
net::ErrorToShortString(net::ERR_INVALID_URL),
url.possibly_invalid_spec());
url.possibly_invalid_spec(),
true);
return;
}
@ -728,6 +756,25 @@ void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) {
params.should_clear_history_list = true;
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
web_contents()->GetController().LoadURLWithParams(params);
// Set the background color of RenderWidgetHostView.
// We have to call it right after LoadURL because the RenderViewHost is only
// created after loading a page.
const auto view = web_contents()->GetRenderWidgetHostView();
WebContentsPreferences* web_preferences =
WebContentsPreferences::FromWebContents(web_contents());
std::string color_name;
if (web_preferences->web_preferences()->GetString(options::kBackgroundColor,
&color_name)) {
view->SetBackgroundColor(ParseHexColor(color_name));
} else {
view->SetBackgroundColor(SK_ColorTRANSPARENT);
}
// For the same reason we can only disable hidden here.
const auto host = static_cast<content::RenderWidgetHostImpl*>(
view->GetRenderWidgetHost());
host->disable_hidden_ = !background_throttling_;
}
void WebContents::DownloadURL(const GURL& url) {
@ -751,6 +798,14 @@ bool WebContents::IsLoading() const {
return web_contents()->IsLoading();
}
bool WebContents::IsLoadingMainFrame() const {
// Comparing site instances works because Electron always creates a new site
// instance when navigating, regardless of origin. See AtomBrowserClient.
return (web_contents()->GetLastCommittedURL().is_empty() ||
web_contents()->GetSiteInstance() !=
web_contents()->GetPendingSiteInstance()) && IsLoading();
}
bool WebContents::IsWaitingForResponse() const {
return web_contents()->IsWaitingForResponse();
}
@ -807,14 +862,20 @@ void WebContents::OpenDevTools(mate::Arguments* args) {
if (type_ == REMOTE)
return;
bool detach = false;
std::string state;
if (type_ == WEB_VIEW) {
detach = true;
state = "detach";
} else if (args && args->Length() == 1) {
bool detach = false;
mate::Dictionary options;
args->GetNext(&options) && options.Get("detach", &detach);
if (args->GetNext(&options)) {
options.Get("mode", &state);
options.Get("detach", &detach);
if (state.empty() && detach)
state = "detach";
}
}
managed_web_contents()->SetCanDock(!detach);
managed_web_contents()->SetDockState(state);
managed_web_contents()->ShowDevTools();
}
@ -1147,6 +1208,7 @@ void WebContents::BuildPrototype(v8::Isolate* isolate,
.SetMethod("_getURL", &WebContents::GetURL)
.SetMethod("getTitle", &WebContents::GetTitle)
.SetMethod("isLoading", &WebContents::IsLoading)
.SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
.SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
.SetMethod("_stop", &WebContents::Stop)
.SetMethod("_goBack", &WebContents::GoBack)
@ -1233,7 +1295,8 @@ mate::Handle<WebContents> WebContents::CreateFrom(
return mate::CreateHandle(isolate, static_cast<WebContents*>(existing));
// Otherwise create a new WebContents wrapper object.
auto handle = mate::CreateHandle(isolate, new WebContents(web_contents));
auto handle = mate::CreateHandle(
isolate, new WebContents(isolate, web_contents));
g_wrap_web_contents.Run(handle.ToV8());
return handle;
}
@ -1246,16 +1309,8 @@ mate::Handle<WebContents> WebContents::Create(
return handle;
}
void ClearWrapWebContents() {
g_wrap_web_contents.Reset();
}
void SetWrapWebContents(const WrapWebContentsCallback& callback) {
g_wrap_web_contents = callback;
// Cleanup the wrapper on exit.
atom::AtomBrowserMainParts::Get()->RegisterDestructionCallback(
base::Bind(ClearWrapWebContents));
}
} // namespace api

View file

@ -55,6 +55,9 @@ class WebContents : public mate::TrackableObject<WebContents>,
static mate::Handle<WebContents> Create(
v8::Isolate* isolate, const mate::Dictionary& options);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
int GetID() const;
bool Equal(const WebContents* web_contents) const;
void LoadURL(const GURL& url, const mate::Dictionary& options);
@ -62,6 +65,7 @@ class WebContents : public mate::TrackableObject<WebContents>,
GURL GetURL() const;
base::string16 GetTitle() const;
bool IsLoading() const;
bool IsLoadingMainFrame() const;
bool IsWaitingForResponse() const;
void Stop();
void ReloadIgnoringCache();
@ -155,12 +159,8 @@ class WebContents : public mate::TrackableObject<WebContents>,
v8::Local<v8::Value> DevToolsWebContents(v8::Isolate* isolate);
v8::Local<v8::Value> Debugger(v8::Isolate* isolate);
// mate::TrackableObject:
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
protected:
explicit WebContents(content::WebContents* web_contents);
WebContents(v8::Isolate* isolate, content::WebContents* web_contents);
WebContents(v8::Isolate* isolate, const mate::Dictionary& options);
~WebContents();
@ -251,6 +251,9 @@ class WebContents : public mate::TrackableObject<WebContents>,
void MediaStoppedPlaying(const MediaPlayerId& id) override;
void DidChangeThemeColor(SkColor theme_color) override;
// brightray::InspectableWebContentsDelegate:
void DevToolsReloadPage() override;
// brightray::InspectableWebContentsViewDelegate:
void DevToolsFocused() override;
void DevToolsOpened() override;
@ -296,6 +299,9 @@ class WebContents : public mate::TrackableObject<WebContents>,
// Request id used for findInPage request.
uint32_t request_id_;
// Whether background throttling is disabled.
bool background_throttling_;
DISALLOW_COPY_AND_ASSIGN(WebContents);
};

View file

@ -36,8 +36,10 @@ namespace atom {
namespace api {
WebRequest::WebRequest(AtomBrowserContext* browser_context)
WebRequest::WebRequest(v8::Isolate* isolate,
AtomBrowserContext* browser_context)
: browser_context_(browser_context) {
Init(isolate);
}
WebRequest::~WebRequest() {
@ -81,7 +83,7 @@ void WebRequest::SetListener(Method method, Event type, mate::Arguments* args) {
mate::Handle<WebRequest> WebRequest::Create(
v8::Isolate* isolate,
AtomBrowserContext* browser_context) {
return mate::CreateHandle(isolate, new WebRequest(browser_context));
return mate::CreateHandle(isolate, new WebRequest(isolate, browser_context));
}
// static

View file

@ -21,13 +21,12 @@ class WebRequest : public mate::TrackableObject<WebRequest> {
static mate::Handle<WebRequest> Create(v8::Isolate* isolate,
AtomBrowserContext* browser_context);
// mate::TrackableObject:
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
protected:
explicit WebRequest(AtomBrowserContext* browser_context);
~WebRequest();
WebRequest(v8::Isolate* isolate, AtomBrowserContext* browser_context);
~WebRequest() override;
// C++ can not distinguish overloaded member function.
template<AtomNetworkDelegate::SimpleEvent type>

View file

@ -2,9 +2,9 @@
// 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_web_contents.h"
#include "atom/browser/web_contents_preferences.h"
#include "atom/browser/web_view_manager.h"
#include "atom/common/native_mate_converters/content_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "content/public/browser/browser_context.h"
@ -12,22 +12,6 @@
using atom::WebContentsPreferences;
namespace mate {
template<>
struct Converter<content::WebContents*> {
static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
content::WebContents** out) {
atom::api::WebContents* contents;
if (!Converter<atom::api::WebContents*>::FromV8(isolate, val, &contents))
return false;
*out = contents->web_contents();
return true;
}
};
} // namespace mate
namespace {
atom::WebViewManager* GetWebViewManager(content::WebContents* web_contents) {

View file

@ -141,13 +141,17 @@ Window::Window(v8::Isolate* isolate, const mate::Dictionary& options) {
if (options.Get(options::kZoomFactor, &value))
web_preferences.Set(options::kZoomFactor, value);
// Copy the backgroundColor to webContents.
if (options.Get(options::kBackgroundColor, &value))
web_preferences.Set(options::kBackgroundColor, value);
// Creates the WebContents used by BrowserWindow.
auto web_contents = WebContents::Create(isolate, web_preferences);
web_contents_.Reset(isolate, web_contents.ToV8());
api_web_contents_ = web_contents.get();
// Keep a copy of the options for later use.
mate::Dictionary(isolate, web_contents->GetWrapper(isolate)).Set(
mate::Dictionary(isolate, web_contents->GetWrapper()).Set(
"browserWindowOptions", options);
// Creates BrowserWindow.
@ -283,7 +287,7 @@ void Window::OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) {
#endif
// static
mate::Wrappable* Window::New(v8::Isolate* isolate, mate::Arguments* args) {
mate::WrappableBase* Window::New(v8::Isolate* isolate, mate::Arguments* args) {
if (!Browser::Get()->is_ready()) {
isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate, "Cannot create BrowserWindow before app is ready")));
@ -436,6 +440,10 @@ std::vector<int> Window::GetMaximumSize() {
return result;
}
void Window::SetSheetOffset(double offset) {
window_->SetSheetOffset(offset);
}
void Window::SetResizable(bool resizable) {
window_->SetResizable(resizable);
}
@ -742,6 +750,7 @@ void Window::BuildPrototype(v8::Isolate* isolate,
.SetMethod("getMinimumSize", &Window::GetMinimumSize)
.SetMethod("setMaximumSize", &Window::SetMaximumSize)
.SetMethod("getMaximumSize", &Window::GetMaximumSize)
.SetMethod("setSheetOffset", &Window::SetSheetOffset)
.SetMethod("setResizable", &Window::SetResizable)
.SetMethod("isResizable", &Window::IsResizable)
.SetMethod("setMovable", &Window::SetMovable)
@ -808,7 +817,7 @@ v8::Local<v8::Value> Window::From(v8::Isolate* isolate,
NativeWindow* native_window) {
auto existing = TrackableObject::FromWrappedClass(isolate, native_window);
if (existing)
return existing->GetWrapper(isolate);
return existing->GetWrapper();
else
return v8::Null(isolate);
}

View file

@ -38,7 +38,7 @@ class WebContents;
class Window : public mate::TrackableObject<Window>,
public NativeWindowObserver {
public:
static mate::Wrappable* New(v8::Isolate* isolate, mate::Arguments* args);
static mate::WrappableBase* New(v8::Isolate* isolate, mate::Arguments* args);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
@ -51,7 +51,7 @@ class Window : public mate::TrackableObject<Window>,
protected:
Window(v8::Isolate* isolate, const mate::Dictionary& options);
virtual ~Window();
~Window() override;
// NativeWindowObserver:
void WillCloseWindow(bool* prevent_default) override;
@ -110,6 +110,7 @@ class Window : public mate::TrackableObject<Window>,
std::vector<int> GetMinimumSize();
void SetMaximumSize(int width, int height);
std::vector<int> GetMaximumSize();
void SetSheetOffset(double offset);
void SetResizable(bool resizable);
bool IsResizable();
void SetMovable(bool movable);

View file

@ -11,31 +11,15 @@
namespace mate {
namespace {
v8::Persistent<v8::ObjectTemplate> template_;
} // namespace
Event::Event()
Event::Event(v8::Isolate* isolate)
: sender_(NULL),
message_(NULL) {
Init(isolate);
}
Event::~Event() {
}
ObjectTemplateBuilder Event::GetObjectTemplateBuilder(v8::Isolate* isolate) {
if (template_.IsEmpty())
template_.Reset(isolate, ObjectTemplateBuilder(isolate)
.SetMethod("preventDefault", &Event::PreventDefault)
.SetMethod("sendReply", &Event::SendReply)
.Build());
return ObjectTemplateBuilder(
isolate, v8::Local<v8::ObjectTemplate>::New(isolate, template_));
}
void Event::SetSenderAndMessage(content::WebContents* sender,
IPC::Message* message) {
DCHECK(!sender_);
@ -52,7 +36,7 @@ void Event::WebContentsDestroyed() {
}
void Event::PreventDefault(v8::Isolate* isolate) {
GetWrapper(isolate)->Set(StringToV8(isolate, "defaultPrevented"),
GetWrapper()->Set(StringToV8(isolate, "defaultPrevented"),
v8::True(isolate));
}
@ -66,7 +50,15 @@ bool Event::SendReply(const base::string16& json) {
// static
Handle<Event> Event::Create(v8::Isolate* isolate) {
return CreateHandle(isolate, new Event);
return mate::CreateHandle(isolate, new Event(isolate));
}
// static
void Event::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
mate::ObjectTemplateBuilder(isolate, prototype)
.SetMethod("preventDefault", &Event::PreventDefault)
.SetMethod("sendReply", &Event::SendReply);
}
} // namespace mate

View file

@ -15,11 +15,14 @@ class Message;
namespace mate {
class Event : public Wrappable,
class Event : public Wrappable<Event>,
public content::WebContentsObserver {
public:
static Handle<Event> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
// Pass the sender and message to be replied.
void SetSenderAndMessage(content::WebContents* sender, IPC::Message* message);
@ -30,11 +33,8 @@ class Event : public Wrappable,
bool SendReply(const base::string16& json);
protected:
Event();
virtual ~Event();
// Wrappable implementations:
ObjectTemplateBuilder GetObjectTemplateBuilder(v8::Isolate* isolate) override;
explicit Event(v8::Isolate* isolate);
~Event() override;
// content::WebContentsObserver implementations:
void WebContentsDestroyed() override;

View file

@ -34,11 +34,13 @@ v8::Local<v8::Object> CreateEventObject(v8::Isolate* isolate) {
} // namespace
EventEmitter::EventEmitter() {
}
namespace internal {
v8::Local<v8::Object> EventEmitter::CreateJSEvent(
v8::Isolate* isolate, content::WebContents* sender, IPC::Message* message) {
v8::Local<v8::Object> CreateJSEvent(
v8::Isolate* isolate,
v8::Local<v8::Object> object,
content::WebContents* sender,
IPC::Message* message) {
v8::Local<v8::Object> event;
bool use_native_event = sender && message;
@ -49,16 +51,20 @@ v8::Local<v8::Object> EventEmitter::CreateJSEvent(
} else {
event = CreateEventObject(isolate);
}
mate::Dictionary(isolate, event).Set("sender", GetWrapper(isolate));
mate::Dictionary(isolate, event).Set("sender", object);
return event;
}
v8::Local<v8::Object> EventEmitter::CreateCustomEvent(
v8::Isolate* isolate, v8::Local<v8::Object> custom_event) {
v8::Local<v8::Object> CreateCustomEvent(
v8::Isolate* isolate,
v8::Local<v8::Object> object,
v8::Local<v8::Object> custom_event) {
v8::Local<v8::Object> event = CreateEventObject(isolate);
(void)event->SetPrototype(custom_event->CreationContext(), custom_event);
mate::Dictionary(isolate, event).Set("sender", GetWrapper(isolate));
mate::Dictionary(isolate, event).Set("sender", object);
return event;
}
} // namespace internal
} // namespace mate

View file

@ -20,17 +20,38 @@ class Message;
namespace mate {
namespace internal {
v8::Local<v8::Object> CreateJSEvent(v8::Isolate* isolate,
v8::Local<v8::Object> object,
content::WebContents* sender,
IPC::Message* message);
v8::Local<v8::Object> CreateCustomEvent(
v8::Isolate* isolate,
v8::Local<v8::Object> object,
v8::Local<v8::Object> event);
} // namespace internal
// Provide helperers to emit event in JavaScript.
class EventEmitter : public Wrappable {
template<typename T>
class EventEmitter : public Wrappable<T> {
public:
typedef std::vector<v8::Local<v8::Value>> ValueArray;
// Make the convinient methods visible:
// https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-members
v8::Local<v8::Object> GetWrapper() { return Wrappable<T>::GetWrapper(); }
v8::Isolate* isolate() const { return Wrappable<T>::isolate(); }
// this.emit(name, event, args...);
template<typename... Args>
bool EmitCustomEvent(const base::StringPiece& name,
v8::Local<v8::Object> event,
const Args&... args) {
return EmitWithEvent(name, CreateCustomEvent(isolate(), event), args...);
return EmitWithEvent(
name,
internal::CreateCustomEvent(isolate(), GetWrapper(), event), args...);
}
// this.emit(name, new Event(), args...);
@ -47,12 +68,13 @@ class EventEmitter : public Wrappable {
const Args&... args) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
v8::Local<v8::Object> event = CreateJSEvent(isolate(), sender, message);
v8::Local<v8::Object> event = internal::CreateJSEvent(
isolate(), GetWrapper(), sender, message);
return EmitWithEvent(name, event, args...);
}
protected:
EventEmitter();
EventEmitter() {}
private:
// this.emit(name, event, args...);
@ -62,17 +84,11 @@ class EventEmitter : public Wrappable {
const Args&... args) {
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
EmitEvent(isolate(), GetWrapper(isolate()), name, event, args...);
EmitEvent(isolate(), GetWrapper(), name, event, args...);
return event->Get(
StringToV8(isolate(), "defaultPrevented"))->BooleanValue();
}
v8::Local<v8::Object> CreateJSEvent(v8::Isolate* isolate,
content::WebContents* sender,
IPC::Message* message);
v8::Local<v8::Object> CreateCustomEvent(
v8::Isolate* isolate, v8::Local<v8::Object> event);
DISALLOW_COPY_AND_ASSIGN(EventEmitter);
};

View file

@ -73,11 +73,6 @@ void SavePageHandler::Destroy(content::DownloadItem* item) {
delete this;
}
// static
bool SavePageHandler::IsSavePageTypes(const std::string& type) {
return type == "multipart/related" || type == "text/html";
}
} // namespace api
} // namespace atom

View file

@ -37,8 +37,6 @@ class SavePageHandler : public content::DownloadManager::Observer,
bool Handle(const base::FilePath& full_path,
const content::SavePageType& save_type);
static bool IsSavePageTypes(const std::string& type);
private:
void Destroy(content::DownloadItem* item);

View file

@ -37,15 +37,6 @@ TrackableObjectBase::~TrackableObjectBase() {
cleanup_.Run();
}
void TrackableObjectBase::AfterInit(v8::Isolate* isolate) {
if (wrapped_)
AttachAsUserData(wrapped_);
}
void TrackableObjectBase::MarkDestroyed() {
GetWrapper(isolate())->SetAlignedPointerInInternalField(0, nullptr);
}
base::Closure TrackableObjectBase::GetDestroyClosure() {
return base::Bind(&TrackableObjectBase::Destroy, weak_factory_.GetWeakPtr());
}

View file

@ -21,7 +21,7 @@ class SupportsUserData;
namespace mate {
// Users should use TrackableObject instead.
class TrackableObjectBase : public mate::EventEmitter {
class TrackableObjectBase {
public:
TrackableObjectBase();
@ -32,13 +32,7 @@ class TrackableObjectBase : public mate::EventEmitter {
void AttachAsUserData(base::SupportsUserData* wrapped);
protected:
~TrackableObjectBase() override;
// mate::Wrappable:
void AfterInit(v8::Isolate* isolate) override;
// Mark the JS object as destroyed.
void MarkDestroyed();
virtual ~TrackableObjectBase();
// Returns a closure that can destroy the native class.
base::Closure GetDestroyClosure();
@ -65,8 +59,14 @@ class TrackableObjectBase : public mate::EventEmitter {
// All instances of TrackableObject will be kept in a weak map and can be got
// from its ID.
template<typename T>
class TrackableObject : public TrackableObjectBase {
class TrackableObject : public TrackableObjectBase,
public mate::EventEmitter<T> {
public:
// Mark the JS object as destroyed.
void MarkDestroyed() {
Wrappable<T>::GetWrapper()->SetAlignedPointerInInternalField(0, nullptr);
}
// Finds out the TrackableObject from its ID in weak map.
static T* FromWeakMapID(v8::Isolate* isolate, int32_t id) {
if (!weak_map_)
@ -106,6 +106,7 @@ class TrackableObject : public TrackableObjectBase {
protected:
TrackableObject() {}
~TrackableObject() override {
RemoveFromWeakMap();
}
@ -113,41 +114,18 @@ class TrackableObject : public TrackableObjectBase {
void AfterInit(v8::Isolate* isolate) override {
if (!weak_map_) {
weak_map_.reset(new atom::IDWeakMap);
RegisterDestructionCallback(
base::Bind(&TrackableObject<T>::ReleaseAllWeakReferences));
}
weak_map_id_ = weak_map_->Add(isolate, GetWrapper(isolate));
TrackableObjectBase::AfterInit(isolate);
weak_map_id_ = weak_map_->Add(isolate, Wrappable<T>::GetWrapper());
if (wrapped_)
AttachAsUserData(wrapped_);
}
private:
// mate::Wrappable:
mate::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override {
if (template_.IsEmpty()) {
auto templ = v8::ObjectTemplate::New(isolate);
T::BuildPrototype(isolate, templ);
template_.Reset(isolate, templ);
}
return ObjectTemplateBuilder(
isolate, v8::Local<v8::ObjectTemplate>::New(isolate, template_));
}
// Releases all weak references in weak map, called when app is terminating.
static void ReleaseAllWeakReferences() {
weak_map_.reset();
}
static v8::Persistent<v8::ObjectTemplate> template_;
static scoped_ptr<atom::IDWeakMap> weak_map_;
DISALLOW_COPY_AND_ASSIGN(TrackableObject);
};
template<typename T>
v8::Persistent<v8::ObjectTemplate> TrackableObject<T>::template_;
template<typename T>
scoped_ptr<atom::IDWeakMap> TrackableObject<T>::weak_map_;

View file

@ -37,7 +37,6 @@
#include "content/public/browser/site_instance.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/web_preferences.h"
#include "net/cert/x509_certificate.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "ppapi/host/ppapi_host.h"
#include "ui/base/l10n/l10n_util.h"
@ -55,26 +54,6 @@ std::string g_custom_schemes = "";
// Custom schemes to be registered to handle service worker.
std::string g_custom_service_worker_schemes = "";
scoped_refptr<net::X509Certificate> ImportCertFromFile(
const base::FilePath& path) {
if (path.empty())
return nullptr;
std::string cert_data;
if (!base::ReadFileToString(path, &cert_data))
return nullptr;
net::CertificateList certs =
net::X509Certificate::CreateCertificateListFromBytes(
cert_data.data(), cert_data.size(),
net::X509Certificate::FORMAT_AUTO);
if (certs.empty())
return nullptr;
return certs[0];
}
} // namespace
// static
@ -242,16 +221,6 @@ void AtomBrowserClient::SelectClientCertificate(
content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info,
scoped_ptr<content::ClientCertificateDelegate> delegate) {
// --client-certificate=`path`
auto cmd = base::CommandLine::ForCurrentProcess();
if (cmd->HasSwitch(switches::kClientCertificate)) {
auto cert_path = cmd->GetSwitchValuePath(switches::kClientCertificate);
auto certificate = ImportCertFromFile(cert_path);
if (certificate.get())
delegate->ContinueWithCertificate(certificate.get());
return;
}
if (!cert_request_info->client_certs.empty() && delegate_) {
delegate_->SelectClientCertificate(
web_contents, cert_request_info, std::move(delegate));

View file

@ -65,7 +65,7 @@ std::string RemoveWhitespace(const std::string& str) {
AtomBrowserContext::AtomBrowserContext(const std::string& partition,
bool in_memory)
: brightray::BrowserContext(partition, in_memory),
cert_verifier_(nullptr),
cert_verifier_(new AtomCertVerifier),
job_factory_(new AtomURLRequestJobFactory),
network_delegate_(new AtomNetworkDelegate),
allow_ntlm_everywhere_(false) {
@ -178,8 +178,6 @@ content::PermissionManager* AtomBrowserContext::GetPermissionManager() {
}
scoped_ptr<net::CertVerifier> AtomBrowserContext::CreateCertVerifier() {
DCHECK(!cert_verifier_);
cert_verifier_ = new AtomCertVerifier;
return make_scoped_ptr(cert_verifier_);
}

View file

@ -49,7 +49,7 @@ AtomBrowserMainParts::~AtomBrowserMainParts() {
// Leak the JavascriptEnvironment on exit.
// This is to work around the bug that V8 would be waiting for background
// tasks to finish on exit, while somehow it waits forever in Electron, more
// about this can be found at https://github.com/atom/electron/issues/4767.
// about this can be found at https://github.com/electron/electron/issues/4767.
// On the other handle there is actually no need to gracefully shutdown V8
// on exit in the main process, we already ensured all necessary resources get
// cleaned up, and it would make quitting faster.
@ -136,9 +136,8 @@ void AtomBrowserMainParts::PreMainMessageLoopRun() {
// Start idle gc.
gc_timer_.Start(
FROM_HERE, base::TimeDelta::FromMinutes(1),
base::Bind(base::IgnoreResult(&v8::Isolate::IdleNotification),
base::Unretained(js_env_->isolate()),
1000));
base::Bind(&v8::Isolate::LowMemoryNotification,
base::Unretained(js_env_->isolate())));
brightray::BrowserMainParts::PreMainMessageLoopRun();
bridge_task_runner_->MessageLoopIsReady();

View file

@ -70,7 +70,9 @@ void AtomDownloadManagerDelegate::OnDownloadPathGenerated(
return;
NativeWindow* window = nullptr;
auto relay = NativeWindowRelay::FromWebContents(item->GetWebContents());
content::WebContents* web_contents = item->GetWebContents();
auto relay = web_contents ? NativeWindowRelay::FromWebContents(web_contents)
: nullptr;
if (relay)
window = relay->window.get();

View file

@ -5,6 +5,7 @@
#include "atom/browser/atom_resource_dispatcher_host_delegate.h"
#include "atom/browser/login_handler.h"
#include "atom/browser/web_contents_permission_helper.h"
#include "atom/common/platform_util.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/escape.h"
@ -14,20 +15,46 @@ using content::BrowserThread;
namespace atom {
namespace {
void OnOpenExternal(const GURL& escaped_url,
bool allowed) {
if (allowed)
platform_util::OpenExternal(escaped_url, true);
}
void HandleExternalProtocolInUI(
const GURL& url,
const content::ResourceRequestInfo::WebContentsGetter& web_contents_getter,
bool has_user_gesture) {
content::WebContents* web_contents = web_contents_getter.Run();
if (!web_contents)
return;
GURL escaped_url(net::EscapeExternalHandlerValue(url.spec()));
auto callback = base::Bind(&OnOpenExternal, escaped_url);
auto permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestOpenExternalPermission(callback, has_user_gesture);
}
} // namespace
AtomResourceDispatcherHostDelegate::AtomResourceDispatcherHostDelegate() {
}
bool AtomResourceDispatcherHostDelegate::HandleExternalProtocol(
const GURL& url,
int child_id,
const content::ResourceRequestInfo::WebContentsGetter&,
const content::ResourceRequestInfo::WebContentsGetter& web_contents_getter,
bool is_main_frame,
ui::PageTransition transition,
bool has_user_gesture) {
GURL escaped_url(net::EscapeExternalHandlerValue(url.spec()));
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(
base::IgnoreResult(platform_util::OpenExternal), escaped_url, true));
base::Bind(&HandleExternalProtocolInUI,
url,
web_contents_getter,
has_user_gesture));
return true;
}

View file

@ -0,0 +1,105 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/atom_security_state_model_client.h"
#include "content/public/browser/cert_store.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/origin_util.h"
#include "content/public/common/ssl_status.h"
#include "net/cert/x509_certificate.h"
DEFINE_WEB_CONTENTS_USER_DATA_KEY(atom::AtomSecurityStateModelClient);
using security_state::SecurityStateModel;
namespace atom {
namespace {
SecurityStateModel::SecurityLevel GetSecurityLevelForSecurityStyle(
content::SecurityStyle style) {
switch (style) {
case content::SECURITY_STYLE_UNKNOWN:
return SecurityStateModel::NONE;
case content::SECURITY_STYLE_UNAUTHENTICATED:
return SecurityStateModel::NONE;
case content::SECURITY_STYLE_AUTHENTICATION_BROKEN:
return SecurityStateModel::SECURITY_ERROR;
case content::SECURITY_STYLE_WARNING:
return SecurityStateModel::SECURITY_WARNING;
case content::SECURITY_STYLE_AUTHENTICATED:
return SecurityStateModel::SECURE;
}
return SecurityStateModel::NONE;
}
} // namespace
AtomSecurityStateModelClient::AtomSecurityStateModelClient(
content::WebContents* web_contents)
: web_contents_(web_contents),
security_state_model_(new SecurityStateModel()) {
security_state_model_->SetClient(this);
}
AtomSecurityStateModelClient::~AtomSecurityStateModelClient() {
}
const SecurityStateModel::SecurityInfo&
AtomSecurityStateModelClient::GetSecurityInfo() const {
return security_state_model_->GetSecurityInfo();
}
bool AtomSecurityStateModelClient::RetrieveCert(
scoped_refptr<net::X509Certificate>* cert) {
content::NavigationEntry* entry =
web_contents_->GetController().GetVisibleEntry();
if (!entry)
return false;
return content::CertStore::GetInstance()->RetrieveCert(
entry->GetSSL().cert_id, cert);
}
bool AtomSecurityStateModelClient::UsedPolicyInstalledCertificate() {
return false;
}
bool AtomSecurityStateModelClient::IsOriginSecure(const GURL& url) {
return content::IsOriginSecure(url);
}
void AtomSecurityStateModelClient::GetVisibleSecurityState(
SecurityStateModel::VisibleSecurityState* state) {
content::NavigationEntry* entry =
web_contents_->GetController().GetVisibleEntry();
if (!entry ||
entry->GetSSL().security_style == content::SECURITY_STYLE_UNKNOWN) {
*state = SecurityStateModel::VisibleSecurityState();
return;
}
state->initialized = true;
state->url = entry->GetURL();
const content::SSLStatus& ssl = entry->GetSSL();
state->initial_security_level =
GetSecurityLevelForSecurityStyle(ssl.security_style);
state->cert_id = ssl.cert_id;
state->cert_status = ssl.cert_status;
state->connection_status = ssl.connection_status;
state->security_bits = ssl.security_bits;
state->sct_verify_statuses.clear();
for (const auto& sct : ssl.signed_certificate_timestamp_ids)
state->sct_verify_statuses.push_back(sct.status);
state->displayed_mixed_content =
(ssl.content_status & content::SSLStatus::DISPLAYED_INSECURE_CONTENT)
? true
: false;
state->ran_mixed_content =
(ssl.content_status & content::SSLStatus::RAN_INSECURE_CONTENT) ? true
: false;
}
} // namespace atom

View file

@ -0,0 +1,42 @@
// Copyright (c) 2016 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_SECURITY_STATE_MODEL_CLIENT_H_
#define ATOM_BROWSER_ATOM_SECURITY_STATE_MODEL_CLIENT_H_
#include "components/security_state/security_state_model.h"
#include "components/security_state/security_state_model_client.h"
#include "content/public/browser/web_contents_user_data.h"
namespace atom {
class AtomSecurityStateModelClient
: public security_state::SecurityStateModelClient,
public content::WebContentsUserData<AtomSecurityStateModelClient> {
public:
~AtomSecurityStateModelClient() override;
const security_state::SecurityStateModel::SecurityInfo&
GetSecurityInfo() const;
// security_state::SecurityStateModelClient:
void GetVisibleSecurityState(
security_state::SecurityStateModel::VisibleSecurityState* state) override;
bool RetrieveCert(scoped_refptr<net::X509Certificate>* cert) override;
bool UsedPolicyInstalledCertificate() override;
bool IsOriginSecure(const GURL& url) override;
private:
explicit AtomSecurityStateModelClient(content::WebContents* web_contents);
friend class content::WebContentsUserData<AtomSecurityStateModelClient>;
content::WebContents* web_contents_;
scoped_ptr<security_state::SecurityStateModel> security_state_model_;
DISALLOW_COPY_AND_ASSIGN(AtomSecurityStateModelClient);
};
} // namespace atom
#endif // ATOM_BROWSER_ATOM_SECURITY_STATE_MODEL_CLIENT_H_

View file

@ -22,6 +22,12 @@ SQRLUpdater* g_updater = nil;
} // namespace
namespace {
bool g_update_available = false;
}
// static
void AutoUpdater::SetFeedURL(const std::string& feed) {
if (g_updater == nil) {
@ -69,6 +75,7 @@ void AutoUpdater::CheckForUpdates() {
take:1]
subscribeNext:^(SQRLDownloadedUpdate *downloadedUpdate) {
if (downloadedUpdate) {
g_update_available = true;
SQRLUpdate* update = downloadedUpdate.update;
// There is a new update that has been downloaded.
delegate->OnUpdateDownloaded(
@ -77,6 +84,7 @@ void AutoUpdater::CheckForUpdates() {
base::Time::FromDoubleT(update.releaseDate.timeIntervalSince1970),
base::SysNSStringToUTF8(update.updateURL.absoluteString));
} else {
g_update_available = false;
// When the completed event is sent with no update, then we know there
// is no update available.
delegate->OnUpdateNotAvailable();
@ -89,11 +97,16 @@ void AutoUpdater::CheckForUpdates() {
}
void AutoUpdater::QuitAndInstall() {
[[g_updater relaunchToInstallUpdate] subscribeError:^(NSError* error) {
Delegate* delegate = AutoUpdater::GetDelegate();
Delegate* delegate = AutoUpdater::GetDelegate();
if (g_update_available) {
[[g_updater relaunchToInstallUpdate] subscribeError:^(NSError* error) {
if (delegate)
delegate->OnError(base::SysNSStringToUTF8(error.localizedDescription));
}];
} else {
if (delegate)
delegate->OnError(base::SysNSStringToUTF8(error.localizedDescription));
}];
delegate->OnError("No update available, can't quit and install");
}
}
} // namespace auto_updater

View file

@ -9,12 +9,16 @@
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/native_window.h"
#include "atom/browser/window_list.h"
#include "base/files/file_util.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "brightray/browser/brightray_paths.h"
namespace atom {
Browser::Browser()
: is_quiting_(false),
is_exiting_(false),
is_ready_(false),
is_shutdown_(false) {
WindowList::AddObserver(this);
@ -49,9 +53,12 @@ void Browser::Exit(int code) {
// Message loop is not ready, quit directly.
exit(code);
} else {
// Prepare to quit when all windows have been closed..
// Prepare to quit when all windows have been closed.
is_quiting_ = true;
// Remember this caller so that we don't emit unrelated events.
is_exiting_ = true;
// Must destroy windows before quitting, otherwise bad things can happen.
atom::WindowList* window_list = atom::WindowList::GetInstance();
if (window_list->size() == 0) {
@ -135,6 +142,11 @@ void Browser::WillFinishLaunching() {
}
void Browser::DidFinishLaunching() {
// Make sure the userData directory is created.
base::FilePath user_data;
if (PathService::Get(brightray::DIR_USER_DATA, &user_data))
base::CreateDirectoryAndGetError(user_data, nullptr);
is_ready_ = true;
FOR_EACH_OBSERVER(BrowserObserver, observers_, OnFinishLaunching());
}
@ -175,14 +187,12 @@ void Browser::OnWindowCloseCancelled(NativeWindow* window) {
}
void Browser::OnWindowAllClosed() {
if (is_quiting_)
if (is_exiting_)
Shutdown();
else if (is_quiting_)
NotifyAndShutdown();
else
FOR_EACH_OBSERVER(BrowserObserver, observers_, OnWindowAllClosed());
}
void Browser::PlatformThemeChanged() {
FOR_EACH_OBSERVER(BrowserObserver, observers_, OnPlatformThemeChanged());
}
} // namespace atom

View file

@ -82,6 +82,9 @@ class Browser : public WindowListObserver {
// Set as default handler for a protocol.
bool SetAsDefaultProtocolClient(const std::string& protocol);
// Query the current state of default handler for a protocol.
bool IsDefaultProtocolClient(const std::string& protocol);
#if defined(OS_MACOSX)
// Hide the application.
void Hide();
@ -89,9 +92,6 @@ class Browser : public WindowListObserver {
// Show the application.
void Show();
// Check if the system is in Dark Mode.
bool IsDarkMode();
// Bounce the dock icon.
enum BounceType {
BOUNCE_CRITICAL = 0,
@ -151,9 +151,6 @@ class Browser : public WindowListObserver {
// Request basic auth login.
void RequestLogin(LoginHandler* login_handler);
// Tell the application that plaform's theme changed.
void PlatformThemeChanged();
void AddObserver(BrowserObserver* obs) {
observers_.AddObserver(obs);
}
@ -189,10 +186,13 @@ class Browser : public WindowListObserver {
// Observers of the browser.
base::ObserverList<BrowserObserver> observers_;
// Whether `app.exit()` has been called
bool is_exiting_;
// Whether "ready" event has been emitted.
bool is_ready_;
// The browse is being shutdown.
// The browser is being shutdown.
bool is_shutdown_;
std::string version_override_;

View file

@ -42,6 +42,10 @@ bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) {
return false;
}
bool Browser::IsDefaultProtocolClient(const std::string& protocol) {
return false;
}
std::string Browser::GetExecutableFileVersion() const {
return brightray::GetApplicationVersion();
}

View file

@ -27,11 +27,6 @@ void Browser::Show() {
[[AtomApplication sharedApplication] unhide:nil];
}
bool Browser::IsDarkMode() {
NSString *mode = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];
return [mode isEqualToString: @"Dark"];
}
void Browser::AddRecentDocument(const base::FilePath& path) {
NSString* path_string = base::mac::FilePathToNSString(path);
if (!path_string)
@ -65,6 +60,30 @@ bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) {
return return_code == noErr;
}
bool Browser::IsDefaultProtocolClient(const std::string& protocol) {
if (protocol.empty())
return false;
NSString* identifier = [base::mac::MainBundle() bundleIdentifier];
if (!identifier)
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
CFStringRef bundle =
LSCopyDefaultHandlerForURLScheme(base::mac::NSToCFCast(protocol_ns));
NSString* bundleId = static_cast<NSString*>(
base::mac::CFTypeRefToNSObjectAutorelease(bundle));
if (!bundleId)
return false;
// Ensure the comparison is case-insensitive
// as LS does not persist the case of the bundle id.
NSComparisonResult result =
[bundleId caseInsensitiveCompare:identifier];
return result == NSOrderedSame;
}
void Browser::SetAppUserModelID(const base::string16& name) {
}

View file

@ -45,8 +45,6 @@ class BrowserObserver {
// The browser requests HTTP login.
virtual void OnLogin(LoginHandler* login_handler) {}
virtual void OnPlatformThemeChanged() {}
protected:
virtual ~BrowserObserver() {}
};

View file

@ -225,6 +225,50 @@ bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) {
return true;
}
bool Browser::IsDefaultProtocolClient(const std::string& protocol) {
if (protocol.empty())
return false;
base::FilePath path;
if (!PathService::Get(base::FILE_EXE, &path)) {
LOG(ERROR) << "Error getting app exe path";
return false;
}
// Main Registry Key
HKEY root = HKEY_CURRENT_USER;
std::string keyPathStr = "Software\\Classes\\" + protocol;
std::wstring keyPath = std::wstring(keyPathStr.begin(), keyPathStr.end());
// Command Key
std::string cmdPathStr = keyPathStr + "\\shell\\open\\command";
std::wstring cmdPath = std::wstring(cmdPathStr.begin(), cmdPathStr.end());
base::win::RegKey key;
base::win::RegKey commandKey;
if (FAILED(key.Open(root, keyPath.c_str(), KEY_ALL_ACCESS)))
// Key doesn't exist, we can confirm that it is not set
return false;
if (FAILED(commandKey.Open(root, cmdPath.c_str(), KEY_ALL_ACCESS)))
// Key doesn't exist, we can confirm that it is not set
return false;
std::wstring keyVal;
if (FAILED(commandKey.ReadValue(L"", &keyVal)))
// Default value not set, we can confirm that it is not set
return false;
std::wstring exePath(path.value());
std::wstring exe = L"\"" + exePath + L"\" \"%1\"";
if (keyVal == exe) {
// Default value is the same as current file path
return true;
} else {
return false;
}
}
PCWSTR Browser::GetAppUserModelID() {
if (app_user_model_id_.empty()) {
SetAppUserModelID(base::ReplaceStringPlaceholders(

View file

@ -10,9 +10,11 @@
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_javascript_dialog_manager.h"
#include "atom/browser/atom_security_state_model_client.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/file_dialog.h"
#include "atom/browser/web_dialog_helper.h"
#include "atom/common/atom_constants.h"
#include "base/files/file_util.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h"
@ -25,6 +27,8 @@
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/security_style_explanation.h"
#include "content/public/browser/security_style_explanations.h"
#include "storage/browser/fileapi/isolated_context.h"
#if defined(TOOLKIT_VIEWS)
@ -36,6 +40,7 @@
#endif
using content::BrowserThread;
using security_state::SecurityStateModel;
namespace atom {
@ -140,6 +145,24 @@ std::set<std::string> GetAddedFileSystemPaths(
return result;
}
content::SecurityStyle SecurityLevelToSecurityStyle(
SecurityStateModel::SecurityLevel security_level) {
switch (security_level) {
case SecurityStateModel::NONE:
return content::SECURITY_STYLE_UNAUTHENTICATED;
case SecurityStateModel::SECURITY_WARNING:
case SecurityStateModel::SECURITY_POLICY_WARNING:
return content::SECURITY_STYLE_WARNING;
case SecurityStateModel::EV_SECURE:
case SecurityStateModel::SECURE:
return content::SECURITY_STYLE_AUTHENTICATED;
case SecurityStateModel::SECURITY_ERROR:
return content::SECURITY_STYLE_AUTHENTICATION_BROKEN;
}
return content::SECURITY_STYLE_UNKNOWN;
}
} // namespace
CommonWebContentsDelegate::CommonWebContentsDelegate()
@ -265,6 +288,90 @@ bool CommonWebContentsDelegate::IsFullscreenForTabOrPending(
return html_fullscreen_;
}
content::SecurityStyle CommonWebContentsDelegate::GetSecurityStyle(
content::WebContents* web_contents,
content::SecurityStyleExplanations* explanations) {
auto model_client =
AtomSecurityStateModelClient::FromWebContents(web_contents);
const SecurityStateModel::SecurityInfo& security_info =
model_client->GetSecurityInfo();
const content::SecurityStyle security_style =
SecurityLevelToSecurityStyle(security_info.security_level);
explanations->ran_insecure_content_style =
SecurityLevelToSecurityStyle(
SecurityStateModel::kRanInsecureContentLevel);
explanations->displayed_insecure_content_style =
SecurityLevelToSecurityStyle(
SecurityStateModel::kDisplayedInsecureContentLevel);
explanations->scheme_is_cryptographic = security_info.scheme_is_cryptographic;
if (!security_info.scheme_is_cryptographic)
return security_style;
if (security_info.sha1_deprecation_status ==
SecurityStateModel::DEPRECATED_SHA1_MAJOR) {
explanations->broken_explanations.push_back(
content::SecurityStyleExplanation(
kSHA1Certificate,
kSHA1MajorDescription,
security_info.cert_id));
} else if (security_info.sha1_deprecation_status ==
SecurityStateModel::DEPRECATED_SHA1_MINOR) {
explanations->unauthenticated_explanations.push_back(
content::SecurityStyleExplanation(
kSHA1Certificate,
kSHA1MinorDescription,
security_info.cert_id));
}
explanations->ran_insecure_content =
security_info.mixed_content_status ==
SecurityStateModel::RAN_MIXED_CONTENT ||
security_info.mixed_content_status ==
SecurityStateModel::RAN_AND_DISPLAYED_MIXED_CONTENT;
explanations->displayed_insecure_content =
security_info.mixed_content_status ==
SecurityStateModel::DISPLAYED_MIXED_CONTENT ||
security_info.mixed_content_status ==
SecurityStateModel::RAN_AND_DISPLAYED_MIXED_CONTENT;
if (net::IsCertStatusError(security_info.cert_status)) {
std::string error_string = net::ErrorToString(
net::MapCertStatusToNetError(security_info.cert_status));
content::SecurityStyleExplanation explanation(
kCertificateError,
"There are issues with the site's certificate chain " + error_string,
security_info.cert_id);
if (net::IsCertStatusMinorError(security_info.cert_status))
explanations->unauthenticated_explanations.push_back(explanation);
else
explanations->broken_explanations.push_back(explanation);
} else {
if (security_info.sha1_deprecation_status ==
SecurityStateModel::NO_DEPRECATED_SHA1) {
explanations->secure_explanations.push_back(
content::SecurityStyleExplanation(
kValidCertificate,
kValidCertificateDescription,
security_info.cert_id));
}
}
if (security_info.is_secure_protocol_and_ciphersuite) {
explanations->secure_explanations.push_back(
content::SecurityStyleExplanation(
kSecureProtocol,
kSecureProtocolDescription));
}
return security_style;
}
void CommonWebContentsDelegate::DevToolsSaveToFile(
const std::string& url, const std::string& content, bool save_as) {
base::FilePath path;

View file

@ -76,6 +76,9 @@ class CommonWebContentsDelegate
void ExitFullscreenModeForTab(content::WebContents* source) override;
bool IsFullscreenForTabOrPending(
const content::WebContents* source) const override;
content::SecurityStyle GetSecurityStyle(
content::WebContents* web_contents,
content::SecurityStyleExplanations* explanations) override;
// brightray::InspectableWebContentsDelegate:
void DevToolsSaveToFile(const std::string& url,

View file

@ -24,9 +24,6 @@
// Don't add the "Enter Full Screen" menu item automatically.
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"NSFullScreenMenuItemEverywhere"];
// Add observer to monitor the system's Dark Mode theme.
[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(platformThemeChanged:) name:@"AppleInterfaceThemeChangedNotification" object:nil];
atom::Browser::Get()->WillFinishLaunching();
}
@ -62,8 +59,4 @@
return flag;
}
- (void)platformThemeChanged:(NSNotification *)notify {
atom::Browser::Get()->PlatformThemeChanged();
}
@end

View file

@ -54,6 +54,7 @@ NativeWindow::NativeWindow(
enable_larger_than_screen_(false),
is_closed_(false),
has_dialog_attached_(false),
sheet_offset_(0.0),
aspect_ratio_(0.0),
inspectable_web_contents_(inspectable_web_contents),
weak_factory_(this) {
@ -162,6 +163,9 @@ void NativeWindow::InitFromOptions(const mate::Dictionary& options) {
std::string color;
if (options.Get(options::kBackgroundColor, &color)) {
SetBackgroundColor(color);
} else if (!transparent()) {
// For normal window, use white as default background.
SetBackgroundColor("#FFFF");
}
std::string title("Electron");
options.Get(options::kTitle, &title);
@ -251,6 +255,14 @@ gfx::Size NativeWindow::GetMaximumSize() {
return GetSizeConstraints().GetMaximumSize();
}
void NativeWindow::SetSheetOffset(const double offset) {
sheet_offset_ = offset;
}
double NativeWindow::GetSheetOffset() {
return sheet_offset_;
}
void NativeWindow::SetRepresentedFilename(const std::string& filename) {
}
@ -594,27 +606,4 @@ void NativeWindow::OnCapturePageDone(const CapturePageCallback& callback,
callback.Run(bitmap);
}
SkColor NativeWindow::ParseHexColor(const std::string& name) {
auto color = name.substr(1);
unsigned length = color.size();
SkColor result = (length != 8 ? 0xFF000000 : 0x00000000);
unsigned value = 0;
if (length != 3 && length != 6 && length != 8)
return result;
for (unsigned i = 0; i < length; ++i) {
if (!base::IsHexDigit(color[i]))
return result;
value <<= 4;
value |= (color[i] < 'A' ? color[i] - '0' : (color[i] - 'A' + 10) & 0xF);
}
if (length == 6 || length == 8) {
result |= value;
return result;
}
result |= (value & 0xF00) << 12 | (value & 0xF00) << 8
| (value & 0xF0) << 8 | (value & 0xF0) << 4
| (value & 0xF) << 4 | (value & 0xF);
return result;
}
} // namespace atom

View file

@ -123,6 +123,8 @@ class NativeWindow : public base::SupportsUserData,
virtual gfx::Size GetMinimumSize();
virtual void SetMaximumSize(const gfx::Size& size);
virtual gfx::Size GetMaximumSize();
virtual void SetSheetOffset(const double offset);
virtual double GetSheetOffset();
virtual void SetResizable(bool resizable) = 0;
virtual bool IsResizable() = 0;
virtual void SetMovable(bool movable) = 0;
@ -282,9 +284,6 @@ class NativeWindow : public base::SupportsUserData,
void BeforeUnloadDialogCancelled() override;
bool OnMessageReceived(const IPC::Message& message) override;
// Parse hex color like "#FFF" or "#EFEFEF"
SkColor ParseHexColor(const std::string& name);
private:
// Schedule a notification unresponsive event.
void ScheduleUnresponsiveEvent(int ms);
@ -329,6 +328,9 @@ class NativeWindow : public base::SupportsUserData,
// it should be cancelled when we can prove that the window is responsive.
base::CancelableClosure window_unresposive_closure_;
// Used to display sheets at the appropriate vertical offset
double sheet_offset_;
// Used to maintain the aspect ratio of a view which is inside of the
// content view.
double aspect_ratio_;

View file

@ -6,9 +6,11 @@
#include <string>
#include "atom/common/color_util.h"
#include "atom/common/draggable_region.h"
#include "atom/common/options_switches.h"
#include "base/mac/mac_util.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/strings/sys_string_conversions.h"
#include "brightray/browser/inspectable_web_contents.h"
#include "brightray/browser/inspectable_web_contents_view.h"
@ -18,6 +20,7 @@
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "native_mate/dictionary.h"
#include "skia/ext/skia_utils_mac.h"
#include "ui/gfx/skia_util.h"
namespace {
@ -240,6 +243,13 @@ bool ScopedDisableResize::disable_resize_ = false;
return NO;
}
- (NSRect)window:(NSWindow*)window
willPositionSheet:(NSWindow*)sheet usingRect:(NSRect)rect {
NSView* view = window.contentView;
rect.origin.y = view.frame.size.height - shell_->GetSheetOffset();
return rect;
}
@end
@interface AtomNSWindow : NSWindow {
@ -592,10 +602,16 @@ bool NativeWindowMac::IsVisible() {
}
void NativeWindowMac::Maximize() {
if (IsMaximized())
return;
[window_ zoom:nil];
}
void NativeWindowMac::Unmaximize() {
if (!IsMaximized())
return;
[window_ zoom:nil];
}
@ -804,12 +820,14 @@ bool NativeWindowMac::IsKiosk() {
}
void NativeWindowMac::SetBackgroundColor(const std::string& color_name) {
SkColor background_color = NativeWindow::ParseHexColor(color_name);
NSColor *color = [NSColor colorWithCalibratedRed:SkColorGetR(background_color)
green:SkColorGetG(background_color)
blue:SkColorGetB(background_color)
alpha:SkColorGetA(background_color)/255.0f];
[window_ setBackgroundColor:color];
SkColor color = ParseHexColor(color_name);
base::ScopedCFTypeRef<CGColorRef> cgcolor =
skia::CGColorCreateFromSkColor(color);
[[[window_ contentView] layer] setBackgroundColor:cgcolor];
const auto view = web_contents()->GetRenderWidgetHostView();
if (view)
view->SetBackgroundColor(color);
}
void NativeWindowMac::SetHasShadow(bool has_shadow) {

View file

@ -9,11 +9,13 @@
#include "atom/browser/ui/views/menu_bar.h"
#include "atom/browser/ui/views/menu_layout.h"
#include "atom/common/color_util.h"
#include "atom/common/draggable_region.h"
#include "atom/common/options_switches.h"
#include "base/strings/utf_string_conversions.h"
#include "brightray/browser/inspectable_web_contents.h"
#include "brightray/browser/inspectable_web_contents_view.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "native_mate/dictionary.h"
#include "ui/aura/window_tree_host.h"
@ -614,7 +616,7 @@ bool NativeWindowViews::IsKiosk() {
void NativeWindowViews::SetBackgroundColor(const std::string& color_name) {
// web views' background color.
SkColor background_color = NativeWindow::ParseHexColor(color_name);
SkColor background_color = ParseHexColor(color_name);
set_background(views::Background::CreateSolidBackground(background_color));
#if defined(OS_WIN)
@ -779,10 +781,12 @@ void NativeWindowViews::OnWidgetActivationChanged(
if (widget != window_.get())
return;
if (active)
NotifyWindowFocus();
else
NotifyWindowBlur();
// Post the notification to next tick.
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(active ? &NativeWindow::NotifyWindowFocus :
&NativeWindow::NotifyWindowBlur,
GetWeakPtr()));
if (active && inspectable_web_contents() &&
!inspectable_web_contents()->IsDevToolsViewShowing())

View file

@ -199,6 +199,10 @@ class NativeWindowViews : public NativeWindow,
// In charge of running taskbar related APIs.
TaskbarHost taskbar_host_;
// If true we have enabled a11y
bool enabled_a11y_support_;
#endif
// Handles unhandled keyboard messages coming back from the renderer process.

View file

@ -84,6 +84,25 @@ bool NativeWindowViews::PreHandleMSG(
NotifyWindowMessage(message, w_param, l_param);
switch (message) {
// Screen readers send WM_GETOBJECT in order to get the accessibility
// object, so take this opportunity to push Chromium into accessible
// mode if it isn't already, always say we didn't handle the message
// because we still want Chromium to handle returning the actual
// accessibility object.
case WM_GETOBJECT: {
const DWORD obj_id = static_cast<DWORD>(l_param);
if (enabled_a11y_support_) return false;
if (obj_id == OBJID_CLIENT) {
const auto axState = content::BrowserAccessibilityState::GetInstance();
if (axState && !axState->IsAccessibleBrowser()) {
axState->OnScreenReaderDetected();
enabled_a11y_support_ = true;
}
}
return false;
}
case WM_COMMAND:
// Handle thumbar button click message.
if (HIWORD(w_param) == THBN_CLICKED)

View file

@ -4,21 +4,20 @@
#include "atom/browser/net/atom_network_delegate.h"
#include <string>
#include <utility>
#include "atom/common/native_mate_converters/net_converter.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "brightray/browser/net/devtools_network_transaction.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_request_info.h"
#include "net/url_request/url_request.h"
using brightray::DevToolsNetworkTransaction;
using content::BrowserThread;
namespace atom {
namespace {
const char* ResourceTypeToString(content::ResourceType type) {
switch (type) {
case content::RESOURCE_TYPE_MAIN_FRAME:
@ -40,6 +39,11 @@ const char* ResourceTypeToString(content::ResourceType type) {
}
}
namespace {
using ResponseHeadersContainer =
std::pair<scoped_refptr<net::HttpResponseHeaders>*, const std::string&>;
void RunSimpleListener(const AtomNetworkDelegate::SimpleListener& listener,
scoped_ptr<base::DictionaryValue> details) {
return listener.Run(*(details.get()));
@ -170,10 +174,15 @@ void ReadFromResponseObject(const base::DictionaryValue& response,
}
void ReadFromResponseObject(const base::DictionaryValue& response,
scoped_refptr<net::HttpResponseHeaders>* headers) {
const ResponseHeadersContainer& container) {
const base::DictionaryValue* dict;
std::string status_line;
if (!response.GetString("statusLine", &status_line))
status_line = container.second;
if (response.GetDictionary("responseHeaders", &dict)) {
auto headers = container.first;
*headers = new net::HttpResponseHeaders("");
(*headers)->ReplaceStatusLine(status_line);
for (base::DictionaryValue::Iterator it(*dict);
!it.IsAtEnd();
it.Advance()) {
@ -218,6 +227,12 @@ void AtomNetworkDelegate::SetResponseListenerInIO(
response_listeners_[type] = { patterns, callback };
}
void AtomNetworkDelegate::SetDevToolsNetworkEmulationClientId(
const std::string& client_id) {
base::AutoLock auto_lock(lock_);
client_id_ = client_id;
}
int AtomNetworkDelegate::OnBeforeURLRequest(
net::URLRequest* request,
const net::CompletionCallback& callback,
@ -233,6 +248,16 @@ int AtomNetworkDelegate::OnBeforeSendHeaders(
net::URLRequest* request,
const net::CompletionCallback& callback,
net::HttpRequestHeaders* headers) {
std::string client_id;
{
base::AutoLock auto_lock(lock_);
client_id = client_id_;
}
if (!client_id.empty())
headers->SetHeader(
DevToolsNetworkTransaction::kDevToolsEmulateNetworkConditionsClientId,
client_id);
if (!ContainsKey(response_listeners_, kOnBeforeSendHeaders))
return brightray::NetworkDelegate::OnBeforeSendHeaders(
request, callback, headers);
@ -263,7 +288,8 @@ int AtomNetworkDelegate::OnHeadersReceived(
request, callback, original, override, allowed);
return HandleResponseEvent(
kOnHeadersReceived, request, callback, override, original);
kOnHeadersReceived, request, callback,
std::make_pair(override, original->GetStatusLine()), original);
}
void AtomNetworkDelegate::OnBeforeRedirect(net::URLRequest* request,

View file

@ -7,14 +7,17 @@
#include <map>
#include <set>
#include <string>
#include "brightray/browser/network_delegate.h"
#include "base/callback.h"
#include "base/synchronization/lock.h"
#include "base/values.h"
#include "extensions/common/url_pattern.h"
#include "net/base/net_errors.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_response_headers.h"
#include "content/public/browser/resource_request_info.h"
namespace extensions {
class URLPattern;
@ -24,6 +27,8 @@ namespace atom {
using URLPatterns = std::set<extensions::URLPattern>;
const char* ResourceTypeToString(content::ResourceType type);
class AtomNetworkDelegate : public brightray::NetworkDelegate {
public:
using ResponseCallback = base::Callback<void(const base::DictionaryValue&)>;
@ -65,6 +70,8 @@ class AtomNetworkDelegate : public brightray::NetworkDelegate {
const URLPatterns& patterns,
const ResponseListener& callback);
void SetDevToolsNetworkEmulationClientId(const std::string& client_id);
protected:
// net::NetworkDelegate:
int OnBeforeURLRequest(net::URLRequest* request,
@ -113,6 +120,11 @@ class AtomNetworkDelegate : public brightray::NetworkDelegate {
std::map<ResponseEvent, ResponseListenerInfo> response_listeners_;
std::map<uint64_t, net::CompletionCallback> callbacks_;
base::Lock lock_;
// Client id for devtools network emulation.
std::string client_id_;
DISALLOW_COPY_AND_ASSIGN(AtomNetworkDelegate);
};

View file

@ -17,9 +17,9 @@
<key>CFBundleIconFile</key>
<string>electron.icns</string>
<key>CFBundleVersion</key>
<string>0.37.3</string>
<string>0.37.8</string>
<key>CFBundleShortVersionString</key>
<string>0.37.3</string>
<string>0.37.8</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.developer-tools</string>
<key>LSMinimumSystemVersion</key>

View file

@ -56,8 +56,8 @@ END
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 0,37,3,0
PRODUCTVERSION 0,37,3,0
FILEVERSION 0,37,8,0
PRODUCTVERSION 0,37,8,0
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
@ -74,12 +74,12 @@ BEGIN
BEGIN
VALUE "CompanyName", "GitHub, Inc."
VALUE "FileDescription", "Electron"
VALUE "FileVersion", "0.37.3"
VALUE "FileVersion", "0.37.8"
VALUE "InternalName", "electron.exe"
VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved."
VALUE "OriginalFilename", "electron.exe"
VALUE "ProductName", "Electron"
VALUE "ProductVersion", "0.37.3"
VALUE "ProductVersion", "0.37.8"
VALUE "SquirrelAwareVersion", "1"
END
END

View file

@ -13,12 +13,6 @@ namespace accelerator_util {
void SetPlatformAccelerator(ui::Accelerator* accelerator) {
unichar character;
unichar characterIgnoringModifiers;
ui::MacKeyCodeForWindowsKeyCode(accelerator->key_code(),
0,
&character,
&characterIgnoringModifiers);
NSString* characters =
[[[NSString alloc] initWithCharacters:&character length:1] autorelease];
NSUInteger modifiers =
(accelerator->IsCtrlDown() ? NSControlKeyMask : 0) |
@ -26,6 +20,18 @@ void SetPlatformAccelerator(ui::Accelerator* accelerator) {
(accelerator->IsAltDown() ? NSAlternateKeyMask : 0) |
(accelerator->IsShiftDown() ? NSShiftKeyMask : 0);
ui::MacKeyCodeForWindowsKeyCode(accelerator->key_code(),
modifiers,
&character,
&characterIgnoringModifiers);
if (character != characterIgnoringModifiers) {
modifiers ^= NSShiftKeyMask;
}
NSString* characters =
[[[NSString alloc] initWithCharacters:&character length:1] autorelease];
scoped_ptr<ui::PlatformAccelerator> platform_accelerator(
new ui::PlatformAcceleratorCocoa(characters, modifiers));
accelerator->set_platform_accelerator(std::move(platform_accelerator));

View file

@ -27,7 +27,6 @@ const CGFloat kVerticalTitleMargin = 2;
BOOL inMouseEventSequence_;
base::scoped_nsobject<NSImage> image_;
base::scoped_nsobject<NSImage> alternateImage_;
base::scoped_nsobject<NSImageView> image_view_;
base::scoped_nsobject<NSString> title_;
base::scoped_nsobject<NSStatusItem> statusItem_;
}
@ -44,15 +43,6 @@ const CGFloat kVerticalTitleMargin = 2;
inMouseEventSequence_ = NO;
if ((self = [super initWithFrame: CGRectZero])) {
// Setup the image view.
image_view_.reset([[NSImageView alloc] initWithFrame: CGRectZero]);
[image_view_ setImageScaling:NSImageScaleNone];
[image_view_ setImageAlignment:NSImageAlignCenter];
[self addSubview:image_view_];
// Unregister image_view_ as a dragged destination, allows its parent view
// (StatusItemView) handle dragging events.
[image_view_ unregisterDraggedTypes];
[self registerForDraggedTypes: @[NSFilenamesPboardType]];
// Create the status item.
@ -69,7 +59,6 @@ const CGFloat kVerticalTitleMargin = 2;
- (void)updateDimensions {
NSStatusBar * bar = [NSStatusBar systemStatusBar];
[image_view_ setFrame: NSMakeRect(0, 0, [self iconWidth], [bar thickness])];
[self setFrame: NSMakeRect(0, 0, [self fullWidth], [bar thickness])];
[self setNeedsDisplay:YES];
}
@ -85,28 +74,44 @@ const CGFloat kVerticalTitleMargin = 2;
// | icon | title |
/// ----------------
// Draw background.
BOOL highlight = [self shouldHighlight];
BOOL highlightContent = highlight | [self isDarkMode];
CGFloat thickness = [[statusItem_ statusBar] thickness];
// Draw the system bar background.
[statusItem_ drawStatusBarBackgroundInRect:self.bounds withHighlight:highlight];
// Make use of NSImageView to draw the image, which can correctly draw
// template image under dark menu bar.
if (inMouseEventSequence_ && alternateImage_ &&
[image_view_ image] != alternateImage_.get()) {
[image_view_ setImage:alternateImage_];
} else if ([image_view_ image] != image_.get()) {
[image_view_ setImage:image_];
// Determine which image to use.
NSImage* image = image_.get();
if (inMouseEventSequence_ && alternateImage_) {
image = alternateImage_.get();
}
// Apply the higlight color if the image is a template image. When this moves
// to using the new [NSStatusItem button] API, this should work automagically.
if ([image isTemplate] == YES) {
NSImage* imageWithColor = [[image copy] autorelease];
[imageWithColor lockFocus];
[[self colorWithHighlight: highlightContent] set];
CGRect imageBounds = CGRectMake(0,0, image.size.width, image.size.height);
NSRectFillUsingOperation(imageBounds, NSCompositeSourceAtop);
[imageWithColor unlockFocus];
image = imageWithColor;
}
// Draw the image
[image drawInRect: CGRectMake(
roundf(([self iconWidth] - image.size.width) / 2),
roundf((thickness - image.size.height) / 2),
image.size.width,
image.size.height
)];
if (title_) {
// Highlight the text when icon is highlighted or in dark mode.
highlight |= [self isDarkMode];
// Draw title.
NSRect titleDrawRect = NSMakeRect(
[self iconWidth], -kVerticalTitleMargin, [self titleWidth], thickness);
[title_ drawInRect:titleDrawRect
withAttributes:[self titleAttributesWithHighlight:highlight]];
withAttributes:[self titleAttributesWithHighlight:highlightContent]];
}
}
@ -157,14 +162,16 @@ const CGFloat kVerticalTitleMargin = 2;
return [attributes size].width;
}
- (NSDictionary*)titleAttributesWithHighlight:(BOOL)highlight {
NSFont* font = [NSFont menuBarFontOfSize:0];
NSColor* foregroundColor = highlight ?
- (NSColor*)colorWithHighlight:(BOOL)highlight {
return highlight ?
[NSColor whiteColor] :
[NSColor colorWithRed:0.265625 green:0.25390625 blue:0.234375 alpha:1.0];
}
- (NSDictionary*)titleAttributesWithHighlight:(BOOL)highlight {
return @{
NSFontAttributeName: font,
NSForegroundColorAttributeName: foregroundColor
NSFontAttributeName:[NSFont menuBarFontOfSize:0],
NSForegroundColorAttributeName:[self colorWithHighlight: highlight]
};
}

View file

@ -91,4 +91,12 @@ void WebContentsPermissionHelper::RequestPointerLockPermission(
user_gesture);
}
void WebContentsPermissionHelper::RequestOpenExternalPermission(
const base::Callback<void(bool)>& callback,
bool user_gesture) {
RequestPermission((content::PermissionType)(PermissionType::OPEN_EXTERNAL),
callback,
user_gesture);
}
} // namespace atom

View file

@ -19,7 +19,8 @@ class WebContentsPermissionHelper
enum class PermissionType {
POINTER_LOCK = static_cast<int>(content::PermissionType::NUM) + 1,
FULLSCREEN
FULLSCREEN,
OPEN_EXTERNAL,
};
void RequestFullscreenPermission(
@ -30,6 +31,9 @@ class WebContentsPermissionHelper
void RequestWebNotificationPermission(
const base::Callback<void(bool)>& callback);
void RequestPointerLockPermission(bool user_gesture);
void RequestOpenExternalPermission(
const base::Callback<void(bool)>& callback,
bool user_gesture);
private:
explicit WebContentsPermissionHelper(content::WebContents* web_contents);

View file

@ -8,6 +8,7 @@
#include <string>
#include <vector>
#include "atom/browser/native_window.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
@ -116,6 +117,11 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches(
LOG(ERROR) << "preload url must be file:// protocol.";
}
// --background-color.
std::string color;
if (web_preferences.GetString(options::kBackgroundColor, &color))
command_line->AppendSwitchASCII(switches::kBackgroundColor, color);
// The zoom factor.
double zoom_factor = 1.0;
if (web_preferences.GetDouble(options::kZoomFactor, &zoom_factor) &&
@ -126,20 +132,28 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches(
// --guest-instance-id, which is used to identify guest WebContents.
int guest_instance_id;
if (web_preferences.GetInteger(options::kGuestInstanceID, &guest_instance_id))
command_line->AppendSwitchASCII(switches::kGuestInstanceID,
base::IntToString(guest_instance_id));
command_line->AppendSwitchASCII(switches::kGuestInstanceID,
base::IntToString(guest_instance_id));
// Pass the opener's window id.
int opener_id;
if (web_preferences.GetInteger(options::kOpenerID, &opener_id))
command_line->AppendSwitchASCII(switches::kOpenerID,
base::IntToString(opener_id));
command_line->AppendSwitchASCII(switches::kOpenerID,
base::IntToString(opener_id));
// Enable blink features.
std::string blink_features;
if (web_preferences.GetString(options::kBlinkFeatures, &blink_features))
command_line->AppendSwitchASCII(::switches::kEnableBlinkFeatures,
blink_features);
command_line->AppendSwitchASCII(::switches::kEnableBlinkFeatures,
blink_features);
// The initial visibility state.
NativeWindow* window = NativeWindow::FromWebContents(web_contents);
if (window) {
bool visible = window->IsVisible() && !window->IsMinimized();
if (!visible) // Default state is visible.
command_line->AppendSwitch("hidden-page");
}
}
// static

View file

@ -18,21 +18,39 @@
namespace {
v8::Persistent<v8::ObjectTemplate> template_;
class Archive : public mate::Wrappable {
class Archive : public mate::Wrappable<Archive> {
public:
static v8::Local<v8::Value> Create(v8::Isolate* isolate,
const base::FilePath& path) {
scoped_ptr<asar::Archive> archive(new asar::Archive(path));
if (!archive->Init())
return v8::False(isolate);
return (new Archive(std::move(archive)))->GetWrapper(isolate);
return (new Archive(isolate, std::move(archive)))->GetWrapper();
}
static void BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
mate::ObjectTemplateBuilder(isolate, prototype)
.SetProperty("path", &Archive::GetPath)
.SetMethod("getFileInfo", &Archive::GetFileInfo)
.SetMethod("stat", &Archive::Stat)
.SetMethod("readdir", &Archive::Readdir)
.SetMethod("realpath", &Archive::Realpath)
.SetMethod("copyFileOut", &Archive::CopyFileOut)
.SetMethod("getFd", &Archive::GetFD)
.SetMethod("destroy", &Archive::Destroy);
}
protected:
explicit Archive(scoped_ptr<asar::Archive> archive)
: archive_(std::move(archive)) {}
Archive(v8::Isolate* isolate, scoped_ptr<asar::Archive> archive)
: archive_(std::move(archive)) {
Init(isolate);
}
// Returns the path of the file.
base::FilePath GetPath() {
return archive_->path();
}
// Reads the offset and size of file.
v8::Local<v8::Value> GetFileInfo(v8::Isolate* isolate,
@ -101,24 +119,6 @@ class Archive : public mate::Wrappable {
archive_.reset();
}
// mate::Wrappable:
mate::ObjectTemplateBuilder GetObjectTemplateBuilder(v8::Isolate* isolate) {
if (template_.IsEmpty())
template_.Reset(isolate, mate::ObjectTemplateBuilder(isolate)
.SetValue("path", archive_->path())
.SetMethod("getFileInfo", &Archive::GetFileInfo)
.SetMethod("stat", &Archive::Stat)
.SetMethod("readdir", &Archive::Readdir)
.SetMethod("realpath", &Archive::Realpath)
.SetMethod("copyFileOut", &Archive::CopyFileOut)
.SetMethod("getFd", &Archive::GetFD)
.SetMethod("destroy", &Archive::Destroy)
.Build());
return mate::ObjectTemplateBuilder(
isolate, v8::Local<v8::ObjectTemplate>::New(isolate, template_));
}
private:
scoped_ptr<asar::Archive> archive_;

View file

@ -12,7 +12,7 @@ namespace atom {
namespace api {
IDWeakMap::IDWeakMap() {
IDWeakMap::IDWeakMap(v8::Isolate* isolate) {
}
IDWeakMap::~IDWeakMap() {
@ -52,8 +52,8 @@ void IDWeakMap::BuildPrototype(v8::Isolate* isolate,
}
// static
mate::Wrappable* IDWeakMap::Create(v8::Isolate* isolate) {
return new IDWeakMap;
mate::WrappableBase* IDWeakMap::Create(v8::Isolate* isolate) {
return new IDWeakMap(isolate);
}
} // namespace api

View file

@ -13,15 +13,15 @@ namespace atom {
namespace api {
class IDWeakMap : public mate::Wrappable {
class IDWeakMap : public mate::Wrappable<IDWeakMap> {
public:
static mate::Wrappable* Create(v8::Isolate* isolate);
static mate::WrappableBase* Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
protected:
IDWeakMap();
explicit IDWeakMap(v8::Isolate* isolate);
~IDWeakMap();
private:

View file

@ -168,35 +168,15 @@ bool ReadImageSkiaFromICO(gfx::ImageSkia* image, const base::FilePath& path) {
}
#endif
v8::Persistent<v8::ObjectTemplate> template_;
} // namespace
NativeImage::NativeImage() {}
NativeImage::NativeImage(const gfx::Image& image) : image_(image) {}
NativeImage::NativeImage(v8::Isolate* isolate, const gfx::Image& image)
: image_(image) {
Init(isolate);
}
NativeImage::~NativeImage() {}
mate::ObjectTemplateBuilder NativeImage::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
if (template_.IsEmpty())
template_.Reset(isolate, mate::ObjectTemplateBuilder(isolate)
.SetMethod("toPng", &NativeImage::ToPNG)
.SetMethod("toJpeg", &NativeImage::ToJPEG)
.SetMethod("getNativeHandle", &NativeImage::GetNativeHandle)
.SetMethod("toDataURL", &NativeImage::ToDataURL)
.SetMethod("toDataUrl", &NativeImage::ToDataURL) // deprecated.
.SetMethod("isEmpty", &NativeImage::IsEmpty)
.SetMethod("getSize", &NativeImage::GetSize)
.SetMethod("setTemplateImage", &NativeImage::SetTemplateImage)
.SetMethod("isTemplateImage", &NativeImage::IsTemplateImage)
.Build());
return mate::ObjectTemplateBuilder(
isolate, v8::Local<v8::ObjectTemplate>::New(isolate, template_));
}
v8::Local<v8::Value> NativeImage::ToPNG(v8::Isolate* isolate) {
scoped_refptr<base::RefCountedMemory> png = image_.As1xPNGBytes();
return node::Buffer::Copy(isolate,
@ -255,13 +235,13 @@ bool NativeImage::IsTemplateImage() {
// static
mate::Handle<NativeImage> NativeImage::CreateEmpty(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new NativeImage);
return mate::CreateHandle(isolate, new NativeImage(isolate, gfx::Image()));
}
// static
mate::Handle<NativeImage> NativeImage::Create(
v8::Isolate* isolate, const gfx::Image& image) {
return mate::CreateHandle(isolate, new NativeImage(image));
return mate::CreateHandle(isolate, new NativeImage(isolate, image));
}
// static
@ -330,6 +310,21 @@ mate::Handle<NativeImage> NativeImage::CreateFromDataURL(
return CreateEmpty(isolate);
}
// static
void NativeImage::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
mate::ObjectTemplateBuilder(isolate, prototype)
.SetMethod("toPng", &NativeImage::ToPNG)
.SetMethod("toJpeg", &NativeImage::ToJPEG)
.SetMethod("getNativeHandle", &NativeImage::GetNativeHandle)
.SetMethod("toDataURL", &NativeImage::ToDataURL)
.SetMethod("toDataUrl", &NativeImage::ToDataURL) // deprecated.
.SetMethod("isEmpty", &NativeImage::IsEmpty)
.SetMethod("getSize", &NativeImage::GetSize)
.SetMethod("setTemplateImage", &NativeImage::SetTemplateImage)
.SetMethod("isTemplateImage", &NativeImage::IsTemplateImage);
}
} // namespace api
} // namespace atom

View file

@ -29,7 +29,7 @@ namespace atom {
namespace api {
class NativeImage : public mate::Wrappable {
class NativeImage : public mate::Wrappable<NativeImage> {
public:
static mate::Handle<NativeImage> CreateEmpty(v8::Isolate* isolate);
static mate::Handle<NativeImage> Create(
@ -45,18 +45,14 @@ class NativeImage : public mate::Wrappable {
static mate::Handle<NativeImage> CreateFromDataURL(
v8::Isolate* isolate, const GURL& url);
// The default constructor should only be used by image_converter.cc.
NativeImage();
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
const gfx::Image& image() const { return image_; }
protected:
explicit NativeImage(const gfx::Image& image);
virtual ~NativeImage();
// mate::Wrappable:
mate::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
NativeImage(v8::Isolate* isolate, const gfx::Image& image);
~NativeImage() override;
private:
v8::Local<v8::Value> ToPNG(v8::Isolate* isolate);

View file

@ -4,7 +4,9 @@
#include <string>
#include "atom/common/api/object_life_monitor.h"
#include "atom/common/api/remote_callback_freer.h"
#include "atom/common/api/remote_object_freer.h"
#include "atom/common/native_mate_converters/content_converter.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
#include "v8/include/v8-profiler.h"
@ -51,12 +53,6 @@ int32_t GetObjectHash(v8::Local<v8::Object> object) {
return object->GetIdentityHash();
}
void SetDestructor(v8::Isolate* isolate,
v8::Local<v8::Object> object,
v8::Local<v8::Function> callback) {
atom::ObjectLifeMonitor::BindTo(isolate, object, callback);
}
void TakeHeapSnapshot(v8::Isolate* isolate) {
isolate->GetHeapProfiler()->TakeHeapSnapshot();
}
@ -68,8 +64,9 @@ void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
dict.SetMethod("setHiddenValue", &SetHiddenValue);
dict.SetMethod("deleteHiddenValue", &DeleteHiddenValue);
dict.SetMethod("getObjectHash", &GetObjectHash);
dict.SetMethod("setDestructor", &SetDestructor);
dict.SetMethod("takeHeapSnapshot", &TakeHeapSnapshot);
dict.SetMethod("setRemoteCallbackFreer", &atom::RemoteCallbackFreer::BindTo);
dict.SetMethod("setRemoteObjectFreer", &atom::RemoteObjectFreer::BindTo);
}
} // namespace

View file

@ -98,8 +98,17 @@ void AtomBindings::OnCallNextTick(uv_async_t* handle) {
self->pending_next_ticks_.begin();
it != self->pending_next_ticks_.end(); ++it) {
node::Environment* env = *it;
// KickNextTick, copied from node.cc:
node::Environment::AsyncCallbackScope callback_scope(env);
env->KickNextTick(&callback_scope);
if (callback_scope.in_makecallback())
continue;
node::Environment::TickInfo* tick_info = env->tick_info();
if (tick_info->length() == 0)
env->isolate()->RunMicrotasks();
v8::Local<v8::Object> process = env->process_object();
if (tick_info->length() == 0)
tick_info->set_index(0);
env->tick_callback_function()->Call(process, 0, nullptr).IsEmpty();
}
self->pending_next_ticks_.clear();

View file

@ -10,30 +10,28 @@
namespace atom {
// static
void ObjectLifeMonitor::BindTo(v8::Isolate* isolate,
v8::Local<v8::Object> target,
v8::Local<v8::Function> destructor) {
new ObjectLifeMonitor(isolate, target, destructor);
}
ObjectLifeMonitor::ObjectLifeMonitor(v8::Isolate* isolate,
v8::Local<v8::Object> target,
v8::Local<v8::Function> destructor)
v8::Local<v8::Object> target)
: isolate_(isolate),
context_(isolate, isolate->GetCurrentContext()),
target_(isolate, target),
destructor_(isolate, destructor),
weak_ptr_factory_(this) {
target_.SetWeak(this, OnObjectGC, v8::WeakCallbackType::kParameter);
}
ObjectLifeMonitor::~ObjectLifeMonitor() {
if (target_.IsEmpty())
return;
target_.ClearWeak();
target_.Reset();
}
// static
void ObjectLifeMonitor::OnObjectGC(
const v8::WeakCallbackInfo<ObjectLifeMonitor>& data) {
ObjectLifeMonitor* self = data.GetParameter();
self->target_.Reset();
self->RunCallback();
self->RunDestructor();
data.SetSecondPassCallback(Free);
}
@ -43,13 +41,4 @@ void ObjectLifeMonitor::Free(
delete data.GetParameter();
}
void ObjectLifeMonitor::RunCallback() {
v8::HandleScope handle_scope(isolate_);
v8::Local<v8::Context> context = v8::Local<v8::Context>::New(
isolate_, context_);
v8::Context::Scope context_scope(context);
v8::Local<v8::Function>::New(isolate_, destructor_)->Call(
context->Global(), 0, nullptr);
}
} // namespace atom

View file

@ -12,25 +12,19 @@
namespace atom {
class ObjectLifeMonitor {
public:
static void BindTo(v8::Isolate* isolate,
v8::Local<v8::Object> target,
v8::Local<v8::Function> destructor);
protected:
ObjectLifeMonitor(v8::Isolate* isolate, v8::Local<v8::Object> target);
virtual ~ObjectLifeMonitor();
virtual void RunDestructor() = 0;
private:
ObjectLifeMonitor(v8::Isolate* isolate,
v8::Local<v8::Object> target,
v8::Local<v8::Function> destructor);
static void OnObjectGC(const v8::WeakCallbackInfo<ObjectLifeMonitor>& data);
static void Free(const v8::WeakCallbackInfo<ObjectLifeMonitor>& data);
void RunCallback();
v8::Isolate* isolate_;
v8::Global<v8::Context> context_;
v8::Global<v8::Object> target_;
v8::Global<v8::Function> destructor_;
base::WeakPtrFactory<ObjectLifeMonitor> weak_ptr_factory_;

View file

@ -0,0 +1,47 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/api/remote_callback_freer.h"
#include "atom/common/api/api_messages.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
namespace atom {
// static
void RemoteCallbackFreer::BindTo(v8::Isolate* isolate,
v8::Local<v8::Object> target,
int object_id,
content::WebContents* web_contents) {
new RemoteCallbackFreer(isolate, target, object_id, web_contents);
}
RemoteCallbackFreer::RemoteCallbackFreer(v8::Isolate* isolate,
v8::Local<v8::Object> target,
int object_id,
content::WebContents* web_contents)
: ObjectLifeMonitor(isolate, target),
content::WebContentsObserver(web_contents),
object_id_(object_id) {
}
RemoteCallbackFreer::~RemoteCallbackFreer() {
}
void RemoteCallbackFreer::RunDestructor() {
base::string16 channel =
base::ASCIIToUTF16("ELECTRON_RENDERER_RELEASE_CALLBACK");
base::ListValue args;
args.AppendInteger(object_id_);
Send(new AtomViewMsg_Message(routing_id(), channel, args));
Observe(nullptr);
}
void RemoteCallbackFreer::RenderViewDeleted(content::RenderViewHost*) {
delete this;
}
} // namespace atom

View file

@ -0,0 +1,40 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_COMMON_API_REMOTE_CALLBACK_FREER_H_
#define ATOM_COMMON_API_REMOTE_CALLBACK_FREER_H_
#include "atom/common/api/object_life_monitor.h"
#include "content/public/browser/web_contents_observer.h"
namespace atom {
class RemoteCallbackFreer : public ObjectLifeMonitor,
public content::WebContentsObserver {
public:
static void BindTo(v8::Isolate* isolate,
v8::Local<v8::Object> target,
int object_id,
content::WebContents* web_conents);
protected:
RemoteCallbackFreer(v8::Isolate* isolate,
v8::Local<v8::Object> target,
int object_id,
content::WebContents* web_conents);
~RemoteCallbackFreer() override;
void RunDestructor() override;
// content::WebContentsObserver:
void RenderViewDeleted(content::RenderViewHost*) override;
private:
int object_id_;
DISALLOW_COPY_AND_ASSIGN(RemoteCallbackFreer);
};
} // namespace atom
#endif // ATOM_COMMON_API_REMOTE_CALLBACK_FREER_H_

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