Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Charlie Hess 2016-06-01 14:38:49 -07:00
commit 10dcb10898
472 changed files with 8177 additions and 3774 deletions

View file

@ -19,8 +19,7 @@ matrix:
- os: linux - os: linux
env: TARGET_ARCH=ia32 env: TARGET_ARCH=ia32
allow_failures: allow_failures:
- env: TARGET_ARCH=arm - os: osx
- env: TARGET_ARCH=ia32
script: './script/cibuild' script: './script/cibuild'

View file

@ -1,24 +1,46 @@
# Contributor Code of Conduct # Contributor Covenant Code of Conduct
As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. ## Our Pledge
We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include: Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery * The use of sexualized language or imagery and unwelcome sexual attention or advances
- Personal attacks * Trolling, insulting/derogatory comments, and personal or political attacks
- Trolling or insulting/derogatory comments * Public or private harassment
- Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission
- Publishing other's private information, such as physical or electronic addresses, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting
- Other unethical or unprofessional conduct
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. ## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a project maintainer at [atom@github.com](mailto:atom@github.com). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. ## Enforcement
This Code of Conduct is adapted from the Contributor Covenant, version 1.3.0, available from http://contributor-covenant.org/version/1/3/0/ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [electron@github.com](mailto:electron@github.com). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View file

@ -1,7 +1,7 @@
[![Electron Logo](http://electron.atom.io/images/electron-logo.svg)](http://electron.atom.io/) [![Electron Logo](http://electron.atom.io/images/electron-logo.svg)](http://electron.atom.io/)
[![Travis Build Status](https://travis-ci.org/electron/electron.svg?branch=master)](https://travis-ci.org/electron/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) [![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/kvxe4byi7jcxbe26/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/electron)
[![devDependency Status](https://david-dm.org/electron/electron/dev-status.svg)](https://david-dm.org/electron/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/) [![Join the Electron Community on Slack](http://atom-slack.herokuapp.com/badge.svg)](http://atom-slack.herokuapp.com/)

View file

@ -5,19 +5,17 @@
[![devDependency Status](https://david-dm.org/electron/electron/dev-status.svg)](https://david-dm.org/electron/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/) [![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:
The Electron framework lets you write cross-platform desktop applications The Electron framework lets you write cross-platform desktop applications
using JavaScript, HTML and CSS. It is based on [Node.js](https://nodejs.org/) and using JavaScript, HTML and CSS. It is based on [Node.js](https://nodejs.org/) and
[Chromium](http://www.chromium.org) and is used in the [Atom [Chromium](http://www.chromium.org) and is used by the [Atom
editor](https://github.com/atom/atom). editor](https://github.com/atom/atom) and many other [apps](http://electron.atom.io/apps).
Follow [@ElectronJS](https://twitter.com/electronjs) on Twitter for important Follow [@ElectronJS](https://twitter.com/electronjs) on Twitter for important
announcements. announcements.
This project adheres to the Contributor Covenant [code of conduct](CODE_OF_CONDUCT.md). This project adheres to the Contributor Covenant [code of conduct](CODE_OF_CONDUCT.md).
By participating, you are expected to uphold this code. Please report unacceptable By participating, you are expected to uphold this code. Please report unacceptable
behavior to atom@github.com. behavior to electron@github.com.
## Downloads ## Downloads

View file

@ -2,6 +2,8 @@
# http://www.appveyor.com/docs/appveyor-yml # http://www.appveyor.com/docs/appveyor-yml
version: "{build}" version: "{build}"
os: Visual Studio 2015
init: init:
- git config --global core.autocrlf input - git config --global core.autocrlf input
@ -10,7 +12,7 @@ platform:
- x64 - x64
install: install:
- cmd: SET PATH=C:\Program Files (x86)\MSBuild\12.0\bin\;%PATH% - cmd: SET PATH=C:\Program Files (x86)\MSBuild\14.0\bin\;%PATH%
- cmd: SET PATH=C:\python27;%PATH% - cmd: SET PATH=C:\python27;%PATH%
- cmd: python script/cibuild - cmd: python script/cibuild

View file

@ -89,11 +89,9 @@ content::PepperPluginInfo CreateWidevineCdmInfo(const base::FilePath& path,
// Add the supported codecs as if they came from the component manifest. // Add the supported codecs as if they came from the component manifest.
std::vector<std::string> codecs; std::vector<std::string> codecs;
codecs.push_back(kCdmSupportedCodecVorbis);
codecs.push_back(kCdmSupportedCodecVp8); codecs.push_back(kCdmSupportedCodecVp8);
codecs.push_back(kCdmSupportedCodecVp9); codecs.push_back(kCdmSupportedCodecVp9);
#if defined(USE_PROPRIETARY_CODECS) #if defined(USE_PROPRIETARY_CODECS)
codecs.push_back(kCdmSupportedCodecAac);
codecs.push_back(kCdmSupportedCodecAvc1); codecs.push_back(kCdmSupportedCodecAvc1);
#endif // defined(USE_PROPRIETARY_CODECS) #endif // defined(USE_PROPRIETARY_CODECS)
std::string codec_string = base::JoinString( std::string codec_string = base::JoinString(
@ -126,7 +124,7 @@ void ConvertStringWithSeparatorToVector(std::vector<std::string>* vec,
void AddPepperFlashFromCommandLine( void AddPepperFlashFromCommandLine(
std::vector<content::PepperPluginInfo>* plugins) { std::vector<content::PepperPluginInfo>* plugins) {
auto command_line = base::CommandLine::ForCurrentProcess(); auto command_line = base::CommandLine::ForCurrentProcess();
auto flash_path = command_line->GetSwitchValueNative( base::FilePath flash_path = command_line->GetSwitchValuePath(
switches::kPpapiFlashPath); switches::kPpapiFlashPath);
if (flash_path.empty()) if (flash_path.empty())
return; return;
@ -134,20 +132,19 @@ void AddPepperFlashFromCommandLine(
auto flash_version = command_line->GetSwitchValueASCII( auto flash_version = command_line->GetSwitchValueASCII(
switches::kPpapiFlashVersion); switches::kPpapiFlashVersion);
plugins->push_back( plugins->push_back(CreatePepperFlashInfo(flash_path, flash_version));
CreatePepperFlashInfo(base::FilePath(flash_path), flash_version));
} }
#if defined(WIDEVINE_CDM_AVAILABLE) && defined(ENABLE_PEPPER_CDMS) #if defined(WIDEVINE_CDM_AVAILABLE) && defined(ENABLE_PEPPER_CDMS)
void AddWidevineCdmFromCommandLine( void AddWidevineCdmFromCommandLine(
std::vector<content::PepperPluginInfo>* plugins) { std::vector<content::PepperPluginInfo>* plugins) {
auto command_line = base::CommandLine::ForCurrentProcess(); auto command_line = base::CommandLine::ForCurrentProcess();
auto widevine_cdm_path = command_line->GetSwitchValueNative( base::FilePath widevine_cdm_path = command_line->GetSwitchValuePath(
switches::kWidevineCdmPath); switches::kWidevineCdmPath);
if (widevine_cdm_path.empty()) if (widevine_cdm_path.empty())
return; return;
if (!base::PathExists(base::FilePath(widevine_cdm_path))) if (!base::PathExists(widevine_cdm_path))
return; return;
auto widevine_cdm_version = command_line->GetSwitchValueASCII( auto widevine_cdm_version = command_line->GetSwitchValueASCII(
@ -155,7 +152,7 @@ void AddWidevineCdmFromCommandLine(
if (widevine_cdm_version.empty()) if (widevine_cdm_version.empty())
return; return;
plugins->push_back(CreateWidevineCdmInfo(base::FilePath(widevine_cdm_path), plugins->push_back(CreateWidevineCdmInfo(widevine_cdm_path,
widevine_cdm_version)); widevine_cdm_version));
} }
#endif #endif
@ -182,14 +179,8 @@ base::string16 AtomContentClient::GetLocalizedString(int message_id) const {
void AtomContentClient::AddAdditionalSchemes( void AtomContentClient::AddAdditionalSchemes(
std::vector<url::SchemeWithType>* standard_schemes, std::vector<url::SchemeWithType>* standard_schemes,
std::vector<url::SchemeWithType>* referrer_schemes,
std::vector<std::string>* savable_schemes) { std::vector<std::string>* savable_schemes) {
std::vector<std::string> schemes;
ConvertStringWithSeparatorToVector(&schemes, ",",
switches::kRegisterStandardSchemes);
if (!schemes.empty()) {
for (const std::string& scheme : schemes)
standard_schemes->push_back({scheme.c_str(), url::SCHEME_WITHOUT_PORT});
}
standard_schemes->push_back({"chrome-extension", url::SCHEME_WITHOUT_PORT}); standard_schemes->push_back({"chrome-extension", url::SCHEME_WITHOUT_PORT});
} }

View file

@ -25,6 +25,7 @@ class AtomContentClient : public brightray::ContentClient {
base::string16 GetLocalizedString(int message_id) const override; base::string16 GetLocalizedString(int message_id) const override;
void AddAdditionalSchemes( void AddAdditionalSchemes(
std::vector<url::SchemeWithType>* standard_schemes, std::vector<url::SchemeWithType>* standard_schemes,
std::vector<url::SchemeWithType>* referrer_schemes,
std::vector<std::string>* savable_schemes) override; std::vector<std::string>* savable_schemes) override;
void AddPepperPlugins( void AddPepperPlugins(
std::vector<content::PepperPluginInfo>* plugins) override; std::vector<content::PepperPluginInfo>* plugins) override;

View file

@ -15,6 +15,7 @@
#include "atom/app/atom_main_delegate.h" #include "atom/app/atom_main_delegate.h"
#include "atom/common/crash_reporter/win/crash_service_main.h" #include "atom/common/crash_reporter/win/crash_service_main.h"
#include "base/environment.h" #include "base/environment.h"
#include "base/process/launch.h"
#include "base/win/windows_version.h" #include "base/win/windows_version.h"
#include "content/public/app/sandbox_helper_win.h" #include "content/public/app/sandbox_helper_win.h"
#include "sandbox/win/src/sandbox_types.h" #include "sandbox/win/src/sandbox_types.h"
@ -34,7 +35,6 @@
namespace { namespace {
const char* kRunAsNode = "ELECTRON_RUN_AS_NODE"; const char* kRunAsNode = "ELECTRON_RUN_AS_NODE";
const char* kOldRunAsNode = "ATOM_SHELL_INTERNAL_RUN_AS_NODE";
bool IsEnvSet(const char* name) { bool IsEnvSet(const char* name) {
#if defined(OS_WIN) #if defined(OS_WIN)
@ -47,50 +47,6 @@ bool IsEnvSet(const char* name) {
#endif #endif
} }
bool IsRunAsNode() {
return IsEnvSet(kRunAsNode) || IsEnvSet(kOldRunAsNode);
}
#if defined(OS_WIN)
// Win8.1 supports monitor-specific DPI scaling.
bool SetProcessDpiAwarenessWrapper(PROCESS_DPI_AWARENESS value) {
typedef HRESULT(WINAPI *SetProcessDpiAwarenessPtr)(PROCESS_DPI_AWARENESS);
SetProcessDpiAwarenessPtr set_process_dpi_awareness_func =
reinterpret_cast<SetProcessDpiAwarenessPtr>(
GetProcAddress(GetModuleHandleA("user32.dll"),
"SetProcessDpiAwarenessInternal"));
if (set_process_dpi_awareness_func) {
HRESULT hr = set_process_dpi_awareness_func(value);
if (SUCCEEDED(hr)) {
VLOG(1) << "SetProcessDpiAwareness succeeded.";
return true;
} else if (hr == E_ACCESSDENIED) {
LOG(ERROR) << "Access denied error from SetProcessDpiAwareness. "
"Function called twice, or manifest was used.";
}
}
return false;
}
// This function works for Windows Vista through Win8. Win8.1 must use
// SetProcessDpiAwareness[Wrapper].
BOOL SetProcessDPIAwareWrapper() {
typedef BOOL(WINAPI *SetProcessDPIAwarePtr)(VOID);
SetProcessDPIAwarePtr set_process_dpi_aware_func =
reinterpret_cast<SetProcessDPIAwarePtr>(
GetProcAddress(GetModuleHandleA("user32.dll"),
"SetProcessDPIAware"));
return set_process_dpi_aware_func &&
set_process_dpi_aware_func();
}
void EnableHighDPISupport() {
if (!SetProcessDpiAwarenessWrapper(PROCESS_SYSTEM_DPI_AWARE)) {
SetProcessDPIAwareWrapper();
}
}
#endif
} // namespace } // namespace
#if defined(OS_WIN) #if defined(OS_WIN)
@ -98,14 +54,11 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
int argc = 0; int argc = 0;
wchar_t** wargv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); wchar_t** wargv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
// Make output work in console if we are not in cygiwn. bool run_as_node = IsEnvSet(kRunAsNode);
if (!IsEnvSet("TERM") && !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE")) {
AttachConsole(ATTACH_PARENT_PROCESS);
FILE* dontcare; // Make sure the output is printed to console.
freopen_s(&dontcare, "CON", "w", stdout); if (run_as_node || !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE"))
freopen_s(&dontcare, "CON", "w", stderr); base::RouteStdioToConsole(false);
}
// Convert argv to to UTF8 // Convert argv to to UTF8
char** argv = new char*[argc]; char** argv = new char*[argc];
@ -141,12 +94,12 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
} }
} }
if (IsRunAsNode()) { if (run_as_node) {
// Now that argv conversion is done, we can finally start. // Now that argv conversion is done, we can finally start.
base::AtExitManager atexit_manager; base::AtExitManager atexit_manager;
base::i18n::InitializeICU(); base::i18n::InitializeICU();
return atom::NodeMain(argc, argv); return atom::NodeMain(argc, argv);
} else if (IsEnvSet("ATOM_SHELL_INTERNAL_CRASH_SERVICE")) { } else if (IsEnvSet("ELECTRON_INTERNAL_CRASH_SERVICE")) {
return crash_service::Main(cmd); return crash_service::Main(cmd);
} }
@ -154,12 +107,6 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
content::InitializeSandboxInfo(&sandbox_info); content::InitializeSandboxInfo(&sandbox_info);
atom::AtomMainDelegate delegate; atom::AtomMainDelegate delegate;
// We don't want to set DPI awareness on pre-Win7 because we don't support
// DirectWrite there. GDI fonts are kerned very badly, so better to leave
// DPI-unaware and at effective 1.0. See also ShouldUseDirectWrite().
if (base::win::GetVersion() >= base::win::VERSION_WIN7)
EnableHighDPISupport();
content::ContentMainParams params(&delegate); content::ContentMainParams params(&delegate);
params.instance = instance; params.instance = instance;
params.sandbox_info = &sandbox_info; params.sandbox_info = &sandbox_info;
@ -170,7 +117,7 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
#elif defined(OS_LINUX) // defined(OS_WIN) #elif defined(OS_LINUX) // defined(OS_WIN)
int main(int argc, const char* argv[]) { int main(int argc, const char* argv[]) {
if (IsRunAsNode()) { if (IsEnvSet(kRunAsNode)) {
base::i18n::InitializeICU(); base::i18n::InitializeICU();
base::AtExitManager atexit_manager; base::AtExitManager atexit_manager;
return atom::NodeMain(argc, const_cast<char**>(argv)); return atom::NodeMain(argc, const_cast<char**>(argv));
@ -187,7 +134,7 @@ int main(int argc, const char* argv[]) {
#else // defined(OS_LINUX) #else // defined(OS_LINUX)
int main(int argc, const char* argv[]) { int main(int argc, const char* argv[]) {
if (IsRunAsNode()) { if (IsEnvSet(kRunAsNode)) {
return AtomInitializeICUandStartNode(argc, const_cast<char**>(argv)); return AtomInitializeICUandStartNode(argc, const_cast<char**>(argv));
} }

View file

@ -30,6 +30,13 @@ bool IsBrowserProcess(base::CommandLine* cmd) {
return process_type.empty(); return process_type.empty();
} }
#if defined(OS_WIN)
void InvalidParameterHandler(const wchar_t*, const wchar_t*, const wchar_t*,
unsigned int, uintptr_t) {
// noop.
}
#endif
} // namespace } // namespace
AtomMainDelegate::AtomMainDelegate() { AtomMainDelegate::AtomMainDelegate() {
@ -61,7 +68,7 @@ bool AtomMainDelegate::BasicStartupComplete(int* exit_code) {
#endif // !defined(OS_WIN) #endif // !defined(OS_WIN)
// Only enable logging when --enable-logging is specified. // Only enable logging when --enable-logging is specified.
scoped_ptr<base::Environment> env(base::Environment::Create()); std::unique_ptr<base::Environment> env(base::Environment::Create());
if (!command_line->HasSwitch(switches::kEnableLogging) && if (!command_line->HasSwitch(switches::kEnableLogging) &&
!env->HasVar("ELECTRON_ENABLE_LOGGING")) { !env->HasVar("ELECTRON_ENABLE_LOGGING")) {
settings.logging_dest = logging::LOG_NONE; settings.logging_dest = logging::LOG_NONE;
@ -83,6 +90,15 @@ bool AtomMainDelegate::BasicStartupComplete(int* exit_code) {
chrome::RegisterPathProvider(); chrome::RegisterPathProvider();
#if defined(OS_MACOSX)
SetUpBundleOverrides();
#endif
#if defined(OS_WIN)
// Ignore invalid parameter errors.
_set_invalid_parameter_handler(InvalidParameterHandler);
#endif
return brightray::MainDelegate::BasicStartupComplete(exit_code); return brightray::MainDelegate::BasicStartupComplete(exit_code);
} }
@ -90,7 +106,7 @@ void AtomMainDelegate::PreSandboxStartup() {
brightray::MainDelegate::PreSandboxStartup(); brightray::MainDelegate::PreSandboxStartup();
// Set google API key. // Set google API key.
scoped_ptr<base::Environment> env(base::Environment::Create()); std::unique_ptr<base::Environment> env(base::Environment::Create());
if (!env->HasVar("GOOGLE_API_KEY")) if (!env->HasVar("GOOGLE_API_KEY"))
env->SetVar("GOOGLE_API_KEY", GOOGLEAPIS_API_KEY); env->SetVar("GOOGLE_API_KEY", GOOGLEAPIS_API_KEY);
@ -130,8 +146,9 @@ content::ContentUtilityClient* AtomMainDelegate::CreateContentUtilityClient() {
return utility_client_.get(); return utility_client_.get();
} }
scoped_ptr<brightray::ContentClient> AtomMainDelegate::CreateContentClient() { std::unique_ptr<brightray::ContentClient>
return scoped_ptr<brightray::ContentClient>(new AtomContentClient); AtomMainDelegate::CreateContentClient() {
return std::unique_ptr<brightray::ContentClient>(new AtomContentClient);
} }
} // namespace atom } // namespace atom

View file

@ -24,17 +24,21 @@ class AtomMainDelegate : public brightray::MainDelegate {
content::ContentUtilityClient* CreateContentUtilityClient() override; content::ContentUtilityClient* CreateContentUtilityClient() override;
// brightray::MainDelegate: // brightray::MainDelegate:
scoped_ptr<brightray::ContentClient> CreateContentClient() override; std::unique_ptr<brightray::ContentClient> CreateContentClient() override;
#if defined(OS_MACOSX) #if defined(OS_MACOSX)
void OverrideChildProcessPath() override; void OverrideChildProcessPath() override;
void OverrideFrameworkBundlePath() override; void OverrideFrameworkBundlePath() override;
#endif #endif
private: private:
#if defined(OS_MACOSX)
void SetUpBundleOverrides();
#endif
brightray::ContentClient content_client_; brightray::ContentClient content_client_;
scoped_ptr<content::ContentBrowserClient> browser_client_; std::unique_ptr<content::ContentBrowserClient> browser_client_;
scoped_ptr<content::ContentRendererClient> renderer_client_; std::unique_ptr<content::ContentRendererClient> renderer_client_;
scoped_ptr<content::ContentUtilityClient> utility_client_; std::unique_ptr<content::ContentUtilityClient> utility_client_;
DISALLOW_COPY_AND_ASSIGN(AtomMainDelegate); DISALLOW_COPY_AND_ASSIGN(AtomMainDelegate);
}; };

View file

@ -7,7 +7,10 @@
#include "base/mac/bundle_locations.h" #include "base/mac/bundle_locations.h"
#include "base/files/file_path.h" #include "base/files/file_path.h"
#include "base/files/file_util.h" #include "base/files/file_util.h"
#include "base/mac/foundation_util.h"
#include "base/mac/scoped_nsautorelease_pool.h"
#include "base/path_service.h" #include "base/path_service.h"
#include "base/strings/sys_string_conversions.h"
#include "brightray/common/application_info.h" #include "brightray/common/application_info.h"
#include "brightray/common/mac/main_application_bundle.h" #include "brightray/common/mac/main_application_bundle.h"
#include "content/public/common/content_paths.h" #include "content/public/common/content_paths.h"
@ -48,4 +51,15 @@ void AtomMainDelegate::OverrideChildProcessPath() {
PathService::Override(content::CHILD_PROCESS_EXE, helper_path); PathService::Override(content::CHILD_PROCESS_EXE, helper_path);
} }
void AtomMainDelegate::SetUpBundleOverrides() {
base::mac::ScopedNSAutoreleasePool pool;
NSBundle* bundle = brightray::MainApplicationBundle();
std::string base_bundle_id =
base::SysNSStringToUTF8([bundle bundleIdentifier]);
NSString* team_id = [bundle objectForInfoDictionaryKey:@"ElectronTeamID"];
if (team_id)
base_bundle_id = base::SysNSStringToUTF8(team_id) + "." + base_bundle_id;
base::mac::SetBaseBundleID(base_bundle_id.c_str());
}
} // namespace atom } // namespace atom

View file

@ -7,8 +7,9 @@
#include "atom/app/uv_task_runner.h" #include "atom/app/uv_task_runner.h"
#include "atom/browser/javascript_environment.h" #include "atom/browser/javascript_environment.h"
#include "atom/browser/node_debugger.h" #include "atom/browser/node_debugger.h"
#include "base/command_line.h"
#include "atom/common/node_includes.h" #include "atom/common/node_includes.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/thread_task_runner_handle.h" #include "base/thread_task_runner_handle.h"
#include "gin/array_buffer.h" #include "gin/array_buffer.h"
#include "gin/public/isolate_holder.h" #include "gin/public/isolate_holder.h"
@ -27,6 +28,11 @@ int NodeMain(int argc, char *argv[]) {
scoped_refptr<UvTaskRunner> uv_task_runner(new UvTaskRunner(loop)); scoped_refptr<UvTaskRunner> uv_task_runner(new UvTaskRunner(loop));
base::ThreadTaskRunnerHandle handle(uv_task_runner); base::ThreadTaskRunnerHandle handle(uv_task_runner);
// Initialize feature list.
std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);
feature_list->InitializeFromCommandLine("", "");
base::FeatureList::SetInstance(std::move(feature_list));
gin::V8Initializer::LoadV8Snapshot(); gin::V8Initializer::LoadV8Snapshot();
gin::V8Initializer::LoadV8Natives(); gin::V8Initializer::LoadV8Natives();
JavascriptEnvironment gin_env; JavascriptEnvironment gin_env;

View file

@ -27,6 +27,7 @@
#include "base/files/file_path.h" #include "base/files/file_path.h"
#include "base/files/file_util.h" #include "base/files/file_util.h"
#include "base/path_service.h" #include "base/path_service.h"
#include "base/strings/string_util.h"
#include "brightray/browser/brightray_paths.h" #include "brightray/browser/brightray_paths.h"
#include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_paths.h"
#include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/client_certificate_delegate.h"
@ -318,7 +319,7 @@ void App::AllowCertificateError(
void App::SelectClientCertificate( void App::SelectClientCertificate(
content::WebContents* web_contents, content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info, net::SSLCertRequestInfo* cert_request_info,
scoped_ptr<content::ClientCertificateDelegate> delegate) { std::unique_ptr<content::ClientCertificateDelegate> delegate) {
std::shared_ptr<content::ClientCertificateDelegate> std::shared_ptr<content::ClientCertificateDelegate>
shared_delegate(delegate.release()); shared_delegate(delegate.release());
bool prevent_default = bool prevent_default =
@ -369,17 +370,11 @@ void App::SetPath(mate::Arguments* args,
void App::SetDesktopName(const std::string& desktop_name) { void App::SetDesktopName(const std::string& desktop_name) {
#if defined(OS_LINUX) #if defined(OS_LINUX)
scoped_ptr<base::Environment> env(base::Environment::Create()); std::unique_ptr<base::Environment> env(base::Environment::Create());
env->SetVar("CHROME_DESKTOP", desktop_name); env->SetVar("CHROME_DESKTOP", desktop_name);
#endif #endif
} }
void App::AllowNTLMCredentialsForAllDomains(bool should_allow) {
auto browser_context = static_cast<AtomBrowserContext*>(
AtomBrowserMainParts::Get()->browser_context());
browser_context->AllowNTLMCredentialsForAllDomains(should_allow);
}
std::string App::GetLocale() { std::string App::GetLocale() {
return l10n_util::GetApplicationLocale(""); return l10n_util::GetApplicationLocale("");
} }
@ -406,13 +401,20 @@ bool App::MakeSingleInstance(
} }
} }
void App::ReleaseSingleInstance() {
if (process_singleton_.get()) {
process_singleton_->Cleanup();
process_singleton_.reset();
}
}
#if defined(USE_NSS_CERTS) #if defined(USE_NSS_CERTS)
void App::ImportCertificate( void App::ImportCertificate(
const base::DictionaryValue& options, const base::DictionaryValue& options,
const net::CompletionCallback& callback) { const net::CompletionCallback& callback) {
auto browser_context = AtomBrowserMainParts::Get()->browser_context(); auto browser_context = AtomBrowserMainParts::Get()->browser_context();
if (!certificate_manager_model_) { if (!certificate_manager_model_) {
scoped_ptr<base::DictionaryValue> copy = options.CreateDeepCopy(); std::unique_ptr<base::DictionaryValue> copy = options.CreateDeepCopy();
CertificateManagerModel::Create(browser_context, CertificateManagerModel::Create(browser_context,
base::Bind(&App::OnCertificateManagerModelCreated, base::Bind(&App::OnCertificateManagerModelCreated,
base::Unretained(this), base::Unretained(this),
@ -426,9 +428,9 @@ void App::ImportCertificate(
} }
void App::OnCertificateManagerModelCreated( void App::OnCertificateManagerModelCreated(
scoped_ptr<base::DictionaryValue> options, std::unique_ptr<base::DictionaryValue> options,
const net::CompletionCallback& callback, const net::CompletionCallback& callback,
scoped_ptr<CertificateManagerModel> model) { std::unique_ptr<CertificateManagerModel> model) {
certificate_manager_model_ = std::move(model); certificate_manager_model_ = std::move(model);
int rv = ImportIntoCertStore(certificate_manager_model_.get(), int rv = ImportIntoCertStore(certificate_manager_model_.get(),
*(options.get())); *(options.get()));
@ -481,13 +483,12 @@ void App::BuildPrototype(
.SetMethod("setPath", &App::SetPath) .SetMethod("setPath", &App::SetPath)
.SetMethod("getPath", &App::GetPath) .SetMethod("getPath", &App::GetPath)
.SetMethod("setDesktopName", &App::SetDesktopName) .SetMethod("setDesktopName", &App::SetDesktopName)
.SetMethod("allowNTLMCredentialsForAllDomains",
&App::AllowNTLMCredentialsForAllDomains)
.SetMethod("getLocale", &App::GetLocale) .SetMethod("getLocale", &App::GetLocale)
#if defined(USE_NSS_CERTS) #if defined(USE_NSS_CERTS)
.SetMethod("importCertificate", &App::ImportCertificate) .SetMethod("importCertificate", &App::ImportCertificate)
#endif #endif
.SetMethod("makeSingleInstance", &App::MakeSingleInstance); .SetMethod("makeSingleInstance", &App::MakeSingleInstance)
.SetMethod("releaseSingleInstance", &App::ReleaseSingleInstance);
} }
} // namespace api } // namespace api
@ -500,7 +501,8 @@ namespace {
void AppendSwitch(const std::string& switch_string, mate::Arguments* args) { void AppendSwitch(const std::string& switch_string, mate::Arguments* args) {
auto command_line = base::CommandLine::ForCurrentProcess(); auto command_line = base::CommandLine::ForCurrentProcess();
if (switch_string == atom::switches::kPpapiFlashPath || if (base::EndsWith(switch_string, "-path",
base::CompareCase::INSENSITIVE_ASCII) ||
switch_string == switches::kLogNetLog) { switch_string == switches::kLogNetLog) {
base::FilePath path; base::FilePath path;
args->GetNext(&path); args->GetNext(&path);
@ -546,6 +548,8 @@ void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
dict.SetMethod("dockBounce", &DockBounce); dict.SetMethod("dockBounce", &DockBounce);
dict.SetMethod("dockCancelBounce", dict.SetMethod("dockCancelBounce",
base::Bind(&Browser::DockCancelBounce, browser)); base::Bind(&Browser::DockCancelBounce, browser));
dict.SetMethod("dockDownloadFinished",
base::Bind(&Browser::DockDownloadFinished, browser));
dict.SetMethod("dockSetBadgeText", dict.SetMethod("dockSetBadgeText",
base::Bind(&Browser::DockSetBadgeText, browser)); base::Bind(&Browser::DockSetBadgeText, browser));
dict.SetMethod("dockGetBadgeText", dict.SetMethod("dockGetBadgeText",

View file

@ -51,9 +51,9 @@ class App : public AtomBrowserClient::Delegate,
#if defined(USE_NSS_CERTS) #if defined(USE_NSS_CERTS)
void OnCertificateManagerModelCreated( void OnCertificateManagerModelCreated(
scoped_ptr<base::DictionaryValue> options, std::unique_ptr<base::DictionaryValue> options,
const net::CompletionCallback& callback, const net::CompletionCallback& callback,
scoped_ptr<CertificateManagerModel> model); std::unique_ptr<CertificateManagerModel> model);
#endif #endif
protected: protected:
@ -93,7 +93,7 @@ class App : public AtomBrowserClient::Delegate,
void SelectClientCertificate( void SelectClientCertificate(
content::WebContents* web_contents, content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info, net::SSLCertRequestInfo* cert_request_info,
scoped_ptr<content::ClientCertificateDelegate> delegate) override; std::unique_ptr<content::ClientCertificateDelegate> delegate) override;
// content::GpuDataManagerObserver: // content::GpuDataManagerObserver:
void OnGpuProcessCrashed(base::TerminationStatus exit_code) override; void OnGpuProcessCrashed(base::TerminationStatus exit_code) override;
@ -106,9 +106,9 @@ class App : public AtomBrowserClient::Delegate,
const base::FilePath& path); const base::FilePath& path);
void SetDesktopName(const std::string& desktop_name); void SetDesktopName(const std::string& desktop_name);
void AllowNTLMCredentialsForAllDomains(bool should_allow);
bool MakeSingleInstance( bool MakeSingleInstance(
const ProcessSingleton::NotificationCallback& callback); const ProcessSingleton::NotificationCallback& callback);
void ReleaseSingleInstance();
std::string GetLocale(); std::string GetLocale();
#if defined(USE_NSS_CERTS) #if defined(USE_NSS_CERTS)
@ -116,10 +116,10 @@ class App : public AtomBrowserClient::Delegate,
const net::CompletionCallback& callback); const net::CompletionCallback& callback);
#endif #endif
scoped_ptr<ProcessSingleton> process_singleton_; std::unique_ptr<ProcessSingleton> process_singleton_;
#if defined(USE_NSS_CERTS) #if defined(USE_NSS_CERTS)
scoped_ptr<CertificateManagerModel> certificate_manager_model_; std::unique_ptr<CertificateManagerModel> certificate_manager_model_;
#endif #endif
DISALLOW_COPY_AND_ASSIGN(App); DISALLOW_COPY_AND_ASSIGN(App);

View file

@ -47,7 +47,7 @@ struct Converter<net::CanonicalCookie> {
dict.Set("secure", val.IsSecure()); dict.Set("secure", val.IsSecure());
dict.Set("httpOnly", val.IsHttpOnly()); dict.Set("httpOnly", val.IsHttpOnly());
dict.Set("session", !val.IsPersistent()); dict.Set("session", !val.IsPersistent());
if (!val.IsPersistent()) if (val.IsPersistent())
dict.Set("expirationDate", val.ExpiryDate().ToDoubleT()); dict.Set("expirationDate", val.ExpiryDate().ToDoubleT());
return dict.GetHandle(); return dict.GetHandle();
} }
@ -112,7 +112,7 @@ void RunCallbackInUI(const base::Closure& callback) {
} }
// Remove cookies from |list| not matching |filter|, and pass it to |callback|. // Remove cookies from |list| not matching |filter|, and pass it to |callback|.
void FilterCookies(scoped_ptr<base::DictionaryValue> filter, void FilterCookies(std::unique_ptr<base::DictionaryValue> filter,
const Cookies::GetCallback& callback, const Cookies::GetCallback& callback,
const net::CookieList& list) { const net::CookieList& list) {
net::CookieList result; net::CookieList result;
@ -125,7 +125,7 @@ void FilterCookies(scoped_ptr<base::DictionaryValue> filter,
// Receives cookies matching |filter| in IO thread. // Receives cookies matching |filter| in IO thread.
void GetCookiesOnIO(scoped_refptr<net::URLRequestContextGetter> getter, void GetCookiesOnIO(scoped_refptr<net::URLRequestContextGetter> getter,
scoped_ptr<base::DictionaryValue> filter, std::unique_ptr<base::DictionaryValue> filter,
const Cookies::GetCallback& callback) { const Cookies::GetCallback& callback) {
std::string url; std::string url;
filter->GetString("url", &url); filter->GetString("url", &url);
@ -133,12 +133,12 @@ void GetCookiesOnIO(scoped_refptr<net::URLRequestContextGetter> getter,
auto filtered_callback = auto filtered_callback =
base::Bind(FilterCookies, base::Passed(&filter), callback); base::Bind(FilterCookies, base::Passed(&filter), callback);
net::CookieMonster* monster = GetCookieStore(getter)->GetCookieMonster();
// Empty url will match all url cookies. // Empty url will match all url cookies.
if (url.empty()) if (url.empty())
monster->GetAllCookiesAsync(filtered_callback); GetCookieStore(getter)->GetAllCookiesAsync(filtered_callback);
else else
monster->GetAllCookiesForURLAsync(GURL(url), filtered_callback); GetCookieStore(getter)->GetAllCookiesForURLAsync(GURL(url),
filtered_callback);
} }
// Removes cookie with |url| and |name| in IO thread. // Removes cookie with |url| and |name| in IO thread.
@ -157,12 +157,14 @@ void OnSetCookie(const Cookies::SetCallback& callback, bool success) {
// Sets cookie with |details| in IO thread. // Sets cookie with |details| in IO thread.
void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter, void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter,
scoped_ptr<base::DictionaryValue> details, std::unique_ptr<base::DictionaryValue> details,
const Cookies::SetCallback& callback) { const Cookies::SetCallback& callback) {
std::string url, name, value, domain, path; std::string url, name, value, domain, path;
bool secure = false; bool secure = false;
bool http_only = false; bool http_only = false;
double creation_date;
double expiration_date; double expiration_date;
double last_access_date;
details->GetString("url", &url); details->GetString("url", &url);
details->GetString("name", &name); details->GetString("name", &name);
details->GetString("value", &value); details->GetString("value", &value);
@ -171,6 +173,13 @@ void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter,
details->GetBoolean("secure", &secure); details->GetBoolean("secure", &secure);
details->GetBoolean("httpOnly", &http_only); details->GetBoolean("httpOnly", &http_only);
base::Time creation_time;
if (details->GetDouble("creationDate", &creation_date)) {
creation_time = (creation_date == 0) ?
base::Time::UnixEpoch() :
base::Time::FromDoubleT(creation_date);
}
base::Time expiration_time; base::Time expiration_time;
if (details->GetDouble("expirationDate", &expiration_date)) { if (details->GetDouble("expirationDate", &expiration_date)) {
expiration_time = (expiration_date == 0) ? expiration_time = (expiration_date == 0) ?
@ -178,10 +187,18 @@ void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter,
base::Time::FromDoubleT(expiration_date); base::Time::FromDoubleT(expiration_date);
} }
GetCookieStore(getter)->GetCookieMonster()->SetCookieWithDetailsAsync( base::Time last_access_time;
GURL(url), name, value, domain, path, expiration_time, secure, http_only, if (details->GetDouble("lastAccessDate", &last_access_date)) {
false, false, false, net::COOKIE_PRIORITY_DEFAULT, last_access_time = (last_access_date == 0) ?
base::Bind(OnSetCookie, callback)); base::Time::UnixEpoch() :
base::Time::FromDoubleT(last_access_date);
}
GetCookieStore(getter)->SetCookieWithDetailsAsync(
GURL(url), name, value, domain, path, creation_time,
expiration_time, last_access_time, secure, http_only,
net::CookieSameSite::DEFAULT_MODE, false,
net::COOKIE_PRIORITY_DEFAULT, base::Bind(OnSetCookie, callback));
} }
} // namespace } // namespace
@ -197,7 +214,7 @@ Cookies::~Cookies() {
void Cookies::Get(const base::DictionaryValue& filter, void Cookies::Get(const base::DictionaryValue& filter,
const GetCallback& callback) { const GetCallback& callback) {
scoped_ptr<base::DictionaryValue> copied(filter.CreateDeepCopy()); std::unique_ptr<base::DictionaryValue> copied(filter.CreateDeepCopy());
auto getter = make_scoped_refptr(request_context_getter_); auto getter = make_scoped_refptr(request_context_getter_);
content::BrowserThread::PostTask( content::BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE, BrowserThread::IO, FROM_HERE,
@ -214,7 +231,7 @@ void Cookies::Remove(const GURL& url, const std::string& name,
void Cookies::Set(const base::DictionaryValue& details, void Cookies::Set(const base::DictionaryValue& details,
const SetCallback& callback) { const SetCallback& callback) {
scoped_ptr<base::DictionaryValue> copied(details.CreateDeepCopy()); std::unique_ptr<base::DictionaryValue> copied(details.CreateDeepCopy());
auto getter = make_scoped_refptr(request_context_getter_); auto getter = make_scoped_refptr(request_context_getter_);
content::BrowserThread::PostTask( content::BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE, BrowserThread::IO, FROM_HERE,

View file

@ -52,7 +52,7 @@ void Debugger::DispatchProtocolMessage(DevToolsAgentHost* agent_host,
const std::string& message) { const std::string& message) {
DCHECK(agent_host == agent_host_.get()); DCHECK(agent_host == agent_host_.get());
scoped_ptr<base::Value> parsed_message(base::JSONReader::Read(message)); std::unique_ptr<base::Value> parsed_message(base::JSONReader::Read(message));
if (!parsed_message->IsType(base::Value::TYPE_DICTIONARY)) if (!parsed_message->IsType(base::Value::TYPE_DICTIONARY))
return; return;

View file

@ -61,9 +61,9 @@ void DesktopCapturer::StartHandling(bool capture_window,
options.set_disable_effects(false); options.set_disable_effects(false);
#endif #endif
scoped_ptr<webrtc::ScreenCapturer> screen_capturer( std::unique_ptr<webrtc::ScreenCapturer> screen_capturer(
capture_screen ? webrtc::ScreenCapturer::Create(options) : nullptr); capture_screen ? webrtc::ScreenCapturer::Create(options) : nullptr);
scoped_ptr<webrtc::WindowCapturer> window_capturer( std::unique_ptr<webrtc::WindowCapturer> window_capturer(
capture_window ? webrtc::WindowCapturer::Create(options) : nullptr); capture_window ? webrtc::WindowCapturer::Create(options) : nullptr);
media_list_.reset(new NativeDesktopMediaList( media_list_.reset(new NativeDesktopMediaList(
std::move(screen_capturer), std::move(window_capturer))); std::move(screen_capturer), std::move(window_capturer)));

View file

@ -39,7 +39,7 @@ class DesktopCapturer: public mate::EventEmitter<DesktopCapturer>,
bool OnRefreshFinished() override; bool OnRefreshFinished() override;
private: private:
scoped_ptr<DesktopMediaList> media_list_; std::unique_ptr<DesktopMediaList> media_list_;
DISALLOW_COPY_AND_ASSIGN(DesktopCapturer); DISALLOW_COPY_AND_ASSIGN(DesktopCapturer);
}; };

View file

@ -67,6 +67,7 @@ void ShowMessageBox(int type,
} }
void ShowOpenDialog(const std::string& title, void ShowOpenDialog(const std::string& title,
const std::string& button_label,
const base::FilePath& default_path, const base::FilePath& default_path,
const file_dialog::Filters& filters, const file_dialog::Filters& filters,
int properties, int properties,
@ -77,17 +78,18 @@ void ShowOpenDialog(const std::string& title,
if (mate::Converter<file_dialog::OpenDialogCallback>::FromV8(args->isolate(), if (mate::Converter<file_dialog::OpenDialogCallback>::FromV8(args->isolate(),
peek, peek,
&callback)) { &callback)) {
file_dialog::ShowOpenDialog(window, title, default_path, filters, file_dialog::ShowOpenDialog(window, title, button_label, default_path,
properties, callback); filters, properties, callback);
} else { } else {
std::vector<base::FilePath> paths; std::vector<base::FilePath> paths;
if (file_dialog::ShowOpenDialog(window, title, default_path, filters, if (file_dialog::ShowOpenDialog(window, title, button_label, default_path,
properties, &paths)) filters, properties, &paths))
args->Return(paths); args->Return(paths);
} }
} }
void ShowSaveDialog(const std::string& title, void ShowSaveDialog(const std::string& title,
const std::string& button_label,
const base::FilePath& default_path, const base::FilePath& default_path,
const file_dialog::Filters& filters, const file_dialog::Filters& filters,
atom::NativeWindow* window, atom::NativeWindow* window,
@ -97,11 +99,12 @@ void ShowSaveDialog(const std::string& title,
if (mate::Converter<file_dialog::SaveDialogCallback>::FromV8(args->isolate(), if (mate::Converter<file_dialog::SaveDialogCallback>::FromV8(args->isolate(),
peek, peek,
&callback)) { &callback)) {
file_dialog::ShowSaveDialog(window, title, default_path, filters, callback); file_dialog::ShowSaveDialog(window, title, button_label, default_path,
filters, callback);
} else { } else {
base::FilePath path; base::FilePath path;
if (file_dialog::ShowSaveDialog(window, title, default_path, filters, if (file_dialog::ShowSaveDialog(window, title, button_label, default_path,
&path)) filters, &path))
args->Return(path); args->Return(path);
} }
} }

View file

@ -55,7 +55,7 @@ class Menu : public mate::TrackableObject<Menu>,
int x = -1, int y = -1, int x = -1, int y = -1,
int positioning_item = 0) = 0; int positioning_item = 0) = 0;
scoped_ptr<AtomMenuModel> model_; std::unique_ptr<AtomMenuModel> model_;
Menu* parent_; Menu* parent_;
private: private:

View file

@ -7,6 +7,8 @@
#include "atom/browser/native_window.h" #include "atom/browser/native_window.h"
#include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop.h"
#include "base/strings/sys_string_conversions.h" #include "base/strings/sys_string_conversions.h"
#include "brightray/browser/inspectable_web_contents.h"
#include "brightray/browser/inspectable_web_contents_view.h"
#include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents.h"
#include "atom/common/node_includes.h" #include "atom/common/node_includes.h"
@ -22,14 +24,15 @@ void MenuMac::PopupAt(Window* window, int x, int y, int positioning_item) {
NativeWindow* native_window = window->window(); NativeWindow* native_window = window->window();
if (!native_window) if (!native_window)
return; return;
content::WebContents* web_contents = native_window->web_contents(); brightray::InspectableWebContents* web_contents =
native_window->inspectable_web_contents();
if (!web_contents) if (!web_contents)
return; return;
base::scoped_nsobject<AtomMenuController> menu_controller( base::scoped_nsobject<AtomMenuController> menu_controller(
[[AtomMenuController alloc] initWithModel:model_.get()]); [[AtomMenuController alloc] initWithModel:model_.get()]);
NSMenu* menu = [menu_controller menu]; NSMenu* menu = [menu_controller menu];
NSView* view = web_contents->GetContentNativeView(); NSView* view = web_contents->GetView()->GetNativeView();
// Which menu item to show. // Which menu item to show.
NSMenuItem* item = nil; NSMenuItem* item = nil;
@ -46,6 +49,23 @@ void MenuMac::PopupAt(Window* window, int x, int y, int positioning_item) {
position = NSMakePoint(x, [view frame].size.height - y); position = NSMakePoint(x, [view frame].size.height - y);
} }
// If no preferred item is specified, try to show all of the menu items.
if (!positioning_item) {
CGFloat windowBottom = CGRectGetMinY([view window].frame);
CGFloat lowestMenuPoint = windowBottom + position.y - [menu size].height;
CGFloat screenBottom = CGRectGetMinY([view window].screen.frame);
CGFloat distanceFromBottom = lowestMenuPoint - screenBottom;
if (distanceFromBottom < 0)
position.y = position.y - distanceFromBottom + 4;
}
// Place the menu left of cursor if it is overflowing off right of screen.
CGFloat windowLeft = CGRectGetMinX([view window].frame);
CGFloat rightmostMenuPoint = windowLeft + position.x + [menu size].width;
CGFloat screenRight = CGRectGetMaxX([view window].screen.frame);
if (rightmostMenuPoint > screenRight)
position.x = position.x - [menu size].width;
// Show the menu. // Show the menu.
[menu popUpMenuPositioningItem:item atLocation:position inView:view]; [menu popUpMenuPositioningItem:item atLocation:position inView:view];
} }

View file

@ -30,7 +30,7 @@ void MenuViews::PopupAt(Window* window, int x, int y, int positioning_item) {
// (-1, -1) means showing on mouse location. // (-1, -1) means showing on mouse location.
gfx::Point location; gfx::Point location;
if (x == -1 || y == -1) { if (x == -1 || y == -1) {
location = gfx::Screen::GetNativeScreen()->GetCursorScreenPoint(); location = gfx::Screen::GetScreen()->GetCursorScreenPoint();
} else { } else {
gfx::Point origin = view->GetViewBounds().origin(); gfx::Point origin = view->GetViewBounds().origin();
location = gfx::Point(origin.x() + x, origin.y() + y); location = gfx::Point(origin.x() + x, origin.y() + y);

View file

@ -70,7 +70,7 @@ void PowerSaveBlocker::UpdatePowerSaveBlocker() {
} }
if (!power_save_blocker_ || new_blocker_type != current_blocker_type_) { if (!power_save_blocker_ || new_blocker_type != current_blocker_type_) {
scoped_ptr<content::PowerSaveBlocker> new_blocker = std::unique_ptr<content::PowerSaveBlocker> new_blocker =
content::PowerSaveBlocker::Create( content::PowerSaveBlocker::Create(
new_blocker_type, new_blocker_type,
content::PowerSaveBlocker::kReasonOther, content::PowerSaveBlocker::kReasonOther,

View file

@ -37,7 +37,7 @@ class PowerSaveBlocker : public mate::TrackableObject<PowerSaveBlocker> {
bool Stop(int id); bool Stop(int id);
bool IsStarted(int id); bool IsStarted(int id);
scoped_ptr<content::PowerSaveBlocker> power_save_blocker_; std::unique_ptr<content::PowerSaveBlocker> power_save_blocker_;
// Currnet blocker type used by |power_save_blocker_| // Currnet blocker type used by |power_save_blocker_|
content::PowerSaveBlocker::PowerSaveBlockerType current_blocker_type_; content::PowerSaveBlocker::PowerSaveBlockerType current_blocker_type_;

View file

@ -15,6 +15,7 @@
#include "atom/common/native_mate_converters/net_converter.h" #include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/node_includes.h" #include "atom/common/node_includes.h"
#include "native_mate/dictionary.h" #include "native_mate/dictionary.h"
#include "url/url_util.h"
using content::BrowserThread; using content::BrowserThread;
@ -29,11 +30,6 @@ Protocol::Protocol(v8::Isolate* isolate, AtomBrowserContext* browser_context)
Init(isolate); Init(isolate);
} }
void Protocol::RegisterStandardSchemes(
const std::vector<std::string>& schemes) {
atom::AtomBrowserClient::SetCustomSchemes(schemes);
}
void Protocol::RegisterServiceWorkerSchemes( void Protocol::RegisterServiceWorkerSchemes(
const std::vector<std::string>& schemes) { const std::vector<std::string>& schemes) {
atom::AtomBrowserClient::SetCustomServiceWorkerSchemes(schemes); atom::AtomBrowserClient::SetCustomServiceWorkerSchemes(schemes);
@ -131,7 +127,6 @@ mate::Handle<Protocol> Protocol::Create(
void Protocol::BuildPrototype( void Protocol::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) { v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
mate::ObjectTemplateBuilder(isolate, prototype) mate::ObjectTemplateBuilder(isolate, prototype)
.SetMethod("registerStandardSchemes", &Protocol::RegisterStandardSchemes)
.SetMethod("registerServiceWorkerSchemes", .SetMethod("registerServiceWorkerSchemes",
&Protocol::RegisterServiceWorkerSchemes) &Protocol::RegisterServiceWorkerSchemes)
.SetMethod("registerStringProtocol", .SetMethod("registerStringProtocol",
@ -161,13 +156,24 @@ void Protocol::BuildPrototype(
namespace { namespace {
void RegisterStandardSchemes(
const std::vector<std::string>& schemes) {
for (const auto& scheme : schemes)
url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITHOUT_PORT);
}
mate::Handle<atom::api::Protocol> CreateProtocol(v8::Isolate* isolate) {
auto browser_context = static_cast<atom::AtomBrowserContext*>(
atom::AtomBrowserMainParts::Get()->browser_context());
return atom::api::Protocol::Create(isolate, browser_context);
}
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) { v8::Local<v8::Context> context, void* priv) {
v8::Isolate* isolate = context->GetIsolate(); v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports); mate::Dictionary dict(isolate, exports);
auto browser_context = static_cast<atom::AtomBrowserContext*>( dict.SetMethod("createProtocolObject", base::Bind(&CreateProtocol, isolate));
atom::AtomBrowserMainParts::Get()->browser_context()); dict.SetMethod("registerStandardSchemes", &RegisterStandardSchemes);
dict.Set("protocol", atom::api::Protocol::Create(isolate, browser_context));
} }
} // namespace } // namespace

View file

@ -88,9 +88,6 @@ class Protocol : public mate::Wrappable<Protocol> {
DISALLOW_COPY_AND_ASSIGN(CustomProtocolHandler); DISALLOW_COPY_AND_ASSIGN(CustomProtocolHandler);
}; };
// Register schemes to standard scheme list.
void RegisterStandardSchemes(const std::vector<std::string>& schemes);
// Register schemes that can handle service worker. // Register schemes that can handle service worker.
void RegisterServiceWorkerSchemes(const std::vector<std::string>& schemes); void RegisterServiceWorkerSchemes(const std::vector<std::string>& schemes);
@ -113,7 +110,7 @@ class Protocol : public mate::Wrappable<Protocol> {
const Handler& handler) { const Handler& handler) {
if (job_factory_->IsHandledProtocol(scheme)) if (job_factory_->IsHandledProtocol(scheme))
return PROTOCOL_REGISTERED; return PROTOCOL_REGISTERED;
scoped_ptr<CustomProtocolHandler<RequestJob>> protocol_handler( std::unique_ptr<CustomProtocolHandler<RequestJob>> protocol_handler(
new CustomProtocolHandler<RequestJob>( new CustomProtocolHandler<RequestJob>(
isolate(), request_context_getter_, handler)); isolate(), request_context_getter_, handler));
if (job_factory_->SetProtocolHandler(scheme, std::move(protocol_handler))) if (job_factory_->SetProtocolHandler(scheme, std::move(protocol_handler)))
@ -155,7 +152,7 @@ class Protocol : public mate::Wrappable<Protocol> {
return PROTOCOL_FAIL; return PROTOCOL_FAIL;
if (ContainsKey(original_protocols_, scheme)) if (ContainsKey(original_protocols_, scheme))
return PROTOCOL_INTERCEPTED; return PROTOCOL_INTERCEPTED;
scoped_ptr<CustomProtocolHandler<RequestJob>> protocol_handler( std::unique_ptr<CustomProtocolHandler<RequestJob>> protocol_handler(
new CustomProtocolHandler<RequestJob>( new CustomProtocolHandler<RequestJob>(
isolate(), request_context_getter_, handler)); isolate(), request_context_getter_, handler));
original_protocols_.set( original_protocols_.set(
@ -179,7 +176,7 @@ class Protocol : public mate::Wrappable<Protocol> {
// Map that stores the original protocols of schemes. // Map that stores the original protocols of schemes.
using OriginalProtocolsMap = base::ScopedPtrHashMap< using OriginalProtocolsMap = base::ScopedPtrHashMap<
std::string, std::string,
scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>>; std::unique_ptr<net::URLRequestJobFactory::ProtocolHandler>>;
OriginalProtocolsMap original_protocols_; OriginalProtocolsMap original_protocols_;
AtomURLRequestJobFactory* job_factory_; // weak ref AtomURLRequestJobFactory* job_factory_; // weak ref

View file

@ -0,0 +1,88 @@
// 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_render_process_preferences.h"
#include "atom/browser/atom_browser_client.h"
#include "atom/browser/native_window.h"
#include "atom/browser/window_list.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "content/public/browser/render_process_host.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
namespace atom {
namespace api {
namespace {
bool IsBrowserWindow(content::RenderProcessHost* process) {
content::WebContents* web_contents =
static_cast<AtomBrowserClient*>(AtomBrowserClient::Get())->
GetWebContentsFromProcessID(process->GetID());
if (!web_contents)
return false;
NativeWindow* window = NativeWindow::FromWebContents(web_contents);
if (!window)
return false;
return true;
}
} // namespace
RenderProcessPreferences::RenderProcessPreferences(
v8::Isolate* isolate,
const atom::RenderProcessPreferences::Predicate& predicate)
: preferences_(predicate) {
Init(isolate);
}
RenderProcessPreferences::~RenderProcessPreferences() {
}
int RenderProcessPreferences::AddEntry(const base::DictionaryValue& entry) {
return preferences_.AddEntry(entry);
}
void RenderProcessPreferences::RemoveEntry(int id) {
preferences_.RemoveEntry(id);
}
// static
void RenderProcessPreferences::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
mate::ObjectTemplateBuilder(isolate, prototype)
.SetMethod("addEntry", &RenderProcessPreferences::AddEntry)
.SetMethod("removeEntry", &RenderProcessPreferences::RemoveEntry);
}
// static
mate::Handle<RenderProcessPreferences>
RenderProcessPreferences::ForAllBrowserWindow(v8::Isolate* isolate) {
return mate::CreateHandle(
isolate,
new RenderProcessPreferences(isolate, base::Bind(&IsBrowserWindow)));
}
} // namespace api
} // namespace atom
namespace {
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
mate::Dictionary dict(context->GetIsolate(), exports);
dict.SetMethod("forAllBrowserWindow",
&atom::api::RenderProcessPreferences::ForAllBrowserWindow);
}
} // namespace
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_render_process_preferences,
Initialize)

View file

@ -0,0 +1,44 @@
// 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_RENDER_PROCESS_PREFERENCES_H_
#define ATOM_BROWSER_API_ATOM_API_RENDER_PROCESS_PREFERENCES_H_
#include "atom/browser/render_process_preferences.h"
#include "native_mate/handle.h"
#include "native_mate/wrappable.h"
namespace atom {
namespace api {
class RenderProcessPreferences
: public mate::Wrappable<RenderProcessPreferences> {
public:
static mate::Handle<RenderProcessPreferences>
ForAllBrowserWindow(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype);
int AddEntry(const base::DictionaryValue& entry);
void RemoveEntry(int id);
protected:
RenderProcessPreferences(
v8::Isolate* isolate,
const atom::RenderProcessPreferences::Predicate& predicate);
~RenderProcessPreferences() override;
private:
atom::RenderProcessPreferences preferences_;
DISALLOW_COPY_AND_ASSIGN(RenderProcessPreferences);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_RENDER_PROCESS_PREFERENCES_H_

View file

@ -99,7 +99,7 @@ v8::Local<v8::Value> Screen::Create(v8::Isolate* isolate) {
return v8::Null(isolate); return v8::Null(isolate);
} }
gfx::Screen* screen = gfx::Screen::GetNativeScreen(); gfx::Screen* screen = gfx::Screen::GetScreen();
if (!screen) { if (!screen) {
isolate->ThrowException(v8::Exception::Error(mate::StringToV8( isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate, "Failed to get screen information"))); isolate, "Failed to get screen information")));

View file

@ -22,7 +22,7 @@
#include "atom/common/node_includes.h" #include "atom/common/node_includes.h"
#include "base/files/file_path.h" #include "base/files/file_path.h"
#include "base/guid.h" #include "base/guid.h"
#include "base/prefs/pref_service.h" #include "components/prefs/pref_service.h"
#include "base/strings/string_number_conversions.h" #include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h" #include "base/strings/string_util.h"
#include "base/thread_task_runner_handle.h" #include "base/thread_task_runner_handle.h"
@ -36,6 +36,8 @@
#include "net/base/load_flags.h" #include "net/base/load_flags.h"
#include "net/disk_cache/disk_cache.h" #include "net/disk_cache/disk_cache.h"
#include "net/dns/host_cache.h" #include "net/dns/host_cache.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_auth_preferences.h"
#include "net/proxy/proxy_service.h" #include "net/proxy/proxy_service.h"
#include "net/proxy/proxy_config_service_fixed.h" #include "net/proxy/proxy_config_service_fixed.h"
#include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context.h"
@ -190,7 +192,7 @@ class ResolveProxyHelper {
// Start the request. // Start the request.
int result = proxy_service->ResolveProxy( int result = proxy_service->ResolveProxy(
url, net::LOAD_NORMAL, &proxy_info_, completion_callback, url, "GET", net::LOAD_NORMAL, &proxy_info_, completion_callback,
&pac_req_, nullptr, net::BoundNetLog()); &pac_req_, nullptr, net::BoundNetLog());
// Completed synchronously. // Completed synchronously.
@ -284,6 +286,19 @@ void ClearHostResolverCacheInIO(
} }
} }
void AllowNTLMCredentialsForDomainsInIO(
const scoped_refptr<net::URLRequestContextGetter>& context_getter,
const std::string& domains) {
auto request_context = context_getter->GetURLRequestContext();
auto auth_handler = request_context->http_auth_handler_factory();
if (auth_handler) {
auto auth_preferences = const_cast<net::HttpAuthPreferences*>(
auth_handler->http_auth_preferences());
if (auth_preferences)
auth_preferences->set_server_whitelist(domains);
}
}
} // namespace } // namespace
Session::Session(v8::Isolate* isolate, AtomBrowserContext* browser_context) Session::Session(v8::Isolate* isolate, AtomBrowserContext* browser_context)
@ -369,7 +384,7 @@ void Session::SetDownloadPath(const base::FilePath& path) {
} }
void Session::EnableNetworkEmulation(const mate::Dictionary& options) { void Session::EnableNetworkEmulation(const mate::Dictionary& options) {
scoped_ptr<brightray::DevToolsNetworkConditions> conditions; std::unique_ptr<brightray::DevToolsNetworkConditions> conditions;
bool offline = false; bool offline = false;
double latency, download_throughput, upload_throughput; double latency, download_throughput, upload_throughput;
if (options.Get("offline", &offline) && offline) { if (options.Get("offline", &offline) && offline) {
@ -392,7 +407,7 @@ void Session::EnableNetworkEmulation(const mate::Dictionary& options) {
} }
void Session::DisableNetworkEmulation() { void Session::DisableNetworkEmulation() {
scoped_ptr<brightray::DevToolsNetworkConditions> conditions; std::unique_ptr<brightray::DevToolsNetworkConditions> conditions;
browser_context_->network_controller_handle()->SetNetworkState( browser_context_->network_controller_handle()->SetNetworkState(
devtools_network_emulation_client_id_, std::move(conditions)); devtools_network_emulation_client_id_, std::move(conditions));
browser_context_->network_delegate()->SetDevToolsNetworkEmulationClientId( browser_context_->network_delegate()->SetDevToolsNetworkEmulationClientId(
@ -432,6 +447,13 @@ void Session::ClearHostResolverCache(mate::Arguments* args) {
callback)); callback));
} }
void Session::AllowNTLMCredentialsForDomains(const std::string& domains) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(&AllowNTLMCredentialsForDomainsInIO,
make_scoped_refptr(browser_context_->GetRequestContext()),
domains));
}
v8::Local<v8::Value> Session::Cookies(v8::Isolate* isolate) { v8::Local<v8::Value> Session::Cookies(v8::Isolate* isolate) {
if (cookies_.IsEmpty()) { if (cookies_.IsEmpty()) {
auto handle = atom::api::Cookies::Create(isolate, browser_context()); auto handle = atom::api::Cookies::Create(isolate, browser_context());
@ -487,6 +509,8 @@ void Session::BuildPrototype(v8::Isolate* isolate,
.SetMethod("setPermissionRequestHandler", .SetMethod("setPermissionRequestHandler",
&Session::SetPermissionRequestHandler) &Session::SetPermissionRequestHandler)
.SetMethod("clearHostResolverCache", &Session::ClearHostResolverCache) .SetMethod("clearHostResolverCache", &Session::ClearHostResolverCache)
.SetMethod("allowNTLMCredentialsForDomains",
&Session::AllowNTLMCredentialsForDomains)
.SetProperty("cookies", &Session::Cookies) .SetProperty("cookies", &Session::Cookies)
.SetProperty("webRequest", &Session::WebRequest); .SetProperty("webRequest", &Session::WebRequest);
} }

View file

@ -79,6 +79,7 @@ class Session: public mate::TrackableObject<Session>,
void SetPermissionRequestHandler(v8::Local<v8::Value> val, void SetPermissionRequestHandler(v8::Local<v8::Value> val,
mate::Arguments* args); mate::Arguments* args);
void ClearHostResolverCache(mate::Arguments* args); void ClearHostResolverCache(mate::Arguments* args);
void AllowNTLMCredentialsForDomains(const std::string& domains);
v8::Local<v8::Value> Cookies(v8::Isolate* isolate); v8::Local<v8::Value> Cookies(v8::Isolate* isolate);
v8::Local<v8::Value> WebRequest(v8::Isolate* isolate); v8::Local<v8::Value> WebRequest(v8::Isolate* isolate);

View file

@ -5,6 +5,7 @@
#include "atom/browser/api/atom_api_system_preferences.h" #include "atom/browser/api/atom_api_system_preferences.h"
#include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h" #include "atom/common/node_includes.h"
#include "native_mate/dictionary.h" #include "native_mate/dictionary.h"

View file

@ -11,6 +11,10 @@
#include "base/callback.h" #include "base/callback.h"
#include "native_mate/handle.h" #include "native_mate/handle.h"
namespace base {
class DictionaryValue;
}
namespace atom { namespace atom {
namespace api { namespace api {
@ -22,11 +26,16 @@ class SystemPreferences : public mate::EventEmitter<SystemPreferences> {
static void BuildPrototype(v8::Isolate* isolate, static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype); v8::Local<v8::ObjectTemplate> prototype);
#if defined(OS_MACOSX)
using NotificationCallback = base::Callback<
void(const std::string&, const base::DictionaryValue&)>;
#endif
#if defined(OS_WIN) #if defined(OS_WIN)
bool IsAeroGlassEnabled(); bool IsAeroGlassEnabled();
#elif defined(OS_MACOSX) #elif defined(OS_MACOSX)
int SubscribeNotification(const std::string& name, int SubscribeNotification(const std::string& name,
const base::Closure& callback); const NotificationCallback& callback);
void UnsubscribeNotification(int id); void UnsubscribeNotification(int id);
v8::Local<v8::Value> GetUserDefault(const std::string& name, v8::Local<v8::Value> GetUserDefault(const std::string& name,
const std::string& type); const std::string& type);

View file

@ -8,8 +8,10 @@
#import <Cocoa/Cocoa.h> #import <Cocoa/Cocoa.h>
#include "atom/browser/mac/dict_util.h"
#include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/gurl_converter.h"
#include "base/strings/sys_string_conversions.h" #include "base/strings/sys_string_conversions.h"
#include "base/values.h"
#include "net/base/mac/url_conversions.h" #include "net/base/mac/url_conversions.h"
namespace atom { namespace atom {
@ -25,16 +27,26 @@ std::map<int, id> g_id_map;
} // namespace } // namespace
int SystemPreferences::SubscribeNotification(const std::string& name, int SystemPreferences::SubscribeNotification(
const base::Closure& callback) { const std::string& name, const NotificationCallback& callback) {
int request_id = g_next_id++; int request_id = g_next_id++;
__block base::Closure copied_callback = callback; __block NotificationCallback copied_callback = callback;
g_id_map[request_id] = [[NSDistributedNotificationCenter defaultCenter] g_id_map[request_id] = [[NSDistributedNotificationCenter defaultCenter]
addObserverForName:base::SysUTF8ToNSString(name) addObserverForName:base::SysUTF8ToNSString(name)
object:nil object:nil
queue:nil queue:nil
usingBlock:^(NSNotification* notification) { usingBlock:^(NSNotification* notification) {
copied_callback.Run(); std::unique_ptr<base::DictionaryValue> user_info =
NSDictionaryToDictionaryValue(notification.userInfo);
if (user_info) {
copied_callback.Run(
base::SysNSStringToUTF8(notification.name),
*user_info);
} else {
copied_callback.Run(
base::SysNSStringToUTF8(notification.name),
base::DictionaryValue());
}
} }
]; ];
return request_id; return request_id;

View file

@ -9,6 +9,7 @@
#include "atom/browser/api/atom_api_menu.h" #include "atom/browser/api/atom_api_menu.h"
#include "atom/browser/browser.h" #include "atom/browser/browser.h"
#include "atom/browser/ui/tray_icon.h" #include "atom/browser/ui/tray_icon.h"
#include "atom/common/api/atom_api_native_image.h"
#include "atom/common/native_mate_converters/gfx_converter.h" #include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/native_mate_converters/image_converter.h" #include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/native_mate_converters/string16_converter.h"
@ -22,9 +23,9 @@ namespace atom {
namespace api { namespace api {
Tray::Tray(v8::Isolate* isolate, const gfx::Image& image) Tray::Tray(v8::Isolate* isolate, mate::Handle<NativeImage> image)
: tray_icon_(TrayIcon::Create()) { : tray_icon_(TrayIcon::Create()) {
tray_icon_->SetImage(image); SetImage(isolate, image);
tray_icon_->AddObserver(this); tray_icon_->AddObserver(this);
} }
@ -32,7 +33,8 @@ Tray::~Tray() {
} }
// static // static
mate::WrappableBase* Tray::New(v8::Isolate* isolate, const gfx::Image& image) { mate::WrappableBase* Tray::New(v8::Isolate* isolate,
mate::Handle<NativeImage> image) {
if (!Browser::Get()->is_ready()) { if (!Browser::Get()->is_ready()) {
isolate->ThrowException(v8::Exception::Error(mate::StringToV8( isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate, "Cannot create Tray before app is ready"))); isolate, "Cannot create Tray before app is ready")));
@ -94,29 +96,38 @@ void Tray::OnDragEnded() {
Emit("drag-end"); Emit("drag-end");
} }
void Tray::SetImage(mate::Arguments* args, const gfx::Image& image) { void Tray::SetImage(v8::Isolate* isolate, mate::Handle<NativeImage> image) {
tray_icon_->SetImage(image); #if defined(OS_WIN)
tray_icon_->SetImage(image->GetHICON(GetSystemMetrics(SM_CXSMICON)));
#else
tray_icon_->SetImage(image->image());
#endif
} }
void Tray::SetPressedImage(mate::Arguments* args, const gfx::Image& image) { void Tray::SetPressedImage(v8::Isolate* isolate,
tray_icon_->SetPressedImage(image); mate::Handle<NativeImage> image) {
#if defined(OS_WIN)
tray_icon_->SetPressedImage(image->GetHICON(GetSystemMetrics(SM_CXSMICON)));
#else
tray_icon_->SetPressedImage(image->image());
#endif
} }
void Tray::SetToolTip(mate::Arguments* args, const std::string& tool_tip) { void Tray::SetToolTip(const std::string& tool_tip) {
tray_icon_->SetToolTip(tool_tip); tray_icon_->SetToolTip(tool_tip);
} }
void Tray::SetTitle(mate::Arguments* args, const std::string& title) { void Tray::SetTitle(const std::string& title) {
tray_icon_->SetTitle(title); tray_icon_->SetTitle(title);
} }
void Tray::SetHighlightMode(mate::Arguments* args, bool highlight) { void Tray::SetHighlightMode(bool highlight) {
tray_icon_->SetHighlightMode(highlight); tray_icon_->SetHighlightMode(highlight);
} }
void Tray::DisplayBalloon(mate::Arguments* args, void Tray::DisplayBalloon(mate::Arguments* args,
const mate::Dictionary& options) { const mate::Dictionary& options) {
gfx::Image icon; mate::Handle<NativeImage> icon;
options.Get("icon", &icon); options.Get("icon", &icon);
base::string16 title, content; base::string16 title, content;
if (!options.Get("title", &title) || if (!options.Get("title", &title) ||
@ -125,7 +136,14 @@ void Tray::DisplayBalloon(mate::Arguments* args,
return; return;
} }
tray_icon_->DisplayBalloon(icon, title, content); #if defined(OS_WIN)
tray_icon_->DisplayBalloon(
icon.IsEmpty() ? NULL : icon->GetHICON(GetSystemMetrics(SM_CXSMICON)),
title, content);
#else
tray_icon_->DisplayBalloon(
icon.IsEmpty() ? gfx::Image() : icon->image(), title, content);
#endif
} }
void Tray::PopUpContextMenu(mate::Arguments* args) { void Tray::PopUpContextMenu(mate::Arguments* args) {
@ -136,7 +154,8 @@ void Tray::PopUpContextMenu(mate::Arguments* args) {
tray_icon_->PopUpContextMenu(pos, menu.IsEmpty() ? nullptr : menu->model()); tray_icon_->PopUpContextMenu(pos, menu.IsEmpty() ? nullptr : menu->model());
} }
void Tray::SetContextMenu(mate::Arguments* args, Menu* menu) { void Tray::SetContextMenu(v8::Isolate* isolate, mate::Handle<Menu> menu) {
menu_.Reset(isolate, menu.ToV8());
tray_icon_->SetContextMenu(menu->model()); tray_icon_->SetContextMenu(menu->model());
} }
@ -162,7 +181,7 @@ void Tray::BuildPrototype(v8::Isolate* isolate,
.SetMethod("setHighlightMode", &Tray::SetHighlightMode) .SetMethod("setHighlightMode", &Tray::SetHighlightMode)
.SetMethod("displayBalloon", &Tray::DisplayBalloon) .SetMethod("displayBalloon", &Tray::DisplayBalloon)
.SetMethod("popUpContextMenu", &Tray::PopUpContextMenu) .SetMethod("popUpContextMenu", &Tray::PopUpContextMenu)
.SetMethod("_setContextMenu", &Tray::SetContextMenu); .SetMethod("setContextMenu", &Tray::SetContextMenu);
} }
} // namespace api } // namespace api

View file

@ -11,6 +11,7 @@
#include "atom/browser/api/trackable_object.h" #include "atom/browser/api/trackable_object.h"
#include "atom/browser/ui/tray_icon_observer.h" #include "atom/browser/ui/tray_icon_observer.h"
#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_ptr.h"
#include "native_mate/handle.h"
namespace gfx { namespace gfx {
class Image; class Image;
@ -28,18 +29,19 @@ class TrayIcon;
namespace api { namespace api {
class Menu; class Menu;
class NativeImage;
class Tray : public mate::TrackableObject<Tray>, class Tray : public mate::TrackableObject<Tray>,
public TrayIconObserver { public TrayIconObserver {
public: public:
static mate::WrappableBase* New( static mate::WrappableBase* New(
v8::Isolate* isolate, const gfx::Image& image); v8::Isolate* isolate, mate::Handle<NativeImage> image);
static void BuildPrototype(v8::Isolate* isolate, static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> prototype); v8::Local<v8::ObjectTemplate> prototype);
protected: protected:
Tray(v8::Isolate* isolate, const gfx::Image& image); Tray(v8::Isolate* isolate, mate::Handle<NativeImage> image);
~Tray() override; ~Tray() override;
// TrayIconObserver: // TrayIconObserver:
@ -55,19 +57,20 @@ class Tray : public mate::TrackableObject<Tray>,
void OnDragExited() override; void OnDragExited() override;
void OnDragEnded() override; void OnDragEnded() override;
void SetImage(mate::Arguments* args, const gfx::Image& image); void SetImage(v8::Isolate* isolate, mate::Handle<NativeImage> image);
void SetPressedImage(mate::Arguments* args, const gfx::Image& image); void SetPressedImage(v8::Isolate* isolate, mate::Handle<NativeImage> image);
void SetToolTip(mate::Arguments* args, const std::string& tool_tip); void SetToolTip(const std::string& tool_tip);
void SetTitle(mate::Arguments* args, const std::string& title); void SetTitle(const std::string& title);
void SetHighlightMode(mate::Arguments* args, bool highlight); void SetHighlightMode(bool highlight);
void DisplayBalloon(mate::Arguments* args, const mate::Dictionary& options); void DisplayBalloon(mate::Arguments* args, const mate::Dictionary& options);
void PopUpContextMenu(mate::Arguments* args); void PopUpContextMenu(mate::Arguments* args);
void SetContextMenu(mate::Arguments* args, Menu* menu); void SetContextMenu(v8::Isolate* isolate, mate::Handle<Menu> menu);
private: private:
v8::Local<v8::Object> ModifiersToObject(v8::Isolate* isolate, int modifiers); v8::Local<v8::Object> ModifiersToObject(v8::Isolate* isolate, int modifiers);
scoped_ptr<TrayIcon> tray_icon_; v8::Global<v8::Object> menu_;
std::unique_ptr<TrayIcon> tray_icon_;
DISALLOW_COPY_AND_ASSIGN(Tray); DISALLOW_COPY_AND_ASSIGN(Tray);
}; };

View file

@ -14,6 +14,7 @@
#include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/atom_security_state_model_client.h" #include "atom/browser/atom_security_state_model_client.h"
#include "atom/browser/lib/bluetooth_chooser.h"
#include "atom/browser/native_window.h" #include "atom/browser/native_window.h"
#include "atom/browser/net/atom_network_delegate.h" #include "atom/browser/net/atom_network_delegate.h"
#include "atom/browser/web_contents_permission_helper.h" #include "atom/browser/web_contents_permission_helper.h"
@ -63,6 +64,7 @@
#include "net/url_request/static_http_user_agent_settings.h" #include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context.h"
#include "third_party/WebKit/public/web/WebInputEvent.h" #include "third_party/WebKit/public/web/WebInputEvent.h"
#include "third_party/WebKit/public/web/WebFindOptions.h"
#include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util.h"
#include "atom/common/node_includes.h" #include "atom/common/node_includes.h"
@ -144,7 +146,7 @@ struct Converter<net::HttpResponseHeaders*> {
net::HttpResponseHeaders* headers) { net::HttpResponseHeaders* headers) {
base::DictionaryValue response_headers; base::DictionaryValue response_headers;
if (headers) { if (headers) {
void* iter = nullptr; size_t iter = 0;
std::string key; std::string key;
std::string value; std::string value;
while (headers->EnumerateHeaderLines(&iter, &key, &value)) { while (headers->EnumerateHeaderLines(&iter, &key, &value)) {
@ -154,7 +156,7 @@ struct Converter<net::HttpResponseHeaders*> {
if (response_headers.GetList(key, &values)) if (response_headers.GetList(key, &values))
values->AppendString(value); values->AppendString(value);
} else { } else {
scoped_ptr<base::ListValue> values(new base::ListValue()); std::unique_ptr<base::ListValue> values(new base::ListValue());
values->AppendString(value); values->AppendString(value);
response_headers.Set(key, std::move(values)); response_headers.Set(key, std::move(values));
} }
@ -260,8 +262,9 @@ WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents; content::WebContents* web_contents;
if (is_guest) { if (is_guest) {
content::SiteInstance* site_instance = content::SiteInstance::CreateForURL( scoped_refptr<content::SiteInstance> site_instance =
session->browser_context(), GURL("chrome-guest://fake-host")); content::SiteInstance::CreateForURL(
session->browser_context(), GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params( content::WebContents::CreateParams params(
session->browser_context(), site_instance); session->browser_context(), site_instance);
guest_delegate_.reset(new WebViewGuestDelegate); guest_delegate_.reset(new WebViewGuestDelegate);
@ -273,7 +276,7 @@ WebContents::WebContents(v8::Isolate* isolate,
} }
Observe(web_contents); Observe(web_contents);
InitWithWebContents(web_contents); InitWithWebContents(web_contents, session->browser_context());
managed_web_contents()->GetView()->SetDelegate(this); managed_web_contents()->GetView()->SetDelegate(this);
@ -378,7 +381,7 @@ void WebContents::MoveContents(content::WebContents* source,
void WebContents::CloseContents(content::WebContents* source) { void WebContents::CloseContents(content::WebContents* source) {
Emit("close"); Emit("close");
if (type_ == BROWSER_WINDOW) if (type_ == BROWSER_WINDOW && owner_window())
owner_window()->CloseContents(source); owner_window()->CloseContents(source);
} }
@ -393,14 +396,12 @@ bool WebContents::IsPopupOrPanel(const content::WebContents* source) const {
void WebContents::HandleKeyboardEvent( void WebContents::HandleKeyboardEvent(
content::WebContents* source, content::WebContents* source,
const content::NativeWebKeyboardEvent& event) { const content::NativeWebKeyboardEvent& event) {
if (event.windowsKeyCode == ui::VKEY_ESCAPE && is_html_fullscreen()) { if (type_ == WEB_VIEW && embedder_) {
// Escape exits tabbed fullscreen mode.
ExitFullscreenModeForTab(source);
} else if (type_ == BROWSER_WINDOW) {
owner_window()->HandleKeyboardEvent(source, event);
} else if (type_ == WEB_VIEW && guest_delegate_) {
// Send the unhandled keyboard events back to the embedder. // Send the unhandled keyboard events back to the embedder.
guest_delegate_->HandleKeyboardEvent(source, event); embedder_->HandleKeyboardEvent(source, event);
} else {
// Go to the default keyboard handling.
CommonWebContentsDelegate::HandleKeyboardEvent(source, event);
} }
} }
@ -429,13 +430,13 @@ void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
void WebContents::RendererUnresponsive(content::WebContents* source) { void WebContents::RendererUnresponsive(content::WebContents* source) {
Emit("unresponsive"); Emit("unresponsive");
if (type_ == BROWSER_WINDOW) if (type_ == BROWSER_WINDOW && owner_window())
owner_window()->RendererUnresponsive(source); owner_window()->RendererUnresponsive(source);
} }
void WebContents::RendererResponsive(content::WebContents* source) { void WebContents::RendererResponsive(content::WebContents* source) {
Emit("responsive"); Emit("responsive");
if (type_ == BROWSER_WINDOW) if (type_ == BROWSER_WINDOW && owner_window())
owner_window()->RendererResponsive(source); owner_window()->RendererResponsive(source);
} }
@ -504,6 +505,14 @@ void WebContents::RequestToLockMouse(
permission_helper->RequestPointerLockPermission(user_gesture); permission_helper->RequestPointerLockPermission(user_gesture);
} }
std::unique_ptr<content::BluetoothChooser> WebContents::RunBluetoothChooser(
content::RenderFrameHost* frame,
const content::BluetoothChooser::EventHandler& event_handler) {
std::unique_ptr<BluetoothChooser> bluetooth_chooser(
new BluetoothChooser(this, event_handler));
return std::move(bluetooth_chooser);
}
void WebContents::BeforeUnloadFired(const base::TimeTicks& proceed_time) { void WebContents::BeforeUnloadFired(const base::TimeTicks& proceed_time) {
// Do nothing, we override this method just to avoid compilation error since // Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired. // there are two virtual functions named BeforeUnloadFired.
@ -655,6 +664,11 @@ void WebContents::DevToolsOpened() {
isolate(), managed_web_contents()->GetDevToolsWebContents()); isolate(), managed_web_contents()->GetDevToolsWebContents());
devtools_web_contents_.Reset(isolate(), handle.ToV8()); devtools_web_contents_.Reset(isolate(), handle.ToV8());
// Set inspected tabID.
base::FundamentalValue tab_id(ID());
managed_web_contents()->CallClientFunction(
"DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr);
// Inherit owner window in devtools. // Inherit owner window in devtools.
if (owner_window()) if (owner_window())
handle->SetOwnerWindow(managed_web_contents()->GetDevToolsWebContents(), handle->SetOwnerWindow(managed_web_contents()->GetDevToolsWebContents(),
@ -865,7 +879,7 @@ void WebContents::OpenDevTools(mate::Arguments* args) {
return; return;
std::string state; std::string state;
if (type_ == WEB_VIEW) { if (type_ == WEB_VIEW || !owner_window()) {
state = "detach"; state = "detach";
} else if (args && args->Length() == 1) { } else if (args && args->Length() == 1) {
bool detach = false; bool detach = false;
@ -1083,9 +1097,10 @@ void WebContents::TabTraverse(bool reverse) {
web_contents()->FocusThroughTabTraversal(reverse); web_contents()->FocusThroughTabTraversal(reverse);
} }
bool WebContents::SendIPCMessage(const base::string16& channel, bool WebContents::SendIPCMessage(bool all_frames,
const base::string16& channel,
const base::ListValue& args) { const base::ListValue& args) {
return Send(new AtomViewMsg_Message(routing_id(), channel, args)); return Send(new AtomViewMsg_Message(routing_id(), all_frames, channel, args));
} }
void WebContents::SendInputEvent(v8::Isolate* isolate, void WebContents::SendInputEvent(v8::Isolate* isolate,
@ -1126,7 +1141,7 @@ void WebContents::BeginFrameSubscription(
const FrameSubscriber::FrameCaptureCallback& callback) { const FrameSubscriber::FrameCaptureCallback& callback) {
const auto view = web_contents()->GetRenderWidgetHostView(); const auto view = web_contents()->GetRenderWidgetHostView();
if (view) { if (view) {
scoped_ptr<FrameSubscriber> frame_subscriber(new FrameSubscriber( std::unique_ptr<FrameSubscriber> frame_subscriber(new FrameSubscriber(
isolate(), view, callback)); isolate(), view, callback));
view->BeginFrameSubscription(std::move(frame_subscriber)); view->BeginFrameSubscription(std::move(frame_subscriber));
} }
@ -1173,6 +1188,10 @@ v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow() {
return v8::Null(isolate()); return v8::Null(isolate());
} }
int32_t WebContents::ID() const {
return weak_map_id();
}
v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
return v8::Local<v8::Value>::New(isolate, session_); return v8::Local<v8::Value>::New(isolate, session_);
} }
@ -1265,6 +1284,7 @@ void WebContents::BuildPrototype(v8::Isolate* isolate,
.SetMethod("_printToPDF", &WebContents::PrintToPDF) .SetMethod("_printToPDF", &WebContents::PrintToPDF)
.SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
.SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
.SetProperty("id", &WebContents::ID)
.SetProperty("session", &WebContents::Session) .SetProperty("session", &WebContents::Session)
.SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("hostWebContents", &WebContents::HostWebContents)
.SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
@ -1328,6 +1348,8 @@ void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
mate::Dictionary dict(isolate, exports); mate::Dictionary dict(isolate, exports);
dict.SetMethod("create", &atom::api::WebContents::Create); dict.SetMethod("create", &atom::api::WebContents::Create);
dict.SetMethod("_setWrapWebContents", &atom::api::SetWrapWebContents); dict.SetMethod("_setWrapWebContents", &atom::api::SetWrapWebContents);
dict.SetMethod("fromId",
&mate::TrackableObject<atom::api::WebContents>::FromWeakMapID);
} }
} // namespace } // namespace

View file

@ -122,7 +122,8 @@ class WebContents : public mate::TrackableObject<WebContents>,
void TabTraverse(bool reverse); void TabTraverse(bool reverse);
// Send messages to browser. // Send messages to browser.
bool SendIPCMessage(const base::string16& channel, bool SendIPCMessage(bool all_frames,
const base::string16& channel,
const base::ListValue& args); const base::ListValue& args);
// Send WebInputEvent to the page. // Send WebInputEvent to the page.
@ -154,6 +155,7 @@ class WebContents : public mate::TrackableObject<WebContents>,
v8::Local<v8::Value> GetOwnerBrowserWindow(); v8::Local<v8::Value> GetOwnerBrowserWindow();
// Properties. // Properties.
int32_t ID() const;
v8::Local<v8::Value> Session(v8::Isolate* isolate); v8::Local<v8::Value> Session(v8::Isolate* isolate);
content::WebContents* HostWebContents(); content::WebContents* HostWebContents();
v8::Local<v8::Value> DevToolsWebContents(v8::Isolate* isolate); v8::Local<v8::Value> DevToolsWebContents(v8::Isolate* isolate);
@ -209,6 +211,9 @@ class WebContents : public mate::TrackableObject<WebContents>,
content::WebContents* web_contents, content::WebContents* web_contents,
bool user_gesture, bool user_gesture,
bool last_unlocked_by_target) override; bool last_unlocked_by_target) override;
std::unique_ptr<content::BluetoothChooser> RunBluetoothChooser(
content::RenderFrameHost* frame,
const content::BluetoothChooser::EventHandler& handler) override;
// content::WebContentsObserver: // content::WebContentsObserver:
void BeforeUnloadFired(const base::TimeTicks& proceed_time) override; void BeforeUnloadFired(const base::TimeTicks& proceed_time) override;
@ -288,7 +293,7 @@ class WebContents : public mate::TrackableObject<WebContents>,
v8::Global<v8::Value> devtools_web_contents_; v8::Global<v8::Value> devtools_web_contents_;
v8::Global<v8::Value> debugger_; v8::Global<v8::Value> debugger_;
scoped_ptr<WebViewGuestDelegate> guest_delegate_; std::unique_ptr<WebViewGuestDelegate> guest_delegate_;
// The host webcontents that may contain this webcontents. // The host webcontents that may contain this webcontents.
WebContents* embedder_; WebContents* embedder_;

View file

@ -14,22 +14,12 @@ using atom::WebContentsPreferences;
namespace { namespace {
atom::WebViewManager* GetWebViewManager(content::WebContents* web_contents) {
auto context = web_contents->GetBrowserContext();
if (context) {
auto manager = context->GetGuestManager();
return static_cast<atom::WebViewManager*>(manager);
} else {
return nullptr;
}
}
void AddGuest(int guest_instance_id, void AddGuest(int guest_instance_id,
int element_instance_id, int element_instance_id,
content::WebContents* embedder, content::WebContents* embedder,
content::WebContents* guest_web_contents, content::WebContents* guest_web_contents,
const base::DictionaryValue& options) { const base::DictionaryValue& options) {
auto manager = GetWebViewManager(embedder); auto manager = atom::WebViewManager::GetWebViewManager(embedder);
if (manager) if (manager)
manager->AddGuest(guest_instance_id, element_instance_id, embedder, manager->AddGuest(guest_instance_id, element_instance_id, embedder,
guest_web_contents); guest_web_contents);
@ -38,7 +28,7 @@ void AddGuest(int guest_instance_id,
} }
void RemoveGuest(content::WebContents* embedder, int guest_instance_id) { void RemoveGuest(content::WebContents* embedder, int guest_instance_id) {
auto manager = GetWebViewManager(embedder); auto manager = atom::WebViewManager::GetWebViewManager(embedder);
if (manager) if (manager)
manager->RemoveGuest(guest_instance_id); manager->RemoveGuest(guest_instance_id);
} }

View file

@ -21,8 +21,11 @@
#include "native_mate/dictionary.h" #include "native_mate/dictionary.h"
#include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect.h"
#if defined(OS_WIN) #if defined(TOOLKIT_VIEWS)
#include "atom/browser/native_window_views.h" #include "atom/browser/native_window_views.h"
#endif
#if defined(OS_WIN)
#include "atom/browser/ui/win/taskbar_host.h" #include "atom/browser/ui/win/taskbar_host.h"
#endif #endif
@ -52,11 +55,6 @@ namespace api {
namespace { namespace {
// This function is implemented in JavaScript
using DeprecatedOptionsCheckCallback =
base::Callback<std::string(v8::Local<v8::Value>)>;
DeprecatedOptionsCheckCallback g_deprecated_options_check;
void OnCapturePageDone( void OnCapturePageDone(
v8::Isolate* isolate, v8::Isolate* isolate,
const base::Callback<void(const gfx::Image&)>& callback, const base::Callback<void(const gfx::Image&)>& callback,
@ -66,52 +64,6 @@ void OnCapturePageDone(
callback.Run(gfx::Image::CreateFrom1xBitmap(bitmap)); callback.Run(gfx::Image::CreateFrom1xBitmap(bitmap));
} }
// Converts min-width to minWidth, returns false if no conversion is needed.
bool TranslateOldKey(const std::string& key, std::string* new_key) {
if (key.find('-') == std::string::npos)
return false;
new_key->reserve(key.size());
bool next_upper_case = false;
for (char c : key) {
if (c == '-') {
next_upper_case = true;
} else if (next_upper_case) {
new_key->push_back(base::ToUpperASCII(c));
next_upper_case = false;
} else {
new_key->push_back(c);
}
}
return true;
}
// Converts min-width to minWidth recursively in the dictionary.
void TranslateOldOptions(v8::Isolate* isolate, v8::Local<v8::Object> options) {
auto context = isolate->GetCurrentContext();
auto maybe_keys = options->GetOwnPropertyNames(context);
if (maybe_keys.IsEmpty())
return;
std::vector<std::string> keys;
if (!mate::ConvertFromV8(isolate, maybe_keys.ToLocalChecked(), &keys))
return;
mate::Dictionary dict(isolate, options);
for (const auto& key : keys) {
v8::Local<v8::Value> value;
if (!dict.Get(key, &value)) // Shouldn't happen, but guard it anyway.
continue;
// Go recursively.
v8::Local<v8::Object> sub_options;
if (mate::ConvertFromV8(isolate, value, &sub_options))
TranslateOldOptions(isolate, sub_options);
// Translate key.
std::string new_key;
if (TranslateOldKey(key, &new_key)) {
dict.Set(new_key, value);
dict.Delete(key);
}
}
}
// Converts binary data to Buffer. // Converts binary data to Buffer.
v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) { v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) {
auto buffer = node::Buffer::Copy(isolate, static_cast<char*>(val), size); auto buffer = node::Buffer::Copy(isolate, static_cast<char*>(val), size);
@ -125,23 +77,12 @@ v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) {
Window::Window(v8::Isolate* isolate, const mate::Dictionary& options) { Window::Window(v8::Isolate* isolate, const mate::Dictionary& options) {
// Be compatible with old style field names like min-width.
TranslateOldOptions(isolate, options.GetHandle());
// Use options.webPreferences to create WebContents. // Use options.webPreferences to create WebContents.
mate::Dictionary web_preferences = mate::Dictionary::CreateEmpty(isolate); mate::Dictionary web_preferences = mate::Dictionary::CreateEmpty(isolate);
options.Get(options::kWebPreferences, &web_preferences); options.Get(options::kWebPreferences, &web_preferences);
// Be compatible with old options which are now in web_preferences.
v8::Local<v8::Value> value;
if (options.Get(options::kNodeIntegration, &value))
web_preferences.Set(options::kNodeIntegration, value);
if (options.Get(options::kPreloadScript, &value))
web_preferences.Set(options::kPreloadScript, value);
if (options.Get(options::kZoomFactor, &value))
web_preferences.Set(options::kZoomFactor, value);
// Copy the backgroundColor to webContents. // Copy the backgroundColor to webContents.
v8::Local<v8::Value> value;
if (options.Get(options::kBackgroundColor, &value)) if (options.Get(options::kBackgroundColor, &value))
web_preferences.Set(options::kBackgroundColor, value); web_preferences.Set(options::kBackgroundColor, value);
@ -161,6 +102,13 @@ Window::Window(v8::Isolate* isolate, const mate::Dictionary& options) {
window_->InitFromOptions(options); window_->InitFromOptions(options);
window_->AddObserver(this); window_->AddObserver(this);
AttachAsUserData(window_.get()); AttachAsUserData(window_.get());
#if defined(TOOLKIT_VIEWS)
// Sets the window icon.
mate::Handle<NativeImage> icon;
if (options.Get(options::kIcon, &icon))
SetIcon(icon);
#endif
} }
Window::~Window() { Window::~Window() {
@ -304,13 +252,6 @@ mate::WrappableBase* Window::New(v8::Isolate* isolate, mate::Arguments* args) {
options = mate::Dictionary::CreateEmpty(isolate); options = mate::Dictionary::CreateEmpty(isolate);
} }
std::string deprecation_message = g_deprecated_options_check.Run(
options.GetHandle());
if (deprecation_message.length() > 0) {
args->ThrowError(deprecation_message);
return nullptr;
}
return new Window(isolate, options); return new Window(isolate, options);
} }
@ -440,8 +381,10 @@ std::vector<int> Window::GetMaximumSize() {
return result; return result;
} }
void Window::SetSheetOffset(double offset) { void Window::SetSheetOffset(double offsetY, mate::Arguments* args) {
window_->SetSheetOffset(offset); double offsetX = 0.0;
args->GetNext(&offsetX);
window_->SetSheetOffset(offsetX, offsetY);
} }
void Window::SetResizable(bool resizable) { void Window::SetResizable(bool resizable) {
@ -686,6 +629,19 @@ void Window::ShowDefinitionForSelection() {
} }
#endif #endif
#if defined(TOOLKIT_VIEWS)
void Window::SetIcon(mate::Handle<NativeImage> icon) {
#if defined(OS_WIN)
static_cast<NativeWindowViews*>(window_.get())->SetIcon(
icon->GetHICON(GetSystemMetrics(SM_CXSMICON)),
icon->GetHICON(GetSystemMetrics(SM_CXICON)));
#elif defined(USE_X11)
static_cast<NativeWindowViews*>(window_.get())->SetIcon(
icon->image().AsImageSkia());
#endif
}
#endif
void Window::SetAspectRatio(double aspect_ratio, mate::Arguments* args) { void Window::SetAspectRatio(double aspect_ratio, mate::Arguments* args) {
gfx::Size extra_size; gfx::Size extra_size;
args->GetNext(&extra_size); args->GetNext(&extra_size);
@ -807,6 +763,9 @@ void Window::BuildPrototype(v8::Isolate* isolate,
#if defined(OS_MACOSX) #if defined(OS_MACOSX)
.SetMethod("showDefinitionForSelection", .SetMethod("showDefinitionForSelection",
&Window::ShowDefinitionForSelection) &Window::ShowDefinitionForSelection)
#endif
#if defined(TOOLKIT_VIEWS)
.SetMethod("setIcon", &Window::SetIcon)
#endif #endif
.SetProperty("id", &Window::ID) .SetProperty("id", &Window::ID)
.SetProperty("webContents", &Window::WebContents); .SetProperty("webContents", &Window::WebContents);
@ -822,10 +781,6 @@ v8::Local<v8::Value> Window::From(v8::Isolate* isolate,
return v8::Null(isolate); return v8::Null(isolate);
} }
void SetDeprecatedOptionsCheck(const DeprecatedOptionsCheckCallback& callback) {
g_deprecated_options_check = callback;
}
} // namespace api } // namespace api
} // namespace atom } // namespace atom
@ -848,8 +803,6 @@ void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
mate::Dictionary dict(isolate, exports); mate::Dictionary dict(isolate, exports);
dict.Set("BrowserWindow", browser_window); dict.Set("BrowserWindow", browser_window);
dict.SetMethod("_setDeprecatedOptionsCheck",
&atom::api::SetDeprecatedOptionsCheck);
} }
} // namespace } // namespace

View file

@ -14,6 +14,7 @@
#include "atom/browser/api/trackable_object.h" #include "atom/browser/api/trackable_object.h"
#include "atom/browser/native_window.h" #include "atom/browser/native_window.h"
#include "atom/browser/native_window_observer.h" #include "atom/browser/native_window_observer.h"
#include "atom/common/api/atom_api_native_image.h"
#include "native_mate/handle.h" #include "native_mate/handle.h"
class GURL; class GURL;
@ -110,7 +111,7 @@ class Window : public mate::TrackableObject<Window>,
std::vector<int> GetMinimumSize(); std::vector<int> GetMinimumSize();
void SetMaximumSize(int width, int height); void SetMaximumSize(int width, int height);
std::vector<int> GetMaximumSize(); std::vector<int> GetMaximumSize();
void SetSheetOffset(double offset); void SetSheetOffset(double offsetY, mate::Arguments* args);
void SetResizable(bool resizable); void SetResizable(bool resizable);
bool IsResizable(); bool IsResizable();
void SetMovable(bool movable); void SetMovable(bool movable);
@ -172,6 +173,10 @@ class Window : public mate::TrackableObject<Window>,
void ShowDefinitionForSelection(); void ShowDefinitionForSelection();
#endif #endif
#if defined(TOOLKIT_VIEWS)
void SetIcon(mate::Handle<NativeImage> icon);
#endif
void SetVisibleOnAllWorkspaces(bool visible); void SetVisibleOnAllWorkspaces(bool visible);
bool IsVisibleOnAllWorkspaces(); bool IsVisibleOnAllWorkspaces();
@ -188,7 +193,7 @@ class Window : public mate::TrackableObject<Window>,
api::WebContents* api_web_contents_; api::WebContents* api_web_contents_;
scoped_ptr<NativeWindow> window_; std::unique_ptr<NativeWindow> window_;
DISALLOW_COPY_AND_ASSIGN(Window); DISALLOW_COPY_AND_ASSIGN(Window);
}; };

View file

@ -45,7 +45,10 @@ bool Event::SendReply(const base::string16& json) {
return false; return false;
AtomViewHostMsg_Message_Sync::WriteReplyParams(message_, json); AtomViewHostMsg_Message_Sync::WriteReplyParams(message_, json);
return sender_->Send(message_); bool success = sender_->Send(message_);
message_ = NULL;
sender_ = NULL;
return success;
} }
// static // static

View file

@ -8,7 +8,7 @@
#include <vector> #include <vector>
#include "atom/browser/api/event_emitter.h" #include "atom/browser/api/event_emitter.h"
#include "atom/common/id_weak_map.h" #include "atom/common/key_weak_map.h"
#include "base/bind.h" #include "base/bind.h"
#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h" #include "base/memory/weak_ptr.h"
@ -113,21 +113,26 @@ class TrackableObject : public TrackableObjectBase,
void AfterInit(v8::Isolate* isolate) override { void AfterInit(v8::Isolate* isolate) override {
if (!weak_map_) { if (!weak_map_) {
weak_map_.reset(new atom::IDWeakMap); weak_map_ = new atom::KeyWeakMap<int32_t>;
} }
weak_map_id_ = weak_map_->Add(isolate, Wrappable<T>::GetWrapper()); weak_map_id_ = ++next_id_;
weak_map_->Set(isolate, weak_map_id_, Wrappable<T>::GetWrapper());
if (wrapped_) if (wrapped_)
AttachAsUserData(wrapped_); AttachAsUserData(wrapped_);
} }
private: private:
static scoped_ptr<atom::IDWeakMap> weak_map_; static int32_t next_id_;
static atom::KeyWeakMap<int32_t>* weak_map_; // leaked on purpose
DISALLOW_COPY_AND_ASSIGN(TrackableObject); DISALLOW_COPY_AND_ASSIGN(TrackableObject);
}; };
template<typename T> template<typename T>
scoped_ptr<atom::IDWeakMap> TrackableObject<T>::weak_map_; int32_t TrackableObject<T>::next_id_ = 0;
template<typename T>
atom::KeyWeakMap<int32_t>* TrackableObject<T>::weak_map_ = nullptr;
} // namespace mate } // namespace mate

View file

@ -32,18 +32,18 @@ AtomAccessTokenStore::~AtomAccessTokenStore() {
} }
void AtomAccessTokenStore::LoadAccessTokens( void AtomAccessTokenStore::LoadAccessTokens(
const LoadAccessTokensCallbackType& callback) { const LoadAccessTokensCallback& callback) {
AccessTokenSet access_token_set; AccessTokenMap access_token_map;
// Equivelent to access_token_set[kGeolocationProviderURL]. // Equivelent to access_token_map[kGeolocationProviderURL].
// Somehow base::string16 is causing compilation errors when used in a pair // Somehow base::string16 is causing compilation errors when used in a pair
// of std::map on Linux, this can work around it. // of std::map on Linux, this can work around it.
std::pair<GURL, base::string16> token_pair; std::pair<GURL, base::string16> token_pair;
token_pair.first = GURL(kGeolocationProviderURL); token_pair.first = GURL(kGeolocationProviderURL);
access_token_set.insert(token_pair); access_token_map.insert(token_pair);
auto browser_context = AtomBrowserMainParts::Get()->browser_context(); auto browser_context = AtomBrowserMainParts::Get()->browser_context();
callback.Run(access_token_set, browser_context->url_request_context_getter()); callback.Run(access_token_map, browser_context->url_request_context_getter());
} }
void AtomAccessTokenStore::SaveAccessToken(const GURL& server_url, void AtomAccessTokenStore::SaveAccessToken(const GURL& server_url,

View file

@ -18,7 +18,7 @@ class AtomAccessTokenStore : public content::AccessTokenStore {
// content::AccessTokenStore: // content::AccessTokenStore:
void LoadAccessTokens( void LoadAccessTokens(
const LoadAccessTokensCallbackType& callback) override; const LoadAccessTokensCallback& callback) override;
void SaveAccessToken(const GURL& server_url, void SaveAccessToken(const GURL& server_url,
const base::string16& access_token) override; const base::string16& access_token) override;

View file

@ -49,11 +49,12 @@ namespace {
// Next navigation should not restart renderer process. // Next navigation should not restart renderer process.
bool g_suppress_renderer_process_restart = false; bool g_suppress_renderer_process_restart = false;
// Custom schemes to be registered to standard.
std::string g_custom_schemes = "";
// Custom schemes to be registered to handle service worker. // Custom schemes to be registered to handle service worker.
std::string g_custom_service_worker_schemes = ""; std::string g_custom_service_worker_schemes = "";
void Noop(scoped_refptr<content::SiteInstance>) {
}
} // namespace } // namespace
// static // static
@ -61,11 +62,6 @@ void AtomBrowserClient::SuppressRendererProcessRestartForOnce() {
g_suppress_renderer_process_restart = true; g_suppress_renderer_process_restart = true;
} }
void AtomBrowserClient::SetCustomSchemes(
const std::vector<std::string>& schemes) {
g_custom_schemes = base::JoinString(schemes, ",");
}
void AtomBrowserClient::SetCustomServiceWorkerSchemes( void AtomBrowserClient::SetCustomServiceWorkerSchemes(
const std::vector<std::string>& schemes) { const std::vector<std::string>& schemes) {
g_custom_service_worker_schemes = base::JoinString(schemes, ","); g_custom_service_worker_schemes = base::JoinString(schemes, ",");
@ -77,6 +73,17 @@ AtomBrowserClient::AtomBrowserClient() : delegate_(nullptr) {
AtomBrowserClient::~AtomBrowserClient() { AtomBrowserClient::~AtomBrowserClient() {
} }
content::WebContents* AtomBrowserClient::GetWebContentsFromProcessID(
int process_id) {
// If the process is a pending process, we should use the old one.
if (ContainsKey(pending_processes_, process_id))
process_id = pending_processes_[process_id];
// Certain render process will be created with no associated render view,
// for example: ServiceWorker.
return WebContentsPreferences::GetWebContentsFromProcessID(process_id);
}
void AtomBrowserClient::RenderProcessWillLaunch( void AtomBrowserClient::RenderProcessWillLaunch(
content::RenderProcessHost* host) { content::RenderProcessHost* host) {
int process_id = host->GetID(); int process_id = host->GetID();
@ -136,7 +143,16 @@ void AtomBrowserClient::OverrideSiteInstanceForNavigation(
if (url.SchemeIs(url::kJavaScriptScheme)) if (url.SchemeIs(url::kJavaScriptScheme))
return; return;
*new_instance = content::SiteInstance::CreateForURL(browser_context, url); scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(browser_context, url);
*new_instance = site_instance.get();
// Make sure the |site_instance| is not freed when this function returns.
// FIXME(zcbenz): We should adjust OverrideSiteInstanceForNavigation's
// interface to solve this.
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(&Noop, base::RetainedRef(site_instance)));
// Remember the original renderer process of the pending renderer process. // Remember the original renderer process of the pending renderer process.
auto current_process = current_instance->GetProcess(); auto current_process = current_instance->GetProcess();
@ -153,11 +169,6 @@ void AtomBrowserClient::AppendExtraCommandLineSwitches(
if (process_type != "renderer") if (process_type != "renderer")
return; return;
// The registered standard schemes.
if (!g_custom_schemes.empty())
command_line->AppendSwitchASCII(switches::kRegisterStandardSchemes,
g_custom_schemes);
// The registered service worker schemes. // The registered service worker schemes.
if (!g_custom_service_worker_schemes.empty()) if (!g_custom_service_worker_schemes.empty())
command_line->AppendSwitchASCII(switches::kRegisterServiceWorkerSchemes, command_line->AppendSwitchASCII(switches::kRegisterServiceWorkerSchemes,
@ -172,14 +183,7 @@ void AtomBrowserClient::AppendExtraCommandLineSwitches(
} }
#endif #endif
// If the process is a pending process, we should use the old one. content::WebContents* web_contents = GetWebContentsFromProcessID(process_id);
if (ContainsKey(pending_processes_, process_id))
process_id = pending_processes_[process_id];
// Certain render process will be created with no associated render view,
// for example: ServiceWorker.
content::WebContents* web_contents =
WebContentsPreferences::GetWebContentsFromProcessID(process_id);
if (!web_contents) if (!web_contents)
return; return;
@ -220,7 +224,7 @@ void AtomBrowserClient::AllowCertificateError(
void AtomBrowserClient::SelectClientCertificate( void AtomBrowserClient::SelectClientCertificate(
content::WebContents* web_contents, content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info, net::SSLCertRequestInfo* cert_request_info,
scoped_ptr<content::ClientCertificateDelegate> delegate) { std::unique_ptr<content::ClientCertificateDelegate> delegate) {
if (!cert_request_info->client_certs.empty() && delegate_) { if (!cert_request_info->client_certs.empty() && delegate_) {
delegate_->SelectClientCertificate( delegate_->SelectClientCertificate(
web_contents, cert_request_info, std::move(delegate)); web_contents, cert_request_info, std::move(delegate));

View file

@ -34,10 +34,12 @@ class AtomBrowserClient : public brightray::BrowserClient,
using Delegate = content::ContentBrowserClient; using Delegate = content::ContentBrowserClient;
void set_delegate(Delegate* delegate) { delegate_ = delegate; } void set_delegate(Delegate* delegate) { delegate_ = delegate; }
// Returns the WebContents for pending render processes.
content::WebContents* GetWebContentsFromProcessID(int process_id);
// Don't force renderer process to restart for once. // Don't force renderer process to restart for once.
static void SuppressRendererProcessRestartForOnce(); static void SuppressRendererProcessRestartForOnce();
// Custom schemes to be registered to standard.
static void SetCustomSchemes(const std::vector<std::string>& schemes);
// Custom schemes to be registered to handle service worker. // Custom schemes to be registered to handle service worker.
static void SetCustomServiceWorkerSchemes( static void SetCustomServiceWorkerSchemes(
const std::vector<std::string>& schemes); const std::vector<std::string>& schemes);
@ -74,7 +76,7 @@ class AtomBrowserClient : public brightray::BrowserClient,
void SelectClientCertificate( void SelectClientCertificate(
content::WebContents* web_contents, content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info, net::SSLCertRequestInfo* cert_request_info,
scoped_ptr<content::ClientCertificateDelegate> delegate) override; std::unique_ptr<content::ClientCertificateDelegate> delegate) override;
void ResourceDispatcherHostCreated() override; void ResourceDispatcherHostCreated() override;
bool CanCreateWindow(const GURL& opener_url, bool CanCreateWindow(const GURL& opener_url,
const GURL& opener_top_level_frame_url, const GURL& opener_top_level_frame_url,
@ -107,7 +109,7 @@ class AtomBrowserClient : public brightray::BrowserClient,
// pending_render_process => current_render_process. // pending_render_process => current_render_process.
std::map<int, int> pending_processes_; std::map<int, int> pending_processes_;
scoped_ptr<AtomResourceDispatcherHostDelegate> std::unique_ptr<AtomResourceDispatcherHostDelegate>
resource_dispatcher_host_delegate_; resource_dispatcher_host_delegate_;
Delegate* delegate_; Delegate* delegate_;

View file

@ -21,7 +21,7 @@
#include "base/command_line.h" #include "base/command_line.h"
#include "base/files/file_path.h" #include "base/files/file_path.h"
#include "base/path_service.h" #include "base/path_service.h"
#include "base/prefs/pref_registry_simple.h" #include "components/prefs/pref_registry_simple.h"
#include "base/strings/string_util.h" #include "base/strings/string_util.h"
#include "base/strings/stringprintf.h" #include "base/strings/stringprintf.h"
#include "base/threading/sequenced_worker_pool.h" #include "base/threading/sequenced_worker_pool.h"
@ -46,7 +46,7 @@ namespace {
class NoCacheBackend : public net::HttpCache::BackendFactory { class NoCacheBackend : public net::HttpCache::BackendFactory {
int CreateBackend(net::NetLog* net_log, int CreateBackend(net::NetLog* net_log,
scoped_ptr<disk_cache::Backend>* backend, std::unique_ptr<disk_cache::Backend>* backend,
const net::CompletionCallback& callback) override { const net::CompletionCallback& callback) override {
return net::ERR_FAILED; return net::ERR_FAILED;
} }
@ -67,8 +67,7 @@ AtomBrowserContext::AtomBrowserContext(const std::string& partition,
: brightray::BrowserContext(partition, in_memory), : brightray::BrowserContext(partition, in_memory),
cert_verifier_(new AtomCertVerifier), cert_verifier_(new AtomCertVerifier),
job_factory_(new AtomURLRequestJobFactory), job_factory_(new AtomURLRequestJobFactory),
network_delegate_(new AtomNetworkDelegate), network_delegate_(new AtomNetworkDelegate) {
allow_ntlm_everywhere_(false) {
} }
AtomBrowserContext::~AtomBrowserContext() { AtomBrowserContext::~AtomBrowserContext() {
@ -95,11 +94,11 @@ std::string AtomBrowserContext::GetUserAgent() {
return content::BuildUserAgentFromProduct(user_agent); return content::BuildUserAgentFromProduct(user_agent);
} }
scoped_ptr<net::URLRequestJobFactory> std::unique_ptr<net::URLRequestJobFactory>
AtomBrowserContext::CreateURLRequestJobFactory( AtomBrowserContext::CreateURLRequestJobFactory(
content::ProtocolHandlerMap* handlers, content::ProtocolHandlerMap* handlers,
content::URLRequestInterceptorScopedVector* interceptors) { content::URLRequestInterceptorScopedVector* interceptors) {
scoped_ptr<AtomURLRequestJobFactory> job_factory(job_factory_); std::unique_ptr<AtomURLRequestJobFactory> job_factory(job_factory_);
for (auto& it : *handlers) { for (auto& it : *handlers) {
job_factory->SetProtocolHandler(it.first, job_factory->SetProtocolHandler(it.first,
@ -134,7 +133,7 @@ AtomBrowserContext::CreateURLRequestJobFactory(
new net::FtpNetworkLayer(host_resolver)))); new net::FtpNetworkLayer(host_resolver))));
// Set up interceptors in the reverse order. // Set up interceptors in the reverse order.
scoped_ptr<net::URLRequestJobFactory> top_job_factory = std::unique_ptr<net::URLRequestJobFactory> top_job_factory =
std::move(job_factory); std::move(job_factory);
content::URLRequestInterceptorScopedVector::reverse_iterator it; content::URLRequestInterceptorScopedVector::reverse_iterator it;
for (it = interceptors->rbegin(); it != interceptors->rend(); ++it) for (it = interceptors->rbegin(); it != interceptors->rend(); ++it)
@ -177,7 +176,7 @@ content::PermissionManager* AtomBrowserContext::GetPermissionManager() {
return permission_manager_.get(); return permission_manager_.get();
} }
scoped_ptr<net::CertVerifier> AtomBrowserContext::CreateCertVerifier() { std::unique_ptr<net::CertVerifier> AtomBrowserContext::CreateCertVerifier() {
return make_scoped_ptr(cert_verifier_); return make_scoped_ptr(cert_verifier_);
} }
@ -195,16 +194,6 @@ void AtomBrowserContext::RegisterPrefs(PrefRegistrySimple* pref_registry) {
pref_registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths); pref_registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths);
} }
bool AtomBrowserContext::AllowNTLMCredentialsForDomain(const GURL& origin) {
if (allow_ntlm_everywhere_)
return true;
return Delegate::AllowNTLMCredentialsForDomain(origin);
}
void AtomBrowserContext::AllowNTLMCredentialsForAllDomains(bool should_allow) {
allow_ntlm_everywhere_ = should_allow;
}
} // namespace atom } // namespace atom
namespace brightray { namespace brightray {

View file

@ -26,14 +26,13 @@ class AtomBrowserContext : public brightray::BrowserContext {
// brightray::URLRequestContextGetter::Delegate: // brightray::URLRequestContextGetter::Delegate:
net::NetworkDelegate* CreateNetworkDelegate() override; net::NetworkDelegate* CreateNetworkDelegate() override;
std::string GetUserAgent() override; std::string GetUserAgent() override;
scoped_ptr<net::URLRequestJobFactory> CreateURLRequestJobFactory( std::unique_ptr<net::URLRequestJobFactory> CreateURLRequestJobFactory(
content::ProtocolHandlerMap* handlers, content::ProtocolHandlerMap* handlers,
content::URLRequestInterceptorScopedVector* interceptors) override; content::URLRequestInterceptorScopedVector* interceptors) override;
net::HttpCache::BackendFactory* CreateHttpCacheBackendFactory( net::HttpCache::BackendFactory* CreateHttpCacheBackendFactory(
const base::FilePath& base_path) override; const base::FilePath& base_path) override;
scoped_ptr<net::CertVerifier> CreateCertVerifier() override; std::unique_ptr<net::CertVerifier> CreateCertVerifier() override;
net::SSLConfigService* CreateSSLConfigService() override; net::SSLConfigService* CreateSSLConfigService() override;
bool AllowNTLMCredentialsForDomain(const GURL& auth_origin) override;
// content::BrowserContext: // content::BrowserContext:
content::DownloadManagerDelegate* GetDownloadManagerDelegate() override; content::DownloadManagerDelegate* GetDownloadManagerDelegate() override;
@ -43,8 +42,6 @@ class AtomBrowserContext : public brightray::BrowserContext {
// brightray::BrowserContext: // brightray::BrowserContext:
void RegisterPrefs(PrefRegistrySimple* pref_registry) override; void RegisterPrefs(PrefRegistrySimple* pref_registry) override;
void AllowNTLMCredentialsForAllDomains(bool should_allow);
AtomCertVerifier* cert_verifier() const { return cert_verifier_; } AtomCertVerifier* cert_verifier() const { return cert_verifier_; }
AtomURLRequestJobFactory* job_factory() const { return job_factory_; } AtomURLRequestJobFactory* job_factory() const { return job_factory_; }
@ -52,17 +49,15 @@ class AtomBrowserContext : public brightray::BrowserContext {
AtomNetworkDelegate* network_delegate() const { return network_delegate_; } AtomNetworkDelegate* network_delegate() const { return network_delegate_; }
private: private:
scoped_ptr<AtomDownloadManagerDelegate> download_manager_delegate_; std::unique_ptr<AtomDownloadManagerDelegate> download_manager_delegate_;
scoped_ptr<WebViewManager> guest_manager_; std::unique_ptr<WebViewManager> guest_manager_;
scoped_ptr<AtomPermissionManager> permission_manager_; std::unique_ptr<AtomPermissionManager> permission_manager_;
// Managed by brightray::BrowserContext. // Managed by brightray::BrowserContext.
AtomCertVerifier* cert_verifier_; AtomCertVerifier* cert_verifier_;
AtomURLRequestJobFactory* job_factory_; AtomURLRequestJobFactory* job_factory_;
AtomNetworkDelegate* network_delegate_; AtomNetworkDelegate* network_delegate_;
bool allow_ntlm_everywhere_;
DISALLOW_COPY_AND_ASSIGN(AtomBrowserContext); DISALLOW_COPY_AND_ASSIGN(AtomBrowserContext);
}; };

View file

@ -68,7 +68,7 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts {
#endif #endif
// A fake BrowserProcess object that used to feed the source code from chrome. // A fake BrowserProcess object that used to feed the source code from chrome.
scoped_ptr<BrowserProcess> fake_browser_process_; std::unique_ptr<BrowserProcess> fake_browser_process_;
// The gin::PerIsolateData requires a task runner to create, so we feed it // The gin::PerIsolateData requires a task runner to create, so we feed it
// with a task runner that will post all work to main loop. // with a task runner that will post all work to main loop.
@ -77,11 +77,11 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts {
// Pointer to exit code. // Pointer to exit code.
int* exit_code_; int* exit_code_;
scoped_ptr<Browser> browser_; std::unique_ptr<Browser> browser_;
scoped_ptr<JavascriptEnvironment> js_env_; std::unique_ptr<JavascriptEnvironment> js_env_;
scoped_ptr<NodeBindings> node_bindings_; std::unique_ptr<NodeBindings> node_bindings_;
scoped_ptr<AtomBindings> atom_bindings_; std::unique_ptr<AtomBindings> atom_bindings_;
scoped_ptr<NodeDebugger> node_debugger_; std::unique_ptr<NodeDebugger> node_debugger_;
base::Timer gc_timer_; base::Timer gc_timer_;

View file

@ -12,7 +12,7 @@
#include "atom/browser/ui/file_dialog.h" #include "atom/browser/ui/file_dialog.h"
#include "base/bind.h" #include "base/bind.h"
#include "base/files/file_util.h" #include "base/files/file_util.h"
#include "base/prefs/pref_service.h" #include "components/prefs/pref_service.h"
#include "chrome/common/pref_names.h" #include "chrome/common/pref_names.h"
#include "content/public/browser/browser_context.h" #include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
@ -77,7 +77,8 @@ void AtomDownloadManagerDelegate::OnDownloadPathGenerated(
window = relay->window.get(); window = relay->window.get();
base::FilePath path; base::FilePath path;
if (file_dialog::ShowSaveDialog(window, item->GetURL().spec(), default_path, if (file_dialog::ShowSaveDialog(window, item->GetURL().spec(),
"", default_path,
file_dialog::Filters(), &path)) { file_dialog::Filters(), &path)) {
// Remember the last selected download directory. // Remember the last selected download directory.
AtomBrowserContext* browser_context = static_cast<AtomBrowserContext*>( AtomBrowserContext* browser_context = static_cast<AtomBrowserContext*>(

View file

@ -13,7 +13,6 @@ namespace atom {
void AtomJavaScriptDialogManager::RunJavaScriptDialog( void AtomJavaScriptDialogManager::RunJavaScriptDialog(
content::WebContents* web_contents, content::WebContents* web_contents,
const GURL& origin_url, const GURL& origin_url,
const std::string& accept_lang,
content::JavaScriptMessageType javascript_message_type, content::JavaScriptMessageType javascript_message_type,
const base::string16& message_text, const base::string16& message_text,
const base::string16& default_prompt_text, const base::string16& default_prompt_text,
@ -24,12 +23,10 @@ void AtomJavaScriptDialogManager::RunJavaScriptDialog(
void AtomJavaScriptDialogManager::RunBeforeUnloadDialog( void AtomJavaScriptDialogManager::RunBeforeUnloadDialog(
content::WebContents* web_contents, content::WebContents* web_contents,
const base::string16& message_text,
bool is_reload, bool is_reload,
const DialogClosedCallback& callback) { const DialogClosedCallback& callback) {
bool prevent_reload = message_text.empty() || // FIXME(zcbenz): the |message_text| is removed, figure out what should we do.
message_text == base::ASCIIToUTF16("false"); callback.Run(false, base::ASCIIToUTF16("This should not be displayed"));
callback.Run(!prevent_reload, message_text);
} }
} // namespace atom } // namespace atom

View file

@ -17,7 +17,6 @@ class AtomJavaScriptDialogManager : public content::JavaScriptDialogManager {
void RunJavaScriptDialog( void RunJavaScriptDialog(
content::WebContents* web_contents, content::WebContents* web_contents,
const GURL& origin_url, const GURL& origin_url,
const std::string& accept_lang,
content::JavaScriptMessageType javascript_message_type, content::JavaScriptMessageType javascript_message_type,
const base::string16& message_text, const base::string16& message_text,
const base::string16& default_prompt_text, const base::string16& default_prompt_text,
@ -25,7 +24,6 @@ class AtomJavaScriptDialogManager : public content::JavaScriptDialogManager {
bool* did_suppress_message) override; bool* did_suppress_message) override;
void RunBeforeUnloadDialog( void RunBeforeUnloadDialog(
content::WebContents* web_contents, content::WebContents* web_contents,
const base::string16& message_text,
bool is_reload, bool is_reload,
const DialogClosedCallback& callback) override; const DialogClosedCallback& callback) override;
void CancelActiveAndPendingDialogs( void CancelActiveAndPendingDialogs(

View file

@ -40,7 +40,7 @@ void AtomPermissionManager::SetPermissionRequestHandler(
if (handler.is_null() && !pending_requests_.empty()) { if (handler.is_null() && !pending_requests_.empty()) {
for (const auto& request : pending_requests_) { for (const auto& request : pending_requests_) {
if (!WebContentsDestroyed(request.second.render_process_id)) if (!WebContentsDestroyed(request.second.render_process_id))
request.second.callback.Run(content::PERMISSION_STATUS_DENIED); request.second.callback.Run(blink::mojom::PermissionStatus::DENIED);
} }
pending_requests_.clear(); pending_requests_.clear();
} }
@ -51,7 +51,6 @@ int AtomPermissionManager::RequestPermission(
content::PermissionType permission, content::PermissionType permission,
content::RenderFrameHost* render_frame_host, content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin, const GURL& requesting_origin,
bool user_gesture,
const ResponseCallback& response_callback) { const ResponseCallback& response_callback) {
int process_id = render_frame_host->GetProcess()->GetID(); int process_id = render_frame_host->GetProcess()->GetID();
@ -74,7 +73,7 @@ int AtomPermissionManager::RequestPermission(
return request_id_; return request_id_;
} }
response_callback.Run(content::PERMISSION_STATUS_GRANTED); response_callback.Run(blink::mojom::PermissionStatus::GRANTED);
return kNoPendingOperation; return kNoPendingOperation;
} }
@ -82,17 +81,16 @@ int AtomPermissionManager::RequestPermissions(
const std::vector<content::PermissionType>& permissions, const std::vector<content::PermissionType>& permissions,
content::RenderFrameHost* render_frame_host, content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin, const GURL& requesting_origin,
bool user_gesture,
const base::Callback<void( const base::Callback<void(
const std::vector<content::PermissionStatus>&)>& callback) { const std::vector<blink::mojom::PermissionStatus>&)>& callback) {
// FIXME(zcbenz): Just ignore multiple permissions request for now. // FIXME(zcbenz): Just ignore multiple permissions request for now.
std::vector<content::PermissionStatus> permissionStatuses; std::vector<blink::mojom::PermissionStatus> permissionStatuses;
for (auto permission : permissions) { for (auto permission : permissions) {
if (permission == content::PermissionType::MIDI_SYSEX) { if (permission == content::PermissionType::MIDI_SYSEX) {
content::ChildProcessSecurityPolicy::GetInstance()-> content::ChildProcessSecurityPolicy::GetInstance()->
GrantSendMidiSysExMessage(render_frame_host->GetProcess()->GetID()); GrantSendMidiSysExMessage(render_frame_host->GetProcess()->GetID());
} }
permissionStatuses.push_back(content::PERMISSION_STATUS_GRANTED); permissionStatuses.push_back(blink::mojom::PermissionStatus::GRANTED);
} }
callback.Run(permissionStatuses); callback.Run(permissionStatuses);
return kNoPendingOperation; return kNoPendingOperation;
@ -102,7 +100,7 @@ void AtomPermissionManager::OnPermissionResponse(
int request_id, int request_id,
const GURL& origin, const GURL& origin,
const ResponseCallback& callback, const ResponseCallback& callback,
content::PermissionStatus status) { blink::mojom::PermissionStatus status) {
auto request = pending_requests_.find(request_id); auto request = pending_requests_.find(request_id);
if (request != pending_requests_.end()) { if (request != pending_requests_.end()) {
if (!WebContentsDestroyed(request->second.render_process_id)) if (!WebContentsDestroyed(request->second.render_process_id))
@ -115,7 +113,7 @@ void AtomPermissionManager::CancelPermissionRequest(int request_id) {
auto request = pending_requests_.find(request_id); auto request = pending_requests_.find(request_id);
if (request != pending_requests_.end()) { if (request != pending_requests_.end()) {
if (!WebContentsDestroyed(request->second.render_process_id)) if (!WebContentsDestroyed(request->second.render_process_id))
request->second.callback.Run(content::PERMISSION_STATUS_DENIED); request->second.callback.Run(blink::mojom::PermissionStatus::DENIED);
pending_requests_.erase(request); pending_requests_.erase(request);
} }
} }
@ -126,11 +124,11 @@ void AtomPermissionManager::ResetPermission(
const GURL& embedding_origin) { const GURL& embedding_origin) {
} }
content::PermissionStatus AtomPermissionManager::GetPermissionStatus( blink::mojom::PermissionStatus AtomPermissionManager::GetPermissionStatus(
content::PermissionType permission, content::PermissionType permission,
const GURL& requesting_origin, const GURL& requesting_origin,
const GURL& embedding_origin) { const GURL& embedding_origin) {
return content::PERMISSION_STATUS_GRANTED; return blink::mojom::PermissionStatus::GRANTED;
} }
void AtomPermissionManager::RegisterPermissionUsage( void AtomPermissionManager::RegisterPermissionUsage(

View file

@ -23,7 +23,7 @@ class AtomPermissionManager : public content::PermissionManager {
~AtomPermissionManager() override; ~AtomPermissionManager() override;
using ResponseCallback = using ResponseCallback =
base::Callback<void(content::PermissionStatus)>; base::Callback<void(blink::mojom::PermissionStatus)>;
using RequestHandler = using RequestHandler =
base::Callback<void(content::WebContents*, base::Callback<void(content::WebContents*,
content::PermissionType, content::PermissionType,
@ -37,28 +37,26 @@ class AtomPermissionManager : public content::PermissionManager {
content::PermissionType permission, content::PermissionType permission,
content::RenderFrameHost* render_frame_host, content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin, const GURL& requesting_origin,
bool user_gesture,
const ResponseCallback& callback) override; const ResponseCallback& callback) override;
int RequestPermissions( int RequestPermissions(
const std::vector<content::PermissionType>& permissions, const std::vector<content::PermissionType>& permissions,
content::RenderFrameHost* render_frame_host, content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin, const GURL& requesting_origin,
bool user_gesture,
const base::Callback<void( const base::Callback<void(
const std::vector<content::PermissionStatus>&)>& callback) override; const std::vector<blink::mojom::PermissionStatus>&)>& callback) override;
protected: protected:
void OnPermissionResponse(int request_id, void OnPermissionResponse(int request_id,
const GURL& url, const GURL& url,
const ResponseCallback& callback, const ResponseCallback& callback,
content::PermissionStatus status); blink::mojom::PermissionStatus status);
// content::PermissionManager: // content::PermissionManager:
void CancelPermissionRequest(int request_id) override; void CancelPermissionRequest(int request_id) override;
void ResetPermission(content::PermissionType permission, void ResetPermission(content::PermissionType permission,
const GURL& requesting_origin, const GURL& requesting_origin,
const GURL& embedding_origin) override; const GURL& embedding_origin) override;
content::PermissionStatus GetPermissionStatus( blink::mojom::PermissionStatus GetPermissionStatus(
content::PermissionType permission, content::PermissionType permission,
const GURL& requesting_origin, const GURL& requesting_origin,
const GURL& embedding_origin) override; const GURL& embedding_origin) override;
@ -69,7 +67,8 @@ class AtomPermissionManager : public content::PermissionManager {
content::PermissionType permission, content::PermissionType permission,
const GURL& requesting_origin, const GURL& requesting_origin,
const GURL& embedding_origin, const GURL& embedding_origin,
const base::Callback<void(content::PermissionStatus)>& callback) override; const base::Callback<void(blink::mojom::PermissionStatus)>& callback)
override;
void UnsubscribePermissionStatusChange(int subscription_id) override; void UnsubscribePermissionStatusChange(int subscription_id) override;
private: private:

View file

@ -32,7 +32,7 @@ class AtomSecurityStateModelClient
friend class content::WebContentsUserData<AtomSecurityStateModelClient>; friend class content::WebContentsUserData<AtomSecurityStateModelClient>;
content::WebContents* web_contents_; content::WebContents* web_contents_;
scoped_ptr<security_state::SecurityStateModel> security_state_model_; std::unique_ptr<security_state::SecurityStateModel> security_state_model_;
DISALLOW_COPY_AND_ASSIGN(AtomSecurityStateModelClient); DISALLOW_COPY_AND_ASSIGN(AtomSecurityStateModelClient);
}; };

View file

@ -14,6 +14,7 @@
#include "base/strings/string16.h" #include "base/strings/string16.h"
#include "atom/browser/browser_observer.h" #include "atom/browser/browser_observer.h"
#include "atom/browser/window_list_observer.h" #include "atom/browser/window_list_observer.h"
#include "native_mate/arguments.h"
#if defined(OS_WIN) #if defined(OS_WIN)
#include "base/files/file_path.h" #include "base/files/file_path.h"
@ -94,7 +95,8 @@ class Browser : public WindowListObserver {
// Creates an activity and sets it as the one currently in use. // Creates an activity and sets it as the one currently in use.
void SetUserActivity(const std::string& type, void SetUserActivity(const std::string& type,
const base::DictionaryValue& user_info); const base::DictionaryValue& user_info,
mate::Arguments* args);
// Returns the type name of the current user activity. // Returns the type name of the current user activity.
std::string GetCurrentActivityType(); std::string GetCurrentActivityType();
@ -111,6 +113,9 @@ class Browser : public WindowListObserver {
int DockBounce(BounceType type); int DockBounce(BounceType type);
void DockCancelBounce(int request_id); void DockCancelBounce(int request_id);
// Bounce the Downloads stack.
void DockDownloadFinished(const std::string& filePath);
// Set/Get dock's badge text. // Set/Get dock's badge text.
void DockSetBadgeText(const std::string& label); void DockSetBadgeText(const std::string& label);
std::string DockGetBadgeText(); std::string DockGetBadgeText();

View file

@ -13,6 +13,8 @@
#include "base/mac/foundation_util.h" #include "base/mac/foundation_util.h"
#include "base/strings/sys_string_conversions.h" #include "base/strings/sys_string_conversions.h"
#include "brightray/common/application_info.h" #include "brightray/common/application_info.h"
#include "net/base/mac/url_conversions.h"
#include "url/gurl.h"
namespace atom { namespace atom {
@ -43,7 +45,31 @@ void Browser::ClearRecentDocuments() {
} }
bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol) { bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol) {
return false; NSString* identifier = [base::mac::MainBundle() bundleIdentifier];
if (!identifier)
return false;
if (!Browser::IsDefaultProtocolClient(protocol))
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
CFStringRef protocol_cf = base::mac::NSToCFCast(protocol_ns);
CFArrayRef bundleList = LSCopyAllHandlersForURLScheme(protocol_cf);
if (!bundleList) {
return false;
}
// On Mac OS X, we can't query the default, but the handlers list seems to put
// Apple's defaults first, so we'll use the first option that isn't our bundle
CFStringRef other = nil;
for (CFIndex i = 0; i < CFArrayGetCount(bundleList); i++) {
other = (CFStringRef)CFArrayGetValueAtIndex(bundleList, i);
if (![identifier isEqualToString: (__bridge NSString *)other]) {
break;
}
}
OSStatus return_code = LSSetDefaultHandlerForURLScheme(protocol_cf, other);
return return_code == noErr;
} }
bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) { bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) {
@ -88,12 +114,16 @@ bool Browser::IsDefaultProtocolClient(const std::string& protocol) {
void Browser::SetAppUserModelID(const base::string16& name) { void Browser::SetAppUserModelID(const base::string16& name) {
} }
void Browser::SetUserActivity( void Browser::SetUserActivity(const std::string& type,
const std::string& type, const base::DictionaryValue& user_info,
const base::DictionaryValue& user_info) { mate::Arguments* args) {
std::string url_string;
args->GetNext(&url_string);
[[AtomApplication sharedApplication] [[AtomApplication sharedApplication]
setCurrentActivity:base::SysUTF8ToNSString(type) setCurrentActivity:base::SysUTF8ToNSString(type)
withUserInfo:DictionaryValueToNSDictionary(user_info)]; withUserInfo:DictionaryValueToNSDictionary(user_info)
withWebpageURL:net::NSURLWithGURL(GURL(url_string))];
} }
std::string Browser::GetCurrentActivityType() { std::string Browser::GetCurrentActivityType() {
@ -102,9 +132,8 @@ std::string Browser::GetCurrentActivityType() {
return base::SysNSStringToUTF8(userActivity.activityType); return base::SysNSStringToUTF8(userActivity.activityType);
} }
bool Browser::ContinueUserActivity( bool Browser::ContinueUserActivity(const std::string& type,
const std::string& type, const base::DictionaryValue& user_info) {
const base::DictionaryValue& user_info) {
bool prevent_default = false; bool prevent_default = false;
FOR_EACH_OBSERVER(BrowserObserver, FOR_EACH_OBSERVER(BrowserObserver,
observers_, observers_,
@ -134,6 +163,12 @@ void Browser::DockSetBadgeText(const std::string& label) {
[tile setBadgeLabel:base::SysUTF8ToNSString(label)]; [tile setBadgeLabel:base::SysUTF8ToNSString(label)];
} }
void Browser::DockDownloadFinished(const std::string& filePath) {
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName: @"com.apple.DownloadFileFinished"
object: base::SysUTF8ToNSString(filePath)];
}
std::string Browser::DockGetBadgeText() { std::string Browser::DockGetBadgeText() {
NSDockTile *tile = [[AtomApplication sharedApplication] dockTile]; NSDockTile *tile = [[AtomApplication sharedApplication] dockTile];
return base::SysNSStringToUTF8([tile badgeLabel]); return base::SysNSStringToUTF8([tile badgeLabel]);

View file

@ -281,7 +281,7 @@ PCWSTR Browser::GetAppUserModelID() {
std::string Browser::GetExecutableFileVersion() const { std::string Browser::GetExecutableFileVersion() const {
base::FilePath path; base::FilePath path;
if (PathService::Get(base::FILE_EXE, &path)) { if (PathService::Get(base::FILE_EXE, &path)) {
scoped_ptr<FileVersionInfo> version_info( std::unique_ptr<FileVersionInfo> version_info(
FileVersionInfo::CreateFileVersionInfo(path)); FileVersionInfo::CreateFileVersionInfo(path));
return base::UTF16ToUTF8(version_info->product_version()); return base::UTF16ToUTF8(version_info->product_version());
} }
@ -292,7 +292,7 @@ std::string Browser::GetExecutableFileVersion() const {
std::string Browser::GetExecutableFileProductName() const { std::string Browser::GetExecutableFileProductName() const {
base::FilePath path; base::FilePath path;
if (PathService::Get(base::FILE_EXE, &path)) { if (PathService::Get(base::FILE_EXE, &path)) {
scoped_ptr<FileVersionInfo> version_info( std::unique_ptr<FileVersionInfo> version_info(
FileVersionInfo::CreateFileVersionInfo(path)); FileVersionInfo::CreateFileVersionInfo(path));
return base::UTF16ToUTF8(version_info->product_name()); return base::UTF16ToUTF8(version_info->product_name());
} }

View file

@ -16,8 +16,8 @@
#include "atom/browser/web_dialog_helper.h" #include "atom/browser/web_dialog_helper.h"
#include "atom/common/atom_constants.h" #include "atom/common/atom_constants.h"
#include "base/files/file_util.h" #include "base/files/file_util.h"
#include "base/prefs/pref_service.h" #include "components/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h" #include "components/prefs/scoped_user_pref_update.h"
#include "chrome/browser/printing/print_preview_message_handler.h" #include "chrome/browser/printing/print_preview_message_handler.h"
#include "chrome/browser/printing/print_view_manager_basic.h" #include "chrome/browser/printing/print_view_manager_basic.h"
#include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/browser_dialogs.h"
@ -31,14 +31,6 @@
#include "content/public/browser/security_style_explanations.h" #include "content/public/browser/security_style_explanations.h"
#include "storage/browser/fileapi/isolated_context.h" #include "storage/browser/fileapi/isolated_context.h"
#if defined(TOOLKIT_VIEWS)
#include "atom/browser/native_window_views.h"
#endif
#if defined(USE_X11)
#include "atom/browser/browser.h"
#endif
using content::BrowserThread; using content::BrowserThread;
using security_state::SecurityStateModel; using security_state::SecurityStateModel;
@ -145,6 +137,13 @@ std::set<std::string> GetAddedFileSystemPaths(
return result; return result;
} }
bool IsDevToolsFileSystemAdded(
content::WebContents* web_contents,
const std::string& file_system_path) {
auto file_system_paths = GetAddedFileSystemPaths(web_contents);
return file_system_paths.find(file_system_path) != file_system_paths.end();
}
content::SecurityStyle SecurityLevelToSecurityStyle( content::SecurityStyle SecurityLevelToSecurityStyle(
SecurityStateModel::SecurityLevel security_level) { SecurityStateModel::SecurityLevel security_level) {
switch (security_level) { switch (security_level) {
@ -167,14 +166,17 @@ content::SecurityStyle SecurityLevelToSecurityStyle(
CommonWebContentsDelegate::CommonWebContentsDelegate() CommonWebContentsDelegate::CommonWebContentsDelegate()
: html_fullscreen_(false), : html_fullscreen_(false),
native_fullscreen_(false) { native_fullscreen_(false),
devtools_file_system_indexer_(new DevToolsFileSystemIndexer) {
} }
CommonWebContentsDelegate::~CommonWebContentsDelegate() { CommonWebContentsDelegate::~CommonWebContentsDelegate() {
} }
void CommonWebContentsDelegate::InitWithWebContents( void CommonWebContentsDelegate::InitWithWebContents(
content::WebContents* web_contents) { content::WebContents* web_contents,
AtomBrowserContext* browser_context) {
browser_context_ = browser_context;
web_contents->SetDelegate(this); web_contents->SetDelegate(this);
printing::PrintViewManagerBasic::CreateForWebContents(web_contents); printing::PrintViewManagerBasic::CreateForWebContents(web_contents);
@ -381,7 +383,7 @@ void CommonWebContentsDelegate::DevToolsSaveToFile(
} else { } else {
file_dialog::Filters filters; file_dialog::Filters filters;
base::FilePath default_path(base::FilePath::FromUTF8Unsafe(url)); base::FilePath default_path(base::FilePath::FromUTF8Unsafe(url));
if (!file_dialog::ShowSaveDialog(owner_window(), url, default_path, if (!file_dialog::ShowSaveDialog(owner_window(), url, "", default_path,
filters, &path)) { filters, &path)) {
base::StringValue url_value(url); base::StringValue url_value(url);
web_contents_->CallClientFunction( web_contents_->CallClientFunction(
@ -447,7 +449,7 @@ void CommonWebContentsDelegate::DevToolsAddFileSystem(
base::FilePath default_path; base::FilePath default_path;
std::vector<base::FilePath> paths; std::vector<base::FilePath> paths;
int flag = file_dialog::FILE_DIALOG_OPEN_DIRECTORY; int flag = file_dialog::FILE_DIALOG_OPEN_DIRECTORY;
if (!file_dialog::ShowOpenDialog(owner_window(), "", default_path, if (!file_dialog::ShowOpenDialog(owner_window(), "", "", default_path,
filters, flag, &paths)) filters, flag, &paths))
return; return;
@ -456,14 +458,13 @@ void CommonWebContentsDelegate::DevToolsAddFileSystem(
std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(),
path); path);
auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe()))
if (file_system_paths.find(path.AsUTF8Unsafe()) != file_system_paths.end())
return; return;
FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(),
file_system_id, file_system_id,
path.AsUTF8Unsafe()); path.AsUTF8Unsafe());
scoped_ptr<base::DictionaryValue> file_system_value( std::unique_ptr<base::DictionaryValue> file_system_value(
CreateFileSystemValue(file_system)); CreateFileSystemValue(file_system));
auto pref_service = GetPrefService(GetDevToolsWebContents()); auto pref_service = GetPrefService(GetDevToolsWebContents());
@ -495,6 +496,61 @@ void CommonWebContentsDelegate::DevToolsRemoveFileSystem(
nullptr, nullptr); nullptr, nullptr);
} }
void CommonWebContentsDelegate::DevToolsIndexPath(
int request_id,
const std::string& file_system_path) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsIndexingDone(request_id, file_system_path);
return;
}
if (devtools_indexing_jobs_.count(request_id) != 0)
return;
devtools_indexing_jobs_[request_id] =
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>(
devtools_file_system_indexer_->IndexPath(
file_system_path,
base::Bind(
&CommonWebContentsDelegate::OnDevToolsIndexingWorkCalculated,
base::Unretained(this),
request_id,
file_system_path),
base::Bind(&CommonWebContentsDelegate::OnDevToolsIndexingWorked,
base::Unretained(this),
request_id,
file_system_path),
base::Bind(&CommonWebContentsDelegate::OnDevToolsIndexingDone,
base::Unretained(this),
request_id,
file_system_path)));
}
void CommonWebContentsDelegate::DevToolsStopIndexing(int request_id) {
auto it = devtools_indexing_jobs_.find(request_id);
if (it == devtools_indexing_jobs_.end())
return;
it->second->Stop();
devtools_indexing_jobs_.erase(it);
}
void CommonWebContentsDelegate::DevToolsSearchInPath(
int request_id,
const std::string& file_system_path,
const std::string& query) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsSearchCompleted(request_id,
file_system_path,
std::vector<std::string>());
return;
}
devtools_file_system_indexer_->SearchInPath(
file_system_path,
query,
base::Bind(&CommonWebContentsDelegate::OnDevToolsSearchCompleted,
base::Unretained(this),
request_id,
file_system_path));
}
void CommonWebContentsDelegate::OnDevToolsSaveToFile( void CommonWebContentsDelegate::OnDevToolsSaveToFile(
const std::string& url) { const std::string& url) {
// Notify DevTools. // Notify DevTools.
@ -511,22 +567,60 @@ void CommonWebContentsDelegate::OnDevToolsAppendToFile(
"DevToolsAPI.appendedToURL", &url_value, nullptr, nullptr); "DevToolsAPI.appendedToURL", &url_value, nullptr, nullptr);
} }
#if defined(TOOLKIT_VIEWS) void CommonWebContentsDelegate::OnDevToolsIndexingWorkCalculated(
gfx::ImageSkia CommonWebContentsDelegate::GetDevToolsWindowIcon() { int request_id,
if (!owner_window()) const std::string& file_system_path,
return gfx::ImageSkia(); int total_work) {
return static_cast<views::WidgetDelegate*>(static_cast<NativeWindowViews*>( base::FundamentalValue request_id_value(request_id);
owner_window()))->GetWindowAppIcon(); base::StringValue file_system_path_value(file_system_path);
base::FundamentalValue total_work_value(total_work);
web_contents_->CallClientFunction("DevToolsAPI.indexingTotalWorkCalculated",
&request_id_value,
&file_system_path_value,
&total_work_value);
} }
#endif
#if defined(USE_X11) void CommonWebContentsDelegate::OnDevToolsIndexingWorked(
void CommonWebContentsDelegate::GetDevToolsWindowWMClass( int request_id,
std::string* name, std::string* class_name) { const std::string& file_system_path,
*class_name = Browser::Get()->GetName(); int worked) {
*name = base::ToLowerASCII(*class_name); base::FundamentalValue request_id_value(request_id);
base::StringValue file_system_path_value(file_system_path);
base::FundamentalValue worked_value(worked);
web_contents_->CallClientFunction("DevToolsAPI.indexingWorked",
&request_id_value,
&file_system_path_value,
&worked_value);
}
void CommonWebContentsDelegate::OnDevToolsIndexingDone(
int request_id,
const std::string& file_system_path) {
devtools_indexing_jobs_.erase(request_id);
base::FundamentalValue request_id_value(request_id);
base::StringValue file_system_path_value(file_system_path);
web_contents_->CallClientFunction("DevToolsAPI.indexingDone",
&request_id_value,
&file_system_path_value,
nullptr);
}
void CommonWebContentsDelegate::OnDevToolsSearchCompleted(
int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths) {
base::ListValue file_paths_value;
for (std::vector<std::string>::const_iterator it(file_paths.begin());
it != file_paths.end(); ++it) {
file_paths_value.AppendString(*it);
}
base::FundamentalValue request_id_value(request_id);
base::StringValue file_system_path_value(file_system_path);
web_contents_->CallClientFunction("DevToolsAPI.searchCompleted",
&request_id_value,
&file_system_path_value,
&file_paths_value);
} }
#endif
void CommonWebContentsDelegate::SetHtmlApiFullscreen(bool enter_fullscreen) { void CommonWebContentsDelegate::SetHtmlApiFullscreen(bool enter_fullscreen) {
// Window is already in fullscreen mode, save the state. // Window is already in fullscreen mode, save the state.

View file

@ -12,10 +12,14 @@
#include "brightray/browser/inspectable_web_contents_impl.h" #include "brightray/browser/inspectable_web_contents_impl.h"
#include "brightray/browser/inspectable_web_contents_delegate.h" #include "brightray/browser/inspectable_web_contents_delegate.h"
#include "brightray/browser/inspectable_web_contents_view_delegate.h" #include "brightray/browser/inspectable_web_contents_view_delegate.h"
#include "brightray/browser/devtools_file_system_indexer.h"
#include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_delegate.h"
using brightray::DevToolsFileSystemIndexer;
namespace atom { namespace atom {
class AtomBrowserContext;
class AtomJavaScriptDialogManager; class AtomJavaScriptDialogManager;
class NativeWindow; class NativeWindow;
class WebDialogHelper; class WebDialogHelper;
@ -30,7 +34,8 @@ class CommonWebContentsDelegate
// Creates a InspectableWebContents object and takes onwership of // Creates a InspectableWebContents object and takes onwership of
// |web_contents|. // |web_contents|.
void InitWithWebContents(content::WebContents* web_contents); void InitWithWebContents(content::WebContents* web_contents,
AtomBrowserContext* browser_context);
// Set the window as owner window. // Set the window as owner window.
void SetOwnerWindow(NativeWindow* owner_window); void SetOwnerWindow(NativeWindow* owner_window);
@ -79,6 +84,9 @@ class CommonWebContentsDelegate
content::SecurityStyle GetSecurityStyle( content::SecurityStyle GetSecurityStyle(
content::WebContents* web_contents, content::WebContents* web_contents,
content::SecurityStyleExplanations* explanations) override; content::SecurityStyleExplanations* explanations) override;
void HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) override;
// brightray::InspectableWebContentsDelegate: // brightray::InspectableWebContentsDelegate:
void DevToolsSaveToFile(const std::string& url, void DevToolsSaveToFile(const std::string& url,
@ -90,6 +98,12 @@ class CommonWebContentsDelegate
void DevToolsAddFileSystem(const base::FilePath& path) override; void DevToolsAddFileSystem(const base::FilePath& path) override;
void DevToolsRemoveFileSystem( void DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) override; const base::FilePath& file_system_path) override;
void DevToolsIndexPath(int request_id,
const std::string& file_system_path) override;
void DevToolsStopIndexing(int request_id) override;
void DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) override;
// brightray::InspectableWebContentsViewDelegate: // brightray::InspectableWebContentsViewDelegate:
#if defined(TOOLKIT_VIEWS) #if defined(TOOLKIT_VIEWS)
@ -107,6 +121,19 @@ class CommonWebContentsDelegate
// Callback for when DevToolsAppendToFile has completed. // Callback for when DevToolsAppendToFile has completed.
void OnDevToolsAppendToFile(const std::string& url); void OnDevToolsAppendToFile(const std::string& url);
//
void OnDevToolsIndexingWorkCalculated(int request_id,
const std::string& file_system_path,
int total_work);
void OnDevToolsIndexingWorked(int request_id,
const std::string& file_system_path,
int worked);
void OnDevToolsIndexingDone(int request_id,
const std::string& file_system_path);
void OnDevToolsSearchCompleted(int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths);
// Set fullscreen mode triggered by html api. // Set fullscreen mode triggered by html api.
void SetHtmlApiFullscreen(bool enter_fullscreen); void SetHtmlApiFullscreen(bool enter_fullscreen);
@ -119,19 +146,30 @@ class CommonWebContentsDelegate
// Whether window is fullscreened by window api. // Whether window is fullscreened by window api.
bool native_fullscreen_; bool native_fullscreen_;
scoped_ptr<WebDialogHelper> web_dialog_helper_; std::unique_ptr<WebDialogHelper> web_dialog_helper_;
scoped_ptr<AtomJavaScriptDialogManager> dialog_manager_; std::unique_ptr<AtomJavaScriptDialogManager> dialog_manager_;
scoped_refptr<DevToolsFileSystemIndexer> devtools_file_system_indexer_;
// Make sure BrowserContext is alwasys destroyed after WebContents.
scoped_refptr<AtomBrowserContext> browser_context_;
// The stored InspectableWebContents object. // The stored InspectableWebContents object.
// Notice that web_contents_ must be placed after dialog_manager_, so we can // Notice that web_contents_ must be placed after dialog_manager_, so we can
// make sure web_contents_ is destroyed before dialog_manager_, otherwise a // make sure web_contents_ is destroyed before dialog_manager_, otherwise a
// crash would happen. // crash would happen.
scoped_ptr<brightray::InspectableWebContents> web_contents_; std::unique_ptr<brightray::InspectableWebContents> web_contents_;
// Maps url to file path, used by the file requests sent from devtools. // Maps url to file path, used by the file requests sent from devtools.
typedef std::map<std::string, base::FilePath> PathsMap; typedef std::map<std::string, base::FilePath> PathsMap;
PathsMap saved_files_; PathsMap saved_files_;
// Map id to index job, used for file system indexing requests from devtools.
typedef std::map<
int,
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>>
DevToolsIndexingJobsMap;
DevToolsIndexingJobsMap devtools_indexing_jobs_;
DISALLOW_COPY_AND_ASSIGN(CommonWebContentsDelegate); DISALLOW_COPY_AND_ASSIGN(CommonWebContentsDelegate);
}; };

View file

@ -0,0 +1,39 @@
// 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/common_web_contents_delegate.h"
#import <Cocoa/Cocoa.h>
#include "content/public/browser/native_web_keyboard_event.h"
#include "ui/events/keycodes/keyboard_codes.h"
namespace atom {
void CommonWebContentsDelegate::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (event.skip_in_browser ||
event.type == content::NativeWebKeyboardEvent::Char)
return;
// Escape exits tabbed fullscreen mode.
if (event.windowsKeyCode == ui::VKEY_ESCAPE && is_html_fullscreen())
ExitFullscreenModeForTab(source);
BOOL handled = [[NSApp mainMenu] performKeyEquivalent:event.os_event];
if (!handled && event.os_event.window) {
// Handle the cmd+~ shortcut.
if ((event.os_event.modifierFlags & NSCommandKeyMask) /* cmd */ &&
(event.os_event.keyCode == 50 /* ~ */)) {
if (event.os_event.modifierFlags & NSShiftKeyMask) {
[NSApp sendAction:@selector(_cycleWindowsReversed:) to:nil from:nil];
} else {
[NSApp sendAction:@selector(_cycleWindows:) to:nil from:nil];
}
}
}
}
} // namespace atom

View file

@ -0,0 +1,45 @@
// 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/common_web_contents_delegate.h"
#include "atom/browser/native_window_views.h"
#include "base/strings/string_util.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "ui/events/keycodes/keyboard_codes.h"
#if defined(USE_X11)
#include "atom/browser/browser.h"
#endif
namespace atom {
void CommonWebContentsDelegate::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
// Escape exits tabbed fullscreen mode.
if (event.windowsKeyCode == ui::VKEY_ESCAPE && is_html_fullscreen())
ExitFullscreenModeForTab(source);
// Let the NativeWindow handle other parts.
if (owner_window())
owner_window()->HandleKeyboardEvent(source, event);
}
gfx::ImageSkia CommonWebContentsDelegate::GetDevToolsWindowIcon() {
if (!owner_window())
return gfx::ImageSkia();
return static_cast<views::WidgetDelegate*>(static_cast<NativeWindowViews*>(
owner_window()))->GetWindowAppIcon();
}
#if defined(USE_X11)
void CommonWebContentsDelegate::GetDevToolsWindowWMClass(
std::string* name, std::string* class_name) {
*class_name = Browser::Get()->GetName();
*name = base::ToLowerASCII(*class_name);
}
#endif
} // namespace atom

View file

@ -0,0 +1,107 @@
// 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/lib/bluetooth_chooser.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "native_mate/dictionary.h"
namespace mate {
template<>
struct Converter<atom::BluetoothChooser::DeviceInfo> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate, const atom::BluetoothChooser::DeviceInfo& val) {
mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
dict.Set("deviceName", val.device_name);
dict.Set("deviceId", val.device_id);
return mate::ConvertToV8(isolate, dict);
}
};
} // namespace mate
namespace atom {
namespace {
const int kMaxScanRetries = 5;
void OnDeviceChosen(
const content::BluetoothChooser::EventHandler& handler,
const std::string& device_id) {
if (device_id.empty()) {
handler.Run(content::BluetoothChooser::Event::CANCELLED, device_id);
} else {
handler.Run(content::BluetoothChooser::Event::SELECTED, device_id);
}
}
} // namespace
BluetoothChooser::BluetoothChooser(
api::WebContents* contents,
const EventHandler& event_handler)
: api_web_contents_(contents),
event_handler_(event_handler),
num_retries_(0) {
}
BluetoothChooser::~BluetoothChooser() {
}
void BluetoothChooser::SetAdapterPresence(AdapterPresence presence) {
switch (presence) {
case AdapterPresence::ABSENT:
case AdapterPresence::POWERED_OFF:
event_handler_.Run(Event::CANCELLED, "");
break;
case AdapterPresence::POWERED_ON:
break;
}
}
void BluetoothChooser::ShowDiscoveryState(DiscoveryState state) {
switch (state) {
case DiscoveryState::FAILED_TO_START:
event_handler_.Run(Event::CANCELLED, "");
break;
case DiscoveryState::IDLE:
if (device_list_.empty()) {
auto event = ++num_retries_ > kMaxScanRetries ? Event::CANCELLED
: Event::RESCAN;
event_handler_.Run(event, "");
} else {
bool prevent_default =
api_web_contents_->Emit("select-bluetooth-device",
device_list_,
base::Bind(&OnDeviceChosen,
event_handler_));
if (!prevent_default) {
auto device_id = device_list_[0].device_id;
event_handler_.Run(Event::SELECTED, device_id);
}
}
break;
case DiscoveryState::DISCOVERING:
break;
}
}
void BluetoothChooser::AddDevice(const std::string& device_id,
const base::string16& device_name) {
DeviceInfo info = {device_id, device_name};
device_list_.push_back(info);
}
void BluetoothChooser::RemoveDevice(const std::string& device_id) {
for (auto it = device_list_.begin(); it != device_list_.end(); ++it) {
if (it->device_id == device_id) {
device_list_.erase(it);
return;
}
}
}
} // namespace atom

View file

@ -0,0 +1,45 @@
// 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_LIB_BLUETOOTH_CHOOSER_H_
#define ATOM_BROWSER_LIB_BLUETOOTH_CHOOSER_H_
#include <string>
#include <vector>
#include "atom/browser/api/atom_api_web_contents.h"
#include "content/public/browser/bluetooth_chooser.h"
namespace atom {
class BluetoothChooser : public content::BluetoothChooser {
public:
struct DeviceInfo {
std::string device_id;
base::string16 device_name;
};
explicit BluetoothChooser(api::WebContents* contents,
const EventHandler& handler);
~BluetoothChooser() override;
// content::BluetoothChooser:
void SetAdapterPresence(AdapterPresence presence) override;
void ShowDiscoveryState(DiscoveryState state) override;
void AddDevice(const std::string& device_id,
const base::string16& device_name) override;
void RemoveDevice(const std::string& device_id) override;
private:
std::vector<DeviceInfo> device_list_;
api::WebContents* api_web_contents_;
EventHandler event_handler_;
int num_retries_;
DISALLOW_COPY_AND_ASSIGN(BluetoothChooser);
};
} // namespace atom
#endif // ATOM_BROWSER_LIB_BLUETOOTH_CHOOSER_H_

View file

@ -37,10 +37,11 @@ LoginHandler::LoginHandler(net::AuthChallengeInfo* auth_info,
render_frame_id_(0) { render_frame_id_(0) {
content::ResourceRequestInfo::ForRequest(request_)->GetAssociatedRenderFrame( content::ResourceRequestInfo::ForRequest(request_)->GetAssociatedRenderFrame(
&render_process_host_id_, &render_frame_id_); &render_process_host_id_, &render_frame_id_);
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, BrowserThread::PostTask(
base::Bind(&Browser::RequestLogin, BrowserThread::UI, FROM_HERE,
base::Unretained(Browser::Get()), base::Bind(&Browser::RequestLogin,
make_scoped_refptr(this))); base::Unretained(Browser::Get()),
base::RetainedRef(make_scoped_refptr(this))));
} }
LoginHandler::~LoginHandler() { LoginHandler::~LoginHandler() {

View file

@ -21,6 +21,8 @@
- (void)setHandlingSendEvent:(BOOL)handlingSendEvent; - (void)setHandlingSendEvent:(BOOL)handlingSendEvent;
- (NSUserActivity*)getCurrentActivity; - (NSUserActivity*)getCurrentActivity;
- (void)setCurrentActivity:(NSString*)type withUserInfo:(NSDictionary*)userInfo; - (void)setCurrentActivity:(NSString*)type
withUserInfo:(NSDictionary*)userInfo
withWebpageURL:(NSURL*)webpageURL;
@end @end

View file

@ -29,10 +29,12 @@
} }
- (void)setCurrentActivity:(NSString*)type - (void)setCurrentActivity:(NSString*)type
withUserInfo:(NSDictionary*)userInfo { withUserInfo:(NSDictionary*)userInfo
withWebpageURL:(NSURL*)webpageURL {
currentActivity_ = base::scoped_nsobject<NSUserActivity>( currentActivity_ = base::scoped_nsobject<NSUserActivity>(
[[NSUserActivity alloc] initWithActivityType:type]); [[NSUserActivity alloc] initWithActivityType:type]);
[currentActivity_ setUserInfo:userInfo]; [currentActivity_ setUserInfo:userInfo];
[currentActivity_ setWebpageURL:webpageURL];
[currentActivity_ becomeCurrent]; [currentActivity_ becomeCurrent];
} }

View file

@ -65,7 +65,7 @@
continueUserActivity:(NSUserActivity*)userActivity continueUserActivity:(NSUserActivity*)userActivity
restorationHandler:(void (^)(NSArray*restorableObjects))restorationHandler { restorationHandler:(void (^)(NSArray*restorableObjects))restorationHandler {
std::string activity_type(base::SysNSStringToUTF8(userActivity.activityType)); std::string activity_type(base::SysNSStringToUTF8(userActivity.activityType));
scoped_ptr<base::DictionaryValue> user_info = std::unique_ptr<base::DictionaryValue> user_info =
atom::NSDictionaryToDictionaryValue(userActivity.userInfo); atom::NSDictionaryToDictionaryValue(userActivity.userInfo);
if (!user_info) if (!user_info)
return NO; return NO;

View file

@ -18,7 +18,7 @@ namespace atom {
NSDictionary* DictionaryValueToNSDictionary(const base::DictionaryValue& value); NSDictionary* DictionaryValueToNSDictionary(const base::DictionaryValue& value);
scoped_ptr<base::DictionaryValue> NSDictionaryToDictionaryValue( std::unique_ptr<base::DictionaryValue> NSDictionaryToDictionaryValue(
NSDictionary* dict); NSDictionary* dict);
} // namespace atom } // namespace atom

View file

@ -4,13 +4,55 @@
#include "atom/browser/mac/dict_util.h" #include "atom/browser/mac/dict_util.h"
#include "base/mac/scoped_nsobject.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h" #include "base/json/json_writer.h"
#include "base/strings/sys_string_conversions.h"
#include "base/values.h" #include "base/values.h"
namespace atom { namespace atom {
namespace {
std::unique_ptr<base::ListValue> NSArrayToListValue(NSArray* arr) {
if (!arr)
return nullptr;
std::unique_ptr<base::ListValue> result(new base::ListValue);
for (id value in arr) {
if ([value isKindOfClass:[NSString class]]) {
result->AppendString(base::SysNSStringToUTF8(value));
} else if ([value isKindOfClass:[NSNumber class]]) {
const char* objc_type = [value objCType];
if (strcmp(objc_type, @encode(BOOL)) == 0 ||
strcmp(objc_type, @encode(char)) == 0)
result->AppendBoolean([value boolValue]);
else if (strcmp(objc_type, @encode(double)) == 0 ||
strcmp(objc_type, @encode(float)) == 0)
result->AppendDouble([value doubleValue]);
else
result->AppendInteger([value intValue]);
} else if ([value isKindOfClass:[NSArray class]]) {
std::unique_ptr<base::ListValue> sub_arr = NSArrayToListValue(value);
if (sub_arr)
result->Append(std::move(sub_arr));
else
result->Append(base::Value::CreateNullValue());
} else if ([value isKindOfClass:[NSDictionary class]]) {
std::unique_ptr<base::DictionaryValue> sub_dict =
NSDictionaryToDictionaryValue(value);
if (sub_dict)
result->Append(std::move(sub_dict));
else
result->Append(base::Value::CreateNullValue());
} else {
result->AppendString(base::SysNSStringToUTF8([value description]));
}
}
return result;
}
} // namespace
NSDictionary* DictionaryValueToNSDictionary(const base::DictionaryValue& value) { NSDictionary* DictionaryValueToNSDictionary(const base::DictionaryValue& value) {
std::string json; std::string json;
if (!base::JSONWriter::Write(value, &json)) if (!base::JSONWriter::Write(value, &json))
@ -24,19 +66,53 @@ NSDictionary* DictionaryValueToNSDictionary(const base::DictionaryValue& value)
return obj; return obj;
} }
scoped_ptr<base::DictionaryValue> NSDictionaryToDictionaryValue( std::unique_ptr<base::DictionaryValue> NSDictionaryToDictionaryValue(
NSDictionary* dict) { NSDictionary* dict) {
NSData* data = [NSJSONSerialization dataWithJSONObject:dict if (!dict)
options:0
error:nil];
if (!data)
return nullptr; return nullptr;
base::scoped_nsobject<NSString> json = std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue);
[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; for (id key in dict) {
scoped_ptr<base::Value> value = std::string str_key = base::SysNSStringToUTF8(
base::JSONReader::Read([json UTF8String]); [key isKindOfClass:[NSString class]] ? key : [key description]);
return base::DictionaryValue::From(std::move(value));
id value = [dict objectForKey:key];
if ([value isKindOfClass:[NSString class]]) {
result->SetStringWithoutPathExpansion(
str_key, base::SysNSStringToUTF8(value));
} else if ([value isKindOfClass:[NSNumber class]]) {
const char* objc_type = [value objCType];
if (strcmp(objc_type, @encode(BOOL)) == 0 ||
strcmp(objc_type, @encode(char)) == 0)
result->SetBooleanWithoutPathExpansion(str_key, [value boolValue]);
else if (strcmp(objc_type, @encode(double)) == 0 ||
strcmp(objc_type, @encode(float)) == 0)
result->SetDoubleWithoutPathExpansion(str_key, [value doubleValue]);
else
result->SetIntegerWithoutPathExpansion(str_key, [value intValue]);
} else if ([value isKindOfClass:[NSArray class]]) {
std::unique_ptr<base::ListValue> sub_arr = NSArrayToListValue(value);
if (sub_arr)
result->SetWithoutPathExpansion(str_key, std::move(sub_arr));
else
result->SetWithoutPathExpansion(str_key,
base::Value::CreateNullValue());
} else if ([value isKindOfClass:[NSDictionary class]]) {
std::unique_ptr<base::DictionaryValue> sub_dict =
NSDictionaryToDictionaryValue(value);
if (sub_dict)
result->SetWithoutPathExpansion(str_key, std::move(sub_dict));
else
result->SetWithoutPathExpansion(str_key,
base::Value::CreateNullValue());
} else {
result->SetStringWithoutPathExpansion(
str_key,
base::SysNSStringToUTF8([value description]));
}
}
return result;
} }
} // namespace atom } // namespace atom

View file

@ -12,12 +12,11 @@
#include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/window_list.h" #include "atom/browser/window_list.h"
#include "atom/common/api/api_messages.h" #include "atom/common/api/api_messages.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/file_path_converter.h" #include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/options_switches.h" #include "atom/common/options_switches.h"
#include "base/files/file_util.h" #include "base/files/file_util.h"
#include "base/json/json_writer.h" #include "base/json/json_writer.h"
#include "base/prefs/pref_service.h" #include "components/prefs/pref_service.h"
#include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop.h"
#include "base/strings/utf_string_conversions.h" #include "base/strings/utf_string_conversions.h"
#include "brightray/browser/inspectable_web_contents.h" #include "brightray/browser/inspectable_web_contents.h"
@ -49,12 +48,12 @@ NativeWindow::NativeWindow(
const mate::Dictionary& options) const mate::Dictionary& options)
: content::WebContentsObserver(inspectable_web_contents->GetWebContents()), : content::WebContentsObserver(inspectable_web_contents->GetWebContents()),
has_frame_(true), has_frame_(true),
force_using_draggable_region_(false),
transparent_(false), transparent_(false),
enable_larger_than_screen_(false), enable_larger_than_screen_(false),
is_closed_(false), is_closed_(false),
has_dialog_attached_(false), has_dialog_attached_(false),
sheet_offset_(0.0), sheet_offset_x_(0.0),
sheet_offset_y_(0.0),
aspect_ratio_(0.0), aspect_ratio_(0.0),
inspectable_web_contents_(inspectable_web_contents), inspectable_web_contents_(inspectable_web_contents),
weak_factory_(this) { weak_factory_(this) {
@ -66,9 +65,6 @@ NativeWindow::NativeWindow(
// mode. // mode.
ui::GpuSwitchingManager::SetTransparent(transparent_); ui::GpuSwitchingManager::SetTransparent(transparent_);
// Read icon before window is created.
options.Get(options::kIcon, &icon_);
WindowList::AddWindow(this); WindowList::AddWindow(this);
} }
@ -141,11 +137,14 @@ void NativeWindow::InitFromOptions(const mate::Dictionary& options) {
if (options.Get(options::kAlwaysOnTop, &top) && top) { if (options.Get(options::kAlwaysOnTop, &top) && top) {
SetAlwaysOnTop(true); SetAlwaysOnTop(true);
} }
// Disable fullscreen button if 'fullscreen' is specified to false.
bool fullscreenable = true; bool fullscreenable = true;
bool fullscreen = false; bool fullscreen = false;
if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) {
// Disable fullscreen button if 'fullscreen' is specified to false.
#if defined(OS_MACOSX)
fullscreenable = false; fullscreenable = false;
#endif
}
// Overriden by 'fullscreenable'. // Overriden by 'fullscreenable'.
options.Get(options::kFullScreenable, &fullscreenable); options.Get(options::kFullScreenable, &fullscreenable);
SetFullScreenable(fullscreenable); SetFullScreenable(fullscreenable);
@ -255,12 +254,17 @@ gfx::Size NativeWindow::GetMaximumSize() {
return GetSizeConstraints().GetMaximumSize(); return GetSizeConstraints().GetMaximumSize();
} }
void NativeWindow::SetSheetOffset(const double offset) { void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) {
sheet_offset_ = offset; sheet_offset_x_ = offsetX;
sheet_offset_y_ = offsetY;
} }
double NativeWindow::GetSheetOffset() { double NativeWindow::GetSheetOffsetX() {
return sheet_offset_; return sheet_offset_x_;
}
double NativeWindow::GetSheetOffsetY() {
return sheet_offset_y_;
} }
void NativeWindow::SetRepresentedFilename(const std::string& filename) { void NativeWindow::SetRepresentedFilename(const std::string& filename) {
@ -318,9 +322,9 @@ void NativeWindow::CapturePage(const gfx::Rect& rect,
// current system, increase the requested bitmap size to capture it all. // current system, increase the requested bitmap size to capture it all.
gfx::Size bitmap_size = view_size; gfx::Size bitmap_size = view_size;
const gfx::NativeView native_view = view->GetNativeView(); const gfx::NativeView native_view = view->GetNativeView();
gfx::Screen* const screen = gfx::Screen::GetScreenFor(native_view);
const float scale = const float scale =
screen->GetDisplayNearestWindow(native_view).device_scale_factor(); gfx::Screen::GetScreen()->GetDisplayNearestWindow(native_view)
.device_scale_factor();
if (scale > 1.0f) if (scale > 1.0f)
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
@ -412,7 +416,7 @@ void NativeWindow::RendererUnresponsive(content::WebContents* source) {
// responsive event soon. This could happen after the whole application had // responsive event soon. This could happen after the whole application had
// blocked for a while. // blocked for a while.
// Also notice that when closing this event would be ignored because we have // Also notice that when closing this event would be ignored because we have
// explicity started a close timeout counter. This is on purpose because we // explicitly started a close timeout counter. This is on purpose because we
// don't want the unresponsive event to be sent too early when user is closing // don't want the unresponsive event to be sent too early when user is closing
// the window. // the window.
ScheduleUnresponsiveEvent(50); ScheduleUnresponsiveEvent(50);
@ -526,9 +530,9 @@ void NativeWindow::NotifyWindowMessage(
} }
#endif #endif
scoped_ptr<SkRegion> NativeWindow::DraggableRegionsToSkRegion( std::unique_ptr<SkRegion> NativeWindow::DraggableRegionsToSkRegion(
const std::vector<DraggableRegion>& regions) { const std::vector<DraggableRegion>& regions) {
scoped_ptr<SkRegion> sk_region(new SkRegion); std::unique_ptr<SkRegion> sk_region(new SkRegion);
for (const DraggableRegion& region : regions) { for (const DraggableRegion& region : regions) {
sk_region->op( sk_region->op(
region.bounds.x(), region.bounds.x(),
@ -573,7 +577,7 @@ bool NativeWindow::OnMessageReceived(const IPC::Message& message) {
void NativeWindow::UpdateDraggableRegions( void NativeWindow::UpdateDraggableRegions(
const std::vector<DraggableRegion>& regions) { const std::vector<DraggableRegion>& regions) {
// Draggable region is not supported for non-frameless window. // Draggable region is not supported for non-frameless window.
if (has_frame_ && !force_using_draggable_region_) if (has_frame_)
return; return;
draggable_region_ = DraggableRegionsToSkRegion(regions); draggable_region_ = DraggableRegionsToSkRegion(regions);
} }

View file

@ -123,8 +123,9 @@ class NativeWindow : public base::SupportsUserData,
virtual gfx::Size GetMinimumSize(); virtual gfx::Size GetMinimumSize();
virtual void SetMaximumSize(const gfx::Size& size); virtual void SetMaximumSize(const gfx::Size& size);
virtual gfx::Size GetMaximumSize(); virtual gfx::Size GetMaximumSize();
virtual void SetSheetOffset(const double offset); virtual void SetSheetOffset(const double offsetX, const double offsetY);
virtual double GetSheetOffset(); virtual double GetSheetOffsetX();
virtual double GetSheetOffsetY();
virtual void SetResizable(bool resizable) = 0; virtual void SetResizable(bool resizable) = 0;
virtual bool IsResizable() = 0; virtual bool IsResizable() = 0;
virtual void SetMovable(bool movable) = 0; virtual void SetMovable(bool movable) = 0;
@ -190,7 +191,7 @@ class NativeWindow : public base::SupportsUserData,
// Set the aspect ratio when resizing window. // Set the aspect ratio when resizing window.
double GetAspectRatio(); double GetAspectRatio();
gfx::Size GetAspectRatioExtraSize(); gfx::Size GetAspectRatioExtraSize();
void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size); virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size);
base::WeakPtr<NativeWindow> GetWeakPtr() { base::WeakPtr<NativeWindow> GetWeakPtr() {
return weak_factory_.GetWeakPtr(); return weak_factory_.GetWeakPtr();
@ -246,17 +247,11 @@ class NativeWindow : public base::SupportsUserData,
} }
bool has_frame() const { return has_frame_; } bool has_frame() const { return has_frame_; }
void set_has_frame(bool has_frame) { has_frame_ = has_frame; }
bool transparent() const { return transparent_; } bool transparent() const { return transparent_; }
SkRegion* draggable_region() const { return draggable_region_.get(); } SkRegion* draggable_region() const { return draggable_region_.get(); }
bool enable_larger_than_screen() const { return enable_larger_than_screen_; } bool enable_larger_than_screen() const { return enable_larger_than_screen_; }
gfx::ImageSkia icon() const { return icon_; }
bool force_using_draggable_region() const {
return force_using_draggable_region_;
}
void set_force_using_draggable_region(bool force) {
force_using_draggable_region_ = true;
}
void set_has_dialog_attached(bool has_dialog_attached) { void set_has_dialog_attached(bool has_dialog_attached) {
has_dialog_attached_ = has_dialog_attached; has_dialog_attached_ = has_dialog_attached;
@ -268,7 +263,7 @@ class NativeWindow : public base::SupportsUserData,
// Convert draggable regions in raw format to SkRegion format. Caller is // Convert draggable regions in raw format to SkRegion format. Caller is
// responsible for deleting the returned SkRegion instance. // responsible for deleting the returned SkRegion instance.
scoped_ptr<SkRegion> DraggableRegionsToSkRegion( std::unique_ptr<SkRegion> DraggableRegionsToSkRegion(
const std::vector<DraggableRegion>& regions); const std::vector<DraggableRegion>& regions);
// Converts between content size to window size. // Converts between content size to window size.
@ -299,15 +294,12 @@ class NativeWindow : public base::SupportsUserData,
// Whether window has standard frame. // Whether window has standard frame.
bool has_frame_; bool has_frame_;
// Force the window to be aware of draggable regions.
bool force_using_draggable_region_;
// Whether window is transparent. // Whether window is transparent.
bool transparent_; bool transparent_;
// For custom drag, the whole window is non-draggable and the draggable region // For custom drag, the whole window is non-draggable and the draggable region
// has to been explicitly provided. // has to been explicitly provided.
scoped_ptr<SkRegion> draggable_region_; // used in custom drag. std::unique_ptr<SkRegion> draggable_region_; // used in custom drag.
// Minimum and maximum size, stored as content size. // Minimum and maximum size, stored as content size.
extensions::SizeConstraints size_constraints_; extensions::SizeConstraints size_constraints_;
@ -315,9 +307,6 @@ class NativeWindow : public base::SupportsUserData,
// Whether window can be resized larger than screen. // Whether window can be resized larger than screen.
bool enable_larger_than_screen_; bool enable_larger_than_screen_;
// Window icon.
gfx::ImageSkia icon_;
// The windows has been closed. // The windows has been closed.
bool is_closed_; bool is_closed_;
@ -328,8 +317,10 @@ class NativeWindow : public base::SupportsUserData,
// it should be cancelled when we can prove that the window is responsive. // it should be cancelled when we can prove that the window is responsive.
base::CancelableClosure window_unresposive_closure_; base::CancelableClosure window_unresposive_closure_;
// Used to display sheets at the appropriate vertical offset // Used to display sheets at the appropriate horizontal and vertical offsets
double sheet_offset_; // on OS X.
double sheet_offset_x_;
double sheet_offset_y_;
// Used to maintain the aspect ratio of a view which is inside of the // Used to maintain the aspect ratio of a view which is inside of the
// content view. // content view.

View file

@ -49,6 +49,8 @@ class NativeWindowMac : public NativeWindow {
void SetResizable(bool resizable) override; void SetResizable(bool resizable) override;
bool IsResizable() override; bool IsResizable() override;
void SetMovable(bool movable) override; void SetMovable(bool movable) override;
void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size)
override;
bool IsMovable() override; bool IsMovable() override;
void SetMinimizable(bool minimizable) override; void SetMinimizable(bool minimizable) override;
bool IsMinimizable() override; bool IsMinimizable() override;
@ -91,16 +93,15 @@ class NativeWindowMac : public NativeWindow {
UpdateDraggableRegionViews(draggable_regions_); UpdateDraggableRegionViews(draggable_regions_);
} }
// Set the attribute of NSWindow while work around a bug of zoom button.
void SetStyleMask(bool on, NSUInteger flag);
void SetCollectionBehavior(bool on, NSUInteger flag);
bool should_hide_native_toolbar_in_fullscreen() const { bool should_hide_native_toolbar_in_fullscreen() const {
return should_hide_native_toolbar_in_fullscreen_; return should_hide_native_toolbar_in_fullscreen_;
} }
protected: protected:
// NativeWindow:
void HandleKeyboardEvent(
content::WebContents*,
const content::NativeWebKeyboardEvent&) override;
// Return a vector of non-draggable regions that fill a window of size // Return a vector of non-draggable regions that fill a window of size
// |width| by |height|, but leave gaps where the window should be draggable. // |width| by |height|, but leave gaps where the window should be draggable.
std::vector<gfx::Rect> CalculateNonDraggableRegions( std::vector<gfx::Rect> CalculateNonDraggableRegions(
@ -120,10 +121,6 @@ class NativeWindowMac : public NativeWindow {
// whehter we can drag. // whehter we can drag.
void UpdateDraggableRegionViews(const std::vector<DraggableRegion>& regions); void UpdateDraggableRegionViews(const std::vector<DraggableRegion>& regions);
// Set the attribute of NSWindow while work around a bug of zo0m button.
void SetStyleMask(bool on, NSUInteger flag);
void SetCollectionBehavior(bool on, NSUInteger flag);
base::scoped_nsobject<AtomNSWindow> window_; base::scoped_nsobject<AtomNSWindow> window_;
base::scoped_nsobject<AtomNSWindowDelegate> window_delegate_; base::scoped_nsobject<AtomNSWindowDelegate> window_delegate_;
@ -142,6 +139,10 @@ class NativeWindowMac : public NativeWindow {
// The presentation options before entering kiosk mode. // The presentation options before entering kiosk mode.
NSApplicationPresentationOptions kiosk_options_; NSApplicationPresentationOptions kiosk_options_;
// Force showing the buttons for frameless window.
bool force_show_buttons_;
// Whether to hide the native toolbar under fullscreen mode.
bool should_hide_native_toolbar_in_fullscreen_; bool should_hide_native_toolbar_in_fullscreen_;
DISALLOW_COPY_AND_ASSIGN(NativeWindowMac); DISALLOW_COPY_AND_ASSIGN(NativeWindowMac);

View file

@ -6,6 +6,7 @@
#include <string> #include <string>
#include "atom/browser/window_list.h"
#include "atom/common/color_util.h" #include "atom/common/color_util.h"
#include "atom/common/draggable_region.h" #include "atom/common/draggable_region.h"
#include "atom/common/options_switches.h" #include "atom/common/options_switches.h"
@ -15,7 +16,6 @@
#include "brightray/browser/inspectable_web_contents.h" #include "brightray/browser/inspectable_web_contents.h"
#include "brightray/browser/inspectable_web_contents_view.h" #include "brightray/browser/inspectable_web_contents_view.h"
#include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents.h"
#include "content/public/browser/render_view_host.h" #include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/render_widget_host_view.h"
@ -142,22 +142,9 @@ bool ScopedDisableResize::disable_resize_ = false;
newSize.width = newSize.width =
roundf((frameSize.height - extraHeightPlusFrame) * aspectRatio + roundf((frameSize.height - extraHeightPlusFrame) * aspectRatio +
extraWidthPlusFrame); extraWidthPlusFrame);
newSize.height =
// If the new width is less than the frame size use it as the primary roundf((newSize.width - extraWidthPlusFrame) / aspectRatio +
// constraint. This ensures that the value returned by this method will extraHeightPlusFrame);
// never be larger than the users requested window size.
if (newSize.width <= frameSize.width) {
newSize.height =
roundf((newSize.width - extraWidthPlusFrame) / aspectRatio +
extraHeightPlusFrame);
} else {
newSize.height =
roundf((frameSize.width - extraWidthPlusFrame) / aspectRatio +
extraHeightPlusFrame);
newSize.width =
roundf((newSize.height - extraHeightPlusFrame) * aspectRatio +
extraWidthPlusFrame);
}
} }
return newSize; return newSize;
@ -214,10 +201,22 @@ bool ScopedDisableResize::disable_resize_ = false;
[[NSToolbar alloc] initWithIdentifier:@"titlebarStylingToolbar"]); [[NSToolbar alloc] initWithIdentifier:@"titlebarStylingToolbar"]);
[toolbar setShowsBaselineSeparator:NO]; [toolbar setShowsBaselineSeparator:NO];
[window setToolbar:toolbar]; [window setToolbar:toolbar];
// Set window style to hide the toolbar, otherwise the toolbar will show in
// fullscreen mode.
shell_->SetStyleMask(true, NSFullSizeContentViewWindowMask);
} }
} }
- (void)windowWillExitFullScreen:(NSNotification*)notification {
// Turn off the style for toolbar.
if (shell_->should_hide_native_toolbar_in_fullscreen())
shell_->SetStyleMask(false, NSFullSizeContentViewWindowMask);
}
- (void)windowDidExitFullScreen:(NSNotification*)notification { - (void)windowDidExitFullScreen:(NSNotification*)notification {
// For certain versions of OS X the fullscreen button will automatically show
// after exiting fullscreen mode.
if (!shell_->has_frame()) { if (!shell_->has_frame()) {
NSWindow* window = shell_->GetNativeWindow(); NSWindow* window = shell_->GetNativeWindow();
[[window standardWindowButton:NSWindowFullScreenButton] setHidden:YES]; [[window standardWindowButton:NSWindowFullScreenButton] setHidden:YES];
@ -246,7 +245,9 @@ bool ScopedDisableResize::disable_resize_ = false;
- (NSRect)window:(NSWindow*)window - (NSRect)window:(NSWindow*)window
willPositionSheet:(NSWindow*)sheet usingRect:(NSRect)rect { willPositionSheet:(NSWindow*)sheet usingRect:(NSRect)rect {
NSView* view = window.contentView; NSView* view = window.contentView;
rect.origin.y = view.frame.size.height - shell_->GetSheetOffset();
rect.origin.x = shell_->GetSheetOffsetX();
rect.origin.y = view.frame.size.height - shell_->GetSheetOffsetY();
return rect; return rect;
} }
@ -391,6 +392,7 @@ NativeWindowMac::NativeWindowMac(
: NativeWindow(web_contents, options), : NativeWindow(web_contents, options),
is_kiosk_(false), is_kiosk_(false),
attention_request_id_(0), attention_request_id_(0),
force_show_buttons_(false),
should_hide_native_toolbar_in_fullscreen_(false) { should_hide_native_toolbar_in_fullscreen_(false) {
int width = 800, height = 600; int width = 800, height = 600;
options.Get(options::kWidth, &width); options.Get(options::kWidth, &width);
@ -438,22 +440,17 @@ NativeWindowMac::NativeWindowMac(
if (closable) { if (closable) {
styleMask |= NSClosableWindowMask; styleMask |= NSClosableWindowMask;
} }
if ((titleBarStyle == "hidden") || (titleBarStyle == "hidden-inset")) {
// The window without titlebar is treated the same with frameless window.
set_has_frame(false);
force_show_buttons_ = true;
}
if (!useStandardWindow || transparent() || !has_frame()) { if (!useStandardWindow || transparent() || !has_frame()) {
styleMask |= NSTexturedBackgroundWindowMask; styleMask |= NSTexturedBackgroundWindowMask;
} }
if (resizable) { if (resizable) {
styleMask |= NSResizableWindowMask; styleMask |= NSResizableWindowMask;
} }
if ((titleBarStyle == "hidden") || (titleBarStyle == "hidden-inset")) {
styleMask |= NSFullSizeContentViewWindowMask;
styleMask |= NSUnifiedTitleAndToolbarWindowMask;
}
// We capture this because we need to access the option later when
// entering/exiting fullscreen and since the options dict is only passed to
// the constructor but not stored, lets store this option this way.
if (titleBarStyle == "hidden-inset") {
should_hide_native_toolbar_in_fullscreen_ = true;
}
window_.reset([[AtomNSWindow alloc] window_.reset([[AtomNSWindow alloc]
initWithContentRect:cocoa_bounds initWithContentRect:cocoa_bounds
@ -490,17 +487,14 @@ NativeWindowMac::NativeWindowMac(
[window_ setReleasedWhenClosed:NO]; [window_ setReleasedWhenClosed:NO];
// Hide the title bar. // Hide the title bar.
if ((titleBarStyle == "hidden") || (titleBarStyle == "hidden-inset")) { if (titleBarStyle == "hidden-inset") {
[window_ setTitlebarAppearsTransparent:YES]; [window_ setTitlebarAppearsTransparent:YES];
[window_ setTitleVisibility:NSWindowTitleHidden]; [window_ setTitleVisibility:NSWindowTitleHidden];
if (titleBarStyle == "hidden-inset") { base::scoped_nsobject<NSToolbar> toolbar(
base::scoped_nsobject<NSToolbar> toolbar( [[NSToolbar alloc] initWithIdentifier:@"titlebarStylingToolbar"]);
[[NSToolbar alloc] initWithIdentifier:@"titlebarStylingToolbar"]); [toolbar setShowsBaselineSeparator:NO];
[toolbar setShowsBaselineSeparator:NO]; [window_ setToolbar:toolbar];
[window_ setToolbar:toolbar]; should_hide_native_toolbar_in_fullscreen_ = true;
}
// We should be aware of draggable regions when using hidden titlebar.
set_force_using_draggable_region(true);
} }
// On OS X the initial window size doesn't include window frame. // On OS X the initial window size doesn't include window frame.
@ -558,6 +552,11 @@ NativeWindowMac::~NativeWindowMac() {
} }
void NativeWindowMac::Close() { void NativeWindowMac::Close() {
if (!IsClosable()) {
WindowList::WindowCloseCancelled(this);
return;
}
[window_ performClose:nil]; [window_ performClose:nil];
} }
@ -713,6 +712,17 @@ bool NativeWindowMac::IsResizable() {
return [window_ styleMask] & NSResizableWindowMask; return [window_ styleMask] & NSResizableWindowMask;
} }
void NativeWindowMac::SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) {
NativeWindow::SetAspectRatio(aspect_ratio, extra_size);
// Reset the behaviour to default if aspect_ratio is set to 0 or less.
if (aspect_ratio > 0.0)
[window_ setAspectRatio:NSMakeSize(aspect_ratio, 1.0)];
else
[window_ setResizeIncrements:NSMakeSize(1.0, 1.0)];
}
void NativeWindowMac::SetMovable(bool movable) { void NativeWindowMac::SetMovable(bool movable) {
[window_ setMovable:movable]; [window_ setMovable:movable];
} }
@ -928,35 +938,14 @@ bool NativeWindowMac::IsVisibleOnAllWorkspaces() {
return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces;
} }
void NativeWindowMac::HandleKeyboardEvent(
content::WebContents*,
const content::NativeWebKeyboardEvent& event) {
if (event.skip_in_browser ||
event.type == content::NativeWebKeyboardEvent::Char)
return;
BOOL handled = [[NSApp mainMenu] performKeyEquivalent:event.os_event];
if (!handled && event.os_event.window) {
// Handle the cmd+~ shortcut.
if ((event.os_event.modifierFlags & NSCommandKeyMask) /* cmd */ &&
(event.os_event.keyCode == 50 /* ~ */)) {
if (event.os_event.modifierFlags & NSShiftKeyMask) {
[NSApp sendAction:@selector(_cycleWindowsReversed:) to:nil from:nil];
} else {
[NSApp sendAction:@selector(_cycleWindows:) to:nil from:nil];
}
}
}
}
std::vector<gfx::Rect> NativeWindowMac::CalculateNonDraggableRegions( std::vector<gfx::Rect> NativeWindowMac::CalculateNonDraggableRegions(
const std::vector<DraggableRegion>& regions, int width, int height) { const std::vector<DraggableRegion>& regions, int width, int height) {
std::vector<gfx::Rect> result; std::vector<gfx::Rect> result;
if (regions.empty()) { if (regions.empty()) {
result.push_back(gfx::Rect(0, 0, width, height)); result.push_back(gfx::Rect(0, 0, width, height));
} else { } else {
scoped_ptr<SkRegion> draggable(DraggableRegionsToSkRegion(regions)); std::unique_ptr<SkRegion> draggable(DraggableRegionsToSkRegion(regions));
scoped_ptr<SkRegion> non_draggable(new SkRegion); std::unique_ptr<SkRegion> non_draggable(new SkRegion);
non_draggable->op(0, 0, width, height, SkRegion::kUnion_Op); non_draggable->op(0, 0, width, height, SkRegion::kUnion_Op);
non_draggable->op(*draggable, SkRegion::kDifference_Op); non_draggable->op(*draggable, SkRegion::kDifference_Op);
for (SkRegion::Iterator it(*non_draggable); !it.done(); it.next()) { for (SkRegion::Iterator it(*non_draggable); !it.done(); it.next()) {
@ -1013,6 +1002,10 @@ void NativeWindowMac::InstallView() {
[view setFrame:[content_view_ bounds]]; [view setFrame:[content_view_ bounds]];
[content_view_ addSubview:view]; [content_view_ addSubview:view];
if (force_show_buttons_)
return;
// Hide the window buttons.
[[window_ standardWindowButton:NSWindowZoomButton] setHidden:YES]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:YES];
[[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES];
[[window_ standardWindowButton:NSWindowCloseButton] setHidden:YES]; [[window_ standardWindowButton:NSWindowCloseButton] setHidden:YES];
@ -1031,7 +1024,7 @@ void NativeWindowMac::UninstallView() {
void NativeWindowMac::UpdateDraggableRegionViews( void NativeWindowMac::UpdateDraggableRegionViews(
const std::vector<DraggableRegion>& regions) { const std::vector<DraggableRegion>& regions) {
if (has_frame() && !force_using_draggable_region()) if (has_frame())
return; return;
// All ControlRegionViews should be added as children of the WebContentsView, // All ControlRegionViews should be added as children of the WebContentsView,

View file

@ -9,8 +9,10 @@
#include "atom/browser/ui/views/menu_bar.h" #include "atom/browser/ui/views/menu_bar.h"
#include "atom/browser/ui/views/menu_layout.h" #include "atom/browser/ui/views/menu_layout.h"
#include "atom/browser/window_list.h"
#include "atom/common/color_util.h" #include "atom/common/color_util.h"
#include "atom/common/draggable_region.h" #include "atom/common/draggable_region.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/options_switches.h" #include "atom/common/options_switches.h"
#include "base/strings/utf_string_conversions.h" #include "base/strings/utf_string_conversions.h"
#include "brightray/browser/inspectable_web_contents.h" #include "brightray/browser/inspectable_web_contents.h"
@ -40,6 +42,7 @@
#include "chrome/browser/ui/libgtk2ui/unity_service.h" #include "chrome/browser/ui/libgtk2ui/unity_service.h"
#include "ui/base/x/x11_util.h" #include "ui/base/x/x11_util.h"
#include "ui/gfx/x/x11_types.h" #include "ui/gfx/x/x11_types.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_x11.h"
#include "ui/views/window/native_frame_view.h" #include "ui/views/window/native_frame_view.h"
#elif defined(OS_WIN) #elif defined(OS_WIN)
#include "atom/browser/ui/views/win_frame_view.h" #include "atom/browser/ui/views/win_frame_view.h"
@ -273,7 +276,6 @@ NativeWindowViews::NativeWindowViews(
use_content_size_) use_content_size_)
size = ContentSizeToWindowSize(size); size = ContentSizeToWindowSize(size);
window_->UpdateWindowIcon();
window_->CenterWindow(size); window_->CenterWindow(size);
Layout(); Layout();
} }
@ -283,6 +285,11 @@ NativeWindowViews::~NativeWindowViews() {
} }
void NativeWindowViews::Close() { void NativeWindowViews::Close() {
if (!IsClosable()) {
WindowList::WindowCloseCancelled(this);
return;
}
window_->Close(); window_->Close();
} }
@ -623,7 +630,9 @@ void NativeWindowViews::SetBackgroundColor(const std::string& color_name) {
// Set the background color of native window. // Set the background color of native window.
HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color));
ULONG_PTR previous_brush = SetClassLongPtr( ULONG_PTR previous_brush = SetClassLongPtr(
GetAcceleratedWidget(), GCLP_HBRBACKGROUND, (LONG)brush); GetAcceleratedWidget(),
GCLP_HBRBACKGROUND,
reinterpret_cast<LONG_PTR>(brush));
if (previous_brush) if (previous_brush)
DeleteObject((HBRUSH)previous_brush); DeleteObject((HBRUSH)previous_brush);
#endif #endif
@ -776,6 +785,27 @@ gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() {
return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); return GetNativeWindow()->GetHost()->GetAcceleratedWidget();
} }
#if defined(OS_WIN)
void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) {
// We are responsible for storing the images.
window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon));
app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon));
HWND hwnd = GetAcceleratedWidget();
SendMessage(hwnd, WM_SETICON, ICON_SMALL,
reinterpret_cast<LPARAM>(window_icon_.get()));
SendMessage(hwnd, WM_SETICON, ICON_BIG,
reinterpret_cast<LPARAM>(app_icon_.get()));
}
#elif defined(USE_X11)
void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) {
views::DesktopWindowTreeHostX11* tree_host =
views::DesktopWindowTreeHostX11::GetHostForXID(GetAcceleratedWidget());
static_cast<views::DesktopWindowTreeHost*>(tree_host)->SetWindowIcons(
icon, icon);
}
#endif
void NativeWindowViews::OnWidgetActivationChanged( void NativeWindowViews::OnWidgetActivationChanged(
views::Widget* widget, bool active) { views::Widget* widget, bool active) {
if (widget != window_.get()) if (widget != window_.get())
@ -840,14 +870,6 @@ bool NativeWindowViews::ShouldHandleSystemCommands() const {
return true; return true;
} }
gfx::ImageSkia NativeWindowViews::GetWindowAppIcon() {
return icon();
}
gfx::ImageSkia NativeWindowViews::GetWindowIcon() {
return GetWindowAppIcon();
}
views::Widget* NativeWindowViews::GetWidget() { views::Widget* NativeWindowViews::GetWidget() {
return window_.get(); return window_.get();
} }

View file

@ -17,6 +17,7 @@
#if defined(OS_WIN) #if defined(OS_WIN)
#include "atom/browser/ui/win/message_handler_delegate.h" #include "atom/browser/ui/win/message_handler_delegate.h"
#include "atom/browser/ui/win/taskbar_host.h" #include "atom/browser/ui/win/taskbar_host.h"
#include "base/win/scoped_gdi_object.h"
#endif #endif
namespace views { namespace views {
@ -104,6 +105,12 @@ class NativeWindowViews : public NativeWindow,
gfx::AcceleratedWidget GetAcceleratedWidget() override; gfx::AcceleratedWidget GetAcceleratedWidget() override;
#if defined(OS_WIN)
void SetIcon(HICON small_icon, HICON app_icon);
#elif defined(USE_X11)
void SetIcon(const gfx::ImageSkia& icon);
#endif
views::Widget* widget() const { return window_.get(); } views::Widget* widget() const { return window_.get(); }
#if defined(OS_WIN) #if defined(OS_WIN)
@ -125,8 +132,6 @@ class NativeWindowViews : public NativeWindow,
bool CanMinimize() const override; bool CanMinimize() const override;
base::string16 GetWindowTitle() const override; base::string16 GetWindowTitle() const override;
bool ShouldHandleSystemCommands() const override; bool ShouldHandleSystemCommands() const override;
gfx::ImageSkia GetWindowAppIcon() override;
gfx::ImageSkia GetWindowIcon() override;
views::Widget* GetWidget() override; views::Widget* GetWidget() override;
const views::Widget* GetWidget() const override; const views::Widget* GetWidget() const override;
views::View* GetContentsView() override; views::View* GetContentsView() override;
@ -145,7 +150,6 @@ class NativeWindowViews : public NativeWindow,
// MessageHandlerDelegate: // MessageHandlerDelegate:
bool PreHandleMSG( bool PreHandleMSG(
UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) override; UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) override;
void HandleSizeEvent(WPARAM w_param, LPARAM l_param); void HandleSizeEvent(WPARAM w_param, LPARAM l_param);
#endif #endif
@ -167,19 +171,19 @@ class NativeWindowViews : public NativeWindow,
// Returns the restore state for the window. // Returns the restore state for the window.
ui::WindowShowState GetRestoredState(); ui::WindowShowState GetRestoredState();
scoped_ptr<views::Widget> window_; std::unique_ptr<views::Widget> window_;
views::View* web_view_; // Managed by inspectable_web_contents_. views::View* web_view_; // Managed by inspectable_web_contents_.
scoped_ptr<MenuBar> menu_bar_; std::unique_ptr<MenuBar> menu_bar_;
bool menu_bar_autohide_; bool menu_bar_autohide_;
bool menu_bar_visible_; bool menu_bar_visible_;
bool menu_bar_alt_pressed_; bool menu_bar_alt_pressed_;
#if defined(USE_X11) #if defined(USE_X11)
scoped_ptr<GlobalMenuBarX11> global_menu_bar_; std::unique_ptr<GlobalMenuBarX11> global_menu_bar_;
// Handles window state events. // Handles window state events.
scoped_ptr<WindowStateWatcher> window_state_watcher_; std::unique_ptr<WindowStateWatcher> window_state_watcher_;
// The "resizable" flag on Linux is implemented by setting size constraints, // The "resizable" flag on Linux is implemented by setting size constraints,
// we need to make sure size constraints are restored when window becomes // we need to make sure size constraints are restored when window becomes
@ -203,10 +207,13 @@ class NativeWindowViews : public NativeWindow,
// If true we have enabled a11y // If true we have enabled a11y
bool enabled_a11y_support_; bool enabled_a11y_support_;
// The icons of window and taskbar.
base::win::ScopedHICON window_icon_;
base::win::ScopedHICON app_icon_;
#endif #endif
// Handles unhandled keyboard messages coming back from the renderer process. // Handles unhandled keyboard messages coming back from the renderer process.
scoped_ptr<views::UnhandledKeyboardEventHandler> keyboard_event_handler_; std::unique_ptr<views::UnhandledKeyboardEventHandler> keyboard_event_handler_;
// Map from accelerator to menu item's command id. // Map from accelerator to menu item's command id.
accelerator_util::AcceleratorTable accelerator_table_; accelerator_util::AcceleratorTable accelerator_table_;

View file

@ -112,7 +112,7 @@ class URLRequestAsarJob : public net::URLRequestJob {
base::FilePath file_path_; base::FilePath file_path_;
Archive::FileInfo file_info_; Archive::FileInfo file_info_;
scoped_ptr<net::FileStream> stream_; std::unique_ptr<net::FileStream> stream_;
FileMetaInfo meta_info_; FileMetaInfo meta_info_;
scoped_refptr<base::TaskRunner> file_task_runner_; scoped_refptr<base::TaskRunner> file_task_runner_;

View file

@ -48,7 +48,7 @@ int AtomCertVerifier::Verify(
net::CRLSet* crl_set, net::CRLSet* crl_set,
net::CertVerifyResult* verify_result, net::CertVerifyResult* verify_result,
const net::CompletionCallback& callback, const net::CompletionCallback& callback,
scoped_ptr<Request>* out_req, std::unique_ptr<Request>* out_req,
const net::BoundNetLog& net_log) { const net::BoundNetLog& net_log) {
DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_CURRENTLY_ON(BrowserThread::IO);

View file

@ -34,14 +34,14 @@ class AtomCertVerifier : public net::CertVerifier {
net::CRLSet* crl_set, net::CRLSet* crl_set,
net::CertVerifyResult* verify_result, net::CertVerifyResult* verify_result,
const net::CompletionCallback& callback, const net::CompletionCallback& callback,
scoped_ptr<Request>* out_req, std::unique_ptr<Request>* out_req,
const net::BoundNetLog& net_log) override; const net::BoundNetLog& net_log) override;
bool SupportsOCSPStapling() override; bool SupportsOCSPStapling() override;
private: private:
base::Lock lock_; base::Lock lock_;
VerifyProc verify_proc_; VerifyProc verify_proc_;
scoped_ptr<net::CertVerifier> default_cert_verifier_; std::unique_ptr<net::CertVerifier> default_cert_verifier_;
DISALLOW_COPY_AND_ASSIGN(AtomCertVerifier); DISALLOW_COPY_AND_ASSIGN(AtomCertVerifier);
}; };

View file

@ -45,13 +45,13 @@ using ResponseHeadersContainer =
std::pair<scoped_refptr<net::HttpResponseHeaders>*, const std::string&>; std::pair<scoped_refptr<net::HttpResponseHeaders>*, const std::string&>;
void RunSimpleListener(const AtomNetworkDelegate::SimpleListener& listener, void RunSimpleListener(const AtomNetworkDelegate::SimpleListener& listener,
scoped_ptr<base::DictionaryValue> details) { std::unique_ptr<base::DictionaryValue> details) {
return listener.Run(*(details.get())); return listener.Run(*(details.get()));
} }
void RunResponseListener( void RunResponseListener(
const AtomNetworkDelegate::ResponseListener& listener, const AtomNetworkDelegate::ResponseListener& listener,
scoped_ptr<base::DictionaryValue> details, std::unique_ptr<base::DictionaryValue> details,
const AtomNetworkDelegate::ResponseCallback& callback) { const AtomNetworkDelegate::ResponseCallback& callback) {
return listener.Run(*(details.get()), callback); return listener.Run(*(details.get()), callback);
} }
@ -79,7 +79,7 @@ void ToDictionary(base::DictionaryValue* details, net::URLRequest* request) {
details->SetString("resourceType", details->SetString("resourceType",
info ? ResourceTypeToString(info->GetResourceType()) info ? ResourceTypeToString(info->GetResourceType())
: "other"); : "other");
scoped_ptr<base::ListValue> list(new base::ListValue); std::unique_ptr<base::ListValue> list(new base::ListValue);
GetUploadData(list.get(), request); GetUploadData(list.get(), request);
if (!list->empty()) if (!list->empty())
details->Set("uploadData", std::move(list)); details->Set("uploadData", std::move(list));
@ -87,7 +87,7 @@ void ToDictionary(base::DictionaryValue* details, net::URLRequest* request) {
void ToDictionary(base::DictionaryValue* details, void ToDictionary(base::DictionaryValue* details,
const net::HttpRequestHeaders& headers) { const net::HttpRequestHeaders& headers) {
scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue); std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
net::HttpRequestHeaders::Iterator it(headers); net::HttpRequestHeaders::Iterator it(headers);
while (it.GetNext()) while (it.GetNext())
dict->SetString(it.name(), it.value()); dict->SetString(it.name(), it.value());
@ -99,8 +99,8 @@ void ToDictionary(base::DictionaryValue* details,
if (!headers) if (!headers)
return; return;
scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue); std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
void* iter = nullptr; size_t iter = 0;
std::string key; std::string key;
std::string value; std::string value;
while (headers->EnumerateHeaderLines(&iter, &key, &value)) { while (headers->EnumerateHeaderLines(&iter, &key, &value)) {
@ -109,7 +109,7 @@ void ToDictionary(base::DictionaryValue* details,
if (dict->GetList(key, &values)) if (dict->GetList(key, &values))
values->AppendString(value); values->AppendString(value);
} else { } else {
scoped_ptr<base::ListValue> values(new base::ListValue); std::unique_ptr<base::ListValue> values(new base::ListValue);
values->AppendString(value); values->AppendString(value);
dict->Set(key, std::move(values)); dict->Set(key, std::move(values));
} }
@ -369,7 +369,7 @@ int AtomNetworkDelegate::HandleResponseEvent(
if (!MatchesFilterCondition(request, info.url_patterns)) if (!MatchesFilterCondition(request, info.url_patterns))
return net::OK; return net::OK;
scoped_ptr<base::DictionaryValue> details(new base::DictionaryValue); std::unique_ptr<base::DictionaryValue> details(new base::DictionaryValue);
FillDetailsObject(details.get(), request, args...); FillDetailsObject(details.get(), request, args...);
// The |request| could be destroyed before the |callback| is called. // The |request| could be destroyed before the |callback| is called.
@ -392,7 +392,7 @@ void AtomNetworkDelegate::HandleSimpleEvent(
if (!MatchesFilterCondition(request, info.url_patterns)) if (!MatchesFilterCondition(request, info.url_patterns))
return; return;
scoped_ptr<base::DictionaryValue> details(new base::DictionaryValue); std::unique_ptr<base::DictionaryValue> details(new base::DictionaryValue);
FillDetailsObject(details.get(), request, args...); FillDetailsObject(details.get(), request, args...);
BrowserThread::PostTask( BrowserThread::PostTask(
@ -402,7 +402,7 @@ void AtomNetworkDelegate::HandleSimpleEvent(
template<typename T> template<typename T>
void AtomNetworkDelegate::OnListenerResultInIO( void AtomNetworkDelegate::OnListenerResultInIO(
uint64_t id, T out, scoped_ptr<base::DictionaryValue> response) { uint64_t id, T out, std::unique_ptr<base::DictionaryValue> response) {
// The request has been destroyed. // The request has been destroyed.
if (!ContainsKey(callbacks_, id)) if (!ContainsKey(callbacks_, id))
return; return;
@ -417,7 +417,7 @@ void AtomNetworkDelegate::OnListenerResultInIO(
template<typename T> template<typename T>
void AtomNetworkDelegate::OnListenerResultInUI( void AtomNetworkDelegate::OnListenerResultInUI(
uint64_t id, T out, const base::DictionaryValue& response) { uint64_t id, T out, const base::DictionaryValue& response) {
scoped_ptr<base::DictionaryValue> copy = response.CreateDeepCopy(); std::unique_ptr<base::DictionaryValue> copy = response.CreateDeepCopy();
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE, BrowserThread::IO, FROM_HERE,
base::Bind(&AtomNetworkDelegate::OnListenerResultInIO<T>, base::Bind(&AtomNetworkDelegate::OnListenerResultInIO<T>,

View file

@ -111,7 +111,7 @@ class AtomNetworkDelegate : public brightray::NetworkDelegate {
// Deal with the results of Listener. // Deal with the results of Listener.
template<typename T> template<typename T>
void OnListenerResultInIO( void OnListenerResultInIO(
uint64_t id, T out, scoped_ptr<base::DictionaryValue> response); uint64_t id, T out, std::unique_ptr<base::DictionaryValue> response);
template<typename T> template<typename T>
void OnListenerResultInUI( void OnListenerResultInUI(
uint64_t id, T out, const base::DictionaryValue& response); uint64_t id, T out, const base::DictionaryValue& response);

View file

@ -23,7 +23,8 @@ AtomURLRequestJobFactory::~AtomURLRequestJobFactory() {
} }
bool AtomURLRequestJobFactory::SetProtocolHandler( bool AtomURLRequestJobFactory::SetProtocolHandler(
const std::string& scheme, scoped_ptr<ProtocolHandler> protocol_handler) { const std::string& scheme,
std::unique_ptr<ProtocolHandler> protocol_handler) {
if (!protocol_handler) { if (!protocol_handler) {
ProtocolHandlerMap::iterator it = protocol_handler_map_.find(scheme); ProtocolHandlerMap::iterator it = protocol_handler_map_.find(scheme);
if (it == protocol_handler_map_.end()) if (it == protocol_handler_map_.end())
@ -40,8 +41,9 @@ bool AtomURLRequestJobFactory::SetProtocolHandler(
return true; return true;
} }
scoped_ptr<ProtocolHandler> AtomURLRequestJobFactory::ReplaceProtocol( std::unique_ptr<ProtocolHandler> AtomURLRequestJobFactory::ReplaceProtocol(
const std::string& scheme, scoped_ptr<ProtocolHandler> protocol_handler) { const std::string& scheme,
std::unique_ptr<ProtocolHandler> protocol_handler) {
if (!ContainsKey(protocol_handler_map_, scheme)) if (!ContainsKey(protocol_handler_map_, scheme))
return nullptr; return nullptr;
ProtocolHandler* original_protocol_handler = protocol_handler_map_[scheme]; ProtocolHandler* original_protocol_handler = protocol_handler_map_[scheme];

View file

@ -24,13 +24,14 @@ class AtomURLRequestJobFactory : public net::URLRequestJobFactory {
// Sets the ProtocolHandler for a scheme. Returns true on success, false on // Sets the ProtocolHandler for a scheme. Returns true on success, false on
// failure (a ProtocolHandler already exists for |scheme|). On success, // failure (a ProtocolHandler already exists for |scheme|). On success,
// URLRequestJobFactory takes ownership of |protocol_handler|. // URLRequestJobFactory takes ownership of |protocol_handler|.
bool SetProtocolHandler( bool SetProtocolHandler(const std::string& scheme,
const std::string& scheme, scoped_ptr<ProtocolHandler> protocol_handler); std::unique_ptr<ProtocolHandler> protocol_handler);
// Intercepts the ProtocolHandler for a scheme. Returns the original protocol // Intercepts the ProtocolHandler for a scheme. Returns the original protocol
// handler on success, otherwise returns NULL. // handler on success, otherwise returns NULL.
scoped_ptr<ProtocolHandler> ReplaceProtocol( std::unique_ptr<ProtocolHandler> ReplaceProtocol(
const std::string& scheme, scoped_ptr<ProtocolHandler> protocol_handler); const std::string& scheme,
std::unique_ptr<ProtocolHandler> protocol_handler);
// Returns the protocol handler registered with scheme. // Returns the protocol handler registered with scheme.
ProtocolHandler* GetProtocolHandler(const std::string& scheme) const; ProtocolHandler* GetProtocolHandler(const std::string& scheme) const;

View file

@ -34,7 +34,7 @@ void HandlerCallback(const BeforeStartCallback& before_start,
// Pass whatever user passed to the actaul request job. // Pass whatever user passed to the actaul request job.
V8ValueConverter converter; V8ValueConverter converter;
v8::Local<v8::Context> context = args->isolate()->GetCurrentContext(); v8::Local<v8::Context> context = args->isolate()->GetCurrentContext();
scoped_ptr<base::Value> options(converter.FromV8Value(value, context)); std::unique_ptr<base::Value> options(converter.FromV8Value(value, context));
content::BrowserThread::PostTask( content::BrowserThread::PostTask(
content::BrowserThread::IO, FROM_HERE, content::BrowserThread::IO, FROM_HERE,
base::Bind(callback, true, base::Passed(&options))); base::Bind(callback, true, base::Passed(&options)));

View file

@ -26,7 +26,7 @@ namespace internal {
using BeforeStartCallback = using BeforeStartCallback =
base::Callback<void(v8::Isolate*, v8::Local<v8::Value>)>; base::Callback<void(v8::Isolate*, v8::Local<v8::Value>)>;
using ResponseCallback = using ResponseCallback =
base::Callback<void(bool, scoped_ptr<base::Value> options)>; base::Callback<void(bool, std::unique_ptr<base::Value> options)>;
// Ask handler for options in UI thread. // Ask handler for options in UI thread.
void AskForOptions(v8::Isolate* isolate, void AskForOptions(v8::Isolate* isolate,
@ -58,7 +58,7 @@ class JsAsker : public RequestJob {
// Subclass should do initailze work here. // Subclass should do initailze work here.
virtual void BeforeStartInUI(v8::Isolate*, v8::Local<v8::Value>) {} virtual void BeforeStartInUI(v8::Isolate*, v8::Local<v8::Value>) {}
virtual void StartAsync(scoped_ptr<base::Value> options) = 0; virtual void StartAsync(std::unique_ptr<base::Value> options) = 0;
net::URLRequestContextGetter* request_context_getter() const { net::URLRequestContextGetter* request_context_getter() const {
return request_context_getter_; return request_context_getter_;
@ -84,7 +84,7 @@ class JsAsker : public RequestJob {
// Called when the JS handler has sent the response, we need to decide whether // Called when the JS handler has sent the response, we need to decide whether
// to start, or fail the job. // to start, or fail the job.
void OnResponse(bool success, scoped_ptr<base::Value> value) { void OnResponse(bool success, std::unique_ptr<base::Value> value) {
int error = net::ERR_NOT_IMPLEMENTED; int error = net::ERR_NOT_IMPLEMENTED;
if (success && value && !internal::IsErrorOptions(value.get(), &error)) { if (success && value && !internal::IsErrorOptions(value.get(), &error)) {
StartAsync(std::move(value)); StartAsync(std::move(value));

View file

@ -16,7 +16,7 @@ URLRequestAsyncAsarJob::URLRequestAsyncAsarJob(
: JsAsker<asar::URLRequestAsarJob>(request, network_delegate) { : JsAsker<asar::URLRequestAsarJob>(request, network_delegate) {
} }
void URLRequestAsyncAsarJob::StartAsync(scoped_ptr<base::Value> options) { void URLRequestAsyncAsarJob::StartAsync(std::unique_ptr<base::Value> options) {
base::FilePath::StringType file_path; base::FilePath::StringType file_path;
if (options->IsType(base::Value::TYPE_DICTIONARY)) { if (options->IsType(base::Value::TYPE_DICTIONARY)) {
static_cast<base::DictionaryValue*>(options.get())->GetString( static_cast<base::DictionaryValue*>(options.get())->GetString(

View file

@ -16,7 +16,7 @@ class URLRequestAsyncAsarJob : public JsAsker<asar::URLRequestAsarJob> {
URLRequestAsyncAsarJob(net::URLRequest*, net::NetworkDelegate*); URLRequestAsyncAsarJob(net::URLRequest*, net::NetworkDelegate*);
// JsAsker: // JsAsker:
void StartAsync(scoped_ptr<base::Value> options) override; void StartAsync(std::unique_ptr<base::Value> options) override;
// URLRequestJob: // URLRequestJob:
void GetResponseInfo(net::HttpResponseInfo* info) override; void GetResponseInfo(net::HttpResponseInfo* info) override;

View file

@ -8,17 +8,31 @@
#include "atom/common/atom_constants.h" #include "atom/common/atom_constants.h"
#include "base/strings/string_number_conversions.h" #include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "net/base/mime_util.h"
#include "net/base/net_errors.h" #include "net/base/net_errors.h"
namespace atom { namespace atom {
namespace {
std::string GetExtFromURL(const GURL& url) {
std::string spec = url.spec();
size_t index = spec.find_last_of('.');
if (index == std::string::npos || index == spec.size())
return std::string();
return spec.substr(index + 1, spec.size() - index - 1);
}
} // namespace
URLRequestBufferJob::URLRequestBufferJob( URLRequestBufferJob::URLRequestBufferJob(
net::URLRequest* request, net::NetworkDelegate* network_delegate) net::URLRequest* request, net::NetworkDelegate* network_delegate)
: JsAsker<net::URLRequestSimpleJob>(request, network_delegate), : JsAsker<net::URLRequestSimpleJob>(request, network_delegate),
status_code_(net::HTTP_NOT_IMPLEMENTED) { status_code_(net::HTTP_NOT_IMPLEMENTED) {
} }
void URLRequestBufferJob::StartAsync(scoped_ptr<base::Value> options) { void URLRequestBufferJob::StartAsync(std::unique_ptr<base::Value> options) {
const base::BinaryValue* binary = nullptr; const base::BinaryValue* binary = nullptr;
if (options->IsType(base::Value::TYPE_DICTIONARY)) { if (options->IsType(base::Value::TYPE_DICTIONARY)) {
base::DictionaryValue* dict = base::DictionaryValue* dict =
@ -30,6 +44,15 @@ void URLRequestBufferJob::StartAsync(scoped_ptr<base::Value> options) {
options->GetAsBinary(&binary); options->GetAsBinary(&binary);
} }
if (mime_type_.empty()) {
std::string ext = GetExtFromURL(request()->url());
#if defined(OS_WIN)
net::GetWellKnownMimeTypeFromExtension(base::UTF8ToUTF16(ext), &mime_type_);
#else
net::GetWellKnownMimeTypeFromExtension(ext, &mime_type_);
#endif
}
if (!binary) { if (!binary) {
NotifyStartError(net::URLRequestStatus( NotifyStartError(net::URLRequestStatus(
net::URLRequestStatus::FAILED, net::ERR_NOT_IMPLEMENTED)); net::URLRequestStatus::FAILED, net::ERR_NOT_IMPLEMENTED));

View file

@ -19,7 +19,7 @@ class URLRequestBufferJob : public JsAsker<net::URLRequestSimpleJob> {
URLRequestBufferJob(net::URLRequest*, net::NetworkDelegate*); URLRequestBufferJob(net::URLRequest*, net::NetworkDelegate*);
// JsAsker: // JsAsker:
void StartAsync(scoped_ptr<base::Value> options) override; void StartAsync(std::unique_ptr<base::Value> options) override;
// URLRequestJob: // URLRequestJob:
void GetResponseInfo(net::HttpResponseInfo* info) override; void GetResponseInfo(net::HttpResponseInfo* info) override;

View file

@ -59,7 +59,7 @@ class ResponsePiper : public net::URLFetcherResponseWriter {
job_->HeadersCompleted(); job_->HeadersCompleted();
first_write_ = false; first_write_ = false;
} }
return job_->DataAvailable(buffer, num_bytes); return job_->DataAvailable(buffer, num_bytes, callback);
} }
int Finish(const net::CompletionCallback& callback) override { int Finish(const net::CompletionCallback& callback) override {
return net::OK; return net::OK;
@ -77,7 +77,8 @@ class ResponsePiper : public net::URLFetcherResponseWriter {
URLRequestFetchJob::URLRequestFetchJob( URLRequestFetchJob::URLRequestFetchJob(
net::URLRequest* request, net::NetworkDelegate* network_delegate) net::URLRequest* request, net::NetworkDelegate* network_delegate)
: JsAsker<net::URLRequestJob>(request, network_delegate), : JsAsker<net::URLRequestJob>(request, network_delegate),
pending_buffer_size_(0) { pending_buffer_size_(0),
write_num_bytes_(0) {
} }
void URLRequestFetchJob::BeforeStartInUI( void URLRequestFetchJob::BeforeStartInUI(
@ -99,7 +100,7 @@ void URLRequestFetchJob::BeforeStartInUI(
} }
} }
void URLRequestFetchJob::StartAsync(scoped_ptr<base::Value> options) { void URLRequestFetchJob::StartAsync(std::unique_ptr<base::Value> options) {
if (!options->IsType(base::Value::TYPE_DICTIONARY)) { if (!options->IsType(base::Value::TYPE_DICTIONARY)) {
NotifyStartError(net::URLRequestStatus( NotifyStartError(net::URLRequestStatus(
net::URLRequestStatus::FAILED, net::ERR_NOT_IMPLEMENTED)); net::URLRequestStatus::FAILED, net::ERR_NOT_IMPLEMENTED));
@ -166,22 +167,23 @@ void URLRequestFetchJob::HeadersCompleted() {
NotifyHeadersComplete(); NotifyHeadersComplete();
} }
int URLRequestFetchJob::DataAvailable(net::IOBuffer* buffer, int num_bytes) { int URLRequestFetchJob::DataAvailable(net::IOBuffer* buffer,
// Do nothing if pending_buffer_ is empty, i.e. there's no ReadRawData() int num_bytes,
// operation waiting for IO completion. const net::CompletionCallback& callback) {
if (!pending_buffer_.get()) // When pending_buffer_ is empty, there's no ReadRawData() operation waiting
// for IO completion, we have to save the parameters until the request is
// ready to read data.
if (!pending_buffer_.get()) {
write_buffer_ = buffer;
write_num_bytes_ = num_bytes;
write_callback_ = callback;
return net::ERR_IO_PENDING; return net::ERR_IO_PENDING;
}
// pending_buffer_ is set to the IOBuffer instance provided to ReadRawData() // Write data to the pending buffer and clear them after the writing.
// by URLRequestJob. int bytes_read = BufferCopy(buffer, num_bytes,
int bytes_read = std::min(num_bytes, pending_buffer_size_); pending_buffer_.get(), pending_buffer_size_);
memcpy(pending_buffer_->data(), buffer->data(), bytes_read); ClearPendingBuffer();
// Clear the buffers before notifying the read is complete, so that it is
// safe for the observer to read.
pending_buffer_ = nullptr;
pending_buffer_size_ = 0;
ReadRawDataComplete(bytes_read); ReadRawDataComplete(bytes_read);
return bytes_read; return bytes_read;
} }
@ -196,9 +198,22 @@ int URLRequestFetchJob::ReadRawData(net::IOBuffer* dest, int dest_size) {
request()->set_received_response_content_length(prefilter_bytes_read()); request()->set_received_response_content_length(prefilter_bytes_read());
return net::OK; return net::OK;
} }
pending_buffer_ = dest;
pending_buffer_size_ = dest_size; // When write_buffer_ is empty, there is no data valable yet, we have to save
return net::ERR_IO_PENDING; // the dest buffer util DataAvailable.
if (!write_buffer_.get()) {
pending_buffer_ = dest;
pending_buffer_size_ = dest_size;
return net::ERR_IO_PENDING;
}
// Read from the write buffer and clear them after reading.
int bytes_read = BufferCopy(write_buffer_.get(), write_num_bytes_,
dest, dest_size);
net::CompletionCallback write_callback = write_callback_;
ClearWriteBuffer();
write_callback.Run(bytes_read);
return bytes_read;
} }
bool URLRequestFetchJob::GetMimeType(std::string* mime_type) const { bool URLRequestFetchJob::GetMimeType(std::string* mime_type) const {
@ -229,12 +244,31 @@ void URLRequestFetchJob::OnURLFetchComplete(const net::URLFetcher* source) {
return; return;
} }
pending_buffer_ = nullptr; ClearPendingBuffer();
pending_buffer_size_ = 0; ClearWriteBuffer();
if (fetcher_->GetStatus().is_success()) if (fetcher_->GetStatus().is_success())
ReadRawDataComplete(0); ReadRawDataComplete(0);
else else
NotifyStartError(fetcher_->GetStatus()); NotifyStartError(fetcher_->GetStatus());
} }
int URLRequestFetchJob::BufferCopy(net::IOBuffer* source, int num_bytes,
net::IOBuffer* target, int target_size) {
int bytes_written = std::min(num_bytes, target_size);
memcpy(target->data(), source->data(), bytes_written);
return bytes_written;
}
void URLRequestFetchJob::ClearPendingBuffer() {
pending_buffer_ = nullptr;
pending_buffer_size_ = 0;
}
void URLRequestFetchJob::ClearWriteBuffer() {
write_buffer_ = nullptr;
write_num_bytes_ = 0;
write_callback_.Reset();
}
} // namespace atom } // namespace atom

View file

@ -9,14 +9,10 @@
#include "atom/browser/net/js_asker.h" #include "atom/browser/net/js_asker.h"
#include "browser/url_request_context_getter.h" #include "browser/url_request_context_getter.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_fetcher_delegate.h" #include "net/url_request/url_fetcher_delegate.h"
#include "net/url_request/url_request_job.h"
namespace atom { namespace atom {
class AtomBrowserContext;
class URLRequestFetchJob : public JsAsker<net::URLRequestJob>, class URLRequestFetchJob : public JsAsker<net::URLRequestJob>,
public net::URLFetcherDelegate, public net::URLFetcherDelegate,
public brightray::URLRequestContextGetter::Delegate { public brightray::URLRequestContextGetter::Delegate {
@ -25,12 +21,14 @@ class URLRequestFetchJob : public JsAsker<net::URLRequestJob>,
// Called by response writer. // Called by response writer.
void HeadersCompleted(); void HeadersCompleted();
int DataAvailable(net::IOBuffer* buffer, int num_bytes); int DataAvailable(net::IOBuffer* buffer,
int num_bytes,
const net::CompletionCallback& callback);
protected: protected:
// JsAsker: // JsAsker:
void BeforeStartInUI(v8::Isolate*, v8::Local<v8::Value>) override; void BeforeStartInUI(v8::Isolate*, v8::Local<v8::Value>) override;
void StartAsync(scoped_ptr<base::Value> options) override; void StartAsync(std::unique_ptr<base::Value> options) override;
// net::URLRequestJob: // net::URLRequestJob:
void Kill() override; void Kill() override;
@ -43,11 +41,23 @@ class URLRequestFetchJob : public JsAsker<net::URLRequestJob>,
void OnURLFetchComplete(const net::URLFetcher* source) override; void OnURLFetchComplete(const net::URLFetcher* source) override;
private: private:
int BufferCopy(net::IOBuffer* source, int num_bytes,
net::IOBuffer* target, int target_size);
void ClearPendingBuffer();
void ClearWriteBuffer();
scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_; scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_;
scoped_ptr<net::URLFetcher> fetcher_; std::unique_ptr<net::URLFetcher> fetcher_;
std::unique_ptr<net::HttpResponseInfo> response_info_;
// Saved arguments passed to ReadRawData.
scoped_refptr<net::IOBuffer> pending_buffer_; scoped_refptr<net::IOBuffer> pending_buffer_;
int pending_buffer_size_; int pending_buffer_size_;
scoped_ptr<net::HttpResponseInfo> response_info_;
// Saved arguments passed to DataAvailable.
scoped_refptr<net::IOBuffer> write_buffer_;
int write_num_bytes_;
net::CompletionCallback write_callback_;
DISALLOW_COPY_AND_ASSIGN(URLRequestFetchJob); DISALLOW_COPY_AND_ASSIGN(URLRequestFetchJob);
}; };

View file

@ -16,7 +16,7 @@ URLRequestStringJob::URLRequestStringJob(
: JsAsker<net::URLRequestSimpleJob>(request, network_delegate) { : JsAsker<net::URLRequestSimpleJob>(request, network_delegate) {
} }
void URLRequestStringJob::StartAsync(scoped_ptr<base::Value> options) { void URLRequestStringJob::StartAsync(std::unique_ptr<base::Value> options) {
if (options->IsType(base::Value::TYPE_DICTIONARY)) { if (options->IsType(base::Value::TYPE_DICTIONARY)) {
base::DictionaryValue* dict = base::DictionaryValue* dict =
static_cast<base::DictionaryValue*>(options.get()); static_cast<base::DictionaryValue*>(options.get());

View file

@ -17,7 +17,7 @@ class URLRequestStringJob : public JsAsker<net::URLRequestSimpleJob> {
URLRequestStringJob(net::URLRequest*, net::NetworkDelegate*); URLRequestStringJob(net::URLRequest*, net::NetworkDelegate*);
// JsAsker: // JsAsker:
void StartAsync(scoped_ptr<base::Value> options) override; void StartAsync(std::unique_ptr<base::Value> options) override;
// URLRequestJob: // URLRequestJob:
void GetResponseInfo(net::HttpResponseInfo* info) override; void GetResponseInfo(net::HttpResponseInfo* info) override;

View file

@ -145,7 +145,7 @@ void NodeDebugger::DebugMessageHandler(const v8::Debug::Message& message) {
void NodeDebugger::DidAccept( void NodeDebugger::DidAccept(
net::test_server::StreamListenSocket* server, net::test_server::StreamListenSocket* server,
scoped_ptr<net::test_server::StreamListenSocket> socket) { std::unique_ptr<net::test_server::StreamListenSocket> socket) {
// Only accept one session. // Only accept one session.
if (accepted_socket_) { if (accepted_socket_) {
socket->Send(std::string("Remote debugging session already active"), true); socket->Send(std::string("Remote debugging session already active"), true);

View file

@ -38,7 +38,7 @@ class NodeDebugger : public net::test_server::StreamListenSocket::Delegate {
// net::test_server::StreamListenSocket::Delegate: // net::test_server::StreamListenSocket::Delegate:
void DidAccept( void DidAccept(
net::test_server::StreamListenSocket* server, net::test_server::StreamListenSocket* server,
scoped_ptr<net::test_server::StreamListenSocket> socket) override; std::unique_ptr<net::test_server::StreamListenSocket> socket) override;
void DidRead(net::test_server::StreamListenSocket* socket, void DidRead(net::test_server::StreamListenSocket* socket,
const char* data, const char* data,
int len) override; int len) override;
@ -49,8 +49,8 @@ class NodeDebugger : public net::test_server::StreamListenSocket::Delegate {
uv_async_t weak_up_ui_handle_; uv_async_t weak_up_ui_handle_;
base::Thread thread_; base::Thread thread_;
scoped_ptr<net::test_server::StreamListenSocket> server_; std::unique_ptr<net::test_server::StreamListenSocket> server_;
scoped_ptr<net::test_server::StreamListenSocket> accepted_socket_; std::unique_ptr<net::test_server::StreamListenSocket> accepted_socket_;
std::string buffer_; std::string buffer_;
int content_length_; int content_length_;

View file

@ -0,0 +1,63 @@
// 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/render_process_preferences.h"
#include "atom/common/api/api_messages.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_process_host.h"
namespace atom {
RenderProcessPreferences::RenderProcessPreferences(const Predicate& predicate)
: predicate_(predicate),
next_id_(0),
cache_needs_update_(true) {
registrar_.Add(this,
content::NOTIFICATION_RENDERER_PROCESS_CREATED,
content::NotificationService::AllBrowserContextsAndSources());
}
RenderProcessPreferences::~RenderProcessPreferences() {
}
int RenderProcessPreferences::AddEntry(const base::DictionaryValue& entry) {
int id = ++next_id_;
entries_[id] = entry.CreateDeepCopy();
cache_needs_update_ = true;
return id;
}
void RenderProcessPreferences::RemoveEntry(int id) {
cache_needs_update_ = true;
entries_.erase(id);
}
void RenderProcessPreferences::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK_EQ(type, content::NOTIFICATION_RENDERER_PROCESS_CREATED);
content::RenderProcessHost* process =
content::Source<content::RenderProcessHost>(source).ptr();
if (!predicate_.Run(process))
return;
UpdateCache();
process->Send(new AtomMsg_UpdatePreferences(cached_entries_));
}
void RenderProcessPreferences::UpdateCache() {
if (!cache_needs_update_)
return;
cached_entries_.Clear();
for (const auto& iter : entries_)
cached_entries_.Append(iter.second->CreateDeepCopy());
cache_needs_update_ = false;
}
} // namespace atom

View file

@ -0,0 +1,61 @@
// 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_RENDER_PROCESS_PREFERENCES_H_
#define ATOM_BROWSER_RENDER_PROCESS_PREFERENCES_H_
#include <memory>
#include <unordered_map>
#include "base/callback.h"
#include "base/values.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
namespace content {
class RenderProcessHost;
}
namespace atom {
// Sets user preferences for render processes.
class RenderProcessPreferences : public content::NotificationObserver {
public:
using Predicate = base::Callback<bool(content::RenderProcessHost*)>;
// The |predicate| is used to determine whether to set preferences for a
// render process.
explicit RenderProcessPreferences(const Predicate& predicate);
virtual ~RenderProcessPreferences();
int AddEntry(const base::DictionaryValue& entry);
void RemoveEntry(int id);
private:
// content::NotificationObserver:
void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) override;
void UpdateCache();
// Manages our notification registrations.
content::NotificationRegistrar registrar_;
Predicate predicate_;
int next_id_;
std::unordered_map<int, std::unique_ptr<base::DictionaryValue>> entries_;
// We need to convert the |entries_| to ListValue for multiple times, this
// caches is only updated when we are sending messages.
bool cache_needs_update_;
base::ListValue cached_entries_;
DISALLOW_COPY_AND_ASSIGN(RenderProcessPreferences);
};
} // namespace atom
#endif // ATOM_BROWSER_RENDER_PROCESS_PREFERENCES_H_

View file

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

View file

@ -30,4 +30,11 @@
</security> </security>
</trustInfo> </trustInfo>
<asmv3:application xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
<asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
<dpiAware>true</dpiAware>
<disableWindowFiltering xmlns="http://schemas.microsoft.com/SMI/2011/WindowsSettings">true</disableWindowFiltering>
</asmv3:windowsSettings>
</asmv3:application>
</assembly> </assembly>

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