diff --git a/.node-version b/.node-version index ed15bef9ae..dffc266d6a 100644 --- a/.node-version +++ b/.node-version @@ -1 +1 @@ -v6.1.0 +v6.3.0 diff --git a/README-ko.md b/README-ko.md index c3c0216c2a..79cc716587 100644 --- a/README-ko.md +++ b/README-ko.md @@ -75,6 +75,7 @@ npm install electron-prebuilt --save-dev - [`electron-br`](https://electron-br.slack.com) *(브라질)* 커뮤니티 - [`electron-kr`](http://www.meetup.com/electron-kr/) *(한국)* 커뮤니티 - [`electron-jp`](https://electron-jp-slackin.herokuapp.com/) *(일본)* 커뮤니티 +- [`electron-tr`](http://www.meetup.com/Electron-JS-Istanbul/) *(터키)* 커뮤니티 [awesome-electron](https://github.com/sindresorhus/awesome-electron) 프로젝트에 커뮤니티가 운영중인 유용한 예시 애플리케이션과 도구, 리소스가 있으니 참고하기 바랍니다. diff --git a/README.md b/README.md index 83ba1f5a61..2726e07789 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,8 @@ forums - [`electron-br`](https://electron-br.slack.com) *(Brazilian Portuguese)* - [`electron-kr`](http://www.meetup.com/electron-kr/) *(Korean)* - [`electron-jp`](https://electron-jp-slackin.herokuapp.com/) *(Japanese)* +- [`electron-tr`](http://www.meetup.com/Electron-JS-Istanbul/) *(Turkish)* +- [`electron-id`](https://electron-id.slack.com) *(Indonesia)* Check out [awesome-electron](https://github.com/sindresorhus/awesome-electron) for a community maintained list of useful example apps, tools and resources. diff --git a/atom/app/atom_main.cc b/atom/app/atom_main.cc index a3e7027002..387b5167f3 100644 --- a/atom/app/atom_main.cc +++ b/atom/app/atom_main.cc @@ -19,7 +19,6 @@ #include "base/win/windows_version.h" #include "content/public/app/sandbox_helper_win.h" #include "sandbox/win/src/sandbox_types.h" -#include "ui/gfx/win/dpi.h" #elif defined(OS_LINUX) // defined(OS_WIN) #include "atom/app/atom_main_delegate.h" // NOLINT #include "content/public/app/content_main.h" diff --git a/atom/app/node_main.cc b/atom/app/node_main.cc index 6f71d39f57..040b4b6157 100644 --- a/atom/app/node_main.cc +++ b/atom/app/node_main.cc @@ -7,14 +7,15 @@ #include "atom/app/uv_task_runner.h" #include "atom/browser/javascript_environment.h" #include "atom/browser/node_debugger.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/threading/thread_task_runner_handle.h" #include "gin/array_buffer.h" #include "gin/public/isolate_holder.h" #include "gin/v8_initializer.h" +#include "atom/common/node_includes.h" + namespace atom { int NodeMain(int argc, char *argv[]) { @@ -69,7 +70,7 @@ int NodeMain(int argc, char *argv[]) { exit_code = node::EmitExit(env); node::RunAtExit(env); - env->Dispose(); + node::FreeEnvironment(env); } v8::V8::Dispose(); diff --git a/atom/app/uv_task_runner.cc b/atom/app/uv_task_runner.cc index 097cc3bcda..7857ace3a2 100644 --- a/atom/app/uv_task_runner.cc +++ b/atom/app/uv_task_runner.cc @@ -21,7 +21,7 @@ UvTaskRunner::~UvTaskRunner() { bool UvTaskRunner::PostDelayedTask(const tracked_objects::Location& from_here, const base::Closure& task, base::TimeDelta delay) { - uv_timer_t* timer = new uv_timer_t; + auto* timer = new uv_timer_t; timer->data = this; uv_timer_init(loop_, timer); uv_timer_start(timer, UvTaskRunner::OnTimeout, delay.InMilliseconds(), 0); diff --git a/atom/browser/api/atom_api_app.cc b/atom/browser/api/atom_api_app.cc index bc29b988ee..8a66c041f4 100644 --- a/atom/browser/api/atom_api_app.cc +++ b/atom/browser/api/atom_api_app.cc @@ -32,6 +32,7 @@ #include "base/strings/string_util.h" #include "brightray/browser/brightray_paths.h" #include "chrome/common/chrome_paths.h" +#include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/gpu_data_manager.h" #include "content/public/browser/render_frame_host.h" @@ -71,6 +72,30 @@ struct Converter { }; #endif +template<> +struct Converter { + static bool FromV8(v8::Isolate* isolate, v8::Local val, + Browser::LoginItemSettings* out) { + mate::Dictionary dict; + if (!ConvertFromV8(isolate, val, &dict)) + return false; + + dict.Get("openAtLogin", &(out->open_at_login)); + dict.Get("openAsHidden", &(out->open_as_hidden)); + return true; + } + + static v8::Local ToV8(v8::Isolate* isolate, + Browser::LoginItemSettings val) { + mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); + dict.Set("openAtLogin", val.open_at_login); + dict.Set("openAsHidden", val.open_as_hidden); + dict.Set("restoreState", val.restore_state); + dict.Set("wasOpenedAtLogin", val.opened_at_login); + dict.Set("wasOpenedAsHidden", val.opened_as_hidden); + return dict.GetHandle(); + } +}; } // namespace mate @@ -254,6 +279,10 @@ void App::OnFinishLaunching() { Emit("ready"); } +void App::OnAccessibilitySupportChanged() { + Emit("accessibility-support-changed", IsAccessibilitySupportEnabled()); +} + #if defined(OS_MACOSX) void App::OnContinueUserActivity( bool* prevent_default, @@ -459,14 +488,20 @@ void App::DisableHardwareAcceleration(mate::Arguments* args) { content::GpuDataManager::GetInstance()->DisableHardwareAcceleration(); } +bool App::IsAccessibilitySupportEnabled() { + auto ax_state = content::BrowserAccessibilityState::GetInstance(); + return ax_state->IsAccessibleBrowser(); +} + #if defined(USE_NSS_CERTS) void App::ImportCertificate( const base::DictionaryValue& options, const net::CompletionCallback& callback) { - auto browser_context = AtomBrowserMainParts::Get()->browser_context(); + auto browser_context = AtomBrowserContext::From("", false); if (!certificate_manager_model_) { std::unique_ptr copy = options.CreateDeepCopy(); - CertificateManagerModel::Create(browser_context, + CertificateManagerModel::Create( + browser_context.get(), base::Bind(&App::OnCertificateManagerModelCreated, base::Unretained(this), base::Passed(©), @@ -519,6 +554,12 @@ void App::BuildPrototype( base::Bind(&Browser::SetAsDefaultProtocolClient, browser)) .SetMethod("removeAsDefaultProtocolClient", base::Bind(&Browser::RemoveAsDefaultProtocolClient, browser)) + .SetMethod("setBadgeCount", base::Bind(&Browser::SetBadgeCount, browser)) + .SetMethod("getBadgeCount", base::Bind(&Browser::GetBadgeCount, browser)) + .SetMethod("getLoginItemSettings", + base::Bind(&Browser::GetLoginItemSettings, browser)) + .SetMethod("setLoginItemSettings", + base::Bind(&Browser::SetLoginItemSettings, browser)) #if defined(OS_MACOSX) .SetMethod("hide", base::Bind(&Browser::Hide, browser)) .SetMethod("show", base::Bind(&Browser::Show, browser)) @@ -528,8 +569,11 @@ void App::BuildPrototype( base::Bind(&Browser::GetCurrentActivityType, browser)) #endif #if defined(OS_WIN) - .SetMethod("setUserTasks", - base::Bind(&Browser::SetUserTasks, browser)) + .SetMethod("setUserTasks", base::Bind(&Browser::SetUserTasks, browser)) +#endif +#if defined(OS_LINUX) + .SetMethod("isUnityRunning", + base::Bind(&Browser::IsUnityRunning, browser)) #endif .SetMethod("setPath", &App::SetPath) .SetMethod("getPath", &App::GetPath) @@ -541,6 +585,8 @@ void App::BuildPrototype( .SetMethod("makeSingleInstance", &App::MakeSingleInstance) .SetMethod("releaseSingleInstance", &App::ReleaseSingleInstance) .SetMethod("relaunch", &App::Relaunch) + .SetMethod("isAccessibilitySupportEnabled", + &App::IsAccessibilitySupportEnabled) .SetMethod("disableHardwareAcceleration", &App::DisableHardwareAcceleration); } diff --git a/atom/browser/api/atom_api_app.h b/atom/browser/api/atom_api_app.h index b550f0ba7b..13cedaa7d8 100644 --- a/atom/browser/api/atom_api_app.h +++ b/atom/browser/api/atom_api_app.h @@ -72,6 +72,7 @@ class App : public AtomBrowserClient::Delegate, void OnFinishLaunching() override; void OnLogin(LoginHandler* login_handler, const base::DictionaryValue& request_details) override; + void OnAccessibilitySupportChanged() override; #if defined(OS_MACOSX) void OnContinueUserActivity( bool* prevent_default, @@ -113,6 +114,7 @@ class App : public AtomBrowserClient::Delegate, void ReleaseSingleInstance(); bool Relaunch(mate::Arguments* args); void DisableHardwareAcceleration(mate::Arguments* args); + bool IsAccessibilitySupportEnabled(); #if defined(USE_NSS_CERTS) void ImportCertificate(const base::DictionaryValue& options, const net::CompletionCallback& callback); diff --git a/atom/browser/api/atom_api_auto_updater.cc b/atom/browser/api/atom_api_auto_updater.cc index 54e2bd9f74..f8d9a2f9ac 100644 --- a/atom/browser/api/atom_api_auto_updater.cc +++ b/atom/browser/api/atom_api_auto_updater.cc @@ -109,6 +109,7 @@ void AutoUpdater::BuildPrototype( v8::Isolate* isolate, v8::Local prototype) { mate::ObjectTemplateBuilder(isolate, prototype) .SetMethod("checkForUpdates", &auto_updater::AutoUpdater::CheckForUpdates) + .SetMethod("getFeedURL", &auto_updater::AutoUpdater::GetFeedURL) .SetMethod("setFeedURL", &AutoUpdater::SetFeedURL) .SetMethod("quitAndInstall", &AutoUpdater::QuitAndInstall); } diff --git a/atom/browser/api/atom_api_auto_updater.h b/atom/browser/api/atom_api_auto_updater.h index e8c135f292..4c73f7ce8e 100644 --- a/atom/browser/api/atom_api_auto_updater.h +++ b/atom/browser/api/atom_api_auto_updater.h @@ -44,6 +44,7 @@ class AutoUpdater : public mate::EventEmitter, void OnWindowAllClosed() override; private: + std::string GetFeedURL(); void SetFeedURL(const std::string& url, mate::Arguments* args); void QuitAndInstall(); diff --git a/atom/browser/api/atom_api_cookies.cc b/atom/browser/api/atom_api_cookies.cc index 6ee15a6cba..4ee2190219 100644 --- a/atom/browser/api/atom_api_cookies.cc +++ b/atom/browser/api/atom_api_cookies.cc @@ -4,6 +4,7 @@ #include "atom/browser/api/atom_api_cookies.h" +#include "atom/browser/atom_browser_context.h" #include "atom/common/native_mate_converters/callback.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/value_converter.h" @@ -30,7 +31,7 @@ struct Converter { if (val == atom::api::Cookies::SUCCESS) return v8::Null(isolate); else - return v8::Exception::Error(StringToV8(isolate, "failed")); + return v8::Exception::Error(StringToV8(isolate, "Setting cookie failed")); } }; @@ -204,8 +205,8 @@ void SetCookieOnIO(scoped_refptr getter, } // namespace Cookies::Cookies(v8::Isolate* isolate, - content::BrowserContext* browser_context) - : request_context_getter_(browser_context->GetRequestContext()) { + AtomBrowserContext* browser_context) + : request_context_getter_(browser_context->url_request_context_getter()) { Init(isolate); } @@ -241,7 +242,7 @@ void Cookies::Set(const base::DictionaryValue& details, // static mate::Handle Cookies::Create( v8::Isolate* isolate, - content::BrowserContext* browser_context) { + AtomBrowserContext* browser_context) { return mate::CreateHandle(isolate, new Cookies(isolate, browser_context)); } diff --git a/atom/browser/api/atom_api_cookies.h b/atom/browser/api/atom_api_cookies.h index 33fee56960..ce20c77597 100644 --- a/atom/browser/api/atom_api_cookies.h +++ b/atom/browser/api/atom_api_cookies.h @@ -16,16 +16,14 @@ namespace base { class DictionaryValue; } -namespace content { -class BrowserContext; -} - namespace net { class URLRequestContextGetter; } namespace atom { +class AtomBrowserContext; + namespace api { class Cookies : public mate::TrackableObject { @@ -39,14 +37,14 @@ class Cookies : public mate::TrackableObject { using SetCallback = base::Callback; static mate::Handle Create(v8::Isolate* isolate, - content::BrowserContext* browser_context); + AtomBrowserContext* browser_context); // mate::TrackableObject: static void BuildPrototype(v8::Isolate* isolate, v8::Local prototype); protected: - Cookies(v8::Isolate* isolate, content::BrowserContext* browser_context); + Cookies(v8::Isolate* isolate, AtomBrowserContext* browser_context); ~Cookies() override; void Get(const base::DictionaryValue& filter, const GetCallback& callback); diff --git a/atom/browser/api/atom_api_menu.cc b/atom/browser/api/atom_api_menu.cc index 996c71739b..54a3d4e813 100644 --- a/atom/browser/api/atom_api_menu.cc +++ b/atom/browser/api/atom_api_menu.cc @@ -21,7 +21,7 @@ namespace api { Menu::Menu(v8::Isolate* isolate) : model_(new AtomMenuModel(this)), - parent_(NULL) { + parent_(nullptr) { } Menu::~Menu() { @@ -53,16 +53,21 @@ bool Menu::IsCommandIdVisible(int command_id) const { return is_visible_.Run(command_id); } -bool Menu::GetAcceleratorForCommandId(int command_id, - ui::Accelerator* accelerator) { +bool Menu::GetAcceleratorForCommandIdWithParams( + int command_id, + bool use_default_accelerator, + ui::Accelerator* accelerator) const { v8::Locker locker(isolate()); v8::HandleScope handle_scope(isolate()); - v8::Local val = get_accelerator_.Run(command_id); + v8::Local val = get_accelerator_.Run( + command_id, use_default_accelerator); return mate::ConvertFromV8(isolate(), val, accelerator); } -void Menu::ExecuteCommand(int command_id, int event_flags) { - execute_command_.Run(command_id); +void Menu::ExecuteCommand(int command_id, int flags) { + execute_command_.Run( + mate::internal::CreateEventFromFlags(isolate(), flags), + command_id); } void Menu::MenuWillShow(ui::SimpleMenuModel* source) { diff --git a/atom/browser/api/atom_api_menu.h b/atom/browser/api/atom_api_menu.h index 9ba4d7a754..e04d189efc 100644 --- a/atom/browser/api/atom_api_menu.h +++ b/atom/browser/api/atom_api_menu.h @@ -5,13 +5,13 @@ #ifndef ATOM_BROWSER_API_ATOM_API_MENU_H_ #define ATOM_BROWSER_API_ATOM_API_MENU_H_ +#include #include #include "atom/browser/api/atom_api_window.h" #include "atom/browser/api/trackable_object.h" #include "atom/browser/ui/atom_menu_model.h" #include "base/callback.h" -#include "base/memory/scoped_ptr.h" namespace atom { @@ -46,8 +46,10 @@ class Menu : public mate::TrackableObject, bool IsCommandIdChecked(int command_id) const override; bool IsCommandIdEnabled(int command_id) const override; bool IsCommandIdVisible(int command_id) const override; - bool GetAcceleratorForCommandId(int command_id, - ui::Accelerator* accelerator) override; + bool GetAcceleratorForCommandIdWithParams( + int command_id, + bool use_default_accelerator, + ui::Accelerator* accelerator) const override; void ExecuteCommand(int command_id, int event_flags) override; void MenuWillShow(ui::SimpleMenuModel* source) override; @@ -89,8 +91,8 @@ class Menu : public mate::TrackableObject, base::Callback is_checked_; base::Callback is_enabled_; base::Callback is_visible_; - base::Callback(int)> get_accelerator_; - base::Callback execute_command_; + base::Callback(int, bool)> get_accelerator_; + base::Callback, int)> execute_command_; base::Callback menu_will_show_; DISALLOW_COPY_AND_ASSIGN(Menu); diff --git a/atom/browser/api/atom_api_menu_mac.mm b/atom/browser/api/atom_api_menu_mac.mm index 3b91dac62a..6a7d43b4da 100644 --- a/atom/browser/api/atom_api_menu_mac.mm +++ b/atom/browser/api/atom_api_menu_mac.mm @@ -5,6 +5,7 @@ #import "atom/browser/api/atom_api_menu_mac.h" #include "atom/browser/native_window.h" +#include "atom/browser/unresponsive_suppressor.h" #include "base/message_loop/message_loop.h" #include "base/strings/sys_string_conversions.h" #include "brightray/browser/inspectable_web_contents.h" @@ -30,7 +31,8 @@ void MenuMac::PopupAt(Window* window, int x, int y, int positioning_item) { return; base::scoped_nsobject menu_controller( - [[AtomMenuController alloc] initWithModel:model_.get()]); + [[AtomMenuController alloc] initWithModel:model_.get() + useDefaultAccelerator:NO]); NSMenu* menu = [menu_controller menu]; NSView* view = web_contents->GetView()->GetNativeView(); @@ -66,6 +68,9 @@ void MenuMac::PopupAt(Window* window, int x, int y, int positioning_item) { if (rightmostMenuPoint > screenRight) position.x = position.x - [menu size].width; + // Don't emit unresponsive event when showing menu. + atom::UnresponsiveSuppressor suppressor; + // Show the menu. [menu popUpMenuPositioningItem:item atLocation:position inView:view]; } @@ -74,7 +79,8 @@ void MenuMac::PopupAt(Window* window, int x, int y, int positioning_item) { void Menu::SetApplicationMenu(Menu* base_menu) { MenuMac* menu = static_cast(base_menu); base::scoped_nsobject menu_controller( - [[AtomMenuController alloc] initWithModel:menu->model_.get()]); + [[AtomMenuController alloc] initWithModel:menu->model_.get() + useDefaultAccelerator:YES]); [NSApp setMainMenu:[menu_controller menu]]; // Ensure the menu_controller_ is destroyed after main menu is set. diff --git a/atom/browser/api/atom_api_menu_views.cc b/atom/browser/api/atom_api_menu_views.cc index 9340bc7673..a6fd8024ab 100644 --- a/atom/browser/api/atom_api_menu_views.cc +++ b/atom/browser/api/atom_api_menu_views.cc @@ -5,8 +5,9 @@ #include "atom/browser/api/atom_api_menu_views.h" #include "atom/browser/native_window_views.h" +#include "atom/browser/unresponsive_suppressor.h" #include "content/public/browser/render_widget_host_view.h" -#include "ui/gfx/screen.h" +#include "ui/display/screen.h" #include "ui/views/controls/menu/menu_runner.h" namespace atom { @@ -30,12 +31,15 @@ void MenuViews::PopupAt(Window* window, int x, int y, int positioning_item) { // (-1, -1) means showing on mouse location. gfx::Point location; if (x == -1 || y == -1) { - location = gfx::Screen::GetScreen()->GetCursorScreenPoint(); + location = display::Screen::GetScreen()->GetCursorScreenPoint(); } else { gfx::Point origin = view->GetViewBounds().origin(); location = gfx::Point(origin.x() + x, origin.y() + y); } + // Don't emit unresponsive event when showing menu. + atom::UnresponsiveSuppressor suppressor; + // Show the menu. views::MenuRunner menu_runner( model(), diff --git a/atom/browser/api/atom_api_menu_views.h b/atom/browser/api/atom_api_menu_views.h index 9a7a740182..9b4ddf77f2 100644 --- a/atom/browser/api/atom_api_menu_views.h +++ b/atom/browser/api/atom_api_menu_views.h @@ -6,7 +6,7 @@ #define ATOM_BROWSER_API_ATOM_API_MENU_VIEWS_H_ #include "atom/browser/api/atom_api_menu.h" -#include "ui/gfx/screen.h" +#include "ui/display/screen.h" namespace atom { diff --git a/atom/browser/api/atom_api_power_save_blocker.h b/atom/browser/api/atom_api_power_save_blocker.h index a20b493e75..ee1e0e3213 100644 --- a/atom/browser/api/atom_api_power_save_blocker.h +++ b/atom/browser/api/atom_api_power_save_blocker.h @@ -6,9 +6,9 @@ #define ATOM_BROWSER_API_ATOM_API_POWER_SAVE_BLOCKER_H_ #include +#include #include "atom/browser/api/trackable_object.h" -#include "base/memory/scoped_ptr.h" #include "content/public/browser/power_save_blocker.h" #include "native_mate/handle.h" diff --git a/atom/browser/api/atom_api_protocol.cc b/atom/browser/api/atom_api_protocol.cc index c762559ab6..4019a96f2a 100644 --- a/atom/browser/api/atom_api_protocol.cc +++ b/atom/browser/api/atom_api_protocol.cc @@ -6,6 +6,7 @@ #include "atom/browser/atom_browser_client.h" #include "atom/browser/atom_browser_main_parts.h" +#include "atom/browser/browser.h" #include "atom/browser/net/url_request_async_asar_job.h" #include "atom/browser/net/url_request_buffer_job.h" #include "atom/browser/net/url_request_fetch_job.h" @@ -26,13 +27,30 @@ namespace atom { namespace api { +namespace { + +// Clear protocol handlers in IO thread. +void ClearJobFactoryInIO( + scoped_refptr request_context_getter) { + auto job_factory = static_cast( + request_context_getter->job_factory()); + job_factory->Clear(); +} + +} // namespace + Protocol::Protocol(v8::Isolate* isolate, AtomBrowserContext* browser_context) - : request_context_getter_(static_cast( - browser_context->GetRequestContext())), + : request_context_getter_(browser_context->GetRequestContext()), weak_factory_(this) { Init(isolate); } +Protocol::~Protocol() { + content::BrowserThread::PostTask( + content::BrowserThread::IO, FROM_HERE, + base::Bind(ClearJobFactoryInIO, request_context_getter_)); +} + void Protocol::RegisterServiceWorkerSchemes( const std::vector& schemes) { atom::AtomBrowserClient::SetCustomServiceWorkerSchemes(schemes); @@ -174,7 +192,13 @@ void Protocol::BuildPrototype( namespace { void RegisterStandardSchemes( - const std::vector& schemes) { + const std::vector& schemes, mate::Arguments* args) { + if (atom::Browser::Get()->is_ready()) { + args->ThrowError("protocol.registerStandardSchemes should be called before " + "app is ready"); + return; + } + auto policy = content::ChildProcessSecurityPolicy::GetInstance(); for (const auto& scheme : schemes) { url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITHOUT_PORT); diff --git a/atom/browser/api/atom_api_protocol.h b/atom/browser/api/atom_api_protocol.h index 379c43bfcd..b5d47def68 100644 --- a/atom/browser/api/atom_api_protocol.h +++ b/atom/browser/api/atom_api_protocol.h @@ -43,6 +43,7 @@ class Protocol : public mate::TrackableObject { protected: Protocol(v8::Isolate* isolate, AtomBrowserContext* browser_context); + ~Protocol(); private: // Possible errors. diff --git a/atom/browser/api/atom_api_screen.cc b/atom/browser/api/atom_api_screen.cc index 425d906e28..68f4baeaf2 100644 --- a/atom/browser/api/atom_api_screen.cc +++ b/atom/browser/api/atom_api_screen.cc @@ -12,7 +12,9 @@ #include "base/bind.h" #include "native_mate/dictionary.h" #include "native_mate/object_template_builder.h" -#include "ui/gfx/screen.h" +#include "ui/display/display.h" +#include "ui/display/screen.h" +#include "ui/gfx/geometry/point.h" #include "atom/common/node_includes.h" @@ -34,20 +36,20 @@ typename T::iterator FindById(T* container, int id) { // Convert the changed_metrics bitmask to string array. std::vector MetricsToArray(uint32_t metrics) { std::vector array; - if (metrics & gfx::DisplayObserver::DISPLAY_METRIC_BOUNDS) + if (metrics & display::DisplayObserver::DISPLAY_METRIC_BOUNDS) array.push_back("bounds"); - if (metrics & gfx::DisplayObserver::DISPLAY_METRIC_WORK_AREA) + if (metrics & display::DisplayObserver::DISPLAY_METRIC_WORK_AREA) array.push_back("workArea"); - if (metrics & gfx::DisplayObserver::DISPLAY_METRIC_DEVICE_SCALE_FACTOR) + if (metrics & display::DisplayObserver::DISPLAY_METRIC_DEVICE_SCALE_FACTOR) array.push_back("scaleFactor"); - if (metrics & gfx::DisplayObserver::DISPLAY_METRIC_ROTATION) + if (metrics & display::DisplayObserver::DISPLAY_METRIC_ROTATION) array.push_back("rotation"); return array; } } // namespace -Screen::Screen(v8::Isolate* isolate, gfx::Screen* screen) +Screen::Screen(v8::Isolate* isolate, display::Screen* screen) : screen_(screen) { screen_->AddObserver(this); Init(isolate); @@ -61,31 +63,31 @@ gfx::Point Screen::GetCursorScreenPoint() { return screen_->GetCursorScreenPoint(); } -gfx::Display Screen::GetPrimaryDisplay() { +display::Display Screen::GetPrimaryDisplay() { return screen_->GetPrimaryDisplay(); } -std::vector Screen::GetAllDisplays() { +std::vector Screen::GetAllDisplays() { return screen_->GetAllDisplays(); } -gfx::Display Screen::GetDisplayNearestPoint(const gfx::Point& point) { +display::Display Screen::GetDisplayNearestPoint(const gfx::Point& point) { return screen_->GetDisplayNearestPoint(point); } -gfx::Display Screen::GetDisplayMatching(const gfx::Rect& match_rect) { +display::Display Screen::GetDisplayMatching(const gfx::Rect& match_rect) { return screen_->GetDisplayMatching(match_rect); } -void Screen::OnDisplayAdded(const gfx::Display& new_display) { +void Screen::OnDisplayAdded(const display::Display& new_display) { Emit("display-added", new_display); } -void Screen::OnDisplayRemoved(const gfx::Display& old_display) { +void Screen::OnDisplayRemoved(const display::Display& old_display) { Emit("display-removed", old_display); } -void Screen::OnDisplayMetricsChanged(const gfx::Display& display, +void Screen::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { Emit("display-metrics-changed", display, MetricsToArray(changed_metrics)); } @@ -99,7 +101,7 @@ v8::Local Screen::Create(v8::Isolate* isolate) { return v8::Null(isolate); } - gfx::Screen* screen = gfx::Screen::GetScreen(); + display::Screen* screen = display::Screen::GetScreen(); if (!screen) { isolate->ThrowException(v8::Exception::Error(mate::StringToV8( isolate, "Failed to get screen information"))); diff --git a/atom/browser/api/atom_api_screen.h b/atom/browser/api/atom_api_screen.h index c17b612885..feff6ddfff 100644 --- a/atom/browser/api/atom_api_screen.h +++ b/atom/browser/api/atom_api_screen.h @@ -9,7 +9,8 @@ #include "atom/browser/api/event_emitter.h" #include "native_mate/handle.h" -#include "ui/gfx/display_observer.h" +#include "ui/display/display_observer.h" +#include "ui/display/screen.h" namespace gfx { class Point; @@ -22,7 +23,7 @@ namespace atom { namespace api { class Screen : public mate::EventEmitter, - public gfx::DisplayObserver { + public display::DisplayObserver { public: static v8::Local Create(v8::Isolate* isolate); @@ -30,23 +31,23 @@ class Screen : public mate::EventEmitter, v8::Local prototype); protected: - Screen(v8::Isolate* isolate, gfx::Screen* screen); + Screen(v8::Isolate* isolate, display::Screen* screen); ~Screen() override; gfx::Point GetCursorScreenPoint(); - gfx::Display GetPrimaryDisplay(); - std::vector GetAllDisplays(); - gfx::Display GetDisplayNearestPoint(const gfx::Point& point); - gfx::Display GetDisplayMatching(const gfx::Rect& match_rect); + display::Display GetPrimaryDisplay(); + std::vector GetAllDisplays(); + display::Display GetDisplayNearestPoint(const gfx::Point& point); + display::Display GetDisplayMatching(const gfx::Rect& match_rect); - // gfx::DisplayObserver: - void OnDisplayAdded(const gfx::Display& new_display) override; - void OnDisplayRemoved(const gfx::Display& old_display) override; - void OnDisplayMetricsChanged(const gfx::Display& display, + // display::DisplayObserver: + void OnDisplayAdded(const display::Display& new_display) override; + void OnDisplayRemoved(const display::Display& old_display) override; + void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; private: - gfx::Screen* screen_; + display::Screen* screen_; DISALLOW_COPY_AND_ASSIGN(Screen); }; diff --git a/atom/browser/api/atom_api_session.cc b/atom/browser/api/atom_api_session.cc index 602729b9e3..02fafddf94 100644 --- a/atom/browser/api/atom_api_session.cc +++ b/atom/browser/api/atom_api_session.cc @@ -11,6 +11,7 @@ #include "atom/browser/api/atom_api_download_item.h" #include "atom/browser/api/atom_api_protocol.h" #include "atom/browser/api/atom_api_web_request.h" +#include "atom/browser/browser.h" #include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/atom_permission_manager.h" @@ -20,13 +21,14 @@ #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/file_path_converter.h" #include "atom/common/native_mate_converters/net_converter.h" +#include "atom/common/native_mate_converters/value_converter.h" #include "atom/common/node_includes.h" #include "base/files/file_path.h" #include "base/guid.h" #include "components/prefs/pref_service.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" -#include "base/thread_task_runner_handle.h" +#include "base/threading/thread_task_runner_handle.h" #include "brightray/browser/net/devtools_network_conditions.h" #include "brightray/browser/net/devtools_network_controller_handle.h" #include "chrome/common/pref_names.h" @@ -41,8 +43,10 @@ #include "net/http/http_auth_preferences.h" #include "net/proxy/proxy_service.h" #include "net/proxy/proxy_config_service_fixed.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_getter.h" +#include "ui/base/l10n/l10n_util.h" using content::BrowserThread; using content::StoragePartition; @@ -93,6 +97,15 @@ uint32_t GetQuotaMask(const std::vector& quota_types) { return quota_mask; } +void SetUserAgentInIO(scoped_refptr getter, + const std::string& accept_lang, + const std::string& user_agent) { + getter->GetURLRequestContext()->set_http_user_agent_settings( + new net::StaticHttpUserAgentSettings( + net::HttpUtil::GenerateAcceptLanguageHeader(accept_lang), + user_agent)); +} + } // namespace namespace mate { @@ -120,7 +133,7 @@ struct Converter { static bool FromV8(v8::Isolate* isolate, v8::Local val, net::ProxyConfig* out) { - std::string proxy_rules; + std::string proxy_rules, proxy_bypass_rules; GURL pac_url; mate::Dictionary options; // Fallback to previous API when passed String. @@ -130,6 +143,7 @@ struct Converter { } else if (ConvertFromV8(isolate, val, &options)) { options.Get("pacScript", &pac_url); options.Get("proxyRules", &proxy_rules); + options.Get("proxyBypassRules", &proxy_bypass_rules); } else { return false; } @@ -139,6 +153,7 @@ struct Converter { out->set_pac_url(pac_url); } else { out->proxy_rules().ParseFromString(proxy_rules); + out->proxy_rules().bypass_rules.ParseFromString(proxy_bypass_rules); } return true; } @@ -152,6 +167,8 @@ namespace api { namespace { +const char kPersistPrefix[] = "persist:"; + // The wrapSession funtion which is implemented in JavaScript using WrapSessionCallback = base::Callback)>; WrapSessionCallback g_wrap_session; @@ -164,7 +181,7 @@ class ResolveProxyHelper { : callback_(callback), original_thread_(base::ThreadTaskRunnerHandle::Get()) { scoped_refptr context_getter = - browser_context->GetRequestContext(); + browser_context->url_request_context_getter(); context_getter->GetNetworkTaskRunner()->PostTask( FROM_HERE, base::Bind(&ResolveProxyHelper::ResolveProxy, @@ -230,10 +247,10 @@ void OnGetBackend(disk_cache::Backend** backend_ptr, } else if (action == Session::CacheAction::STATS) { base::StringPairs stats; (*backend_ptr)->GetStats(&stats); - for (size_t i = 0; i < stats.size(); ++i) { - if (stats[i].first == "Current size") { + for (const auto& stat : stats) { + if (stat.first == "Current size") { int current_size; - base::StringToInt(stats[i].second, ¤t_size); + base::StringToInt(stat.second, ¤t_size); RunCallbackInUI(callback, current_size); break; } @@ -255,7 +272,7 @@ void DoCacheActionInIO( // Call GetBackend and make the backend's ptr accessable in OnGetBackend. using BackendPtr = disk_cache::Backend*; - BackendPtr* backend_ptr = new BackendPtr(nullptr); + auto* backend_ptr = new BackendPtr(nullptr); net::CompletionCallback on_get_backend = base::Bind(&OnGetBackend, base::Owned(backend_ptr), action, callback); int rv = http_cache->GetBackend(backend_ptr, on_get_backend); @@ -267,13 +284,21 @@ void SetProxyInIO(net::URLRequestContextGetter* getter, const net::ProxyConfig& config, const base::Closure& callback) { auto proxy_service = getter->GetURLRequestContext()->proxy_service(); - proxy_service->ResetConfigService(make_scoped_ptr( + proxy_service->ResetConfigService(base::WrapUnique( new net::ProxyConfigServiceFixed(config))); // Refetches and applies the new pac script if provided. proxy_service->ForceReloadProxyConfig(); RunCallbackInUI(callback); } +void SetCertVerifyProcInIO( + const scoped_refptr& context_getter, + const AtomCertVerifier::VerifyProc& proc) { + auto request_context = context_getter->GetURLRequestContext(); + static_cast(request_context->cert_verifier())-> + SetVerifyProc(proc); +} + void ClearHostResolverCacheInIO( const scoped_refptr& context_getter, const base::Closure& callback) { @@ -300,6 +325,11 @@ void AllowNTLMCredentialsForDomainsInIO( } } +void OnClearStorageDataDone(const base::Closure& callback) { + if (!callback.is_null()) + callback.Run(); +} + } // namespace Session::Session(v8::Isolate* isolate, AtomBrowserContext* browser_context) @@ -349,21 +379,19 @@ void Session::DoCacheAction(const net::CompletionCallback& callback) { } void Session::ClearStorageData(mate::Arguments* args) { - // clearStorageData([options, ]callback) + // clearStorageData([options, callback]) ClearStorageDataOptions options; - args->GetNext(&options); base::Closure callback; - if (!args->GetNext(&callback)) { - args->ThrowError(); - return; - } + args->GetNext(&options); + args->GetNext(&callback); auto storage_partition = content::BrowserContext::GetStoragePartition(browser_context(), nullptr); storage_partition->ClearData( options.storage_types, options.quota_types, options.origin, content::StoragePartition::OriginMatcherFunction(), - base::Time(), base::Time::Max(), callback); + base::Time(), base::Time::Max(), + base::Bind(&OnClearStorageDataDone, callback)); } void Session::FlushStorageData() { @@ -423,7 +451,10 @@ void Session::SetCertVerifyProc(v8::Local val, return; } - browser_context_->cert_verifier()->SetVerifyProc(proc); + BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, + base::Bind(&SetCertVerifyProcInIO, + make_scoped_refptr(browser_context_->GetRequestContext()), + proc)); } void Session::SetPermissionRequestHandler(v8::Local val, @@ -455,6 +486,23 @@ void Session::AllowNTLMCredentialsForDomains(const std::string& domains) { domains)); } +void Session::SetUserAgent(const std::string& user_agent, + mate::Arguments* args) { + browser_context_->SetUserAgent(user_agent); + + std::string accept_lang = l10n_util::GetApplicationLocale(""); + args->GetNext(&accept_lang); + + auto getter = browser_context_->GetRequestContext(); + getter->GetNetworkTaskRunner()->PostTask( + FROM_HERE, + base::Bind(&SetUserAgentInIO, getter, accept_lang, user_agent)); +} + +std::string Session::GetUserAgent() { + return browser_context_->GetUserAgent(); +} + v8::Local Session::Cookies(v8::Isolate* isolate) { if (cookies_.IsEmpty()) { auto handle = atom::api::Cookies::Create(isolate, browser_context()); @@ -494,10 +542,19 @@ mate::Handle Session::CreateFrom( // static mate::Handle Session::FromPartition( - v8::Isolate* isolate, const std::string& partition, bool in_memory) { - auto browser_context = brightray::BrowserContext::From(partition, in_memory); - return CreateFrom(isolate, - static_cast(browser_context.get())); + v8::Isolate* isolate, const std::string& partition, + const base::DictionaryValue& options) { + scoped_refptr browser_context; + if (partition.empty()) { + browser_context = AtomBrowserContext::From("", false, options); + } else if (base::StartsWith(partition, kPersistPrefix, + base::CompareCase::SENSITIVE)) { + std::string name = partition.substr(8); + browser_context = AtomBrowserContext::From(name, false, options); + } else { + browser_context = AtomBrowserContext::From(partition, true, options); + } + return CreateFrom(isolate, browser_context.get()); } // static @@ -520,6 +577,8 @@ void Session::BuildPrototype(v8::Isolate* isolate, .SetMethod("clearHostResolverCache", &Session::ClearHostResolverCache) .SetMethod("allowNTLMCredentialsForDomains", &Session::AllowNTLMCredentialsForDomains) + .SetMethod("setUserAgent", &Session::SetUserAgent) + .SetMethod("getUserAgent", &Session::GetUserAgent) .SetProperty("cookies", &Session::Cookies) .SetProperty("protocol", &Session::Protocol) .SetProperty("webRequest", &Session::WebRequest); @@ -535,11 +594,23 @@ void SetWrapSession(const WrapSessionCallback& callback) { namespace { +v8::Local FromPartition( + const std::string& partition, mate::Arguments* args) { + if (!atom::Browser::Get()->is_ready()) { + args->ThrowError("Session can only be received when app is ready"); + return v8::Null(args->isolate()); + } + base::DictionaryValue options; + args->GetNext(&options); + return atom::api::Session::FromPartition( + args->isolate(), partition, options).ToV8(); +} + void Initialize(v8::Local exports, v8::Local unused, v8::Local context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); mate::Dictionary dict(isolate, exports); - dict.SetMethod("fromPartition", &atom::api::Session::FromPartition); + dict.SetMethod("fromPartition", &FromPartition); dict.SetMethod("_setWrapSession", &atom::api::SetWrapSession); } diff --git a/atom/browser/api/atom_api_session.h b/atom/browser/api/atom_api_session.h index bb67fa106d..c3bb82eeba 100644 --- a/atom/browser/api/atom_api_session.h +++ b/atom/browser/api/atom_api_session.h @@ -8,6 +8,7 @@ #include #include "atom/browser/api/trackable_object.h" +#include "base/values.h" #include "content/public/browser/download_manager.h" #include "native_mate/handle.h" #include "net/base/completion_callback.h" @@ -47,9 +48,10 @@ class Session: public mate::TrackableObject, static mate::Handle CreateFrom( v8::Isolate* isolate, AtomBrowserContext* browser_context); - // Gets the Session of |partition| and |in_memory|. + // Gets the Session of |partition|. static mate::Handle FromPartition( - v8::Isolate* isolate, const std::string& partition, bool in_memory); + v8::Isolate* isolate, const std::string& partition, + const base::DictionaryValue& options = base::DictionaryValue()); AtomBrowserContext* browser_context() const { return browser_context_.get(); } @@ -57,15 +59,7 @@ class Session: public mate::TrackableObject, static void BuildPrototype(v8::Isolate* isolate, v8::Local prototype); - protected: - Session(v8::Isolate* isolate, AtomBrowserContext* browser_context); - ~Session(); - - // content::DownloadManager::Observer: - void OnDownloadCreated(content::DownloadManager* manager, - content::DownloadItem* item) override; - - private: + // Methods. void ResolveProxy(const GURL& url, ResolveProxyCallback callback); template void DoCacheAction(const net::CompletionCallback& callback); @@ -80,10 +74,21 @@ class Session: public mate::TrackableObject, mate::Arguments* args); void ClearHostResolverCache(mate::Arguments* args); void AllowNTLMCredentialsForDomains(const std::string& domains); + void SetUserAgent(const std::string& user_agent, mate::Arguments* args); + std::string GetUserAgent(); v8::Local Cookies(v8::Isolate* isolate); v8::Local Protocol(v8::Isolate* isolate); v8::Local WebRequest(v8::Isolate* isolate); + protected: + Session(v8::Isolate* isolate, AtomBrowserContext* browser_context); + ~Session(); + + // content::DownloadManager::Observer: + void OnDownloadCreated(content::DownloadManager* manager, + content::DownloadItem* item) override; + + private: // Cached object. v8::Global cookies_; v8::Global protocol_; diff --git a/atom/browser/api/atom_api_system_preferences.cc b/atom/browser/api/atom_api_system_preferences.cc index 2b11aad252..c3421365f0 100644 --- a/atom/browser/api/atom_api_system_preferences.cc +++ b/atom/browser/api/atom_api_system_preferences.cc @@ -53,6 +53,10 @@ void SystemPreferences::BuildPrototype( &SystemPreferences::SubscribeNotification) .SetMethod("unsubscribeNotification", &SystemPreferences::UnsubscribeNotification) + .SetMethod("subscribeLocalNotification", + &SystemPreferences::SubscribeLocalNotification) + .SetMethod("unsubscribeLocalNotification", + &SystemPreferences::UnsubscribeLocalNotification) .SetMethod("getUserDefault", &SystemPreferences::GetUserDefault) #endif .SetMethod("isDarkMode", &SystemPreferences::IsDarkMode); diff --git a/atom/browser/api/atom_api_system_preferences.h b/atom/browser/api/atom_api_system_preferences.h index 7779ce0078..9a5cf99035 100644 --- a/atom/browser/api/atom_api_system_preferences.h +++ b/atom/browser/api/atom_api_system_preferences.h @@ -26,17 +26,18 @@ class SystemPreferences : public mate::EventEmitter { static void BuildPrototype(v8::Isolate* isolate, v8::Local prototype); -#if defined(OS_MACOSX) - using NotificationCallback = base::Callback< - void(const std::string&, const base::DictionaryValue&)>; -#endif - #if defined(OS_WIN) bool IsAeroGlassEnabled(); #elif defined(OS_MACOSX) + using NotificationCallback = base::Callback< + void(const std::string&, const base::DictionaryValue&)>; + int SubscribeNotification(const std::string& name, const NotificationCallback& callback); void UnsubscribeNotification(int id); + int SubscribeLocalNotification(const std::string& name, + const NotificationCallback& callback); + void UnsubscribeLocalNotification(int request_id); v8::Local GetUserDefault(const std::string& name, const std::string& type); #endif @@ -46,6 +47,13 @@ class SystemPreferences : public mate::EventEmitter { explicit SystemPreferences(v8::Isolate* isolate); ~SystemPreferences() override; +#if defined(OS_MACOSX) + int DoSubscribeNotification(const std::string& name, + const NotificationCallback& callback, + bool is_local); + void DoUnsubscribeNotification(int request_id, bool is_local); +#endif + private: DISALLOW_COPY_AND_ASSIGN(SystemPreferences); }; diff --git a/atom/browser/api/atom_api_system_preferences_mac.mm b/atom/browser/api/atom_api_system_preferences_mac.mm index 72011500bd..6f7055ab91 100644 --- a/atom/browser/api/atom_api_system_preferences_mac.mm +++ b/atom/browser/api/atom_api_system_preferences_mac.mm @@ -30,34 +30,59 @@ std::map g_id_map; int SystemPreferences::SubscribeNotification( const std::string& name, const NotificationCallback& callback) { + return DoSubscribeNotification(name, callback, false); +} + +void SystemPreferences::UnsubscribeNotification(int request_id) { + DoUnsubscribeNotification(request_id, false); +} + +int SystemPreferences::SubscribeLocalNotification( + const std::string& name, const NotificationCallback& callback) { + return DoSubscribeNotification(name, callback, true); +} + +void SystemPreferences::UnsubscribeLocalNotification(int request_id) { + DoUnsubscribeNotification(request_id, true); +} + +int SystemPreferences::DoSubscribeNotification(const std::string& name, + const NotificationCallback& callback, bool is_local) { int request_id = g_next_id++; __block NotificationCallback copied_callback = callback; - g_id_map[request_id] = [[NSDistributedNotificationCenter defaultCenter] - addObserverForName:base::SysUTF8ToNSString(name) - object:nil - queue:nil - usingBlock:^(NSNotification* notification) { - std::unique_ptr 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()); - } + NSNotificationCenter* center = is_local ? + [NSNotificationCenter defaultCenter] : + [NSDistributedNotificationCenter defaultCenter]; + + g_id_map[request_id] = [center + addObserverForName:base::SysUTF8ToNSString(name) + object:nil + queue:nil + usingBlock:^(NSNotification* notification) { + std::unique_ptr 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; } -void SystemPreferences::UnsubscribeNotification(int request_id) { +void SystemPreferences::DoUnsubscribeNotification(int request_id, bool is_local) { auto iter = g_id_map.find(request_id); if (iter != g_id_map.end()) { id observer = iter->second; - [[NSDistributedNotificationCenter defaultCenter] removeObserver:observer]; + NSNotificationCenter* center = is_local ? + [NSNotificationCenter defaultCenter] : + [NSDistributedNotificationCenter defaultCenter]; + [center removeObserver:observer]; g_id_map.erase(iter); } } diff --git a/atom/browser/api/atom_api_tray.cc b/atom/browser/api/atom_api_tray.cc index c84e8a1d66..213ddbfd89 100644 --- a/atom/browser/api/atom_api_tray.cc +++ b/atom/browser/api/atom_api_tray.cc @@ -8,7 +8,6 @@ #include "atom/browser/api/atom_api_menu.h" #include "atom/browser/browser.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/image_converter.h" @@ -16,9 +15,47 @@ #include "atom/common/node_includes.h" #include "native_mate/constructor.h" #include "native_mate/dictionary.h" -#include "ui/events/event_constants.h" #include "ui/gfx/image/image.h" +namespace mate { + +template<> +struct Converter { + static bool FromV8(v8::Isolate* isolate, v8::Local val, + atom::TrayIcon::HighlightMode* out) { + std::string mode; + if (ConvertFromV8(isolate, val, &mode)) { + if (mode == "always") { + *out = atom::TrayIcon::HighlightMode::ALWAYS; + return true; + } + if (mode == "selection") { + *out = atom::TrayIcon::HighlightMode::SELECTION; + return true; + } + if (mode == "never") { + *out = atom::TrayIcon::HighlightMode::NEVER; + return true; + } + } + + // Support old boolean parameter + // TODO(kevinsawicki): Remove in 2.0, deprecate before then with warnings + bool highlight; + if (ConvertFromV8(isolate, val, &highlight)) { + if (highlight) + *out = atom::TrayIcon::HighlightMode::SELECTION; + else + *out = atom::TrayIcon::HighlightMode::NEVER; + return true; + } + + return false; + } +}; +} // namespace mate + + namespace atom { namespace api { @@ -30,6 +67,8 @@ Tray::Tray(v8::Isolate* isolate, mate::Handle image) } Tray::~Tray() { + // Destroy the native tray in next tick. + base::MessageLoop::current()->DeleteSoon(FROM_HERE, tray_icon_.release()); } // static @@ -44,24 +83,15 @@ mate::WrappableBase* Tray::New(v8::Isolate* isolate, } void Tray::OnClicked(const gfx::Rect& bounds, int modifiers) { - v8::Locker locker(isolate()); - v8::HandleScope handle_scope(isolate()); - EmitCustomEvent("click", - ModifiersToObject(isolate(), modifiers), bounds); + EmitWithFlags("click", modifiers, bounds); } void Tray::OnDoubleClicked(const gfx::Rect& bounds, int modifiers) { - v8::Locker locker(isolate()); - v8::HandleScope handle_scope(isolate()); - EmitCustomEvent("double-click", - ModifiersToObject(isolate(), modifiers), bounds); + EmitWithFlags("double-click", modifiers, bounds); } void Tray::OnRightClicked(const gfx::Rect& bounds, int modifiers) { - v8::Locker locker(isolate()); - v8::HandleScope handle_scope(isolate()); - EmitCustomEvent("right-click", - ModifiersToObject(isolate(), modifiers), bounds); + EmitWithFlags("right-click", modifiers, bounds); } void Tray::OnBalloonShow() { @@ -84,6 +114,10 @@ void Tray::OnDropFiles(const std::vector& files) { Emit("drop-files", files); } +void Tray::OnDropText(const std::string& text) { + Emit("drop-text", text); +} + void Tray::OnDragEntered() { Emit("drag-enter"); } @@ -121,8 +155,8 @@ void Tray::SetTitle(const std::string& title) { tray_icon_->SetTitle(title); } -void Tray::SetHighlightMode(bool highlight) { - tray_icon_->SetHighlightMode(highlight); +void Tray::SetHighlightMode(TrayIcon::HighlightMode mode) { + tray_icon_->SetHighlightMode(mode); } void Tray::DisplayBalloon(mate::Arguments* args, @@ -159,14 +193,8 @@ void Tray::SetContextMenu(v8::Isolate* isolate, mate::Handle menu) { tray_icon_->SetContextMenu(menu->model()); } -v8::Local Tray::ModifiersToObject(v8::Isolate* isolate, - int modifiers) { - mate::Dictionary obj(isolate, v8::Object::New(isolate)); - obj.Set("shiftKey", static_cast(modifiers & ui::EF_SHIFT_DOWN)); - obj.Set("ctrlKey", static_cast(modifiers & ui::EF_CONTROL_DOWN)); - obj.Set("altKey", static_cast(modifiers & ui::EF_ALT_DOWN)); - obj.Set("metaKey", static_cast(modifiers & ui::EF_COMMAND_DOWN)); - return obj.GetHandle(); +gfx::Rect Tray::GetBounds() { + return tray_icon_->GetBounds(); } // static @@ -181,7 +209,8 @@ void Tray::BuildPrototype(v8::Isolate* isolate, .SetMethod("setHighlightMode", &Tray::SetHighlightMode) .SetMethod("displayBalloon", &Tray::DisplayBalloon) .SetMethod("popUpContextMenu", &Tray::PopUpContextMenu) - .SetMethod("setContextMenu", &Tray::SetContextMenu); + .SetMethod("setContextMenu", &Tray::SetContextMenu) + .SetMethod("getBounds", &Tray::GetBounds); } } // namespace api diff --git a/atom/browser/api/atom_api_tray.h b/atom/browser/api/atom_api_tray.h index a6c329567c..1e1bc13075 100644 --- a/atom/browser/api/atom_api_tray.h +++ b/atom/browser/api/atom_api_tray.h @@ -5,12 +5,13 @@ #ifndef ATOM_BROWSER_API_ATOM_API_TRAY_H_ #define ATOM_BROWSER_API_ATOM_API_TRAY_H_ +#include #include #include #include "atom/browser/api/trackable_object.h" +#include "atom/browser/ui/tray_icon.h" #include "atom/browser/ui/tray_icon_observer.h" -#include "base/memory/scoped_ptr.h" #include "native_mate/handle.h" namespace gfx { @@ -53,6 +54,7 @@ class Tray : public mate::TrackableObject, void OnBalloonClosed() override; void OnDrop() override; void OnDropFiles(const std::vector& files) override; + void OnDropText(const std::string& text) override; void OnDragEntered() override; void OnDragExited() override; void OnDragEnded() override; @@ -61,14 +63,13 @@ class Tray : public mate::TrackableObject, void SetPressedImage(v8::Isolate* isolate, mate::Handle image); void SetToolTip(const std::string& tool_tip); void SetTitle(const std::string& title); - void SetHighlightMode(bool highlight); + void SetHighlightMode(TrayIcon::HighlightMode mode); void DisplayBalloon(mate::Arguments* args, const mate::Dictionary& options); void PopUpContextMenu(mate::Arguments* args); void SetContextMenu(v8::Isolate* isolate, mate::Handle menu); + gfx::Rect GetBounds(); private: - v8::Local ModifiersToObject(v8::Isolate* isolate, int modifiers); - v8::Global menu_; std::unique_ptr tray_icon_; diff --git a/atom/browser/api/atom_api_web_contents.cc b/atom/browser/api/atom_api_web_contents.cc index bfedddce8a..43ef9d35d5 100644 --- a/atom/browser/api/atom_api_web_contents.cc +++ b/atom/browser/api/atom_api_web_contents.cc @@ -17,6 +17,7 @@ #include "atom/browser/lib/bluetooth_chooser.h" #include "atom/browser/native_window.h" #include "atom/browser/net/atom_network_delegate.h" +#include "atom/browser/ui/drag_util.h" #include "atom/browser/web_contents_permission_helper.h" #include "atom/browser/web_contents_preferences.h" #include "atom/browser/web_view_guest_delegate.h" @@ -46,6 +47,7 @@ #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" +#include "content/public/browser/navigation_handle.h" #include "content/public/browser/plugin_service.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" @@ -61,11 +63,10 @@ #include "native_mate/dictionary.h" #include "native_mate/object_template_builder.h" #include "net/http/http_response_headers.h" -#include "net/url_request/static_http_user_agent_settings.h" #include "net/url_request/url_request_context.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/display/screen.h" #include "atom/common/node_includes.h" @@ -76,15 +77,6 @@ struct PrintSettings { bool print_background; }; -void SetUserAgentInIO(scoped_refptr getter, - std::string accept_lang, - std::string user_agent) { - getter->GetURLRequestContext()->set_http_user_agent_settings( - new net::StaticHttpUserAgentSettings( - net::HttpUtil::GenerateAcceptLanguageHeader(accept_lang), - user_agent)); -} - } // namespace namespace mate { @@ -248,6 +240,13 @@ content::ServiceWorkerContext* GetServiceWorkerContext( return storage_partition->GetServiceWorkerContext(); } +// Called when CapturePage is done. +void OnCapturePageDone(base::Callback callback, + const SkBitmap& bitmap, + content::ReadbackResponse response) { + callback.Run(gfx::Image::CreateFrom1xBitmap(bitmap)); +} + } // namespace WebContents::WebContents(v8::Isolate* isolate, @@ -287,16 +286,11 @@ WebContents::WebContents(v8::Isolate* isolate, std::string partition; mate::Handle session; if (options.Get("session", &session)) { - } else if (options.Get("partition", &partition) && !partition.empty()) { - bool in_memory = true; - if (base::StartsWith(partition, "persist:", base::CompareCase::SENSITIVE)) { - in_memory = false; - partition = partition.substr(8); - } - session = Session::FromPartition(isolate, partition, in_memory); + } else if (options.Get("partition", &partition)) { + session = Session::FromPartition(isolate, partition); } else { // Use the default session if not specified. - session = Session::FromPartition(isolate, "", false); + session = Session::FromPartition(isolate, ""); } session_.Reset(isolate, session.ToV8()); @@ -610,17 +604,6 @@ void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, Emit("did-finish-load"); } -void WebContents::DidFailProvisionalLoad( - content::RenderFrameHost* render_frame_host, - const GURL& url, - int code, - const base::string16& description, - bool was_ignored_by_handler) { - bool is_main_frame = !render_frame_host->GetParent(); - Emit("did-fail-provisional-load", code, description, url, is_main_frame); - Emit("did-fail-load", code, description, url, is_main_frame); -} - void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code, @@ -664,13 +647,27 @@ void WebContents::DidGetRedirectForResourceRequest( details.headers.get()); } -void WebContents::DidNavigateMainFrame( - const content::LoadCommittedDetails& details, - const content::FrameNavigateParams& params) { - if (details.is_navigation_to_different_page()) - Emit("did-navigate", params.url); - else if (details.is_in_page) - Emit("did-navigate-in-page", params.url); +void WebContents::DidFinishNavigation( + content::NavigationHandle* navigation_handle) { + bool is_main_frame = navigation_handle->IsInMainFrame(); + if (navigation_handle->HasCommitted() && !navigation_handle->IsErrorPage()) { + auto url = navigation_handle->GetURL(); + bool is_in_page = navigation_handle->IsSamePage(); + if (is_main_frame && !is_in_page) { + Emit("did-navigate", url); + } else if (is_in_page) { + Emit("did-navigate-in-page", url); + } + } else { + auto url = navigation_handle->GetURL(); + int code = navigation_handle->GetNetErrorCode(); + auto description = net::ErrorToShortString(code); + Emit("did-fail-provisional-load", code, description, url, is_main_frame); + + // Do not emit "did-fail-load" for canceled requests. + if (code != net::ERR_ABORTED) + Emit("did-fail-load", code, description, url, is_main_frame); + } } void WebContents::TitleWasSet(content::NavigationEntry* entry, @@ -684,10 +681,10 @@ void WebContents::TitleWasSet(content::NavigationEntry* entry, void WebContents::DidUpdateFaviconURL( const std::vector& urls) { std::set unique_urls; - for (auto iter = urls.begin(); iter != urls.end(); ++iter) { - if (iter->icon_type != content::FaviconURL::FAVICON) + for (const auto& iter : urls) { + if (iter.icon_type != content::FaviconURL::FAVICON) continue; - const GURL& url = iter->icon_url; + const GURL& url = iter.icon_url; if (url.is_valid()) unique_urls.insert(url); } @@ -736,6 +733,7 @@ bool WebContents::OnMessageReceived(const IPC::Message& message) { IPC_MESSAGE_HANDLER(AtomViewHostMsg_Message, OnRendererMessage) IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_Message_Sync, OnRendererMessageSync) + IPC_MESSAGE_HANDLER(AtomViewHostMsg_DidCommitCompositorFrame, OnViewPainted) IPC_MESSAGE_HANDLER_CODE(ViewHostMsg_SetCursor, OnCursorChange, handled = false) IPC_MESSAGE_UNHANDLED(handled = false) @@ -745,7 +743,7 @@ bool WebContents::OnMessageReceived(const IPC::Message& message) { } // There are three ways of destroying a webContents: -// 1. call webContents.destory(); +// 1. call webContents.destroy(); // 2. garbage collection; // 3. user closes the window of webContents; // For webview only #1 will happen, for BrowserWindow both #1 and #3 may @@ -788,6 +786,13 @@ WebContents::Type WebContents::GetType() const { return type_; } +#if !defined(OS_MACOSX) +bool WebContents::IsFocused() const { + auto view = web_contents()->GetRenderWidgetHostView(); + return view && view->HasFocus(); +} +#endif + bool WebContents::Equal(const WebContents* web_contents) const { return GetID() == web_contents->GetID(); } @@ -811,7 +816,7 @@ void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) { std::string user_agent; if (options.Get("userAgent", &user_agent)) - SetUserAgent(user_agent); + web_contents()->SetUserAgentOverride(user_agent); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) @@ -898,14 +903,9 @@ bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } -void WebContents::SetUserAgent(const std::string& user_agent) { +void WebContents::SetUserAgent(const std::string& user_agent, + mate::Arguments* args) { web_contents()->SetUserAgentOverride(user_agent); - scoped_refptr getter = - web_contents()->GetBrowserContext()->GetRequestContext(); - - auto accept_lang = l10n_util::GetApplicationLocale(""); - getter->GetNetworkTaskRunner()->PostTask(FROM_HERE, - base::Bind(&SetUserAgentInIO, getter, accept_lang, user_agent)); } std::string WebContents::GetUserAgent() { @@ -1146,6 +1146,12 @@ void WebContents::ShowDefinitionForSelection() { #endif } +void WebContents::CopyImageAt(int x, int y) { + const auto host = web_contents()->GetRenderViewHost(); + if (host) + host->CopyImageAt(x, y); +} + void WebContents::Focus() { web_contents()->Focus(); } @@ -1194,15 +1200,14 @@ void WebContents::SendInputEvent(v8::Isolate* isolate, isolate, "Invalid event object"))); } -void WebContents::BeginFrameSubscription( - mate::Arguments* args) { - FrameSubscriber::FrameCaptureCallback callback; +void WebContents::BeginFrameSubscription(mate::Arguments* args) { bool only_dirty = false; + FrameSubscriber::FrameCaptureCallback callback; + args->GetNext(&only_dirty); if (!args->GetNext(&callback)) { - args->GetNext(&only_dirty); - if (!args->GetNext(&callback)) - args->ThrowTypeError("'callback' must be defined"); + args->ThrowError(); + return; } const auto view = web_contents()->GetRenderWidgetHostView(); @@ -1219,6 +1224,74 @@ void WebContents::EndFrameSubscription() { view->EndFrameSubscription(); } +void WebContents::StartDrag(const mate::Dictionary& item, + mate::Arguments* args) { + base::FilePath file; + std::vector files; + if (!item.Get("files", &files) && item.Get("file", &file)) { + files.push_back(file); + } + + mate::Handle icon; + if (!item.Get("icon", &icon) && !file.empty()) { + // TODO(zcbenz): Set default icon from file. + } + + // Error checking. + if (icon.IsEmpty()) { + args->ThrowError("icon must be set"); + return; + } + + // Start dragging. + if (!files.empty()) { + base::MessageLoop::ScopedNestableTaskAllower allow( + base::MessageLoop::current()); + DragFileItems(files, icon->image(), web_contents()->GetNativeView()); + } else { + args->ThrowError("There is nothing to drag"); + } +} + +void WebContents::CapturePage(mate::Arguments* args) { + gfx::Rect rect; + base::Callback callback; + + if (!(args->Length() == 1 && args->GetNext(&callback)) && + !(args->Length() == 2 && args->GetNext(&rect) + && args->GetNext(&callback))) { + args->ThrowError(); + return; + } + + const auto view = web_contents()->GetRenderWidgetHostView(); + const auto host = view ? view->GetRenderWidgetHost() : nullptr; + if (!view || !host) { + callback.Run(gfx::Image()); + return; + } + + // Capture full page if user doesn't specify a |rect|. + const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : + rect.size(); + + // By default, the requested bitmap size is the view size in screen + // coordinates. However, if there's more pixel detail available on the + // current system, increase the requested bitmap size to capture it all. + gfx::Size bitmap_size = view_size; + const gfx::NativeView native_view = view->GetNativeView(); + const float scale = + display::Screen::GetScreen()->GetDisplayNearestWindow(native_view) + .device_scale_factor(); + if (scale > 1.0f) + bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); + + host->CopyFromBackingStore(gfx::Rect(rect.origin(), view_size), + bitmap_size, + base::Bind(&OnCapturePageDone, callback), + kBGRA_8888_SkColorType); +} + void WebContents::OnCursorChange(const content::WebCursor& cursor) { content::WebCursor::CursorInfo info; cursor.GetCursorInfo(&info); @@ -1232,6 +1305,10 @@ void WebContents::OnCursorChange(const content::WebCursor& cursor) { } } +void WebContents::OnViewPainted() { + Emit("view-painted"); +} + void WebContents::SetSize(const SetSizeParams& params) { if (guest_delegate_) guest_delegate_->SetSize(params); @@ -1338,6 +1415,7 @@ void WebContents::BuildPrototype(v8::Isolate* isolate, .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) + .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("setSize", &WebContents::SetSize) .SetMethod("isGuest", &WebContents::IsGuest) .SetMethod("getType", &WebContents::GetType) @@ -1353,6 +1431,9 @@ void WebContents::BuildPrototype(v8::Isolate* isolate, .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) + .SetMethod("copyImageAt", &WebContents::CopyImageAt) + .SetMethod("capturePage", &WebContents::CapturePage) + .SetMethod("isFocused", &WebContents::IsFocused) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) diff --git a/atom/browser/api/atom_api_web_contents.h b/atom/browser/api/atom_api_web_contents.h index dd91360c5f..381f3770d3 100644 --- a/atom/browser/api/atom_api_web_contents.h +++ b/atom/browser/api/atom_api_web_contents.h @@ -67,6 +67,7 @@ class WebContents : public mate::TrackableObject, int GetID() const; Type GetType() const; + bool IsFocused() const; bool Equal(const WebContents* web_contents) const; void LoadURL(const GURL& url, const mate::Dictionary& options); void DownloadURL(const GURL& url); @@ -81,7 +82,7 @@ class WebContents : public mate::TrackableObject, void GoForward(); void GoToOffset(int offset); bool IsCrashed() const; - void SetUserAgent(const std::string& user_agent); + void SetUserAgent(const std::string& user_agent, mate::Arguments* args); std::string GetUserAgent(); void InsertCSS(const std::string& css); bool SavePage(const base::FilePath& full_file_path, @@ -125,6 +126,7 @@ class WebContents : public mate::TrackableObject, uint32_t FindInPage(mate::Arguments* args); void StopFindInPage(content::StopFindAction action); void ShowDefinitionForSelection(); + void CopyImageAt(int x, int y); // Focus. void Focus(); @@ -142,6 +144,13 @@ class WebContents : public mate::TrackableObject, void BeginFrameSubscription(mate::Arguments* args); void EndFrameSubscription(); + // Dragging native items. + void StartDrag(const mate::Dictionary& item, mate::Arguments* args); + + // Captures the page with |rect|, |callback| would be called when capturing is + // done. + void CapturePage(mate::Arguments* args); + // Methods for creating . void SetSize(const SetSizeParams& params); bool IsGuest() const; @@ -237,11 +246,6 @@ class WebContents : public mate::TrackableObject, int error_code, const base::string16& error_description, bool was_ignored_by_handler) override; - void DidFailProvisionalLoad(content::RenderFrameHost* render_frame_host, - const GURL& validated_url, - int error_code, - const base::string16& error_description, - bool was_ignored_by_handler) override; void DidStartLoading() override; void DidStopLoading() override; void DidGetResourceResponseStart( @@ -249,9 +253,8 @@ class WebContents : public mate::TrackableObject, void DidGetRedirectForResourceRequest( content::RenderFrameHost* render_frame_host, const content::ResourceRedirectDetails& details) override; - void DidNavigateMainFrame( - const content::LoadCommittedDetails& details, - const content::FrameNavigateParams& params) override; + void DidFinishNavigation( + content::NavigationHandle* navigation_handle) override; bool OnMessageReceived(const IPC::Message& message) override; void WebContentsDestroyed() override; void NavigationEntryCommitted( @@ -292,6 +295,9 @@ class WebContents : public mate::TrackableObject, const base::ListValue& args, IPC::Message* message); + // Called when the hosted view gets graphical updates. + void OnViewPainted(); + v8::Global session_; v8::Global devtools_web_contents_; v8::Global debugger_; diff --git a/atom/browser/api/atom_api_web_contents_mac.mm b/atom/browser/api/atom_api_web_contents_mac.mm new file mode 100644 index 0000000000..913951737f --- /dev/null +++ b/atom/browser/api/atom_api_web_contents_mac.mm @@ -0,0 +1,32 @@ +// 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_web_contents.h" + +@interface NSWindow +- (BOOL)isKeyWindow; +@end + +namespace atom { + +namespace api { + +bool WebContents::IsFocused() const { + auto view = web_contents()->GetRenderWidgetHostView(); + if (!view) return false; + + if (GetType() != BACKGROUND_PAGE) { + auto window = web_contents()->GetTopLevelNativeWindow(); + // On Mac the render widget host view does not lose focus when the window + // loses focus so check if the top level window is the key window. + if (window && ![window isKeyWindow]) + return false; + } + + return view->HasFocus(); +} + +} // namespace api + +} // namespace atom diff --git a/atom/browser/api/atom_api_window.cc b/atom/browser/api/atom_api_window.cc index cc3749bd01..8482940454 100644 --- a/atom/browser/api/atom_api_window.cc +++ b/atom/browser/api/atom_api_window.cc @@ -55,15 +55,6 @@ namespace api { namespace { -void OnCapturePageDone( - v8::Isolate* isolate, - const base::Callback& callback, - const SkBitmap& bitmap) { - v8::Locker locker(isolate); - v8::HandleScope handle_scope(isolate); - callback.Run(gfx::Image::CreateFrom1xBitmap(bitmap)); -} - // Converts binary data to Buffer. v8::Local ToBuffer(v8::Isolate* isolate, void* val, int size) { auto buffer = node::Buffer::Copy(isolate, static_cast(val), size); @@ -106,9 +97,6 @@ Window::Window(v8::Isolate* isolate, const mate::Dictionary& options) { options, parent.IsEmpty() ? nullptr : parent->window_.get())); web_contents->SetOwnerWindow(window_.get()); - window_->InitFromOptions(options); - window_->AddObserver(this); - AttachAsUserData(window_.get()); #if defined(TOOLKIT_VIEWS) // Sets the window icon. @@ -116,6 +104,10 @@ Window::Window(v8::Isolate* isolate, const mate::Dictionary& options) { if (options.Get(options::kIcon, &icon)) SetIcon(icon); #endif + + window_->InitFromOptions(options); + window_->AddObserver(this); + AttachAsUserData(window_.get()); } Window::~Window() { @@ -572,23 +564,12 @@ void Window::SetIgnoreMouseEvents(bool ignore) { return window_->SetIgnoreMouseEvents(ignore); } -void Window::SetFocusable(bool focusable) { - return window_->SetFocusable(focusable); +void Window::SetContentProtection(bool enable) { + return window_->SetContentProtection(enable); } -void Window::CapturePage(mate::Arguments* args) { - gfx::Rect rect; - base::Callback callback; - - if (!(args->Length() == 1 && args->GetNext(&callback)) && - !(args->Length() == 2 && args->GetNext(&rect) - && args->GetNext(&callback))) { - args->ThrowError(); - return; - } - - window_->CapturePage( - rect, base::Bind(&OnCapturePageDone, args->isolate(), callback)); +void Window::SetFocusable(bool focusable) { + return window_->SetFocusable(focusable); } void Window::SetProgressBar(double progress) { @@ -668,6 +649,12 @@ bool Window::IsWindowMessageHooked(UINT message) { void Window::UnhookAllWindowMessages() { messages_callback_map_.clear(); } + +bool Window::SetThumbnailClip(const gfx::Rect& region) { + auto window = static_cast(window_.get()); + return window->taskbar_host().SetThumbnailClip( + window_->GetAcceleratedWidget(), region); +} #endif #if defined(TOOLKIT_VIEWS) @@ -833,11 +820,11 @@ void Window::BuildPrototype(v8::Isolate* isolate, .SetMethod("setDocumentEdited", &Window::SetDocumentEdited) .SetMethod("isDocumentEdited", &Window::IsDocumentEdited) .SetMethod("setIgnoreMouseEvents", &Window::SetIgnoreMouseEvents) + .SetMethod("setContentProtection", &Window::SetContentProtection) .SetMethod("setFocusable", &Window::SetFocusable) .SetMethod("focusOnWebView", &Window::FocusOnWebView) .SetMethod("blurWebView", &Window::BlurWebView) .SetMethod("isWebViewFocused", &Window::IsWebViewFocused) - .SetMethod("capturePage", &Window::CapturePage) .SetMethod("setProgressBar", &Window::SetProgressBar) .SetMethod("setOverlayIcon", &Window::SetOverlayIcon) .SetMethod("setThumbarButtons", &Window::SetThumbarButtons) @@ -855,6 +842,7 @@ void Window::BuildPrototype(v8::Isolate* isolate, .SetMethod("isWindowMessageHooked", &Window::IsWindowMessageHooked) .SetMethod("unhookWindowMessage", &Window::UnhookWindowMessage) .SetMethod("unhookAllWindowMessages", &Window::UnhookAllWindowMessages) + .SetMethod("setThumbnailClip", &Window::SetThumbnailClip) #endif #if defined(TOOLKIT_VIEWS) .SetMethod("setIcon", &Window::SetIcon) diff --git a/atom/browser/api/atom_api_window.h b/atom/browser/api/atom_api_window.h index 21ecca4c72..7736f835f7 100644 --- a/atom/browser/api/atom_api_window.h +++ b/atom/browser/api/atom_api_window.h @@ -153,8 +153,8 @@ class Window : public mate::TrackableObject, void SetDocumentEdited(bool edited); bool IsDocumentEdited(); void SetIgnoreMouseEvents(bool ignore); + void SetContentProtection(bool enable); void SetFocusable(bool focusable); - void CapturePage(mate::Arguments* args); void SetProgressBar(double progress); void SetOverlayIcon(const gfx::Image& overlay, const std::string& description); @@ -179,6 +179,7 @@ class Window : public mate::TrackableObject, bool IsWindowMessageHooked(UINT message); void UnhookWindowMessage(UINT message); void UnhookAllWindowMessages(); + bool SetThumbnailClip(const gfx::Rect& region); #endif #if defined(TOOLKIT_VIEWS) diff --git a/atom/browser/api/event.cc b/atom/browser/api/event.cc index 2554e4ad0d..8c60eda247 100644 --- a/atom/browser/api/event.cc +++ b/atom/browser/api/event.cc @@ -12,8 +12,8 @@ namespace mate { Event::Event(v8::Isolate* isolate) - : sender_(NULL), - message_(NULL) { + : sender_(nullptr), + message_(nullptr) { Init(isolate); } @@ -31,8 +31,8 @@ void Event::SetSenderAndMessage(content::WebContents* sender, } void Event::WebContentsDestroyed() { - sender_ = NULL; - message_ = NULL; + sender_ = nullptr; + message_ = nullptr; } void Event::PreventDefault(v8::Isolate* isolate) { @@ -41,13 +41,13 @@ void Event::PreventDefault(v8::Isolate* isolate) { } bool Event::SendReply(const base::string16& json) { - if (message_ == NULL || sender_ == NULL) + if (message_ == nullptr || sender_ == nullptr) return false; AtomViewHostMsg_Message_Sync::WriteReplyParams(message_, json); bool success = sender_->Send(message_); - message_ = NULL; - sender_ = NULL; + message_ = nullptr; + sender_ = nullptr; return success; } diff --git a/atom/browser/api/event_emitter.cc b/atom/browser/api/event_emitter.cc index 7e392fddee..e98008b85d 100644 --- a/atom/browser/api/event_emitter.cc +++ b/atom/browser/api/event_emitter.cc @@ -8,6 +8,7 @@ #include "native_mate/arguments.h" #include "native_mate/dictionary.h" #include "native_mate/object_template_builder.h" +#include "ui/events/event_constants.h" namespace mate { @@ -65,6 +66,15 @@ v8::Local CreateCustomEvent( return event; } +v8::Local CreateEventFromFlags(v8::Isolate* isolate, int flags) { + mate::Dictionary obj = mate::Dictionary::CreateEmpty(isolate); + obj.Set("shiftKey", static_cast(flags & ui::EF_SHIFT_DOWN)); + obj.Set("ctrlKey", static_cast(flags & ui::EF_CONTROL_DOWN)); + obj.Set("altKey", static_cast(flags & ui::EF_ALT_DOWN)); + obj.Set("metaKey", static_cast(flags & ui::EF_COMMAND_DOWN)); + return obj.GetHandle(); +} + } // namespace internal } // namespace mate diff --git a/atom/browser/api/event_emitter.h b/atom/browser/api/event_emitter.h index 99f6ed46e4..ead3beddaa 100644 --- a/atom/browser/api/event_emitter.h +++ b/atom/browser/api/event_emitter.h @@ -30,6 +30,7 @@ v8::Local CreateCustomEvent( v8::Isolate* isolate, v8::Local object, v8::Local event); +v8::Local CreateEventFromFlags(v8::Isolate* isolate, int flags); } // namespace internal @@ -54,6 +55,16 @@ class EventEmitter : public Wrappable { internal::CreateCustomEvent(isolate(), GetWrapper(), event), args...); } + // this.emit(name, new Event(flags), args...); + template + bool EmitWithFlags(const base::StringPiece& name, + int flags, + const Args&... args) { + return EmitCustomEvent( + name, + internal::CreateEventFromFlags(isolate(), flags), args...); + } + // this.emit(name, new Event(), args...); template bool Emit(const base::StringPiece& name, const Args&... args) { diff --git a/atom/browser/api/frame_subscriber.cc b/atom/browser/api/frame_subscriber.cc index 91b6765db1..d6d2cf759e 100644 --- a/atom/browser/api/frame_subscriber.cc +++ b/atom/browser/api/frame_subscriber.cc @@ -5,8 +5,8 @@ #include "atom/browser/api/frame_subscriber.h" #include "base/bind.h" -#include "atom/common/node_includes.h" #include "atom/common/native_mate_converters/gfx_converter.h" +#include "atom/common/node_includes.h" #include "content/public/browser/render_widget_host.h" namespace atom { @@ -17,8 +17,11 @@ FrameSubscriber::FrameSubscriber(v8::Isolate* isolate, content::RenderWidgetHostView* view, const FrameCaptureCallback& callback, bool only_dirty) - : isolate_(isolate), view_(view), callback_(callback), - only_dirty_(only_dirty), weak_factory_(this) { + : isolate_(isolate), + view_(view), + callback_(callback), + only_dirty_(only_dirty), + weak_factory_(this) { } bool FrameSubscriber::ShouldCaptureFrame( @@ -48,8 +51,9 @@ bool FrameSubscriber::ShouldCaptureFrame( } void FrameSubscriber::OnFrameDelivered(const FrameCaptureCallback& callback, - const gfx::Rect& damage_rect, const SkBitmap& bitmap, - content::ReadbackResponse response) { + const gfx::Rect& damage_rect, + const SkBitmap& bitmap, + content::ReadbackResponse response) { if (response != content::ReadbackResponse::READBACK_SUCCESS) return; @@ -67,7 +71,7 @@ void FrameSubscriber::OnFrameDelivered(const FrameCaptureCallback& callback, rgb_arr_size); v8::Local damage = - mate::Converter::ToV8(isolate_, damage_rect); + mate::Converter::ToV8(isolate_, damage_rect); callback_.Run(buffer.ToLocalChecked(), damage); } diff --git a/atom/browser/api/frame_subscriber.h b/atom/browser/api/frame_subscriber.h index b6cff3da81..0da554ac47 100644 --- a/atom/browser/api/frame_subscriber.h +++ b/atom/browser/api/frame_subscriber.h @@ -21,7 +21,7 @@ namespace api { class FrameSubscriber : public content::RenderWidgetHostViewFrameSubscriber { public: using FrameCaptureCallback = - base::Callback, v8::Local)>; + base::Callback, v8::Local)>; FrameSubscriber(v8::Isolate* isolate, content::RenderWidgetHostView* view, @@ -35,8 +35,9 @@ class FrameSubscriber : public content::RenderWidgetHostViewFrameSubscriber { private: void OnFrameDelivered(const FrameCaptureCallback& callback, - const gfx::Rect& damage_rect, const SkBitmap& bitmap, - content::ReadbackResponse response); + const gfx::Rect& damage_rect, + const SkBitmap& bitmap, + content::ReadbackResponse response); v8::Isolate* isolate_; content::RenderWidgetHostView* view_; diff --git a/atom/browser/api/trackable_object.h b/atom/browser/api/trackable_object.h index bbed547540..2cb9428a00 100644 --- a/atom/browser/api/trackable_object.h +++ b/atom/browser/api/trackable_object.h @@ -10,7 +10,6 @@ #include "atom/browser/api/event_emitter.h" #include "atom/common/key_weak_map.h" #include "base/bind.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "native_mate/object_template_builder.h" diff --git a/atom/browser/atom_access_token_store.cc b/atom/browser/atom_access_token_store.cc index ed87ea9799..5a4482b00b 100644 --- a/atom/browser/atom_access_token_store.cc +++ b/atom/browser/atom_access_token_store.cc @@ -7,8 +7,8 @@ #include #include "atom/browser/atom_browser_context.h" -#include "atom/browser/atom_browser_main_parts.h" #include "atom/common/google_api_key.h" +#include "content/public/browser/browser_thread.h" #include "content/public/browser/geolocation_provider.h" namespace atom { @@ -33,21 +33,35 @@ AtomAccessTokenStore::~AtomAccessTokenStore() { void AtomAccessTokenStore::LoadAccessTokens( const LoadAccessTokensCallback& callback) { - AccessTokenMap access_token_map; - - // Equivelent to access_token_map[kGeolocationProviderURL]. - // Somehow base::string16 is causing compilation errors when used in a pair - // of std::map on Linux, this can work around it. - std::pair token_pair; - token_pair.first = GURL(kGeolocationProviderURL); - access_token_map.insert(token_pair); - - auto browser_context = AtomBrowserMainParts::Get()->browser_context(); - callback.Run(access_token_map, browser_context->url_request_context_getter()); + content::BrowserThread::PostTaskAndReply( + content::BrowserThread::UI, + FROM_HERE, + base::Bind(&AtomAccessTokenStore::GetRequestContextOnUIThread, this), + base::Bind(&AtomAccessTokenStore::RespondOnOriginatingThread, + this, callback)); } void AtomAccessTokenStore::SaveAccessToken(const GURL& server_url, const base::string16& access_token) { } +void AtomAccessTokenStore::GetRequestContextOnUIThread() { + auto browser_context = AtomBrowserContext::From("", false); + request_context_getter_ = browser_context->GetRequestContext(); +} + +void AtomAccessTokenStore::RespondOnOriginatingThread( + const LoadAccessTokensCallback& callback) { + // Equivelent to access_token_map[kGeolocationProviderURL]. + // Somehow base::string16 is causing compilation errors when used in a pair + // of std::map on Linux, this can work around it. + AccessTokenMap access_token_map; + std::pair token_pair; + token_pair.first = GURL(kGeolocationProviderURL); + access_token_map.insert(token_pair); + + callback.Run(access_token_map, request_context_getter_.get()); + request_context_getter_ = nullptr; +} + } // namespace atom diff --git a/atom/browser/atom_access_token_store.h b/atom/browser/atom_access_token_store.h index 54bc2cee3c..27c1911a65 100644 --- a/atom/browser/atom_access_token_store.h +++ b/atom/browser/atom_access_token_store.h @@ -9,12 +9,10 @@ namespace atom { -class AtomBrowserContext; - class AtomAccessTokenStore : public content::AccessTokenStore { public: AtomAccessTokenStore(); - virtual ~AtomAccessTokenStore(); + ~AtomAccessTokenStore(); // content::AccessTokenStore: void LoadAccessTokens( @@ -23,6 +21,11 @@ class AtomAccessTokenStore : public content::AccessTokenStore { const base::string16& access_token) override; private: + void GetRequestContextOnUIThread(); + void RespondOnOriginatingThread(const LoadAccessTokensCallback& callback); + + scoped_refptr request_context_getter_; + DISALLOW_COPY_AND_ASSIGN(AtomAccessTokenStore); }; diff --git a/atom/browser/atom_browser_client.cc b/atom/browser/atom_browser_client.cc index c1b50459c6..323acdd9b3 100644 --- a/atom/browser/atom_browser_client.cc +++ b/atom/browser/atom_browser_client.cc @@ -202,7 +202,7 @@ void AtomBrowserClient::AppendExtraCommandLineSwitches( void AtomBrowserClient::DidCreatePpapiPlugin( content::BrowserPpapiHost* host) { host->GetPpapiHost()->AddHostFactoryFilter( - make_scoped_ptr(new chrome::ChromeBrowserPepperHostFactory(host))); + base::WrapUnique(new chrome::ChromeBrowserPepperHostFactory(host))); } content::QuotaPermissionContext* @@ -287,20 +287,21 @@ brightray::BrowserMainParts* AtomBrowserClient::OverrideCreateBrowserMainParts( void AtomBrowserClient::WebNotificationAllowed( int render_process_id, - const base::Callback& callback) { + const base::Callback& callback) { content::WebContents* web_contents = WebContentsPreferences::GetWebContentsFromProcessID(render_process_id); if (!web_contents) { - callback.Run(false); + callback.Run(false, false); return; } auto permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); if (!permission_helper) { - callback.Run(false); + callback.Run(false, false); return; } - permission_helper->RequestWebNotificationPermission(callback); + permission_helper->RequestWebNotificationPermission( + base::Bind(callback, web_contents->IsAudioMuted())); } void AtomBrowserClient::RenderProcessHostDestroyed( diff --git a/atom/browser/atom_browser_client.h b/atom/browser/atom_browser_client.h index cf1a4cc438..a61706534a 100644 --- a/atom/browser/atom_browser_client.h +++ b/atom/browser/atom_browser_client.h @@ -100,7 +100,7 @@ class AtomBrowserClient : public brightray::BrowserClient, const content::MainFunctionParams&) override; void WebNotificationAllowed( int render_process_id, - const base::Callback& callback) override; + const base::Callback& callback) override; // content::RenderProcessHostObserver: void RenderProcessHostDestroyed(content::RenderProcessHost* host) override; diff --git a/atom/browser/atom_browser_context.cc b/atom/browser/atom_browser_context.cc index 8268a77781..7ac5dde4ef 100644 --- a/atom/browser/atom_browser_context.cc +++ b/atom/browser/atom_browser_context.cc @@ -63,21 +63,12 @@ std::string RemoveWhitespace(const std::string& str) { } // namespace -AtomBrowserContext::AtomBrowserContext(const std::string& partition, - bool in_memory) +AtomBrowserContext::AtomBrowserContext( + const std::string& partition, bool in_memory, + const base::DictionaryValue& options) : brightray::BrowserContext(partition, in_memory), - cert_verifier_(new AtomCertVerifier), network_delegate_(new AtomNetworkDelegate) { -} - -AtomBrowserContext::~AtomBrowserContext() { -} - -net::NetworkDelegate* AtomBrowserContext::CreateNetworkDelegate() { - return network_delegate_; -} - -std::string AtomBrowserContext::GetUserAgent() { + // Construct user agent string. Browser* browser = Browser::Get(); std::string name = RemoveWhitespace(browser->GetName()); std::string user_agent; @@ -91,7 +82,29 @@ std::string AtomBrowserContext::GetUserAgent() { browser->GetVersion().c_str(), CHROME_VERSION_STRING); } - return content::BuildUserAgentFromProduct(user_agent); + user_agent_ = content::BuildUserAgentFromProduct(user_agent); + + // Read options. + use_cache_ = true; + options.GetBoolean("cache", &use_cache_); + + // Initialize Pref Registry in brightray. + InitPrefs(); +} + +AtomBrowserContext::~AtomBrowserContext() { +} + +void AtomBrowserContext::SetUserAgent(const std::string& user_agent) { + user_agent_ = user_agent; +} + +net::NetworkDelegate* AtomBrowserContext::CreateNetworkDelegate() { + return network_delegate_; +} + +std::string AtomBrowserContext::GetUserAgent() { + return user_agent_; } std::unique_ptr @@ -107,29 +120,29 @@ AtomBrowserContext::CreateURLRequestJobFactory( protocol_handlers->clear(); job_factory->SetProtocolHandler( - url::kDataScheme, make_scoped_ptr(new net::DataProtocolHandler)); + url::kDataScheme, base::WrapUnique(new net::DataProtocolHandler)); job_factory->SetProtocolHandler( - url::kFileScheme, make_scoped_ptr(new asar::AsarProtocolHandler( + url::kFileScheme, base::WrapUnique(new asar::AsarProtocolHandler( BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)))); job_factory->SetProtocolHandler( url::kHttpScheme, - make_scoped_ptr(new HttpProtocolHandler(url::kHttpScheme))); + base::WrapUnique(new HttpProtocolHandler(url::kHttpScheme))); job_factory->SetProtocolHandler( url::kHttpsScheme, - make_scoped_ptr(new HttpProtocolHandler(url::kHttpsScheme))); + base::WrapUnique(new HttpProtocolHandler(url::kHttpsScheme))); job_factory->SetProtocolHandler( url::kWsScheme, - make_scoped_ptr(new HttpProtocolHandler(url::kWsScheme))); + base::WrapUnique(new HttpProtocolHandler(url::kWsScheme))); job_factory->SetProtocolHandler( url::kWssScheme, - make_scoped_ptr(new HttpProtocolHandler(url::kWssScheme))); + base::WrapUnique(new HttpProtocolHandler(url::kWssScheme))); auto host_resolver = url_request_context_getter()->GetURLRequestContext()->host_resolver(); job_factory->SetProtocolHandler( url::kFtpScheme, - make_scoped_ptr(new net::FtpProtocolHandler( + base::WrapUnique(new net::FtpProtocolHandler( new net::FtpNetworkLayer(host_resolver)))); return std::move(job_factory); @@ -139,7 +152,7 @@ net::HttpCache::BackendFactory* AtomBrowserContext::CreateHttpCacheBackendFactory( const base::FilePath& base_path) { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(switches::kDisableHttpCache)) + if (!use_cache_ || command_line->HasSwitch(switches::kDisableHttpCache)) return new NoCacheBackend; else return brightray::BrowserContext::CreateHttpCacheBackendFactory(base_path); @@ -168,7 +181,7 @@ content::PermissionManager* AtomBrowserContext::GetPermissionManager() { } std::unique_ptr AtomBrowserContext::CreateCertVerifier() { - return make_scoped_ptr(cert_verifier_); + return base::WrapUnique(new AtomCertVerifier); } net::SSLConfigService* AtomBrowserContext::CreateSSLConfigService() { @@ -185,14 +198,15 @@ void AtomBrowserContext::RegisterPrefs(PrefRegistrySimple* pref_registry) { pref_registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths); } -} // namespace atom - -namespace brightray { - // static -scoped_refptr BrowserContext::Create( - const std::string& partition, bool in_memory) { - return make_scoped_refptr(new atom::AtomBrowserContext(partition, in_memory)); +scoped_refptr AtomBrowserContext::From( + const std::string& partition, bool in_memory, + const base::DictionaryValue& options) { + auto browser_context = brightray::BrowserContext::Get(partition, in_memory); + if (browser_context) + return static_cast(browser_context.get()); + + return new AtomBrowserContext(partition, in_memory, options); } -} // namespace brightray +} // namespace atom diff --git a/atom/browser/atom_browser_context.h b/atom/browser/atom_browser_context.h index c9b1de947f..ed3817da60 100644 --- a/atom/browser/atom_browser_context.h +++ b/atom/browser/atom_browser_context.h @@ -12,15 +12,20 @@ namespace atom { class AtomDownloadManagerDelegate; -class AtomCertVerifier; class AtomNetworkDelegate; class AtomPermissionManager; class WebViewManager; class AtomBrowserContext : public brightray::BrowserContext { public: - AtomBrowserContext(const std::string& partition, bool in_memory); - ~AtomBrowserContext() override; + // Get or create the BrowserContext according to its |partition| and + // |in_memory|. The |options| will be passed to constructor when there is no + // existing BrowserContext. + static scoped_refptr From( + const std::string& partition, bool in_memory, + const base::DictionaryValue& options = base::DictionaryValue()); + + void SetUserAgent(const std::string& user_agent); // brightray::URLRequestContextGetter::Delegate: net::NetworkDelegate* CreateNetworkDelegate() override; @@ -40,16 +45,21 @@ class AtomBrowserContext : public brightray::BrowserContext { // brightray::BrowserContext: void RegisterPrefs(PrefRegistrySimple* pref_registry) override; - AtomCertVerifier* cert_verifier() const { return cert_verifier_; } AtomNetworkDelegate* network_delegate() const { return network_delegate_; } + protected: + AtomBrowserContext(const std::string& partition, bool in_memory, + const base::DictionaryValue& options); + ~AtomBrowserContext() override; + private: std::unique_ptr download_manager_delegate_; std::unique_ptr guest_manager_; std::unique_ptr permission_manager_; + std::string user_agent_; + bool use_cache_; // Managed by brightray::BrowserContext. - AtomCertVerifier* cert_verifier_; AtomNetworkDelegate* network_delegate_; DISALLOW_COPY_AND_ASSIGN(AtomBrowserContext); diff --git a/atom/browser/atom_browser_main_parts.cc b/atom/browser/atom_browser_main_parts.cc index 75f71d4231..a8d18e8c5a 100644 --- a/atom/browser/atom_browser_main_parts.cc +++ b/atom/browser/atom_browser_main_parts.cc @@ -15,7 +15,7 @@ #include "atom/common/node_bindings.h" #include "atom/common/node_includes.h" #include "base/command_line.h" -#include "base/thread_task_runner_handle.h" +#include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/browser_process.h" #include "v8/include/v8-debug.h" @@ -32,7 +32,7 @@ void Erase(T* container, typename T::iterator iter) { } // static -AtomBrowserMainParts* AtomBrowserMainParts::self_ = NULL; +AtomBrowserMainParts* AtomBrowserMainParts::self_ = nullptr; AtomBrowserMainParts::AtomBrowserMainParts() : fake_browser_process_(new BrowserProcess), @@ -124,6 +124,8 @@ void AtomBrowserMainParts::PostEarlyInitialization() { } void AtomBrowserMainParts::PreMainMessageLoopRun() { + js_env_->OnMessageLoopCreated(); + // Run user's main script before most things get initialized, so we can have // a chance to setup everything. node_bindings_->PrepareMessageLoop(); @@ -169,6 +171,8 @@ void AtomBrowserMainParts::PostMainMessageLoopStart() { void AtomBrowserMainParts::PostMainMessageLoopRun() { brightray::BrowserMainParts::PostMainMessageLoopRun(); + js_env_->OnMessageLoopDestroying(); + #if defined(OS_MACOSX) FreeAppDelegate(); #endif diff --git a/atom/browser/atom_browser_main_parts_posix.cc b/atom/browser/atom_browser_main_parts_posix.cc index 2a0dddc474..8c96f91bfe 100644 --- a/atom/browser/atom_browser_main_parts_posix.cc +++ b/atom/browser/atom_browser_main_parts_posix.cc @@ -43,7 +43,7 @@ void GracefulShutdownHandler(int signal) { struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIG_DFL; - RAW_CHECK(sigaction(signal, &action, NULL) == 0); + RAW_CHECK(sigaction(signal, &action, nullptr) == 0); RAW_CHECK(g_pipe_pid == getpid()); RAW_CHECK(g_shutdown_pipe_write_fd != -1); @@ -171,7 +171,7 @@ void AtomBrowserMainParts::HandleSIGCHLD() { struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIGCHLDHandler; - CHECK_EQ(sigaction(SIGCHLD, &action, NULL), 0); + CHECK_EQ(sigaction(SIGCHLD, &action, nullptr), 0); } void AtomBrowserMainParts::HandleShutdownSignals() { @@ -211,15 +211,15 @@ void AtomBrowserMainParts::HandleShutdownSignals() { struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIGTERMHandler; - CHECK_EQ(sigaction(SIGTERM, &action, NULL), 0); + CHECK_EQ(sigaction(SIGTERM, &action, nullptr), 0); // Also handle SIGINT - when the user terminates the browser via Ctrl+C. If // the browser process is being debugged, GDB will catch the SIGINT first. action.sa_handler = SIGINTHandler; - CHECK_EQ(sigaction(SIGINT, &action, NULL), 0); + CHECK_EQ(sigaction(SIGINT, &action, nullptr), 0); // And SIGHUP, for when the terminal disappears. On shutdown, many Linux // distros send SIGHUP, SIGTERM, and then SIGKILL. action.sa_handler = SIGHUPHandler; - CHECK_EQ(sigaction(SIGHUP, &action, NULL), 0); + CHECK_EQ(sigaction(SIGHUP, &action, nullptr), 0); } } // namespace atom diff --git a/atom/browser/atom_download_manager_delegate.cc b/atom/browser/atom_download_manager_delegate.cc index 6d7e3c7172..63ca5f661f 100644 --- a/atom/browser/atom_download_manager_delegate.cc +++ b/atom/browser/atom_download_manager_delegate.cc @@ -85,6 +85,14 @@ void AtomDownloadManagerDelegate::OnDownloadPathGenerated( download_manager_->GetBrowserContext()); browser_context->prefs()->SetFilePath(prefs::kDownloadDefaultDirectory, path.DirName()); + + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + v8::Locker locker(isolate); + v8::HandleScope handle_scope(isolate); + api::DownloadItem* download_item = api::DownloadItem::FromWrappedClass( + isolate, item); + if (download_item) + download_item->SetSavePath(path); } // Running the DownloadTargetCallback with an empty FilePath signals that the diff --git a/atom/browser/atom_resource_dispatcher_host_delegate.cc b/atom/browser/atom_resource_dispatcher_host_delegate.cc index 1115aa049d..c64a21d26d 100644 --- a/atom/browser/atom_resource_dispatcher_host_delegate.cc +++ b/atom/browser/atom_resource_dispatcher_host_delegate.cc @@ -7,6 +7,7 @@ #include "atom/browser/login_handler.h" #include "atom/browser/web_contents_permission_helper.h" #include "atom/common/platform_util.h" +#include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "net/base/escape.h" #include "url/gurl.h" @@ -20,7 +21,13 @@ namespace { void OnOpenExternal(const GURL& escaped_url, bool allowed) { if (allowed) - platform_util::OpenExternal(escaped_url, true); + platform_util::OpenExternal( +#if defined(OS_WIN) + base::UTF8ToUTF16(escaped_url.spec()), +#else + escaped_url, +#endif + true); } void HandleExternalProtocolInUI( diff --git a/atom/browser/atom_security_state_model_client.cc b/atom/browser/atom_security_state_model_client.cc index 911849c5c2..77a91bdec9 100644 --- a/atom/browser/atom_security_state_model_client.cc +++ b/atom/browser/atom_security_state_model_client.cc @@ -91,8 +91,14 @@ void AtomSecurityStateModelClient::GetVisibleSecurityState( state->connection_status = ssl.connection_status; state->security_bits = ssl.security_bits; state->sct_verify_statuses.clear(); - for (const auto& sct : ssl.signed_certificate_timestamp_ids) - state->sct_verify_statuses.push_back(sct.status); + state->sct_verify_statuses.insert(state->sct_verify_statuses.end(), + ssl.num_unknown_scts, + net::ct::SCT_STATUS_LOG_UNKNOWN); + state->sct_verify_statuses.insert(state->sct_verify_statuses.end(), + ssl.num_invalid_scts, + net::ct::SCT_STATUS_INVALID); + state->sct_verify_statuses.insert(state->sct_verify_statuses.end(), + ssl.num_valid_scts, net::ct::SCT_STATUS_OK); state->displayed_mixed_content = (ssl.content_status & content::SSLStatus::DISPLAYED_INSECURE_CONTENT) ? true diff --git a/atom/browser/atom_speech_recognition_manager_delegate.cc b/atom/browser/atom_speech_recognition_manager_delegate.cc index 06727332f0..d2e7135c9a 100644 --- a/atom/browser/atom_speech_recognition_manager_delegate.cc +++ b/atom/browser/atom_speech_recognition_manager_delegate.cc @@ -50,11 +50,6 @@ void AtomSpeechRecognitionManagerDelegate::OnAudioLevelsChange( int session_id, float volume, float noise_volume) { } -void AtomSpeechRecognitionManagerDelegate::GetDiagnosticInformation( - bool* can_report_metrics, std::string* hardware_info) { - *can_report_metrics = false; -} - void AtomSpeechRecognitionManagerDelegate::CheckRecognitionIsAllowed( int session_id, base::Callback callback) { diff --git a/atom/browser/atom_speech_recognition_manager_delegate.h b/atom/browser/atom_speech_recognition_manager_delegate.h index 4c78e0eead..a6b2f059f7 100644 --- a/atom/browser/atom_speech_recognition_manager_delegate.h +++ b/atom/browser/atom_speech_recognition_manager_delegate.h @@ -36,8 +36,6 @@ class AtomSpeechRecognitionManagerDelegate float noise_volume) override; // content::SpeechRecognitionManagerDelegate: - void GetDiagnosticInformation(bool* can_report_metrics, - std::string* hardware_info) override; void CheckRecognitionIsAllowed( int session_id, base::Callback callback) override; diff --git a/atom/browser/auto_updater.cc b/atom/browser/auto_updater.cc index 5a14eda2e1..8ada3ff6ab 100644 --- a/atom/browser/auto_updater.cc +++ b/atom/browser/auto_updater.cc @@ -17,6 +17,10 @@ void AutoUpdater::SetDelegate(Delegate* delegate) { } #if !defined(OS_MACOSX) || defined(MAS_BUILD) +std::string AutoUpdater::GetFeedURL() { + return ""; +} + void AutoUpdater::SetFeedURL(const std::string& url, const HeaderMap& requestHeaders) { } diff --git a/atom/browser/auto_updater.h b/atom/browser/auto_updater.h index ad0b2cc18b..aa4ca19cf2 100644 --- a/atom/browser/auto_updater.h +++ b/atom/browser/auto_updater.h @@ -49,6 +49,7 @@ class AutoUpdater { static Delegate* GetDelegate(); static void SetDelegate(Delegate* delegate); + static std::string GetFeedURL(); static void SetFeedURL(const std::string& url, const HeaderMap& requestHeaders); static void CheckForUpdates(); diff --git a/atom/browser/auto_updater_mac.mm b/atom/browser/auto_updater_mac.mm index 005627e6c0..1987f33621 100644 --- a/atom/browser/auto_updater_mac.mm +++ b/atom/browser/auto_updater_mac.mm @@ -25,9 +25,14 @@ SQRLUpdater* g_updater = nil; namespace { bool g_update_available = false; +std::string update_url_ = ""; } +std::string AutoUpdater::GetFeedURL() { + return update_url_; +} + // static void AutoUpdater::SetFeedURL(const std::string& feed, const HeaderMap& requestHeaders) { @@ -35,6 +40,8 @@ void AutoUpdater::SetFeedURL(const std::string& feed, if (!delegate) return; + update_url_ = feed; + NSURL* url = [NSURL URLWithString:base::SysUTF8ToNSString(feed)]; NSMutableURLRequest* urlRequest = [NSMutableURLRequest requestWithURL:url]; diff --git a/atom/browser/browser.cc b/atom/browser/browser.cc index 8c00c12873..dd958d0dc7 100644 --- a/atom/browser/browser.cc +++ b/atom/browser/browser.cc @@ -118,6 +118,10 @@ void Browser::SetName(const std::string& name) { name_override_ = name; } +int Browser::GetBadgeCount() { + return badge_count_; +} + bool Browser::OpenFile(const std::string& file_path) { bool prevent_default = false; FOR_EACH_OBSERVER(BrowserObserver, @@ -151,6 +155,12 @@ void Browser::DidFinishLaunching() { FOR_EACH_OBSERVER(BrowserObserver, observers_, OnFinishLaunching()); } +void Browser::OnAccessibilitySupportChanged() { + FOR_EACH_OBSERVER(BrowserObserver, + observers_, + OnAccessibilitySupportChanged()); +} + void Browser::RequestLogin( LoginHandler* login_handler, std::unique_ptr request_details) { diff --git a/atom/browser/browser.h b/atom/browser/browser.h index 2c16780830..771a29a87a 100644 --- a/atom/browser/browser.h +++ b/atom/browser/browser.h @@ -25,16 +25,13 @@ class DictionaryValue; class FilePath; } -namespace ui { -class MenuModel; -} - namespace gfx { class Image; } namespace atom { +class AtomMenuModel; class LoginHandler; // This class is used for control application-wide operations. @@ -87,6 +84,21 @@ class Browser : public WindowListObserver { // Query the current state of default handler for a protocol. bool IsDefaultProtocolClient(const std::string& protocol); + // Set/Get the badge count. + bool SetBadgeCount(int count); + int GetBadgeCount(); + + // Set/Get the login item settings of the app + struct LoginItemSettings { + bool open_at_login = false; + bool open_as_hidden = false; + bool restore_state = false; + bool opened_at_login = false; + bool opened_as_hidden = false; + }; + void SetLoginItemSettings(LoginItemSettings settings); + LoginItemSettings GetLoginItemSettings(); + #if defined(OS_MACOSX) // Hide the application. void Hide(); @@ -126,7 +138,7 @@ class Browser : public WindowListObserver { void DockShow(); // Set docks' menu. - void DockSetMenu(ui::MenuModel* model); + void DockSetMenu(AtomMenuModel* model); // Set docks' icon. void DockSetIcon(const gfx::Image& image); @@ -149,7 +161,12 @@ class Browser : public WindowListObserver { // one from app's name. // The returned string managed by Browser, and should not be modified. PCWSTR GetAppUserModelID(); -#endif +#endif // defined(OS_WIN) + +#if defined(OS_LINUX) + // Whether Unity launcher is running. + bool IsUnityRunning(); +#endif // defined(OS_LINUX) // Tell the application to open a file. bool OpenFile(const std::string& file_path); @@ -165,6 +182,8 @@ class Browser : public WindowListObserver { void WillFinishLaunching(); void DidFinishLaunching(); + void OnAccessibilitySupportChanged(); + // Request basic auth login. void RequestLogin(LoginHandler* login_handler, std::unique_ptr request_details); @@ -216,6 +235,8 @@ class Browser : public WindowListObserver { std::string version_override_; std::string name_override_; + int badge_count_ = 0; + #if defined(OS_WIN) base::string16 app_user_model_id_; #endif diff --git a/atom/browser/browser_linux.cc b/atom/browser/browser_linux.cc index d994bb4109..6aff602726 100644 --- a/atom/browser/browser_linux.cc +++ b/atom/browser/browser_linux.cc @@ -10,6 +10,7 @@ #include "atom/browser/window_list.h" #include "atom/common/atom_version.h" #include "brightray/common/application_info.h" +#include "chrome/browser/ui/libgtk2ui/unity_service.h" namespace atom { @@ -46,6 +47,23 @@ bool Browser::IsDefaultProtocolClient(const std::string& protocol) { return false; } +bool Browser::SetBadgeCount(int count) { + if (IsUnityRunning()) { + unity::SetDownloadCount(count); + badge_count_ = count; + return true; + } else { + return false; + } +} + +void Browser::SetLoginItemSettings(LoginItemSettings settings) { +} + +Browser::LoginItemSettings Browser::GetLoginItemSettings() { + return LoginItemSettings(); +} + std::string Browser::GetExecutableFileVersion() const { return brightray::GetApplicationVersion(); } @@ -54,4 +72,8 @@ std::string Browser::GetExecutableFileProductName() const { return brightray::GetApplicationName(); } +bool Browser::IsUnityRunning() { + return unity::IsRunning(); +} + } // namespace atom diff --git a/atom/browser/browser_mac.mm b/atom/browser/browser_mac.mm index a50de2a07f..d4b615e73e 100644 --- a/atom/browser/browser_mac.mm +++ b/atom/browser/browser_mac.mm @@ -11,6 +11,8 @@ #include "atom/browser/window_list.h" #include "base/mac/bundle_locations.h" #include "base/mac/foundation_util.h" +#include "base/mac/mac_util.h" +#include "base/strings/string_number_conversions.h" #include "base/strings/sys_string_conversions.h" #include "brightray/common/application_info.h" #include "net/base/mac/url_conversions.h" @@ -114,6 +116,12 @@ bool Browser::IsDefaultProtocolClient(const std::string& protocol) { void Browser::SetAppUserModelID(const base::string16& name) { } +bool Browser::SetBadgeCount(int count) { + DockSetBadgeText(count != 0 ? base::IntToString(count) : ""); + badge_count_ = count; + return true; +} + void Browser::SetUserActivity(const std::string& type, const base::DictionaryValue& user_info, mate::Arguments* args) { @@ -141,6 +149,23 @@ bool Browser::ContinueUserActivity(const std::string& type, return prevent_default; } +Browser::LoginItemSettings Browser::GetLoginItemSettings() { + LoginItemSettings settings; + settings.open_at_login = base::mac::CheckLoginItemStatus( + &settings.open_as_hidden); + settings.restore_state = base::mac::WasLaunchedAsLoginItemRestoreState(); + settings.opened_at_login = base::mac::WasLaunchedAsLoginOrResumeItem(); + settings.opened_as_hidden = base::mac::WasLaunchedAsHiddenLoginItem(); + return settings; +} + +void Browser::SetLoginItemSettings(LoginItemSettings settings) { + if (settings.open_at_login) + base::mac::AddToLoginItems(settings.open_as_hidden); + else + base::mac::RemoveFromLoginItems(); +} + std::string Browser::GetExecutableFileVersion() const { return brightray::GetApplicationVersion(); } @@ -209,7 +234,7 @@ void Browser::DockShow() { } } -void Browser::DockSetMenu(ui::MenuModel* model) { +void Browser::DockSetMenu(AtomMenuModel* model) { AtomApplicationDelegate* delegate = (AtomApplicationDelegate*)[NSApp delegate]; [delegate setApplicationDockMenu:model]; } diff --git a/atom/browser/browser_observer.h b/atom/browser/browser_observer.h index 6e85b599d0..54617e5e09 100644 --- a/atom/browser/browser_observer.h +++ b/atom/browser/browser_observer.h @@ -52,6 +52,9 @@ class BrowserObserver { virtual void OnLogin(LoginHandler* login_handler, const base::DictionaryValue& request_details) {} + // The browser's accessibility suppport has changed. + virtual void OnAccessibilitySupportChanged() {} + #if defined(OS_MACOSX) // The browser wants to resume a user activity via handoff. (macOS only) virtual void OnContinueUserActivity( diff --git a/atom/browser/browser_win.cc b/atom/browser/browser_win.cc index 345e2bcf67..059b289094 100644 --- a/atom/browser/browser_win.cc +++ b/atom/browser/browser_win.cc @@ -13,7 +13,6 @@ #include "base/base_paths.h" #include "base/file_version_info.h" #include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" @@ -269,6 +268,43 @@ bool Browser::IsDefaultProtocolClient(const std::string& protocol) { } } +bool Browser::SetBadgeCount(int count) { + return false; +} + +void Browser::SetLoginItemSettings(LoginItemSettings settings) { + std::wstring keyPath = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; + base::win::RegKey key(HKEY_CURRENT_USER, keyPath.c_str(), KEY_ALL_ACCESS); + + if (settings.open_at_login) { + base::FilePath path; + if (PathService::Get(base::FILE_EXE, &path)) { + std::wstring exePath(path.value()); + key.WriteValue(GetAppUserModelID(), exePath.c_str()); + } + } else { + key.DeleteValue(GetAppUserModelID()); + } +} + +Browser::LoginItemSettings Browser::GetLoginItemSettings() { + LoginItemSettings settings; + std::wstring keyPath = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; + base::win::RegKey key(HKEY_CURRENT_USER, keyPath.c_str(), KEY_ALL_ACCESS); + std::wstring keyVal; + + if (!FAILED(key.ReadValue(GetAppUserModelID(), &keyVal))) { + base::FilePath path; + if (PathService::Get(base::FILE_EXE, &path)) { + std::wstring exePath(path.value()); + settings.open_at_login = keyVal == exePath; + } + } + + return settings; +} + + PCWSTR Browser::GetAppUserModelID() { if (app_user_model_id_.empty()) { SetAppUserModelID(base::ReplaceStringPlaceholders( diff --git a/atom/browser/common_web_contents_delegate.cc b/atom/browser/common_web_contents_delegate.cc index c275d4aee7..f2f0ee8aec 100644 --- a/atom/browser/common_web_contents_delegate.cc +++ b/atom/browser/common_web_contents_delegate.cc @@ -94,7 +94,7 @@ FileSystem CreateFileSystemStruct( } base::DictionaryValue* CreateFileSystemValue(const FileSystem& file_system) { - base::DictionaryValue* file_system_value = new base::DictionaryValue(); + auto* file_system_value = new base::DictionaryValue(); file_system_value->SetString("fileSystemName", file_system.file_system_name); file_system_value->SetString("rootURL", file_system.root_url); file_system_value->SetString("fileSystemPath", file_system.file_system_path); @@ -377,7 +377,7 @@ content::SecurityStyle CommonWebContentsDelegate::GetSecurityStyle( void CommonWebContentsDelegate::DevToolsSaveToFile( const std::string& url, const std::string& content, bool save_as) { base::FilePath path; - PathsMap::iterator it = saved_files_.find(url); + auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { @@ -402,7 +402,7 @@ void CommonWebContentsDelegate::DevToolsSaveToFile( void CommonWebContentsDelegate::DevToolsAppendToFile( const std::string& url, const std::string& content) { - PathsMap::iterator it = saved_files_.find(url); + auto it = saved_files_.find(url); if (it == saved_files_.end()) return; @@ -435,8 +435,8 @@ void CommonWebContentsDelegate::DevToolsRequestFileSystems() { } base::ListValue file_system_value; - for (size_t i = 0; i < file_systems.size(); ++i) - file_system_value.Append(CreateFileSystemValue(file_systems[i])); + for (const auto& file_system : file_systems) + file_system_value.Append(CreateFileSystemValue(file_system)); web_contents_->CallClientFunction("DevToolsAPI.fileSystemsLoaded", &file_system_value, nullptr, nullptr); } @@ -610,9 +610,8 @@ void CommonWebContentsDelegate::OnDevToolsSearchCompleted( const std::string& file_system_path, const std::vector& file_paths) { base::ListValue file_paths_value; - for (std::vector::const_iterator it(file_paths.begin()); - it != file_paths.end(); ++it) { - file_paths_value.AppendString(*it); + for (const auto& file_path : file_paths) { + file_paths_value.AppendString(file_path); } base::FundamentalValue request_id_value(request_id); base::StringValue file_system_path_value(file_system_path); diff --git a/atom/browser/common_web_contents_delegate_mac.mm b/atom/browser/common_web_contents_delegate_mac.mm index aa67540830..c766061379 100644 --- a/atom/browser/common_web_contents_delegate_mac.mm +++ b/atom/browser/common_web_contents_delegate_mac.mm @@ -27,7 +27,13 @@ void CommonWebContentsDelegate::HandleKeyboardEvent( if (event.windowsKeyCode == ui::VKEY_ESCAPE && is_html_fullscreen()) ExitFullscreenModeForTab(source); - if (event.os_event.window) + // Send the event to the menu before sending it to the window + if (event.os_event.type == NSKeyDown && + [[NSApp mainMenu] performKeyEquivalent:event.os_event]) + return; + + if (event.os_event.window && + [event.os_event.window isKindOfClass:[EventDispatchingWindow class]]) [event.os_event.window redispatchKeyEvent:event.os_event]; } diff --git a/atom/browser/javascript_environment.cc b/atom/browser/javascript_environment.cc index 970132b47c..0f87a2ca32 100644 --- a/atom/browser/javascript_environment.cc +++ b/atom/browser/javascript_environment.cc @@ -7,6 +7,7 @@ #include #include "base/command_line.h" +#include "base/message_loop/message_loop.h" #include "content/public/common/content_switches.h" #include "gin/array_buffer.h" #include "gin/v8_initializer.h" @@ -23,6 +24,14 @@ JavascriptEnvironment::JavascriptEnvironment() context_scope_(v8::Local::New(isolate_, context_)) { } +void JavascriptEnvironment::OnMessageLoopCreated() { + isolate_holder_.AddRunMicrotasksObserver(); +} + +void JavascriptEnvironment::OnMessageLoopDestroying() { + isolate_holder_.RemoveRunMicrotasksObserver(); +} + bool JavascriptEnvironment::Initialize() { auto cmd = base::CommandLine::ForCurrentProcess(); if (cmd->HasSwitch("debug-brk")) { diff --git a/atom/browser/javascript_environment.h b/atom/browser/javascript_environment.h index 07cd602cf0..1f4d2f4534 100644 --- a/atom/browser/javascript_environment.h +++ b/atom/browser/javascript_environment.h @@ -14,6 +14,9 @@ class JavascriptEnvironment { public: JavascriptEnvironment(); + void OnMessageLoopCreated(); + void OnMessageLoopDestroying(); + v8::Isolate* isolate() const { return isolate_; } v8::Local context() const { return v8::Local::New(isolate_, context_); diff --git a/atom/browser/mac/atom_application.mm b/atom/browser/mac/atom_application.mm index ea64af3a04..159852a59a 100644 --- a/atom/browser/mac/atom_application.mm +++ b/atom/browser/mac/atom_application.mm @@ -83,6 +83,8 @@ } else { ax_state->DisableAccessibility(); } + + atom::Browser::Get()->OnAccessibilitySupportChanged(); } @end diff --git a/atom/browser/mac/atom_application_delegate.h b/atom/browser/mac/atom_application_delegate.h index 3e5c59c3ff..777475213e 100644 --- a/atom/browser/mac/atom_application_delegate.h +++ b/atom/browser/mac/atom_application_delegate.h @@ -11,9 +11,7 @@ base::scoped_nsobject menu_controller_; } -- (id)init; - // Sets the menu that will be returned in "applicationDockMenu:". -- (void)setApplicationDockMenu:(ui::MenuModel*)model; +- (void)setApplicationDockMenu:(atom::AtomMenuModel*)model; @end diff --git a/atom/browser/mac/atom_application_delegate.mm b/atom/browser/mac/atom_application_delegate.mm index 84caae9d5e..e77bd12520 100644 --- a/atom/browser/mac/atom_application_delegate.mm +++ b/atom/browser/mac/atom_application_delegate.mm @@ -12,14 +12,9 @@ @implementation AtomApplicationDelegate -- (id)init { - self = [super init]; - menu_controller_.reset([[AtomMenuController alloc] init]); - return self; -} - -- (void)setApplicationDockMenu:(ui::MenuModel*)model { - [menu_controller_ populateWithModel:model]; +- (void)setApplicationDockMenu:(atom::AtomMenuModel*)model { + menu_controller_.reset([[AtomMenuController alloc] initWithModel:model + useDefaultAccelerator:NO]); } - (void)applicationWillFinishLaunching:(NSNotification*)notify { @@ -34,7 +29,10 @@ } - (NSMenu*)applicationDockMenu:(NSApplication*)sender { - return [menu_controller_ menu]; + if (menu_controller_) + return [menu_controller_ menu]; + else + return nil; } - (BOOL)application:(NSApplication*)sender diff --git a/atom/browser/mac/dict_util.h b/atom/browser/mac/dict_util.h index 3ffd8ba510..74a2b7234c 100644 --- a/atom/browser/mac/dict_util.h +++ b/atom/browser/mac/dict_util.h @@ -5,9 +5,9 @@ #ifndef ATOM_BROWSER_MAC_DICT_UTIL_H_ #define ATOM_BROWSER_MAC_DICT_UTIL_H_ -#import +#include -#include "base/memory/scoped_ptr.h" +#import namespace base { class ListValue; diff --git a/atom/browser/native_window.cc b/atom/browser/native_window.cc index 4eb72dfe08..d6f8dcf3cb 100644 --- a/atom/browser/native_window.cc +++ b/atom/browser/native_window.cc @@ -11,6 +11,7 @@ #include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_main_parts.h" #include "atom/browser/browser.h" +#include "atom/browser/unresponsive_suppressor.h" #include "atom/browser/window_list.h" #include "atom/common/api/api_messages.h" #include "atom/common/native_mate_converters/file_path_converter.h" @@ -37,9 +38,13 @@ #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/geometry/size_conversions.h" -#include "ui/gfx/screen.h" #include "ui/gl/gpu_switching_manager.h" +#if defined(OS_LINUX) || defined(OS_WIN) +#include "content/public/common/renderer_preferences.h" +#include "ui/gfx/font_render_params.h" +#endif + DEFINE_WEB_CONTENTS_USER_DATA_KEY(atom::NativeWindowRelay); namespace atom { @@ -53,7 +58,6 @@ NativeWindow::NativeWindow( transparent_(false), enable_larger_than_screen_(false), is_closed_(false), - has_dialog_attached_(false), sheet_offset_x_(0.0), sheet_offset_y_(0.0), aspect_ratio_(0.0), @@ -68,6 +72,20 @@ NativeWindow::NativeWindow( if (parent) options.Get("modal", &is_modal_); +#if defined(OS_LINUX) || defined(OS_WIN) + auto* prefs = web_contents()->GetMutableRendererPrefs(); + + // Update font settings. + CR_DEFINE_STATIC_LOCAL(const gfx::FontRenderParams, params, + (gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr))); + prefs->should_antialias_text = params.antialiasing; + prefs->use_subpixel_positioning = params.subpixel_positioning; + prefs->hinting = params.hinting; + prefs->use_autohinter = params.autohinter; + prefs->use_bitmaps = params.use_bitmaps; + prefs->subpixel_rendering = params.subpixel_rendering; +#endif + // Tell the content module to initialize renderer widget with transparent // mode. ui::GpuSwitchingManager::SetTransparent(transparent_); @@ -210,7 +228,7 @@ gfx::Size NativeWindow::GetContentSize() { void NativeWindow::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { - extensions::SizeConstraints content_constraints; + extensions::SizeConstraints content_constraints(GetContentSizeConstraints()); if (window_constraints.HasMaximumSize()) content_constraints.set_maximum_size( WindowSizeToContentSize(window_constraints.GetMaximumSize())); @@ -291,11 +309,7 @@ bool NativeWindow::IsDocumentEdited() { void NativeWindow::SetFocusable(bool focusable) { } -void NativeWindow::SetMenu(ui::MenuModel* menu) { -} - -bool NativeWindow::HasModalDialog() { - return has_dialog_attached_; +void NativeWindow::SetMenu(AtomMenuModel* menu) { } void NativeWindow::SetParentWindow(NativeWindow* parent) { @@ -315,39 +329,6 @@ bool NativeWindow::IsWebViewFocused() { return host_view && host_view->HasFocus(); } -void NativeWindow::CapturePage(const gfx::Rect& rect, - const CapturePageCallback& callback) { - const auto view = web_contents()->GetRenderWidgetHostView(); - const auto host = view ? view->GetRenderWidgetHost() : nullptr; - if (!view || !host) { - callback.Run(SkBitmap()); - return; - } - - // Capture full page if user doesn't specify a |rect|. - const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : - rect.size(); - - // By default, the requested bitmap size is the view size in screen - // coordinates. However, if there's more pixel detail available on the - // current system, increase the requested bitmap size to capture it all. - gfx::Size bitmap_size = view_size; - const gfx::NativeView native_view = view->GetNativeView(); - const float scale = - gfx::Screen::GetScreen()->GetDisplayNearestWindow(native_view) - .device_scale_factor(); - if (scale > 1.0f) - bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); - - host->CopyFromBackingStore( - gfx::Rect(rect.origin(), view_size), - bitmap_size, - base::Bind(&NativeWindow::OnCapturePageDone, - weak_factory_.GetWeakPtr(), - callback), - kBGRA_8888_SkColorType); -} - void NativeWindow::SetAutoHideMenuBar(bool auto_hide) { } @@ -394,7 +375,7 @@ void NativeWindow::RequestToClosePage() { ScheduleUnresponsiveEvent(5000); if (web_contents()->NeedToFireBeforeUnload()) - web_contents()->DispatchBeforeUnload(false); + web_contents()->DispatchBeforeUnload(); else web_contents()->Close(); } @@ -624,7 +605,7 @@ void NativeWindow::ScheduleUnresponsiveEvent(int ms) { void NativeWindow::NotifyWindowUnresponsive() { window_unresposive_closure_.Cancel(); - if (!is_closed_ && !HasModalDialog() && IsEnabled()) + if (!is_closed_ && !IsUnresponsiveEventSuppressed() && IsEnabled()) FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnRendererUnresponsive()); @@ -634,10 +615,4 @@ void NativeWindow::NotifyReadyToShow() { FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnReadyToShow()); } -void NativeWindow::OnCapturePageDone(const CapturePageCallback& callback, - const SkBitmap& bitmap, - content::ReadbackResponse response) { - callback.Run(bitmap); -} - } // namespace atom diff --git a/atom/browser/native_window.h b/atom/browser/native_window.h index d3b6f8a2b0..b932c6317b 100644 --- a/atom/browser/native_window.h +++ b/atom/browser/native_window.h @@ -6,13 +6,14 @@ #define ATOM_BROWSER_NATIVE_WINDOW_H_ #include +#include #include #include #include "atom/browser/native_window_observer.h" #include "atom/browser/ui/accelerator_util.h" +#include "atom/browser/ui/atom_menu_model.h" #include "base/cancelable_callback.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/supports_user_data.h" @@ -43,10 +44,6 @@ namespace mate { class Dictionary; } -namespace ui { -class MenuModel; -} - namespace atom { struct DraggableRegion; @@ -54,28 +51,7 @@ struct DraggableRegion; class NativeWindow : public base::SupportsUserData, public content::WebContentsObserver { public: - using CapturePageCallback = base::Callback; - - class DialogScope { - public: - explicit DialogScope(NativeWindow* window) - : window_(window) { - if (window_ != NULL) - window_->set_has_dialog_attached(true); - } - - ~DialogScope() { - if (window_ != NULL) - window_->set_has_dialog_attached(false); - } - - private: - NativeWindow* window_; - - DISALLOW_COPY_AND_ASSIGN(DialogScope); - }; - - virtual ~NativeWindow(); + ~NativeWindow() override; // Create window with existing WebContents, the caller is responsible for // managing the window's live. @@ -157,9 +133,9 @@ class NativeWindow : public base::SupportsUserData, virtual void SetDocumentEdited(bool edited); virtual bool IsDocumentEdited(); virtual void SetIgnoreMouseEvents(bool ignore) = 0; + virtual void SetContentProtection(bool enable) = 0; virtual void SetFocusable(bool focusable); - virtual void SetMenu(ui::MenuModel* menu); - virtual bool HasModalDialog(); + virtual void SetMenu(AtomMenuModel* menu); virtual void SetParentWindow(NativeWindow* parent); virtual gfx::NativeWindow GetNativeWindow() = 0; virtual gfx::AcceleratedWidget GetAcceleratedWidget() = 0; @@ -178,11 +154,6 @@ class NativeWindow : public base::SupportsUserData, virtual void BlurWebView(); virtual bool IsWebViewFocused(); - // Captures the page with |rect|, |callback| would be called when capturing is - // done. - virtual void CapturePage(const gfx::Rect& rect, - const CapturePageCallback& callback); - // Toggle the menu bar. virtual void SetAutoHideMenuBar(bool auto_hide); virtual bool IsMenuBarAutoHide(); @@ -254,10 +225,6 @@ class NativeWindow : public base::SupportsUserData, SkRegion* draggable_region() const { return draggable_region_.get(); } bool enable_larger_than_screen() const { return enable_larger_than_screen_; } - void set_has_dialog_attached(bool has_dialog_attached) { - has_dialog_attached_ = has_dialog_attached; - } - NativeWindow* parent() const { return parent_; } bool is_modal() const { return is_modal_; } @@ -295,11 +262,6 @@ class NativeWindow : public base::SupportsUserData, // Dispatch ReadyToShow event to observers. void NotifyReadyToShow(); - // Called when CapturePage has done. - void OnCapturePageDone(const CapturePageCallback& callback, - const SkBitmap& bitmap, - content::ReadbackResponse response); - // Whether window has standard frame. bool has_frame_; @@ -319,9 +281,6 @@ class NativeWindow : public base::SupportsUserData, // The windows has been closed. bool is_closed_; - // There is a dialog that has been attached to window. - bool has_dialog_attached_; - // Closure that would be called when window is unresponsive when closing, // it should be cancelled when we can prove that the window is responsive. base::CancelableClosure window_unresposive_closure_; diff --git a/atom/browser/native_window_mac.h b/atom/browser/native_window_mac.h index af99b3912e..d09faa18f6 100644 --- a/atom/browser/native_window_mac.h +++ b/atom/browser/native_window_mac.h @@ -79,7 +79,7 @@ class NativeWindowMac : public NativeWindow { void SetDocumentEdited(bool edited) override; bool IsDocumentEdited() override; void SetIgnoreMouseEvents(bool ignore) override; - bool HasModalDialog() override; + void SetContentProtection(bool enable) override; void SetParentWindow(NativeWindow* parent) override; gfx::NativeWindow GetNativeWindow() override; gfx::AcceleratedWidget GetAcceleratedWidget() override; diff --git a/atom/browser/native_window_mac.mm b/atom/browser/native_window_mac.mm index 5f997ee9b6..743e308d59 100644 --- a/atom/browser/native_window_mac.mm +++ b/atom/browser/native_window_mac.mm @@ -70,6 +70,7 @@ bool ScopedDisableResize::disable_resize_ = false; @interface AtomNSWindowDelegate : NSObject { @private atom::NativeWindowMac* shell_; + bool is_zooming_; } - (id)initWithShell:(atom::NativeWindowMac*)shell; @end @@ -79,6 +80,7 @@ bool ScopedDisableResize::disable_resize_ = false; - (id)initWithShell:(atom::NativeWindowMac*)shell { if ((self = [super init])) { shell_ = shell; + is_zooming_ = false; } return self; } @@ -172,16 +174,20 @@ bool ScopedDisableResize::disable_resize_ = false; } - (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)newFrame { - // Cocoa doen't have concept of maximize/unmaximize, so wee need to emulate - // them by calculating size change when zooming. - if (newFrame.size.width < [window frame].size.width || - newFrame.size.height < [window frame].size.height) - shell_->NotifyWindowUnmaximize(); - else - shell_->NotifyWindowMaximize(); + is_zooming_ = true; return YES; } +- (void)windowDidEndLiveResize:(NSNotification*)notification { + if (is_zooming_) { + if (shell_->IsMaximized()) + shell_->NotifyWindowMaximize(); + else + shell_->NotifyWindowUnmaximize(); + is_zooming_ = false; + } +} + - (void)windowWillEnterFullScreen:(NSNotification*)notification { // Hide the native toolbar before entering fullscreen, so there is no visual // artifacts. @@ -199,6 +205,7 @@ bool ScopedDisableResize::disable_resize_ = false; // have to set one, because title bar is visible here. NSWindow* window = shell_->GetNativeWindow(); if ((shell_->transparent() || !shell_->has_frame()) && + base::mac::IsOSYosemiteOrLater() && // FIXME(zcbenz): Showing titlebar for hiddenInset window is weird under // fullscreen mode. shell_->title_bar_style() != atom::NativeWindowMac::HIDDEN_INSET) { @@ -223,6 +230,7 @@ bool ScopedDisableResize::disable_resize_ = false; // Restore the titlebar visibility. NSWindow* window = shell_->GetNativeWindow(); if ((shell_->transparent() || !shell_->has_frame()) && + base::mac::IsOSYosemiteOrLater() && shell_->title_bar_style() != atom::NativeWindowMac::HIDDEN_INSET) { [window setTitleVisibility:NSWindowTitleHidden]; } @@ -233,13 +241,6 @@ bool ScopedDisableResize::disable_resize_ = false; } - (void)windowDidExitFullScreen:(NSNotification*)notification { - // For certain versions of macOS the fullscreen button will automatically show - // after exiting fullscreen mode. - if (!shell_->has_frame()) { - NSWindow* window = shell_->GetNativeWindow(); - [[window standardWindowButton:NSWindowFullScreenButton] setHidden:YES]; - } - shell_->NotifyWindowLeaveFullScreen(); } @@ -526,8 +527,10 @@ NativeWindowMac::NativeWindowMac( [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { - // Don't show title bar. - [window_ setTitleVisibility:NSWindowTitleHidden]; + if (base::mac::IsOSYosemiteOrLater()) { + // Don't show title bar. + [window_ setTitleVisibility:NSWindowTitleHidden]; + } // Remove non-transparent corners, see http://git.io/vfonD. [window_ setOpaque:NO]; } @@ -714,11 +717,6 @@ void NativeWindowMac::SetFullScreen(bool fullscreen) { if (fullscreen == IsFullscreen()) return; - if (!base::mac::IsOSLionOrLater()) { - LOG(ERROR) << "Fullscreen mode is only supported above Lion"; - return; - } - [window_ toggleFullScreen:nil]; } @@ -727,13 +725,22 @@ bool NativeWindowMac::IsFullscreen() const { } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { - NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, - bounds.width(), - bounds.height()); + // Do nothing if in fullscreen mode. + if (IsFullscreen()) + return; + + // Check size constraints since setFrame does not check it. + gfx::Size size = bounds.size(); + size.SetToMax(GetMinimumSize()); + gfx::Size max_size = GetMaximumSize(); + if (!max_size.IsEmpty()) + size.SetToMin(max_size); + + NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] objectAtIndex:0]; cocoa_bounds.origin.y = - NSHeight([screen frame]) - bounds.height() - bounds.y(); + NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; } @@ -785,13 +792,13 @@ bool NativeWindowMac::IsResizable() { void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { - NativeWindow::SetAspectRatio(aspect_ratio, 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)]; + // 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) { @@ -852,6 +859,11 @@ void NativeWindowMac::Center() { } void NativeWindowMac::SetTitle(const std::string& title) { + // For macOS <= 10.9, the setTitleVisibility API is not available, we have + // to avoid calling setTitle for frameless window. + if (!base::mac::IsOSYosemiteOrLater() && (transparent() || !has_frame())) + return; + [window_ setTitle:base::SysUTF8ToNSString(title)]; } @@ -935,8 +947,9 @@ void NativeWindowMac::SetIgnoreMouseEvents(bool ignore) { [window_ setIgnoresMouseEvents:ignore]; } -bool NativeWindowMac::HasModalDialog() { - return [window_ attachedSheet] != nil; +void NativeWindowMac::SetContentProtection(bool enable) { + [window_ setSharingType:enable ? NSWindowSharingNone + : NSWindowSharingReadOnly]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { @@ -1057,7 +1070,10 @@ void NativeWindowMac::UpdateDraggableRegions( void NativeWindowMac::InstallView() { // Make sure the bottom corner is rounded: http://crbug.com/396264. - [[window_ contentView] setWantsLayer:YES]; + // But do not enable it on OS X 10.9 for transparent window, otherwise a + // semi-transparent frame would show. + if (!(transparent() && base::mac::IsOSMavericks())) + [[window_ contentView] setWantsLayer:YES]; NSView* view = inspectable_web_contents()->GetView()->GetNativeView(); if (has_frame()) { @@ -1077,6 +1093,9 @@ void NativeWindowMac::InstallView() { [view setFrame:[content_view_ bounds]]; [content_view_ addSubview:view]; + // The fullscreen button should always be hidden for frameless window. + [[window_ standardWindowButton:NSWindowFullScreenButton] setHidden:YES]; + if (title_bar_style_ != NORMAL) return; diff --git a/atom/browser/native_window_views.cc b/atom/browser/native_window_views.cc index 1feb9618ac..b4dcf29171 100644 --- a/atom/browser/native_window_views.cc +++ b/atom/browser/native_window_views.cc @@ -51,7 +51,9 @@ #include "atom/browser/ui/win/atom_desktop_window_tree_host_win.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" -#include "ui/gfx/win/dpi.h" +#include "ui/display/win/screen_win.h" +#include "ui/display/display.h" +#include "ui/display/screen.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #endif @@ -135,6 +137,10 @@ NativeWindowViews::NativeWindowViews( menu_bar_autohide_(false), menu_bar_visible_(false), menu_bar_alt_pressed_(false), +#if defined(OS_WIN) + enabled_a11y_support_(false), + thick_frame_(true), +#endif keyboard_event_handler_(new views::UnhandledKeyboardEventHandler), disable_count_(0), use_content_size_(false), @@ -152,6 +158,11 @@ NativeWindowViews::NativeWindowViews( options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); + + // Transparent window must not have thick frame. + options.Get("thickFrame", &thick_frame_); + if (transparent()) + thick_frame_ = false; #endif if (enable_larger_than_screen()) @@ -214,6 +225,9 @@ NativeWindowViews::NativeWindowViews( bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); + std::string window_type; + options.Get(options::kType, &window_type); + #if defined(USE_X11) // Start monitoring window states. window_state_watcher_.reset(new WindowStateWatcher(this)); @@ -243,9 +257,6 @@ NativeWindowViews::NativeWindowViews( state_atom_list.push_back(GetAtom("_NET_WM_STATE_FULLSCREEN")); } - std::string window_type; - options.Get(options::kType, &window_type); - if (parent) { SetParentWindow(parent); // Force using dialog type for child window. @@ -269,13 +280,6 @@ NativeWindowViews::NativeWindowViews( AddChildView(web_view_); #if defined(OS_WIN) - // Save initial window state. - if (fullscreen) - last_window_state_ = ui::SHOW_STATE_FULLSCREEN; - else - last_window_state_ = ui::SHOW_STATE_NORMAL; - last_normal_size_ = gfx::Size(widget_size_); - if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. @@ -287,17 +291,18 @@ NativeWindowViews::NativeWindowViews( if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. - if (transparent()) + if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } - if (transparent()) { - // Transparent window on Windows has to have WS_EX_COMPOSITED style. - LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); + LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); + // Window without thick frame has to have WS_EX_COMPOSITED style. + if (!thick_frame_) ex_style |= WS_EX_COMPOSITED; - ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); - } + if (window_type == "toolbar") + ex_style |= WS_EX_TOOLWINDOW; + ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif // TODO(zcbenz): This was used to force using native frame on Windows 2003, we @@ -315,6 +320,15 @@ NativeWindowViews::NativeWindowViews( window_->CenterWindow(size); Layout(); + +#if defined(OS_WIN) + // Save initial window state. + if (fullscreen) + last_window_state_ = ui::SHOW_STATE_FULLSCREEN; + else + last_window_state_ = ui::SHOW_STATE_NORMAL; + last_normal_bounds_ = GetBounds(); +#endif } NativeWindowViews::~NativeWindowViews() { @@ -335,6 +349,10 @@ void NativeWindowViews::CloseImmediately() { } void NativeWindowViews::Focus(bool focus) { + // For hidden window focus() should do nothing. + if (!IsVisible()) + return; + if (focus) { #if defined(OS_WIN) window_->Activate(); @@ -406,6 +424,17 @@ bool NativeWindowViews::IsEnabled() { } void NativeWindowViews::Maximize() { +#if defined(OS_WIN) + // For window without WS_THICKFRAME style, we can not call Maximize(). + if (!thick_frame_) { + restore_bounds_ = GetBounds(); + auto display = + display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); + SetBounds(display.work_area(), false); + return; + } +#endif + if (IsVisible()) window_->Maximize(); else @@ -414,6 +443,13 @@ void NativeWindowViews::Maximize() { } void NativeWindowViews::Unmaximize() { +#if defined(OS_WIN) + if (!thick_frame_) { + SetBounds(restore_bounds_, false); + return; + } +#endif + window_->Restore(); } @@ -450,6 +486,20 @@ void NativeWindowViews::SetFullScreen(bool fullscreen) { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } + + // For window without WS_THICKFRAME style, we can not call SetFullscreen(). + if (!thick_frame_) { + if (fullscreen) { + restore_bounds_ = GetBounds(); + auto display = + display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); + SetBounds(display.bounds(), false); + } else { + SetBounds(restore_bounds_, false); + } + return; + } + // We set the new value after notifying, so we can handle the size event // correctly. window_->SetFullscreen(fullscreen); @@ -459,6 +509,12 @@ void NativeWindowViews::SetFullScreen(bool fullscreen) { else window_->native_widget_private()->ShowWithWindowState( ui::SHOW_STATE_FULLSCREEN); + + // Auto-hide menubar when in fullscreen. + if (fullscreen) + SetMenuBarVisibility(false); + else + SetMenuBarVisibility(!menu_bar_autohide_); #endif } @@ -466,8 +522,7 @@ bool NativeWindowViews::IsFullscreen() const { return window_->IsFullscreen(); } -void NativeWindowViews::SetBounds(const gfx::Rect& bounds, - bool animate = false) { +void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if defined(USE_X11) // On Linux the minimum and maximum size should be updated with window size // when window is not resizable. @@ -513,7 +568,7 @@ void NativeWindowViews::SetContentSizeConstraints( void NativeWindowViews::SetResizable(bool resizable) { #if defined(OS_WIN) - if (!transparent()) + if (thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #elif defined(USE_X11) if (resizable != resizable_) { @@ -536,7 +591,11 @@ void NativeWindowViews::SetResizable(bool resizable) { bool NativeWindowViews::IsResizable() { #if defined(OS_WIN) - return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; + if (thick_frame_) { + return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; + } else { + return CanResize(); + } #else return CanResize(); #endif @@ -728,6 +787,13 @@ void NativeWindowViews::SetIgnoreMouseEvents(bool ignore) { #endif } +void NativeWindowViews::SetContentProtection(bool enable) { +#if defined(OS_WIN) + DWORD affinity = enable ? WDA_MONITOR : WDA_NONE; + ::SetWindowDisplayAffinity(GetAcceleratedWidget(), affinity); +#endif +} + void NativeWindowViews::SetFocusable(bool focusable) { #if defined(OS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); @@ -741,7 +807,7 @@ void NativeWindowViews::SetFocusable(bool focusable) { #endif } -void NativeWindowViews::SetMenu(ui::MenuModel* menu_model) { +void NativeWindowViews::SetMenu(AtomMenuModel* menu_model) { if (menu_model == nullptr) { // Remove accelerators accelerator_table_.clear(); @@ -1086,9 +1152,11 @@ gfx::Size NativeWindowViews::ContentSizeToWindowSize(const gfx::Size& size) { gfx::Size window_size(size); #if defined(OS_WIN) - gfx::Rect dpi_bounds = - gfx::Rect(gfx::Point(), gfx::win::DIPToScreenSize(size)); - gfx::Rect window_bounds = gfx::win::ScreenToDIPRect( + HWND hwnd = GetAcceleratedWidget(); + gfx::Rect dpi_bounds = gfx::Rect( + gfx::Point(), display::win::ScreenWin::DIPToScreenSize(hwnd, size)); + gfx::Rect window_bounds = display::win::ScreenWin::ScreenToDIPRect( + hwnd, window_->non_client_view()->GetWindowBoundsForClientBounds(dpi_bounds)); window_size = window_bounds.size(); #endif @@ -1104,16 +1172,16 @@ gfx::Size NativeWindowViews::WindowSizeToContentSize(const gfx::Size& size) { gfx::Size content_size(size); #if defined(OS_WIN) - content_size = gfx::win::DIPToScreenSize(content_size); + HWND hwnd = GetAcceleratedWidget(); + content_size = display::win::ScreenWin::DIPToScreenSize(hwnd, content_size); RECT rect; SetRectEmpty(&rect); - HWND hwnd = GetAcceleratedWidget(); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_size.set_width(content_size.width() - (rect.right - rect.left)); content_size.set_height(content_size.height() - (rect.bottom - rect.top)); - content_size = gfx::win::ScreenToDIPSize(content_size); + content_size = display::win::ScreenWin::ScreenToDIPSize(hwnd, content_size); #endif if (menu_bar_ && menu_bar_visible_) @@ -1175,7 +1243,7 @@ bool NativeWindowViews::AcceleratorPressed(const ui::Accelerator& accelerator) { &accelerator_table_, accelerator); } -void NativeWindowViews::RegisterAccelerators(ui::MenuModel* menu_model) { +void NativeWindowViews::RegisterAccelerators(AtomMenuModel* menu_model) { // Clear previous accelerators. views::FocusManager* focus_manager = GetFocusManager(); accelerator_table_.clear(); diff --git a/atom/browser/native_window_views.h b/atom/browser/native_window_views.h index 69d3d27a35..7ad5e8ec29 100644 --- a/atom/browser/native_window_views.h +++ b/atom/browser/native_window_views.h @@ -96,8 +96,9 @@ class NativeWindowViews : public NativeWindow, void SetHasShadow(bool has_shadow) override; bool HasShadow() override; void SetIgnoreMouseEvents(bool ignore) override; + void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; - void SetMenu(ui::MenuModel* menu_model) override; + void SetMenu(AtomMenuModel* menu_model) override; void SetParentWindow(NativeWindow* parent) override; gfx::NativeWindow GetNativeWindow() override; void SetOverlayIcon(const gfx::Image& overlay, @@ -175,7 +176,7 @@ class NativeWindowViews : public NativeWindow, bool AcceleratorPressed(const ui::Accelerator& accelerator) override; // Register accelerators supported by the menu model. - void RegisterAccelerators(ui::MenuModel* menu_model); + void RegisterAccelerators(AtomMenuModel* menu_model); // Returns the restore state for the window. ui::WindowShowState GetRestoredState(); @@ -211,7 +212,7 @@ class NativeWindowViews : public NativeWindow, // to receive the wrong size (#2498). To circumvent that, we keep tabs on the // size of the window while in the normal state (not maximized, minimized or // fullscreen), so we restore it correctly. - gfx::Size last_normal_size_; + gfx::Rect last_normal_bounds_; // In charge of running taskbar related APIs. TaskbarHost taskbar_host_; @@ -219,6 +220,12 @@ class NativeWindowViews : public NativeWindow, // If true we have enabled a11y bool enabled_a11y_support_; + // Whether to show the WS_THICKFRAME style. + bool thick_frame_; + + // The bounds of window before maximize/fullscreen. + gfx::Rect restore_bounds_; + // The icons of window and taskbar. base::win::ScopedHICON window_icon_; base::win::ScopedHICON app_icon_; diff --git a/atom/browser/native_window_views_win.cc b/atom/browser/native_window_views_win.cc index 038ab10522..2da0293f34 100644 --- a/atom/browser/native_window_views_win.cc +++ b/atom/browser/native_window_views_win.cc @@ -2,6 +2,7 @@ // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. +#include "atom/browser/browser.h" #include "atom/browser/native_window_views.h" #include "content/public/browser/browser_accessibility_state.h" @@ -98,6 +99,7 @@ bool NativeWindowViews::PreHandleMSG( if (axState && !axState->IsAccessibleBrowser()) { axState->OnScreenReaderDetected(); enabled_a11y_support_ = true; + Browser::Get()->OnAccessibilitySupportChanged(); } } @@ -119,7 +121,10 @@ bool NativeWindowViews::PreHandleMSG( ::GetWindowRect(GetAcceleratedWidget(), (LPRECT)l_param); return false; } - + case WM_MOVE: { + last_normal_bounds_ = GetBounds(); + return false; + } default: return false; } @@ -140,7 +145,7 @@ void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) { case SIZE_RESTORED: if (last_window_state_ == ui::SHOW_STATE_NORMAL) { // Window was resized so we save it's new size. - last_normal_size_ = GetSize(); + last_normal_bounds_ = GetBounds(); } else { switch (last_window_state_) { case ui::SHOW_STATE_MAXIMIZED: @@ -148,7 +153,7 @@ void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) { // When the window is restored we resize it to the previous known // normal size. - NativeWindow::SetSize(last_normal_size_); + SetBounds(last_normal_bounds_, false); NotifyWindowUnmaximize(); break; @@ -161,7 +166,7 @@ void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) { // When the window is restored we resize it to the previous known // normal size. - NativeWindow::SetSize(last_normal_size_); + SetBounds(last_normal_bounds_, false); NotifyWindowRestore(); } diff --git a/atom/browser/net/asar/asar_protocol_handler.cc b/atom/browser/net/asar/asar_protocol_handler.cc index 324f8339c8..ffa2b3c9f2 100644 --- a/atom/browser/net/asar/asar_protocol_handler.cc +++ b/atom/browser/net/asar/asar_protocol_handler.cc @@ -22,7 +22,7 @@ net::URLRequestJob* AsarProtocolHandler::MaybeCreateJob( net::NetworkDelegate* network_delegate) const { base::FilePath full_path; net::FileURLToFilePath(request->url(), &full_path); - URLRequestAsarJob* job = new URLRequestAsarJob(request, network_delegate); + auto* job = new URLRequestAsarJob(request, network_delegate); job->Initialize(file_task_runner_, full_path); return job; } diff --git a/atom/browser/net/asar/url_request_asar_job.cc b/atom/browser/net/asar/url_request_asar_job.cc index 39e55a35cb..ad3a4c2724 100644 --- a/atom/browser/net/asar/url_request_asar_job.cc +++ b/atom/browser/net/asar/url_request_asar_job.cc @@ -111,7 +111,7 @@ void URLRequestAsarJob::Start() { if (rv != net::ERR_IO_PENDING) DidOpen(rv); } else if (type_ == TYPE_FILE) { - FileMetaInfo* meta_info = new FileMetaInfo(); + auto* meta_info = new FileMetaInfo(); file_task_runner_->PostTaskAndReply( FROM_HERE, base::Bind(&URLRequestAsarJob::FetchMetaInfo, file_path_, @@ -180,10 +180,10 @@ bool URLRequestAsarJob::IsRedirectResponse(GURL* location, #endif } -net::Filter* URLRequestAsarJob::SetupFilter() const { +std::unique_ptr URLRequestAsarJob::SetupFilter() const { // Bug 9936 - .svgz files needs to be decompressed. return base::LowerCaseEqualsASCII(file_path_.Extension(), ".svgz") - ? net::Filter::GZipFactory() : NULL; + ? net::Filter::GZipFactory() : nullptr; } bool URLRequestAsarJob::GetMimeType(std::string* mime_type) const { @@ -224,7 +224,7 @@ int URLRequestAsarJob::GetResponseCode() const { void URLRequestAsarJob::GetResponseInfo(net::HttpResponseInfo* info) { std::string status("HTTP/1.1 200 OK"); - net::HttpResponseHeaders* headers = new net::HttpResponseHeaders(status); + auto* headers = new net::HttpResponseHeaders(status); headers->AddHeader(atom::kCORSHeader); info->headers = headers; @@ -338,7 +338,7 @@ void URLRequestAsarJob::DidRead(scoped_refptr buf, int result) { DCHECK_GE(remaining_bytes_, 0); } - buf = NULL; + buf = nullptr; ReadRawDataComplete(result); } diff --git a/atom/browser/net/asar/url_request_asar_job.h b/atom/browser/net/asar/url_request_asar_job.h index 56c519823c..8c32932fa5 100644 --- a/atom/browser/net/asar/url_request_asar_job.h +++ b/atom/browser/net/asar/url_request_asar_job.h @@ -56,7 +56,7 @@ class URLRequestAsarJob : public net::URLRequestJob { void Kill() override; int ReadRawData(net::IOBuffer* buf, int buf_size) override; bool IsRedirectResponse(GURL* location, int* http_status_code) override; - net::Filter* SetupFilter() const override; + std::unique_ptr SetupFilter() const override; bool GetMimeType(std::string* mime_type) const override; void SetExtraRequestHeaders(const net::HttpRequestHeaders& headers) override; int GetResponseCode() const override; diff --git a/atom/browser/net/atom_cert_verifier.cc b/atom/browser/net/atom_cert_verifier.cc index adfba7060c..dd588b9501 100644 --- a/atom/browser/net/atom_cert_verifier.cc +++ b/atom/browser/net/atom_cert_verifier.cc @@ -36,7 +36,6 @@ AtomCertVerifier::~AtomCertVerifier() { } void AtomCertVerifier::SetVerifyProc(const VerifyProc& proc) { - base::AutoLock auto_lock(lock_); verify_proc_ = proc; } @@ -52,20 +51,14 @@ int AtomCertVerifier::Verify( const net::BoundNetLog& net_log) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - VerifyProc proc; - { - base::AutoLock auto_lock(lock_); - proc = verify_proc_; - } - - if (proc.is_null()) + if (verify_proc_.is_null()) return default_cert_verifier_->Verify( cert, hostname, ocsp_response, flags, crl_set, verify_result, callback, out_req, net_log); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, - base::Bind(proc, hostname, make_scoped_refptr(cert), + base::Bind(verify_proc_, hostname, make_scoped_refptr(cert), base::Bind(OnResult, verify_result, callback))); return net::ERR_IO_PENDING; } diff --git a/atom/browser/net/atom_cert_verifier.h b/atom/browser/net/atom_cert_verifier.h index e00ba260ec..c8b4bf9290 100644 --- a/atom/browser/net/atom_cert_verifier.h +++ b/atom/browser/net/atom_cert_verifier.h @@ -5,10 +5,9 @@ #ifndef ATOM_BROWSER_NET_ATOM_CERT_VERIFIER_H_ #define ATOM_BROWSER_NET_ATOM_CERT_VERIFIER_H_ +#include #include -#include "base/memory/ref_counted.h" -#include "base/synchronization/lock.h" #include "net/cert/cert_verifier.h" namespace atom { @@ -39,7 +38,6 @@ class AtomCertVerifier : public net::CertVerifier { bool SupportsOCSPStapling() override; private: - base::Lock lock_; VerifyProc verify_proc_; std::unique_ptr default_cert_verifier_; diff --git a/atom/browser/net/atom_url_request_job_factory.cc b/atom/browser/net/atom_url_request_job_factory.cc index d78b7026e5..7e2eb95149 100644 --- a/atom/browser/net/atom_url_request_job_factory.cc +++ b/atom/browser/net/atom_url_request_job_factory.cc @@ -20,14 +20,14 @@ typedef net::URLRequestJobFactory::ProtocolHandler ProtocolHandler; AtomURLRequestJobFactory::AtomURLRequestJobFactory() {} AtomURLRequestJobFactory::~AtomURLRequestJobFactory() { - STLDeleteValues(&protocol_handler_map_); + Clear(); } bool AtomURLRequestJobFactory::SetProtocolHandler( const std::string& scheme, std::unique_ptr protocol_handler) { if (!protocol_handler) { - ProtocolHandlerMap::iterator it = protocol_handler_map_.find(scheme); + auto it = protocol_handler_map_.find(scheme); if (it == protocol_handler_map_.end()) return false; @@ -66,7 +66,7 @@ ProtocolHandler* AtomURLRequestJobFactory::GetProtocolHandler( const std::string& scheme) const { DCHECK_CURRENTLY_ON(BrowserThread::IO); - ProtocolHandlerMap::const_iterator it = protocol_handler_map_.find(scheme); + auto it = protocol_handler_map_.find(scheme); if (it == protocol_handler_map_.end()) return nullptr; return it->second; @@ -77,13 +77,17 @@ bool AtomURLRequestJobFactory::HasProtocolHandler( return ContainsKey(protocol_handler_map_, scheme); } +void AtomURLRequestJobFactory::Clear() { + STLDeleteValues(&protocol_handler_map_); +} + net::URLRequestJob* AtomURLRequestJobFactory::MaybeCreateJobWithProtocolHandler( const std::string& scheme, net::URLRequest* request, net::NetworkDelegate* network_delegate) const { DCHECK_CURRENTLY_ON(BrowserThread::IO); - ProtocolHandlerMap::const_iterator it = protocol_handler_map_.find(scheme); + auto it = protocol_handler_map_.find(scheme); if (it == protocol_handler_map_.end()) return nullptr; return it->second->MaybeCreateJob(request, network_delegate); diff --git a/atom/browser/net/atom_url_request_job_factory.h b/atom/browser/net/atom_url_request_job_factory.h index ea2710bb4c..5b439c2f9c 100644 --- a/atom/browser/net/atom_url_request_job_factory.h +++ b/atom/browser/net/atom_url_request_job_factory.h @@ -39,6 +39,9 @@ class AtomURLRequestJobFactory : public net::URLRequestJobFactory { // Whether the protocol handler is registered by the job factory. bool HasProtocolHandler(const std::string& scheme) const; + // Clear all protocol handlers. + void Clear(); + // URLRequestJobFactory implementation net::URLRequestJob* MaybeCreateJobWithProtocolHandler( const std::string& scheme, diff --git a/atom/browser/net/url_request_async_asar_job.cc b/atom/browser/net/url_request_async_asar_job.cc index 1234bccf43..942f06233e 100644 --- a/atom/browser/net/url_request_async_asar_job.cc +++ b/atom/browser/net/url_request_async_asar_job.cc @@ -40,7 +40,7 @@ void URLRequestAsyncAsarJob::StartAsync(std::unique_ptr options) { void URLRequestAsyncAsarJob::GetResponseInfo(net::HttpResponseInfo* info) { std::string status("HTTP/1.1 200 OK"); - net::HttpResponseHeaders* headers = new net::HttpResponseHeaders(status); + auto* headers = new net::HttpResponseHeaders(status); headers->AddHeader(kCORSHeader); info->headers = headers; diff --git a/atom/browser/net/url_request_buffer_job.cc b/atom/browser/net/url_request_buffer_job.cc index c713099c76..70f4603081 100644 --- a/atom/browser/net/url_request_buffer_job.cc +++ b/atom/browser/net/url_request_buffer_job.cc @@ -72,7 +72,7 @@ void URLRequestBufferJob::GetResponseInfo(net::HttpResponseInfo* info) { status.append(" "); status.append(net::GetHttpReasonPhrase(status_code_)); status.append("\0\0", 2); - net::HttpResponseHeaders* headers = new net::HttpResponseHeaders(status); + auto* headers = new net::HttpResponseHeaders(status); headers->AddHeader(kCORSHeader); diff --git a/atom/browser/net/url_request_fetch_job.cc b/atom/browser/net/url_request_fetch_job.cc index 8279d09d5d..5f11c67476 100644 --- a/atom/browser/net/url_request_fetch_job.cc +++ b/atom/browser/net/url_request_fetch_job.cc @@ -7,6 +7,7 @@ #include #include +#include "base/memory/ptr_util.h" #include "base/strings/string_util.h" #include "native_mate/dictionary.h" #include "net/base/io_buffer.h" @@ -132,7 +133,7 @@ void URLRequestFetchJob::StartAsync(std::unique_ptr options) { request_type = GetRequestType(method); fetcher_ = net::URLFetcher::Create(formated_url, request_type, this); - fetcher_->SaveResponseWithWriter(make_scoped_ptr(new ResponsePiper(this))); + fetcher_->SaveResponseWithWriter(base::WrapUnique(new ResponsePiper(this))); // A request context getter is passed by the user. if (url_request_context_getter_) diff --git a/atom/browser/net/url_request_string_job.cc b/atom/browser/net/url_request_string_job.cc index 59945e66db..abec345e63 100644 --- a/atom/browser/net/url_request_string_job.cc +++ b/atom/browser/net/url_request_string_job.cc @@ -31,7 +31,7 @@ void URLRequestStringJob::StartAsync(std::unique_ptr options) { void URLRequestStringJob::GetResponseInfo(net::HttpResponseInfo* info) { std::string status("HTTP/1.1 200 OK"); - net::HttpResponseHeaders* headers = new net::HttpResponseHeaders(status); + auto* headers = new net::HttpResponseHeaders(status); headers->AddHeader(kCORSHeader); diff --git a/atom/browser/node_debugger.h b/atom/browser/node_debugger.h index f708de6329..118812a139 100644 --- a/atom/browser/node_debugger.h +++ b/atom/browser/node_debugger.h @@ -5,9 +5,9 @@ #ifndef ATOM_BROWSER_NODE_DEBUGGER_H_ #define ATOM_BROWSER_NODE_DEBUGGER_H_ +#include #include -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread.h" #include "net/test/embedded_test_server/stream_listen_socket.h" diff --git a/atom/browser/relauncher_linux.cc b/atom/browser/relauncher_linux.cc index 2fbbd47faf..6d60b072f6 100644 --- a/atom/browser/relauncher_linux.cc +++ b/atom/browser/relauncher_linux.cc @@ -4,11 +4,13 @@ #include "atom/browser/relauncher.h" +#include #include #include #include #include "base/files/file_util.h" +#include "base/files/scoped_file.h" #include "base/logging.h" #include "base/posix/eintr_wrapper.h" #include "base/process/launch.h" @@ -55,9 +57,17 @@ void RelauncherSynchronizeWithParent() { int LaunchProgram(const StringVector& relauncher_args, const StringVector& argv) { + // Redirect the stdout of child process to /dev/null, otherwise after + // relaunch the child process will raise exception when writing to stdout. + base::ScopedFD devnull(HANDLE_EINTR(open("/dev/null", O_WRONLY))); + base::FileHandleMappingVector no_stdout; + no_stdout.push_back(std::make_pair(devnull.get(), STDERR_FILENO)); + no_stdout.push_back(std::make_pair(devnull.get(), STDOUT_FILENO)); + base::LaunchOptions options; options.allow_new_privs = true; options.new_process_group = true; // detach + options.fds_to_remap = &no_stdout; base::Process process = base::LaunchProcess(argv, options); return process.IsValid() ? 0 : 1; } diff --git a/atom/browser/relauncher_mac.cc b/atom/browser/relauncher_mac.cc index ef26f8441d..6e28850245 100644 --- a/atom/browser/relauncher_mac.cc +++ b/atom/browser/relauncher_mac.cc @@ -43,7 +43,7 @@ void RelauncherSynchronizeWithParent() { struct kevent change = { 0 }; EV_SET(&change, parent_pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL); - if (kevent(kq.get(), &change, 1, NULL, 0, NULL) == -1) { + if (kevent(kq.get(), &change, 1, nullptr, 0, nullptr) == -1) { PLOG(ERROR) << "kevent (add)"; return; } @@ -58,7 +58,7 @@ void RelauncherSynchronizeWithParent() { // write above to complete. The parent process is now free to exit. Wait for // that to happen. struct kevent event; - int events = kevent(kq.get(), NULL, 0, &event, 1, NULL); + int events = kevent(kq.get(), nullptr, 0, &event, 1, nullptr); if (events != 1) { if (events < 0) { PLOG(ERROR) << "kevent (monitor)"; @@ -79,8 +79,16 @@ void RelauncherSynchronizeWithParent() { int LaunchProgram(const StringVector& relauncher_args, const StringVector& argv) { + // Redirect the stdout of child process to /dev/null, otherwise after + // relaunch the child process will raise exception when writing to stdout. + base::ScopedFD devnull(HANDLE_EINTR(open("/dev/null", O_WRONLY))); + base::FileHandleMappingVector no_stdout; + no_stdout.push_back(std::make_pair(devnull.get(), STDERR_FILENO)); + no_stdout.push_back(std::make_pair(devnull.get(), STDOUT_FILENO)); + base::LaunchOptions options; options.new_process_group = true; // detach + options.fds_to_remap = &no_stdout; base::Process process = base::LaunchProcess(argv, options); return process.IsValid() ? 0 : 1; } diff --git a/atom/browser/resources/mac/Info.plist b/atom/browser/resources/mac/Info.plist index 46898637c5..b3f3bc69a4 100644 --- a/atom/browser/resources/mac/Info.plist +++ b/atom/browser/resources/mac/Info.plist @@ -17,9 +17,9 @@ CFBundleIconFile electron.icns CFBundleVersion - 1.2.3 + 1.3.1 CFBundleShortVersionString - 1.2.3 + 1.3.1 LSApplicationCategoryType public.app-category.developer-tools LSMinimumSystemVersion diff --git a/atom/browser/resources/win/atom.ico b/atom/browser/resources/win/atom.ico index aa09177554..004176004f 100644 Binary files a/atom/browser/resources/win/atom.ico and b/atom/browser/resources/win/atom.ico differ diff --git a/atom/browser/resources/win/atom.rc b/atom/browser/resources/win/atom.rc index b6df17ca1d..d95e04c07b 100644 --- a/atom/browser/resources/win/atom.rc +++ b/atom/browser/resources/win/atom.rc @@ -56,8 +56,8 @@ END // VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,2,3,0 - PRODUCTVERSION 1,2,3,0 + FILEVERSION 1,3,1,0 + PRODUCTVERSION 1,3,1,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -74,12 +74,12 @@ BEGIN BEGIN VALUE "CompanyName", "GitHub, Inc." VALUE "FileDescription", "Electron" - VALUE "FileVersion", "1.2.3" + VALUE "FileVersion", "1.3.1" VALUE "InternalName", "electron.exe" VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved." VALUE "OriginalFilename", "electron.exe" VALUE "ProductName", "Electron" - VALUE "ProductVersion", "1.2.3" + VALUE "ProductVersion", "1.3.1" VALUE "SquirrelAwareVersion", "1" END END diff --git a/atom/browser/ui/accelerator_util.cc b/atom/browser/ui/accelerator_util.cc index f683c99c63..eb89bf0c35 100644 --- a/atom/browser/ui/accelerator_util.cc +++ b/atom/browser/ui/accelerator_util.cc @@ -14,7 +14,6 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" -#include "ui/base/models/simple_menu_model.h" namespace accelerator_util { @@ -31,9 +30,9 @@ bool StringToAccelerator(const std::string& shortcut, // Now, parse it into an accelerator. int modifiers = ui::EF_NONE; ui::KeyboardCode key = ui::VKEY_UNKNOWN; - for (size_t i = 0; i < tokens.size(); i++) { + for (const auto& token : tokens) { bool shifted = false; - ui::KeyboardCode code = atom::KeyboardCodeFromStr(tokens[i], &shifted); + ui::KeyboardCode code = atom::KeyboardCodeFromStr(token, &shifted); if (shifted) modifiers |= ui::EF_SHIFT_DOWN; switch (code) { @@ -69,16 +68,17 @@ bool StringToAccelerator(const std::string& shortcut, return true; } -void GenerateAcceleratorTable(AcceleratorTable* table, ui::MenuModel* model) { +void GenerateAcceleratorTable(AcceleratorTable* table, + atom::AtomMenuModel* model) { int count = model->GetItemCount(); for (int i = 0; i < count; ++i) { - ui::MenuModel::ItemType type = model->GetTypeAt(i); - if (type == ui::MenuModel::TYPE_SUBMENU) { - ui::MenuModel* submodel = model->GetSubmenuModelAt(i); + atom::AtomMenuModel::ItemType type = model->GetTypeAt(i); + if (type == atom::AtomMenuModel::TYPE_SUBMENU) { + auto submodel = model->GetSubmenuModelAt(i); GenerateAcceleratorTable(table, submodel); } else { ui::Accelerator accelerator; - if (model->GetAcceleratorAt(i, &accelerator)) { + if (model->GetAcceleratorAtWithParams(i, true, &accelerator)) { MenuItem item = { i, model }; (*table)[accelerator] = item; } diff --git a/atom/browser/ui/accelerator_util.h b/atom/browser/ui/accelerator_util.h index 584041980b..38f206f537 100644 --- a/atom/browser/ui/accelerator_util.h +++ b/atom/browser/ui/accelerator_util.h @@ -8,15 +8,12 @@ #include #include +#include "atom/browser/ui/atom_menu_model.h" #include "ui/base/accelerators/accelerator.h" -namespace ui { -class MenuModel; -} - namespace accelerator_util { -typedef struct { int position; ui::MenuModel* model; } MenuItem; +typedef struct { int position; atom::AtomMenuModel* model; } MenuItem; typedef std::map AcceleratorTable; // Parse a string as an accelerator. @@ -27,7 +24,8 @@ bool StringToAccelerator(const std::string& description, void SetPlatformAccelerator(ui::Accelerator* accelerator); // Generate a table that contains memu model's accelerators and command ids. -void GenerateAcceleratorTable(AcceleratorTable* table, ui::MenuModel* model); +void GenerateAcceleratorTable(AcceleratorTable* table, + atom::AtomMenuModel* model); // Trigger command from the accelerators table. bool TriggerAcceleratorTableCommand(AcceleratorTable* table, diff --git a/atom/browser/ui/accelerator_util_mac.mm b/atom/browser/ui/accelerator_util_mac.mm index e2448833ab..cf1d3de4d2 100644 --- a/atom/browser/ui/accelerator_util_mac.mm +++ b/atom/browser/ui/accelerator_util_mac.mm @@ -29,6 +29,10 @@ void SetPlatformAccelerator(ui::Accelerator* accelerator) { modifiers ^= NSShiftKeyMask; } + if (character == NSDeleteFunctionKey) { + character = NSDeleteCharacter; + } + NSString* characters = [[[NSString alloc] initWithCharacters:&character length:1] autorelease]; diff --git a/atom/browser/ui/atom_menu_model.cc b/atom/browser/ui/atom_menu_model.cc index 9add7a2271..de3465e8ab 100644 --- a/atom/browser/ui/atom_menu_model.cc +++ b/atom/browser/ui/atom_menu_model.cc @@ -17,19 +17,37 @@ AtomMenuModel::~AtomMenuModel() { } void AtomMenuModel::SetRole(int index, const base::string16& role) { - roles_[index] = role; + int command_id = GetCommandIdAt(index); + roles_[command_id] = role; } base::string16 AtomMenuModel::GetRoleAt(int index) { - if (ContainsKey(roles_, index)) - return roles_[index]; + int command_id = GetCommandIdAt(index); + if (ContainsKey(roles_, command_id)) + return roles_[command_id]; else return base::string16(); } +bool AtomMenuModel::GetAcceleratorAtWithParams( + int index, + bool use_default_accelerator, + ui::Accelerator* accelerator) const { + if (delegate_) { + return delegate_->GetAcceleratorForCommandIdWithParams( + GetCommandIdAt(index), use_default_accelerator, accelerator); + } + return false; +} + void AtomMenuModel::MenuClosed() { ui::SimpleMenuModel::MenuClosed(); FOR_EACH_OBSERVER(Observer, observers_, MenuClosed()); } +AtomMenuModel* AtomMenuModel::GetSubmenuModelAt(int index) { + return static_cast( + ui::SimpleMenuModel::GetSubmenuModelAt(index)); +} + } // namespace atom diff --git a/atom/browser/ui/atom_menu_model.h b/atom/browser/ui/atom_menu_model.h index d091df9fb5..887f6123bc 100644 --- a/atom/browser/ui/atom_menu_model.h +++ b/atom/browser/ui/atom_menu_model.h @@ -17,6 +17,19 @@ class AtomMenuModel : public ui::SimpleMenuModel { class Delegate : public ui::SimpleMenuModel::Delegate { public: virtual ~Delegate() {} + + virtual bool GetAcceleratorForCommandIdWithParams( + int command_id, + bool use_default_accelerator, + ui::Accelerator* accelerator) const = 0; + + private: + // ui::SimpleMenuModel::Delegate: + bool GetAcceleratorForCommandId(int command_id, + ui::Accelerator* accelerator) { + return GetAcceleratorForCommandIdWithParams( + command_id, false, accelerator); + } }; class Observer { @@ -35,14 +48,20 @@ class AtomMenuModel : public ui::SimpleMenuModel { void SetRole(int index, const base::string16& role); base::string16 GetRoleAt(int index); + bool GetAcceleratorAtWithParams(int index, + bool use_default_accelerator, + ui::Accelerator* accelerator) const; // ui::SimpleMenuModel: void MenuClosed() override; + using SimpleMenuModel::GetSubmenuModelAt; + AtomMenuModel* GetSubmenuModelAt(int index); + private: Delegate* delegate_; // weak ref. - std::map roles_; + std::map roles_; // command id -> role base::ObserverList observers_; DISALLOW_COPY_AND_ASSIGN(AtomMenuModel); diff --git a/atom/browser/ui/cocoa/atom_menu_controller.h b/atom/browser/ui/cocoa/atom_menu_controller.h index f8c48aa5dc..af0b276961 100644 --- a/atom/browser/ui/cocoa/atom_menu_controller.h +++ b/atom/browser/ui/cocoa/atom_menu_controller.h @@ -11,8 +11,8 @@ #include "base/mac/scoped_nsobject.h" #include "base/strings/string16.h" -namespace ui { -class MenuModel; +namespace atom { +class AtomMenuModel; } // A controller for the cross-platform menu model. The menu that's created @@ -23,24 +23,20 @@ class MenuModel; // as it only maintains weak references. @interface AtomMenuController : NSObject { @protected - ui::MenuModel* model_; // weak + atom::AtomMenuModel* model_; // weak base::scoped_nsobject menu_; BOOL isMenuOpen_; + BOOL useDefaultAccelerator_; } -@property(nonatomic, assign) ui::MenuModel* model; - -// NIB-based initializer. This does not create a menu. Clients can set the -// properties of the object and the menu will be created upon the first call to -// |-menu|. Note that the menu will be immutable after creation. -- (id)init; +@property(nonatomic, assign) atom::AtomMenuModel* model; // Builds a NSMenu from the pre-built model (must not be nil). Changes made // to the contents of the model after calling this will not be noticed. -- (id)initWithModel:(ui::MenuModel*)model; +- (id)initWithModel:(atom::AtomMenuModel*)model useDefaultAccelerator:(BOOL)use; // Populate current NSMenu with |model|. -- (void)populateWithModel:(ui::MenuModel*)model; +- (void)populateWithModel:(atom::AtomMenuModel*)model; // Programmatically close the constructed menu. - (void)cancel; diff --git a/atom/browser/ui/cocoa/atom_menu_controller.mm b/atom/browser/ui/cocoa/atom_menu_controller.mm index 642721e6bd..3efd161151 100644 --- a/atom/browser/ui/cocoa/atom_menu_controller.mm +++ b/atom/browser/ui/cocoa/atom_menu_controller.mm @@ -38,6 +38,8 @@ Role kRolesMap[] = { { @selector(performMiniaturize:), "minimize" }, { @selector(performClose:), "close" }, { @selector(performZoom:), "zoom" }, + { @selector(terminate:), "quit" }, + { @selector(toggleFullScreen:), "togglefullscreen" }, }; } // namespace @@ -46,15 +48,11 @@ Role kRolesMap[] = { @synthesize model = model_; -- (id)init { - if ((self = [super init])) - [self menu]; - return self; -} - -- (id)initWithModel:(ui::MenuModel*)model { +- (id)initWithModel:(atom::AtomMenuModel*)model useDefaultAccelerator:(BOOL)use { if ((self = [super init])) { model_ = model; + isMenuOpen_ = NO; + useDefaultAccelerator_ = use; [self menu]; } return self; @@ -71,7 +69,7 @@ Role kRolesMap[] = { [super dealloc]; } -- (void)populateWithModel:(ui::MenuModel*)model { +- (void)populateWithModel:(atom::AtomMenuModel*)model { if (!menu_) return; @@ -80,7 +78,7 @@ Role kRolesMap[] = { const int count = model->GetItemCount(); for (int index = 0; index < count; index++) { - if (model->GetTypeAt(index) == ui::MenuModel::TYPE_SEPARATOR) + if (model->GetTypeAt(index) == atom::AtomMenuModel::TYPE_SEPARATOR) [self addSeparatorToMenu:menu_ atIndex:index]; else [self addItemToMenu:menu_ atIndex:index fromModel:model]; @@ -97,12 +95,12 @@ Role kRolesMap[] = { // Creates a NSMenu from the given model. If the model has submenus, this can // be invoked recursively. -- (NSMenu*)menuFromModel:(ui::MenuModel*)model { +- (NSMenu*)menuFromModel:(atom::AtomMenuModel*)model { NSMenu* menu = [[[NSMenu alloc] initWithTitle:@""] autorelease]; const int count = model->GetItemCount(); for (int index = 0; index < count; index++) { - if (model->GetTypeAt(index) == ui::MenuModel::TYPE_SEPARATOR) + if (model->GetTypeAt(index) == atom::AtomMenuModel::TYPE_SEPARATOR) [self addSeparatorToMenu:menu atIndex:index]; else [self addItemToMenu:menu atIndex:index fromModel:model]; @@ -124,9 +122,7 @@ Role kRolesMap[] = { // associated with the entry in the model identified by |modelIndex|. - (void)addItemToMenu:(NSMenu*)menu atIndex:(NSInteger)index - fromModel:(ui::MenuModel*)ui_model { - atom::AtomMenuModel* model = static_cast(ui_model); - + fromModel:(atom::AtomMenuModel*)model { base::string16 label16 = model->GetLabelAt(index); NSString* label = l10n_util::FixUpWindowsStyleLabel(label16); base::scoped_nsobject item( @@ -139,12 +135,13 @@ Role kRolesMap[] = { if (model->GetIconAt(index, &icon) && !icon.IsEmpty()) [item setImage:icon.ToNSImage()]; - ui::MenuModel::ItemType type = model->GetTypeAt(index); - if (type == ui::MenuModel::TYPE_SUBMENU) { + atom::AtomMenuModel::ItemType type = model->GetTypeAt(index); + if (type == atom::AtomMenuModel::TYPE_SUBMENU) { // Recursively build a submenu from the sub-model at this index. [item setTarget:nil]; [item setAction:nil]; - ui::MenuModel* submenuModel = model->GetSubmenuModelAt(index); + atom::AtomMenuModel* submenuModel = static_cast( + model->GetSubmenuModelAt(index)); NSMenu* submenu = [self menuFromModel:submenuModel]; [submenu setTitle:[item title]]; [item setSubmenu:submenu]; @@ -168,7 +165,8 @@ Role kRolesMap[] = { NSValue* modelObject = [NSValue valueWithPointer:model]; [item setRepresentedObject:modelObject]; // Retains |modelObject|. ui::Accelerator accelerator; - if (model->GetAcceleratorAt(index, &accelerator)) { + if (model->GetAcceleratorAtWithParams( + index, useDefaultAccelerator_, &accelerator)) { const ui::PlatformAcceleratorCocoa* platformAccelerator = static_cast( accelerator.platform_accelerator()); @@ -204,8 +202,8 @@ Role kRolesMap[] = { return NO; NSInteger modelIndex = [item tag]; - ui::MenuModel* model = - static_cast( + atom::AtomMenuModel* model = + static_cast( [[(id)item representedObject] pointerValue]); DCHECK(model); if (model) { @@ -232,8 +230,8 @@ Role kRolesMap[] = { // item chosen. - (void)itemSelected:(id)sender { NSInteger modelIndex = [sender tag]; - ui::MenuModel* model = - static_cast( + atom::AtomMenuModel* model = + static_cast( [[sender representedObject] pointerValue]); DCHECK(model); if (model) { diff --git a/atom/browser/ui/drag_util.h b/atom/browser/ui/drag_util.h new file mode 100644 index 0000000000..df5303c65e --- /dev/null +++ b/atom/browser/ui/drag_util.h @@ -0,0 +1,24 @@ +// 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_UI_DRAG_UTIL_H_ +#define ATOM_BROWSER_UI_DRAG_UTIL_H_ + +#include + +#include "ui/gfx/image/image.h" + +namespace base { +class FilePath; +} + +namespace atom { + +void DragFileItems(const std::vector& files, + const gfx::Image& icon, + gfx::NativeView view); + +} // namespace atom + +#endif // ATOM_BROWSER_UI_DRAG_UTIL_H_ diff --git a/atom/browser/ui/drag_util_mac.mm b/atom/browser/ui/drag_util_mac.mm new file mode 100644 index 0000000000..7197e79af6 --- /dev/null +++ b/atom/browser/ui/drag_util_mac.mm @@ -0,0 +1,58 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#import + +#include "atom/browser/ui/drag_util.h" +#include "base/files/file_path.h" +#include "base/strings/sys_string_conversions.h" + +namespace atom { + +namespace { + +// Write information about the file being dragged to the pasteboard. +void AddFilesToPasteboard(NSPasteboard* pasteboard, + const std::vector& files) { + NSMutableArray* fileList = [NSMutableArray array]; + for (const base::FilePath& file : files) + [fileList addObject:base::SysUTF8ToNSString(file.value())]; + [pasteboard declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType] + owner:nil]; + [pasteboard setPropertyList:fileList forType:NSFilenamesPboardType]; +} + +} // namespace + +void DragFileItems(const std::vector& files, + const gfx::Image& icon, + gfx::NativeView view) { + NSPasteboard* pasteboard = [NSPasteboard pasteboardWithName:NSDragPboard]; + AddFilesToPasteboard(pasteboard, files); + + // Synthesize a drag event, since we don't have access to the actual event + // that initiated a drag (possibly consumed by the Web UI, for example). + NSPoint position = [[view window] mouseLocationOutsideOfEventStream]; + NSTimeInterval eventTime = [[NSApp currentEvent] timestamp]; + NSEvent* dragEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged + location:position + modifierFlags:NSLeftMouseDraggedMask + timestamp:eventTime + windowNumber:[[view window] windowNumber] + context:nil + eventNumber:0 + clickCount:1 + pressure:1.0]; + + // Run the drag operation. + [[view window] dragImage:icon.ToNSImage() + at:position + offset:NSZeroSize + event:dragEvent + pasteboard:pasteboard + source:view + slideBack:YES]; +} + +} // namespace atom diff --git a/atom/browser/ui/drag_util_views.cc b/atom/browser/ui/drag_util_views.cc new file mode 100644 index 0000000000..9a035bf082 --- /dev/null +++ b/atom/browser/ui/drag_util_views.cc @@ -0,0 +1,48 @@ +// Copyright (c) 2016 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/browser/ui/drag_util.h" + +#include "ui/aura/window.h" +#include "ui/base/dragdrop/drag_drop_types.h" +#include "ui/base/dragdrop/drag_utils.h" +#include "ui/base/dragdrop/file_info.h" +#include "ui/base/dragdrop/os_exchange_data.h" +#include "ui/gfx/geometry/point.h" +#include "ui/display/screen.h" +#include "ui/views/widget/widget.h" +#include "ui/wm/public/drag_drop_client.h" + +namespace atom { + +void DragFileItems(const std::vector& files, + const gfx::Image& icon, + gfx::NativeView view) { + // Set up our OLE machinery + ui::OSExchangeData data; + + drag_utils::CreateDragImageForFile(files[0], icon.AsImageSkia(), &data); + + std::vector file_infos; + for (const base::FilePath& file : files) { + file_infos.push_back(ui::FileInfo(file, base::FilePath())); + } + data.SetFilenames(file_infos); + + aura::Window* root_window = view->GetRootWindow(); + if (!root_window || !aura::client::GetDragDropClient(root_window)) + return; + + gfx::Point location = display::Screen::GetScreen()->GetCursorScreenPoint(); + // TODO(varunjain): Properly determine and send DRAG_EVENT_SOURCE below. + aura::client::GetDragDropClient(root_window)->StartDragAndDrop( + data, + root_window, + view, + location, + ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_LINK, + ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE); +} + +} // namespace atom diff --git a/atom/browser/ui/file_dialog.h b/atom/browser/ui/file_dialog.h index b857648161..f65204c10e 100644 --- a/atom/browser/ui/file_dialog.h +++ b/atom/browser/ui/file_dialog.h @@ -23,10 +23,11 @@ typedef std::pair > Filter; typedef std::vector Filters; enum FileDialogProperty { - FILE_DIALOG_OPEN_FILE = 1 << 0, - FILE_DIALOG_OPEN_DIRECTORY = 1 << 1, - FILE_DIALOG_MULTI_SELECTIONS = 1 << 2, - FILE_DIALOG_CREATE_DIRECTORY = 1 << 3, + FILE_DIALOG_OPEN_FILE = 1 << 0, + FILE_DIALOG_OPEN_DIRECTORY = 1 << 1, + FILE_DIALOG_MULTI_SELECTIONS = 1 << 2, + FILE_DIALOG_CREATE_DIRECTORY = 1 << 3, + FILE_DIALOG_SHOW_HIDDEN_FILES = 1 << 4, }; typedef base::Callback(parent_window)), filters_(filters) { const char* confirm_text = GTK_STOCK_OK; @@ -58,9 +59,10 @@ class FileChooserDialog { GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, confirm_text, GTK_RESPONSE_ACCEPT, NULL); - if (parent_window) { - gfx::NativeWindow window = parent_window->GetNativeWindow(); - libgtk2ui::SetGtkTransientForAura(dialog_, window); + if (parent_) { + parent_->SetEnabled(false); + libgtk2ui::SetGtkTransientForAura(dialog_, parent_->GetNativeWindow()); + gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE); } if (action == GTK_FILE_CHOOSER_ACTION_SAVE) @@ -69,8 +71,6 @@ class FileChooserDialog { if (action != GTK_FILE_CHOOSER_ACTION_OPEN) gtk_file_chooser_set_create_folders(GTK_FILE_CHOOSER(dialog_), TRUE); - gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE); - if (!default_path.empty()) { if (base::DirectoryExists(default_path)) { gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog_), @@ -87,8 +87,17 @@ class FileChooserDialog { AddFilters(filters); } - virtual ~FileChooserDialog() { + ~FileChooserDialog() { gtk_widget_destroy(dialog_); + if (parent_) + parent_->SetEnabled(true); + } + + void SetupProperties(int properties) { + if (properties & FILE_DIALOG_MULTI_SELECTIONS) + gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog()), TRUE); + if (properties & FILE_DIALOG_SHOW_HIDDEN_FILES) + g_object_set(dialog(), "show-hidden", TRUE, NULL); } void RunAsynchronous() { @@ -143,7 +152,8 @@ class FileChooserDialog { void AddFilters(const Filters& filters); base::FilePath AddExtensionForFilename(const gchar* filename) const; - atom::NativeWindow::DialogScope dialog_scope_; + atom::NativeWindowViews* parent_; + atom::UnresponsiveSuppressor unresponsive_suppressor_; GtkWidget* dialog_; @@ -208,7 +218,9 @@ base::FilePath FileChooserDialog::AddExtensionForFilename( const auto& extensions = filters_[i].second; for (const auto& extension : extensions) { - if (extension == "*" || path.MatchesExtension("." + extension)) + if (extension == "*" || + base::EndsWith(path.value(), "." + extension, + base::CompareCase::INSENSITIVE_ASCII)) return path; } @@ -230,9 +242,7 @@ bool ShowOpenDialog(atom::NativeWindow* parent_window, action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER; FileChooserDialog open_dialog(action, parent_window, title, button_label, default_path, filters); - if (properties & FILE_DIALOG_MULTI_SELECTIONS) - gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(open_dialog.dialog()), - TRUE); + open_dialog.SetupProperties(properties); gtk_widget_show_all(open_dialog.dialog()); int response = gtk_dialog_run(GTK_DIALOG(open_dialog.dialog())); @@ -256,10 +266,7 @@ void ShowOpenDialog(atom::NativeWindow* parent_window, action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER; FileChooserDialog* open_dialog = new FileChooserDialog( action, parent_window, title, button_label, default_path, filters); - if (properties & FILE_DIALOG_MULTI_SELECTIONS) - gtk_file_chooser_set_select_multiple( - GTK_FILE_CHOOSER(open_dialog->dialog()), TRUE); - + open_dialog->SetupProperties(properties); open_dialog->RunOpenAsynchronous(callback); } diff --git a/atom/browser/ui/file_dialog_mac.mm b/atom/browser/ui/file_dialog_mac.mm index d674817a2a..398357b0b1 100644 --- a/atom/browser/ui/file_dialog_mac.mm +++ b/atom/browser/ui/file_dialog_mac.mm @@ -86,6 +86,8 @@ void SetupDialogForProperties(NSOpenPanel* dialog, int properties) { [dialog setCanCreateDirectories:YES]; if (properties & FILE_DIALOG_MULTI_SELECTIONS) [dialog setAllowsMultipleSelection:YES]; + if (properties & FILE_DIALOG_SHOW_HIDDEN_FILES) + [dialog setShowsHiddenFiles:YES]; } // Run modal dialog with parent window and return user's choice. diff --git a/atom/browser/ui/file_dialog_win.cc b/atom/browser/ui/file_dialog_win.cc index 5314b63a45..ff7d8f9723 100644 --- a/atom/browser/ui/file_dialog_win.cc +++ b/atom/browser/ui/file_dialog_win.cc @@ -10,6 +10,7 @@ #include #include "atom/browser/native_window_views.h" +#include "atom/browser/unresponsive_suppressor.h" #include "base/files/file_util.h" #include "base/i18n/case_conversion.h" #include "base/strings/string_util.h" @@ -108,7 +109,7 @@ class FileDialog { } bool Show(atom::NativeWindow* parent_window) { - atom::NativeWindow::DialogScope dialog_scope(parent_window); + atom::UnresponsiveSuppressor suppressor; HWND window = parent_window ? static_cast( parent_window)->GetAcceleratedWidget() : NULL; @@ -201,6 +202,8 @@ bool ShowOpenDialog(atom::NativeWindow* parent_window, options |= FOS_PICKFOLDERS; if (properties & FILE_DIALOG_MULTI_SELECTIONS) options |= FOS_ALLOWMULTISELECT; + if (properties & FILE_DIALOG_SHOW_HIDDEN_FILES) + options |= FOS_FORCESHOWHIDDEN; FileDialog open_dialog( default_path, title, button_label, filters, options); diff --git a/atom/browser/ui/message_box_gtk.cc b/atom/browser/ui/message_box_gtk.cc index b09ccdd482..8f11c94b7d 100644 --- a/atom/browser/ui/message_box_gtk.cc +++ b/atom/browser/ui/message_box_gtk.cc @@ -5,7 +5,8 @@ #include "atom/browser/ui/message_box.h" #include "atom/browser/browser.h" -#include "atom/browser/native_window.h" +#include "atom/browser/native_window_views.h" +#include "atom/browser/unresponsive_suppressor.h" #include "base/callback.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -35,8 +36,8 @@ class GtkMessageBox { const std::string& message, const std::string& detail, const gfx::ImageSkia& icon) - : dialog_scope_(parent_window), - cancel_id_(cancel_id) { + : cancel_id_(cancel_id), + parent_(static_cast(parent_window)) { // Create dialog. dialog_ = gtk_message_dialog_new( nullptr, // parent @@ -75,14 +76,17 @@ class GtkMessageBox { } // Parent window. - if (parent_window) { - gfx::NativeWindow window = parent_window->GetNativeWindow(); - libgtk2ui::SetGtkTransientForAura(dialog_, window); + if (parent_) { + parent_->SetEnabled(false); + libgtk2ui::SetGtkTransientForAura(dialog_, parent_->GetNativeWindow()); + gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE); } } ~GtkMessageBox() { gtk_widget_destroy(dialog_); + if (parent_) + parent_->SetEnabled(true); } GtkMessageType GetMessageType(MessageBoxType type) { @@ -123,7 +127,6 @@ class GtkMessageBox { } int RunSynchronous() { - gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE); Show(); int response = gtk_dialog_run(GTK_DIALOG(dialog_)); if (response < 0) @@ -144,11 +147,12 @@ class GtkMessageBox { CHROMEGTK_CALLBACK_1(GtkMessageBox, void, OnResponseDialog, int); private: - atom::NativeWindow::DialogScope dialog_scope_; + atom::UnresponsiveSuppressor unresponsive_suppressor_; // The id to return when the dialog is closed without pressing buttons. int cancel_id_; + NativeWindowViews* parent_; GtkWidget* dialog_; MessageBoxCallback callback_; diff --git a/atom/browser/ui/message_box_win.cc b/atom/browser/ui/message_box_win.cc index b966ef92a8..e5615fb1fc 100644 --- a/atom/browser/ui/message_box_win.cc +++ b/atom/browser/ui/message_box_win.cc @@ -12,6 +12,7 @@ #include "atom/browser/browser.h" #include "atom/browser/native_window_views.h" +#include "atom/browser/unresponsive_suppressor.h" #include "base/callback.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -198,7 +199,7 @@ int ShowMessageBox(NativeWindow* parent, static_cast(parent)->GetAcceleratedWidget() : NULL; - NativeWindow::DialogScope dialog_scope(parent); + atom::UnresponsiveSuppressor suppressor; return ShowMessageBoxUTF16(hwnd_parent, type, utf16_buttons, @@ -239,6 +240,7 @@ void ShowMessageBox(NativeWindow* parent, } void ShowErrorBox(const base::string16& title, const base::string16& content) { + atom::UnresponsiveSuppressor suppressor; ShowMessageBoxUTF16(NULL, MESSAGE_BOX_TYPE_ERROR, {}, -1, 0, 0, L"Error", title, content, gfx::ImageSkia()); } diff --git a/atom/browser/ui/tray_icon.cc b/atom/browser/ui/tray_icon.cc index dcdb90ac15..273f5c0843 100644 --- a/atom/browser/ui/tray_icon.cc +++ b/atom/browser/ui/tray_icon.cc @@ -18,7 +18,7 @@ void TrayIcon::SetPressedImage(ImageType image) { void TrayIcon::SetTitle(const std::string& title) { } -void TrayIcon::SetHighlightMode(bool highlight) { +void TrayIcon::SetHighlightMode(TrayIcon::HighlightMode mode) { } void TrayIcon::DisplayBalloon(ImageType icon, @@ -27,7 +27,11 @@ void TrayIcon::DisplayBalloon(ImageType icon, } void TrayIcon::PopUpContextMenu(const gfx::Point& pos, - ui::SimpleMenuModel* menu_model) { + AtomMenuModel* menu_model) { +} + +gfx::Rect TrayIcon::GetBounds() { + return gfx::Rect(); } void TrayIcon::NotifyClicked(const gfx::Rect& bounds, int modifiers) { @@ -64,6 +68,10 @@ void TrayIcon::NotifyDropFiles(const std::vector& files) { FOR_EACH_OBSERVER(TrayIconObserver, observers_, OnDropFiles(files)); } +void TrayIcon::NotifyDropText(const std::string& text) { + FOR_EACH_OBSERVER(TrayIconObserver, observers_, OnDropText(text)); +} + void TrayIcon::NotifyDragEntered() { FOR_EACH_OBSERVER(TrayIconObserver, observers_, OnDragEntered()); } diff --git a/atom/browser/ui/tray_icon.h b/atom/browser/ui/tray_icon.h index 1916c11b23..90e81657aa 100644 --- a/atom/browser/ui/tray_icon.h +++ b/atom/browser/ui/tray_icon.h @@ -8,9 +8,9 @@ #include #include +#include "atom/browser/ui/atom_menu_model.h" #include "atom/browser/ui/tray_icon_observer.h" #include "base/observer_list.h" -#include "ui/base/models/simple_menu_model.h" #include "ui/gfx/geometry/rect.h" namespace atom { @@ -43,9 +43,13 @@ class TrayIcon { // only works on macOS. virtual void SetTitle(const std::string& title); - // Sets whether the status icon is highlighted when it is clicked. This only - // works on macOS. - virtual void SetHighlightMode(bool highlight); + // Sets the status icon highlight mode. This only works on macOS. + enum HighlightMode { + ALWAYS, // Always highlight the tray icon + NEVER, // Never highlight the tray icon + SELECTION // Highlight the tray icon when clicked or the menu is opened + }; + virtual void SetHighlightMode(HighlightMode mode); // Displays a notification balloon with the specified contents. // Depending on the platform it might not appear by the icon tray. @@ -55,13 +59,17 @@ class TrayIcon { // Popups the menu. virtual void PopUpContextMenu(const gfx::Point& pos, - ui::SimpleMenuModel* menu_model); + AtomMenuModel* menu_model); // Set the context menu for this icon. - virtual void SetContextMenu(ui::SimpleMenuModel* menu_model) = 0; + virtual void SetContextMenu(AtomMenuModel* menu_model) = 0; + + // Returns the bounds of tray icon. + virtual gfx::Rect GetBounds(); void AddObserver(TrayIconObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(TrayIconObserver* obs) { observers_.RemoveObserver(obs); } + void NotifyClicked(const gfx::Rect& = gfx::Rect(), int modifiers = 0); void NotifyDoubleClicked(const gfx::Rect& = gfx::Rect(), int modifiers = 0); void NotifyBalloonShow(); @@ -71,6 +79,7 @@ class TrayIcon { int modifiers = 0); void NotifyDrop(); void NotifyDropFiles(const std::vector& files); + void NotifyDropText(const std::string& text); void NotifyDragEntered(); void NotifyDragExited(); void NotifyDragEnded(); diff --git a/atom/browser/ui/tray_icon_cocoa.h b/atom/browser/ui/tray_icon_cocoa.h index 59e2241aa4..fb66a6b3f1 100644 --- a/atom/browser/ui/tray_icon_cocoa.h +++ b/atom/browser/ui/tray_icon_cocoa.h @@ -9,7 +9,6 @@ #include -#include "atom/browser/ui/atom_menu_model.h" #include "atom/browser/ui/tray_icon.h" #include "base/mac/scoped_nsobject.h" @@ -28,10 +27,11 @@ class TrayIconCocoa : public TrayIcon, void SetPressedImage(const gfx::Image& image) override; void SetToolTip(const std::string& tool_tip) override; void SetTitle(const std::string& title) override; - void SetHighlightMode(bool highlight) override; + void SetHighlightMode(TrayIcon::HighlightMode mode) override; void PopUpContextMenu(const gfx::Point& pos, - ui::SimpleMenuModel* menu_model) override; - void SetContextMenu(ui::SimpleMenuModel* menu_model) override; + AtomMenuModel* menu_model) override; + void SetContextMenu(AtomMenuModel* menu_model) override; + gfx::Rect GetBounds() override; protected: // AtomMenuModel::Observer: diff --git a/atom/browser/ui/tray_icon_cocoa.mm b/atom/browser/ui/tray_icon_cocoa.mm index 0dfd59132a..5ac9050b62 100644 --- a/atom/browser/ui/tray_icon_cocoa.mm +++ b/atom/browser/ui/tray_icon_cocoa.mm @@ -8,7 +8,8 @@ #include "base/strings/sys_string_conversions.h" #include "ui/events/cocoa/cocoa_event_utils.h" #include "ui/gfx/image/image.h" -#include "ui/gfx/screen.h" +#include "ui/gfx/mac/coordinate_conversion.h" +#include "ui/display/screen.h" namespace { @@ -22,7 +23,7 @@ const CGFloat kVerticalTitleMargin = 2; @interface StatusItemView : NSView { atom::TrayIconCocoa* trayIcon_; // weak AtomMenuController* menuController_; // weak - BOOL isHighlightEnable_; + atom::TrayIcon::HighlightMode highlight_mode_; BOOL forceHighlight_; BOOL inMouseEventSequence_; base::scoped_nsobject image_; @@ -38,12 +39,15 @@ const CGFloat kVerticalTitleMargin = 2; - (id)initWithImage:(NSImage*)image icon:(atom::TrayIconCocoa*)icon { image_.reset([image copy]); trayIcon_ = icon; - isHighlightEnable_ = YES; + highlight_mode_ = atom::TrayIcon::HighlightMode::SELECTION; forceHighlight_ = NO; inMouseEventSequence_ = NO; if ((self = [super initWithFrame: CGRectZero])) { - [self registerForDraggedTypes: @[NSFilenamesPboardType]]; + [self registerForDraggedTypes: @[ + NSFilenamesPboardType, + NSStringPboardType, + ]]; // Create the status item. NSStatusItem * item = [[NSStatusBar systemStatusBar] @@ -188,8 +192,9 @@ const CGFloat kVerticalTitleMargin = 2; alternateImage_.reset([image copy]); } -- (void)setHighlight:(BOOL)highlight { - isHighlightEnable_ = highlight; +- (void)setHighlight:(atom::TrayIcon::HighlightMode)mode { + highlight_mode_ = mode; + [self setNeedsDisplay:YES]; } - (void)setTitle:(NSString*)title { @@ -236,23 +241,24 @@ const CGFloat kVerticalTitleMargin = 2; // Single click event. if (event.clickCount == 1) trayIcon_->NotifyClicked( - [self getBoundsFromEvent:event], + gfx::ScreenRectFromNSRect(event.window.frame), ui::EventFlagsFromModifiers([event modifierFlags])); // Double click event. if (event.clickCount == 2) trayIcon_->NotifyDoubleClicked( - [self getBoundsFromEvent:event], + gfx::ScreenRectFromNSRect(event.window.frame), ui::EventFlagsFromModifiers([event modifierFlags])); [self setNeedsDisplay:YES]; } -- (void)popUpContextMenu:(ui::SimpleMenuModel*)menu_model { +- (void)popUpContextMenu:(atom::AtomMenuModel*)menu_model { // Show a custom menu. if (menu_model) { base::scoped_nsobject menuController( - [[AtomMenuController alloc] initWithModel:menu_model]); + [[AtomMenuController alloc] initWithModel:menu_model + useDefaultAccelerator:NO]); forceHighlight_ = YES; // Should highlight when showing menu. [self setNeedsDisplay:YES]; [statusItem_ popUpStatusItemMenu:[menuController menu]]; @@ -262,7 +268,7 @@ const CGFloat kVerticalTitleMargin = 2; } if (menuController_ && ![menuController_ isMenuOpen]) { - // Redraw the dray icon to show highlight if it is enabled. + // Redraw the tray icon to show highlight if it is enabled. [self setNeedsDisplay:YES]; [statusItem_ popUpStatusItemMenu:[menuController_ menu]]; // The popUpStatusItemMenu returns only after the showing menu is closed. @@ -273,7 +279,7 @@ const CGFloat kVerticalTitleMargin = 2; - (void)rightMouseUp:(NSEvent*)event { trayIcon_->NotifyRightClicked( - [self getBoundsFromEvent:event], + gfx::ScreenRectFromNSRect(event.window.frame), ui::EventFlagsFromModifiers([event modifierFlags])); } @@ -305,7 +311,12 @@ const CGFloat kVerticalTitleMargin = 2; dropFiles.push_back(base::SysNSStringToUTF8(file)); trayIcon_->NotifyDropFiles(dropFiles); return YES; + } else if ([[pboard types] containsObject:NSStringPboardType]) { + NSString* dropText = [pboard stringForType:NSStringPboardType]; + trayIcon_->NotifyDropText(base::SysNSStringToUTF8(dropText)); + return YES; } + return NO; } @@ -318,19 +329,17 @@ const CGFloat kVerticalTitleMargin = 2; } - (BOOL)shouldHighlight { - if (isHighlightEnable_ && forceHighlight_) - return true; - BOOL isMenuOpen = menuController_ && [menuController_ isMenuOpen]; - return isHighlightEnable_ && (inMouseEventSequence_ || isMenuOpen); + switch (highlight_mode_) { + case atom::TrayIcon::HighlightMode::ALWAYS: + return true; + case atom::TrayIcon::HighlightMode::NEVER: + return false; + case atom::TrayIcon::HighlightMode::SELECTION: + BOOL isMenuOpen = menuController_ && [menuController_ isMenuOpen]; + return forceHighlight_ || inMouseEventSequence_ || isMenuOpen; + } } -- (gfx::Rect)getBoundsFromEvent:(NSEvent*)event { - NSRect frame = event.window.frame; - gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); - NSScreen* screen = [[NSScreen screens] objectAtIndex:0]; - bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); - return bounds; -} @end namespace atom { @@ -366,26 +375,36 @@ void TrayIconCocoa::SetTitle(const std::string& title) { [status_item_view_ setTitle:base::SysUTF8ToNSString(title)]; } -void TrayIconCocoa::SetHighlightMode(bool highlight) { - [status_item_view_ setHighlight:highlight]; +void TrayIconCocoa::SetHighlightMode(TrayIcon::HighlightMode mode) { + [status_item_view_ setHighlight:mode]; } void TrayIconCocoa::PopUpContextMenu(const gfx::Point& pos, - ui::SimpleMenuModel* menu_model) { + AtomMenuModel* menu_model) { [status_item_view_ popUpContextMenu:menu_model]; } -void TrayIconCocoa::SetContextMenu(ui::SimpleMenuModel* menu_model) { +void TrayIconCocoa::SetContextMenu(AtomMenuModel* menu_model) { // Substribe to MenuClosed event. if (menu_model_) menu_model_->RemoveObserver(this); - static_cast(menu_model)->AddObserver(this); + menu_model->AddObserver(this); // Create native menu. - menu_.reset([[AtomMenuController alloc] initWithModel:menu_model]); + menu_.reset([[AtomMenuController alloc] initWithModel:menu_model + useDefaultAccelerator:NO]); [status_item_view_ setMenuController:menu_.get()]; } +gfx::Rect TrayIconCocoa::GetBounds() { + auto bounds = gfx::ScreenRectFromNSRect([status_item_view_ window].frame); + // Calling [window frame] immediately after the view gets created will have + // negative |y| sometimes. + if (bounds.y() < 0) + bounds.set_y(0); + return bounds; +} + void TrayIconCocoa::MenuClosed() { [status_item_view_ setNeedsDisplay:YES]; } diff --git a/atom/browser/ui/tray_icon_gtk.cc b/atom/browser/ui/tray_icon_gtk.cc index 3e53390609..3286a95a7c 100644 --- a/atom/browser/ui/tray_icon_gtk.cc +++ b/atom/browser/ui/tray_icon_gtk.cc @@ -50,7 +50,7 @@ void TrayIconGtk::SetToolTip(const std::string& tool_tip) { icon_->SetToolTip(base::UTF8ToUTF16(tool_tip)); } -void TrayIconGtk::SetContextMenu(ui::SimpleMenuModel* menu_model) { +void TrayIconGtk::SetContextMenu(AtomMenuModel* menu_model) { icon_->UpdatePlatformContextMenu(menu_model); } diff --git a/atom/browser/ui/tray_icon_gtk.h b/atom/browser/ui/tray_icon_gtk.h index cfeb8ab3d0..8cb00363f0 100644 --- a/atom/browser/ui/tray_icon_gtk.h +++ b/atom/browser/ui/tray_icon_gtk.h @@ -25,7 +25,7 @@ class TrayIconGtk : public TrayIcon, // TrayIcon: void SetImage(const gfx::Image& image) override; void SetToolTip(const std::string& tool_tip) override; - void SetContextMenu(ui::SimpleMenuModel* menu_model) override; + void SetContextMenu(AtomMenuModel* menu_model) override; private: // views::StatusIconLinux::Delegate: diff --git a/atom/browser/ui/tray_icon_observer.h b/atom/browser/ui/tray_icon_observer.h index ed421ed854..1782e913d5 100644 --- a/atom/browser/ui/tray_icon_observer.h +++ b/atom/browser/ui/tray_icon_observer.h @@ -24,6 +24,7 @@ class TrayIconObserver { virtual void OnRightClicked(const gfx::Rect& bounds, int modifiers) {} virtual void OnDrop() {} virtual void OnDropFiles(const std::vector& files) {} + virtual void OnDropText(const std::string& text) {} virtual void OnDragEntered() {} virtual void OnDragExited() {} virtual void OnDragEnded() {} diff --git a/atom/browser/ui/views/global_menu_bar_x11.cc b/atom/browser/ui/views/global_menu_bar_x11.cc index b393e3f465..266d10b96d 100644 --- a/atom/browser/ui/views/global_menu_bar_x11.cc +++ b/atom/browser/ui/views/global_menu_bar_x11.cc @@ -16,6 +16,7 @@ #include #include "atom/browser/native_window_views.h" +#include "atom/browser/ui/atom_menu_model.h" #include "base/logging.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -23,7 +24,6 @@ #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/base/accelerators/menu_label_accelerator_util_linux.h" -#include "ui/base/models/menu_model.h" #include "ui/events/keycodes/keyboard_code_conversion_x.h" // libdbusmenu-glib types @@ -141,8 +141,8 @@ void EnsureMethodsLoaded() { dlsym(dbusmenu_lib, "dbusmenu_server_set_root")); } -ui::MenuModel* ModelForMenuItem(DbusmenuMenuitem* item) { - return reinterpret_cast( +AtomMenuModel* ModelForMenuItem(DbusmenuMenuitem* item) { + return reinterpret_cast( g_object_get_data(G_OBJECT(item), "model")); } @@ -188,7 +188,7 @@ std::string GlobalMenuBarX11::GetPathForWindow(gfx::AcceleratedWidget xid) { return base::StringPrintf("/com/canonical/menu/%lX", xid); } -void GlobalMenuBarX11::SetMenu(ui::MenuModel* menu_model) { +void GlobalMenuBarX11::SetMenu(AtomMenuModel* menu_model) { if (!IsServerStarted()) return; @@ -218,14 +218,14 @@ void GlobalMenuBarX11::OnWindowUnmapped() { GlobalMenuBarRegistrarX11::GetInstance()->OnWindowUnmapped(xid_); } -void GlobalMenuBarX11::BuildMenuFromModel(ui::MenuModel* model, +void GlobalMenuBarX11::BuildMenuFromModel(AtomMenuModel* model, DbusmenuMenuitem* parent) { for (int i = 0; i < model->GetItemCount(); ++i) { DbusmenuMenuitem* item = menuitem_new(); menuitem_property_set_bool(item, kPropertyVisible, model->IsVisibleAt(i)); - ui::MenuModel::ItemType type = model->GetTypeAt(i); - if (type == ui::MenuModel::TYPE_SEPARATOR) { + AtomMenuModel::ItemType type = model->GetTypeAt(i); + if (type == AtomMenuModel::TYPE_SEPARATOR) { menuitem_property_set(item, kPropertyType, kTypeSeparator); } else { std::string label = ui::ConvertAcceleratorsFromWindowsStyle( @@ -236,22 +236,22 @@ void GlobalMenuBarX11::BuildMenuFromModel(ui::MenuModel* model, g_object_set_data(G_OBJECT(item), "model", model); SetMenuItemID(item, i); - if (type == ui::MenuModel::TYPE_SUBMENU) { + if (type == AtomMenuModel::TYPE_SUBMENU) { menuitem_property_set(item, kPropertyChildrenDisplay, kDisplaySubmenu); g_signal_connect(item, "about-to-show", G_CALLBACK(OnSubMenuShowThunk), this); } else { ui::Accelerator accelerator; - if (model->GetAcceleratorAt(i, &accelerator)) + if (model->GetAcceleratorAtWithParams(i, true, &accelerator)) RegisterAccelerator(item, accelerator); g_signal_connect(item, "item-activated", G_CALLBACK(OnItemActivatedThunk), this); - if (type == ui::MenuModel::TYPE_CHECK || - type == ui::MenuModel::TYPE_RADIO) { + if (type == AtomMenuModel::TYPE_CHECK || + type == AtomMenuModel::TYPE_RADIO) { menuitem_property_set(item, kPropertyToggleType, - type == ui::MenuModel::TYPE_CHECK ? kToggleCheck : kToggleRadio); + type == AtomMenuModel::TYPE_CHECK ? kToggleCheck : kToggleRadio); menuitem_property_set_int(item, kPropertyToggleState, model->IsItemCheckedAt(i)); } @@ -296,14 +296,14 @@ void GlobalMenuBarX11::RegisterAccelerator(DbusmenuMenuitem* item, void GlobalMenuBarX11::OnItemActivated(DbusmenuMenuitem* item, unsigned int timestamp) { int id; - ui::MenuModel* model = ModelForMenuItem(item); + AtomMenuModel* model = ModelForMenuItem(item); if (model && GetMenuItemID(item, &id)) model->ActivatedAt(id, 0); } void GlobalMenuBarX11::OnSubMenuShow(DbusmenuMenuitem* item) { int id; - ui::MenuModel* model = ModelForMenuItem(item); + AtomMenuModel* model = ModelForMenuItem(item); if (!model || !GetMenuItemID(item, &id)) return; diff --git a/atom/browser/ui/views/global_menu_bar_x11.h b/atom/browser/ui/views/global_menu_bar_x11.h index 89b2680cab..9bb4dd3385 100644 --- a/atom/browser/ui/views/global_menu_bar_x11.h +++ b/atom/browser/ui/views/global_menu_bar_x11.h @@ -7,6 +7,7 @@ #include +#include "atom/browser/ui/atom_menu_model.h" #include "base/macros.h" #include "base/compiler_specific.h" #include "ui/base/glib/glib_signal.h" @@ -17,7 +18,6 @@ typedef struct _DbusmenuServer DbusmenuServer; namespace ui { class Accelerator; -class MenuModel; } namespace atom { @@ -43,7 +43,7 @@ class GlobalMenuBarX11 { // Creates the object path for DbusmenuServer which is attached to |xid|. static std::string GetPathForWindow(gfx::AcceleratedWidget xid); - void SetMenu(ui::MenuModel* menu_model); + void SetMenu(AtomMenuModel* menu_model); bool IsServerStarted() const; // Called by NativeWindow when it show/hides. @@ -55,7 +55,7 @@ class GlobalMenuBarX11 { void InitServer(gfx::AcceleratedWidget xid); // Create a menu from menu model. - void BuildMenuFromModel(ui::MenuModel* model, DbusmenuMenuitem* parent); + void BuildMenuFromModel(AtomMenuModel* model, DbusmenuMenuitem* parent); // Sets the accelerator for |item|. void RegisterAccelerator(DbusmenuMenuitem* item, diff --git a/atom/browser/ui/views/menu_bar.cc b/atom/browser/ui/views/menu_bar.cc index 872375ccbb..cb7af509cc 100644 --- a/atom/browser/ui/views/menu_bar.cc +++ b/atom/browser/ui/views/menu_bar.cc @@ -50,14 +50,7 @@ void GetMenuBarColor(SkColor* enabled, SkColor* disabled, SkColor* highlight, MenuBar::MenuBar() : background_color_(kDefaultColor), menu_model_(NULL) { -#if defined(OS_WIN) - background_color_ = color_utils::GetSysSkColor(COLOR_MENUBAR); -#elif defined(USE_X11) - GetMenuBarColor(&enabled_color_, &disabled_color_, &highlight_color_, - &hover_color_, &background_color_); -#endif - - set_background(views::Background::CreateSolidBackground(background_color_)); + UpdateMenuBarColor(); SetLayoutManager(new views::BoxLayout( views::BoxLayout::kHorizontal, 0, 0, 0)); } @@ -65,7 +58,7 @@ MenuBar::MenuBar() MenuBar::~MenuBar() { } -void MenuBar::SetMenu(ui::MenuModel* model) { +void MenuBar::SetMenu(AtomMenuModel* model) { menu_model_ = model; RemoveAllChildViews(true); @@ -112,7 +105,7 @@ int MenuBar::GetItemCount() const { } bool MenuBar::GetMenuButtonFromScreenPoint(const gfx::Point& point, - ui::MenuModel** menu_model, + AtomMenuModel** menu_model, views::MenuButton** button) { gfx::Point location(point); views::View::ConvertPointFromScreen(this, &location); @@ -124,7 +117,7 @@ bool MenuBar::GetMenuButtonFromScreenPoint(const gfx::Point& point, for (int i = 0; i < child_count(); ++i) { views::View* view = child_at(i); if (view->bounds().Contains(location) && - (menu_model_->GetTypeAt(i) == ui::MenuModel::TYPE_SUBMENU)) { + (menu_model_->GetTypeAt(i) == AtomMenuModel::TYPE_SUBMENU)) { *menu_model = menu_model_->GetSubmenuModelAt(i); *button = static_cast(view); return true; @@ -151,12 +144,28 @@ void MenuBar::OnMenuButtonClicked(views::MenuButton* source, return; int id = source->tag(); - ui::MenuModel::ItemType type = menu_model_->GetTypeAt(id); - if (type != ui::MenuModel::TYPE_SUBMENU) + AtomMenuModel::ItemType type = menu_model_->GetTypeAt(id); + if (type != AtomMenuModel::TYPE_SUBMENU) { + menu_model_->ActivatedAt(id, 0); return; + } MenuDelegate menu_delegate(this); menu_delegate.RunMenu(menu_model_->GetSubmenuModelAt(id), source); } +void MenuBar::OnNativeThemeChanged(const ui::NativeTheme* theme) { + UpdateMenuBarColor(); +} + +void MenuBar::UpdateMenuBarColor() { +#if defined(OS_WIN) + background_color_ = color_utils::GetSysSkColor(COLOR_MENUBAR); +#elif defined(USE_X11) + GetMenuBarColor(&enabled_color_, &disabled_color_, &highlight_color_, + &hover_color_, &background_color_); +#endif + set_background(views::Background::CreateSolidBackground(background_color_)); +} + } // namespace atom diff --git a/atom/browser/ui/views/menu_bar.h b/atom/browser/ui/views/menu_bar.h index 9f38a5981c..5b86e292c8 100644 --- a/atom/browser/ui/views/menu_bar.h +++ b/atom/browser/ui/views/menu_bar.h @@ -5,14 +5,11 @@ #ifndef ATOM_BROWSER_UI_VIEWS_MENU_BAR_H_ #define ATOM_BROWSER_UI_VIEWS_MENU_BAR_H_ +#include "atom/browser/ui/atom_menu_model.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/menu_button_listener.h" #include "ui/views/view.h" -namespace ui { -class MenuModel; -} - namespace views { class MenuButton; } @@ -29,7 +26,7 @@ class MenuBar : public views::View, virtual ~MenuBar(); // Replaces current menu with a new one. - void SetMenu(ui::MenuModel* menu_model); + void SetMenu(AtomMenuModel* menu_model); // Shows underline under accelerators. void SetAcceleratorVisibility(bool visible); @@ -46,7 +43,7 @@ class MenuBar : public views::View, // Get the menu under specified screen point. bool GetMenuButtonFromScreenPoint(const gfx::Point& point, - ui::MenuModel** menu_model, + AtomMenuModel** menu_model, views::MenuButton** button); protected: @@ -60,9 +57,11 @@ class MenuBar : public views::View, void OnMenuButtonClicked(views::MenuButton* source, const gfx::Point& point, const ui::Event* event) override; - + void OnNativeThemeChanged(const ui::NativeTheme* theme) override; private: + void UpdateMenuBarColor(); + SkColor background_color_; #if defined(USE_X11) @@ -72,7 +71,7 @@ class MenuBar : public views::View, SkColor hover_color_; #endif - ui::MenuModel* menu_model_; + AtomMenuModel* menu_model_; DISALLOW_COPY_AND_ASSIGN(MenuBar); }; diff --git a/atom/browser/ui/views/menu_delegate.cc b/atom/browser/ui/views/menu_delegate.cc index a107a69625..3a1a151b72 100644 --- a/atom/browser/ui/views/menu_delegate.cc +++ b/atom/browser/ui/views/menu_delegate.cc @@ -5,10 +5,10 @@ #include "atom/browser/ui/views/menu_delegate.h" #include "atom/browser/ui/views/menu_bar.h" +#include "atom/browser/ui/views/menu_model_adapter.h" #include "content/public/browser/browser_thread.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/controls/menu/menu_item_view.h" -#include "ui/views/controls/menu/menu_model_adapter.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/widget/widget.h" @@ -22,7 +22,7 @@ MenuDelegate::MenuDelegate(MenuBar* menu_bar) MenuDelegate::~MenuDelegate() { } -void MenuDelegate::RunMenu(ui::MenuModel* model, views::MenuButton* button) { +void MenuDelegate::RunMenu(AtomMenuModel* model, views::MenuButton* button) { gfx::Point screen_loc; views::View::ConvertPointToScreen(button, &screen_loc); // Subtract 1 from the height to make the popup flush with the button border. @@ -30,10 +30,10 @@ void MenuDelegate::RunMenu(ui::MenuModel* model, views::MenuButton* button) { button->height() - 1); id_ = button->tag(); - adapter_.reset(new views::MenuModelAdapter(model)); + adapter_.reset(new MenuModelAdapter(model)); views::MenuItemView* item = new views::MenuItemView(this); - static_cast(adapter_.get())->BuildMenu(item); + static_cast(adapter_.get())->BuildMenu(item); menu_runner_.reset(new views::MenuRunner( item, @@ -102,7 +102,7 @@ views::MenuItemView* MenuDelegate::GetSiblingMenu( bool* has_mnemonics, views::MenuButton**) { views::MenuButton* button; - ui::MenuModel* model; + AtomMenuModel* model; if (menu_bar_->GetMenuButtonFromScreenPoint(screen_point, &model, &button) && button->tag() != id_) { DCHECK(menu_runner_->IsRunning()); diff --git a/atom/browser/ui/views/menu_delegate.h b/atom/browser/ui/views/menu_delegate.h index ad7093b48f..f813f9cc7d 100644 --- a/atom/browser/ui/views/menu_delegate.h +++ b/atom/browser/ui/views/menu_delegate.h @@ -5,17 +5,15 @@ #ifndef ATOM_BROWSER_UI_VIEWS_MENU_DELEGATE_H_ #define ATOM_BROWSER_UI_VIEWS_MENU_DELEGATE_H_ -#include "base/memory/scoped_ptr.h" +#include + +#include "atom/browser/ui/atom_menu_model.h" #include "ui/views/controls/menu/menu_delegate.h" namespace views { class MenuRunner; } -namespace ui { -class MenuModel; -} - namespace atom { class MenuBar; @@ -25,7 +23,7 @@ class MenuDelegate : public views::MenuDelegate { explicit MenuDelegate(MenuBar* menu_bar); virtual ~MenuDelegate(); - void RunMenu(ui::MenuModel* model, views::MenuButton* button); + void RunMenu(AtomMenuModel* model, views::MenuButton* button); protected: // views::MenuDelegate: diff --git a/atom/browser/ui/views/menu_model_adapter.cc b/atom/browser/ui/views/menu_model_adapter.cc new file mode 100644 index 0000000000..303cdb9bab --- /dev/null +++ b/atom/browser/ui/views/menu_model_adapter.cc @@ -0,0 +1,28 @@ +// 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/ui/views/menu_model_adapter.h" + +namespace atom { + +MenuModelAdapter::MenuModelAdapter(AtomMenuModel* menu_model) + : views::MenuModelAdapter(menu_model), + menu_model_(menu_model) { +} + +MenuModelAdapter::~MenuModelAdapter() { +} + +bool MenuModelAdapter::GetAccelerator(int id, + ui::Accelerator* accelerator) const { + ui::MenuModel* model = menu_model_; + int index = 0; + if (ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index)) { + return static_cast(model)-> + GetAcceleratorAtWithParams(index, true, accelerator); + } + return false; +} + +} // namespace atom diff --git a/atom/browser/ui/views/menu_model_adapter.h b/atom/browser/ui/views/menu_model_adapter.h new file mode 100644 index 0000000000..4b87bc32fd --- /dev/null +++ b/atom/browser/ui/views/menu_model_adapter.h @@ -0,0 +1,29 @@ +// 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_UI_VIEWS_MENU_MODEL_ADAPTER_H_ +#define ATOM_BROWSER_UI_VIEWS_MENU_MODEL_ADAPTER_H_ + +#include "atom/browser/ui/atom_menu_model.h" +#include "ui/views/controls/menu/menu_model_adapter.h" + +namespace atom { + +class MenuModelAdapter : public views::MenuModelAdapter { + public: + explicit MenuModelAdapter(AtomMenuModel* menu_model); + virtual ~MenuModelAdapter(); + + protected: + bool GetAccelerator(int id, ui::Accelerator* accelerator) const override; + + private: + AtomMenuModel* menu_model_; + + DISALLOW_COPY_AND_ASSIGN(MenuModelAdapter); +}; + +} // namespace atom + +#endif // ATOM_BROWSER_UI_VIEWS_MENU_MODEL_ADAPTER_H_ diff --git a/atom/browser/ui/win/notify_icon.cc b/atom/browser/ui/win/notify_icon.cc index 1cc616216c..e62b682e3e 100644 --- a/atom/browser/ui/win/notify_icon.cc +++ b/atom/browser/ui/win/notify_icon.cc @@ -12,7 +12,8 @@ #include "ui/gfx/image/image.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" -#include "ui/gfx/screen.h" +#include "ui/display/screen.h" +#include "ui/display/win/screen_win.h" #include "ui/views/controls/menu/menu_runner.h" namespace atom { @@ -48,26 +49,19 @@ NotifyIcon::~NotifyIcon() { void NotifyIcon::HandleClickEvent(int modifiers, bool left_mouse_click, bool double_button_click) { - NOTIFYICONIDENTIFIER icon_id; - memset(&icon_id, 0, sizeof(NOTIFYICONIDENTIFIER)); - icon_id.uID = icon_id_; - icon_id.hWnd = window_; - icon_id.cbSize = sizeof(NOTIFYICONIDENTIFIER); - - RECT rect = { 0 }; - Shell_NotifyIconGetRect(&icon_id, &rect); + gfx::Rect bounds = GetBounds(); if (left_mouse_click) { if (double_button_click) // double left click - NotifyDoubleClicked(gfx::Rect(rect), modifiers); + NotifyDoubleClicked(bounds, modifiers); else // single left click - NotifyClicked(gfx::Rect(rect), modifiers); + NotifyClicked(bounds, modifiers); return; } else if (!double_button_click) { // single right click if (menu_model_) PopUpContextMenu(gfx::Point(), menu_model_); else - NotifyRightClicked(gfx::Rect(rect), modifiers); + NotifyRightClicked(bounds, modifiers); } } @@ -138,10 +132,11 @@ void NotifyIcon::DisplayBalloon(HICON icon, } void NotifyIcon::PopUpContextMenu(const gfx::Point& pos, - ui::SimpleMenuModel* menu_model) { + AtomMenuModel* menu_model) { // Returns if context menu isn't set. - if (!menu_model) + if (menu_model == nullptr && menu_model_ == nullptr) return; + // Set our window as the foreground window, so the context menu closes when // we click away from it. if (!SetForegroundWindow(window_)) @@ -150,19 +145,31 @@ void NotifyIcon::PopUpContextMenu(const gfx::Point& pos, // Show menu at mouse's position by default. gfx::Rect rect(pos, gfx::Size()); if (pos.IsOrigin()) - rect.set_origin(gfx::Screen::GetScreen()->GetCursorScreenPoint()); + rect.set_origin(display::Screen::GetScreen()->GetCursorScreenPoint()); views::MenuRunner menu_runner( - menu_model, + menu_model != nullptr ? menu_model : menu_model_, views::MenuRunner::CONTEXT_MENU | views::MenuRunner::HAS_MNEMONICS); ignore_result(menu_runner.RunMenuAt( NULL, NULL, rect, views::MENU_ANCHOR_TOPLEFT, ui::MENU_SOURCE_MOUSE)); } -void NotifyIcon::SetContextMenu(ui::SimpleMenuModel* menu_model) { +void NotifyIcon::SetContextMenu(AtomMenuModel* menu_model) { menu_model_ = menu_model; } +gfx::Rect NotifyIcon::GetBounds() { + NOTIFYICONIDENTIFIER icon_id; + memset(&icon_id, 0, sizeof(NOTIFYICONIDENTIFIER)); + icon_id.uID = icon_id_; + icon_id.hWnd = window_; + icon_id.cbSize = sizeof(NOTIFYICONIDENTIFIER); + + RECT rect = { 0 }; + Shell_NotifyIconGetRect(&icon_id, &rect); + return display::win::ScreenWin::ScreenToDIPRect(window_, gfx::Rect(rect)); +} + void NotifyIcon::InitIconData(NOTIFYICONDATA* icon_data) { memset(icon_data, 0, sizeof(NOTIFYICONDATA)); icon_data->cbSize = sizeof(NOTIFYICONDATA); diff --git a/atom/browser/ui/win/notify_icon.h b/atom/browser/ui/win/notify_icon.h index 95e9945a17..ae6c9ca8a1 100644 --- a/atom/browser/ui/win/notify_icon.h +++ b/atom/browser/ui/win/notify_icon.h @@ -13,7 +13,6 @@ #include "atom/browser/ui/tray_icon.h" #include "base/macros.h" #include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" #include "base/win/scoped_gdi_object.h" namespace gfx { @@ -52,8 +51,9 @@ class NotifyIcon : public TrayIcon { const base::string16& title, const base::string16& contents) override; void PopUpContextMenu(const gfx::Point& pos, - ui::SimpleMenuModel* menu_model) override; - void SetContextMenu(ui::SimpleMenuModel* menu_model) override; + AtomMenuModel* menu_model) override; + void SetContextMenu(AtomMenuModel* menu_model) override; + gfx::Rect GetBounds() override; private: void InitIconData(NOTIFYICONDATA* icon_data); @@ -74,7 +74,7 @@ class NotifyIcon : public TrayIcon { base::win::ScopedHICON icon_; // The context menu. - ui::SimpleMenuModel* menu_model_; + AtomMenuModel* menu_model_; DISALLOW_COPY_AND_ASSIGN(NotifyIcon); }; diff --git a/atom/browser/ui/win/taskbar_host.cc b/atom/browser/ui/win/taskbar_host.cc index 78bcc578c1..8fef5e08a3 100644 --- a/atom/browser/ui/win/taskbar_host.cc +++ b/atom/browser/ui/win/taskbar_host.cc @@ -142,6 +142,22 @@ bool TaskbarHost::SetOverlayIcon( window, icon.get(), base::UTF8ToUTF16(text).c_str())); } +bool TaskbarHost::SetThumbnailClip(HWND window, const gfx::Rect& region) { + if (!InitializeTaskbar()) + return false; + + if (region.IsEmpty()) { + return SUCCEEDED(taskbar_->SetThumbnailClip(window, NULL)); + } else { + RECT rect; + rect.left = region.x(); + rect.right = region.right(); + rect.top = region.y(); + rect.bottom = region.bottom(); + return SUCCEEDED(taskbar_->SetThumbnailClip(window, &rect)); + } +} + bool TaskbarHost::HandleThumbarButtonEvent(int button_id) { if (ContainsKey(callback_map_, button_id)) { auto callback = callback_map_[button_id]; diff --git a/atom/browser/ui/win/taskbar_host.h b/atom/browser/ui/win/taskbar_host.h index 0cd5aa714f..c10e05f764 100644 --- a/atom/browser/ui/win/taskbar_host.h +++ b/atom/browser/ui/win/taskbar_host.h @@ -13,6 +13,7 @@ #include "base/callback.h" #include "base/win/scoped_comptr.h" +#include "ui/gfx/geometry/rect.h" #include "ui/gfx/image/image.h" namespace atom { @@ -40,6 +41,9 @@ class TaskbarHost { bool SetOverlayIcon( HWND window, const gfx::Image& overlay, const std::string& text); + // Set the region of the window to show as a thumbnail in taskbar. + bool TaskbarHost::SetThumbnailClip(HWND window, const gfx::Rect& region); + // Called by the window that there is a button in thumbar clicked. bool HandleThumbarButtonEvent(int button_id); diff --git a/atom/browser/unresponsive_suppressor.cc b/atom/browser/unresponsive_suppressor.cc new file mode 100644 index 0000000000..89bfa6b900 --- /dev/null +++ b/atom/browser/unresponsive_suppressor.cc @@ -0,0 +1,27 @@ +// 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/unresponsive_suppressor.h" + +namespace atom { + +namespace { + +int g_suppress_level = 0; + +} // namespace + +bool IsUnresponsiveEventSuppressed() { + return g_suppress_level > 0; +} + +UnresponsiveSuppressor::UnresponsiveSuppressor() { + g_suppress_level++; +} + +UnresponsiveSuppressor::~UnresponsiveSuppressor() { + g_suppress_level--; +} + +} // namespace atom diff --git a/atom/browser/unresponsive_suppressor.h b/atom/browser/unresponsive_suppressor.h new file mode 100644 index 0000000000..9fb3819237 --- /dev/null +++ b/atom/browser/unresponsive_suppressor.h @@ -0,0 +1,25 @@ +// 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_UNRESPONSIVE_SUPPRESSOR_H_ +#define ATOM_BROWSER_UNRESPONSIVE_SUPPRESSOR_H_ + +#include "base/macros.h" + +namespace atom { + +bool IsUnresponsiveEventSuppressed(); + +class UnresponsiveSuppressor { + public: + UnresponsiveSuppressor(); + ~UnresponsiveSuppressor(); + + private: + DISALLOW_COPY_AND_ASSIGN(UnresponsiveSuppressor); +}; + +} // namespace atom + +#endif // ATOM_BROWSER_UNRESPONSIVE_SUPPRESSOR_H_ diff --git a/atom/browser/web_contents_preferences.cc b/atom/browser/web_contents_preferences.cc index 8a7eee0920..978ca22e86 100644 --- a/atom/browser/web_contents_preferences.cc +++ b/atom/browser/web_contents_preferences.cc @@ -79,12 +79,6 @@ void WebContentsPreferences::AppendExtraCommandLineSwitches( base::DictionaryValue& web_preferences = self->web_preferences_; bool b; -#if defined(OS_WIN) - // Check if DirectWrite is disabled. - if (web_preferences.GetBoolean(options::kDirectWrite, &b) && !b) - command_line->AppendSwitch(::switches::kDisableDirectWrite); -#endif - // Check if plugins are enabled. if (web_preferences.GetBoolean("plugins", &b) && b) command_line->AppendSwitch(switches::kEnablePlugins); diff --git a/atom/browser/web_view_guest_delegate.cc b/atom/browser/web_view_guest_delegate.cc index 11f8219bf0..7f5a9261b9 100644 --- a/atom/browser/web_view_guest_delegate.cc +++ b/atom/browser/web_view_guest_delegate.cc @@ -7,6 +7,7 @@ #include "atom/browser/api/atom_api_web_contents.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "content/public/browser/guest_host.h" +#include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" @@ -95,10 +96,13 @@ void WebViewGuestDelegate::SetSize(const SetSizeParams& params) { auto_size_enabled_ = enable_auto_size; } -void WebViewGuestDelegate::DidCommitProvisionalLoadForFrame( - content::RenderFrameHost* render_frame_host, - const GURL& url, ui::PageTransition transition_type) { - api_web_contents_->Emit("load-commit", url, !render_frame_host->GetParent()); +void WebViewGuestDelegate::DidFinishNavigation( + content::NavigationHandle* navigation_handle) { + if (navigation_handle->HasCommitted() && !navigation_handle->IsErrorPage()) { + auto is_main_frame = navigation_handle->IsInMainFrame(); + auto url = navigation_handle->GetURL(); + api_web_contents_->Emit("load-commit", url, is_main_frame); + } } void WebViewGuestDelegate::DidAttach(int guest_proxy_routing_id) { diff --git a/atom/browser/web_view_guest_delegate.h b/atom/browser/web_view_guest_delegate.h index d65eb14635..f63a46cf76 100644 --- a/atom/browser/web_view_guest_delegate.h +++ b/atom/browser/web_view_guest_delegate.h @@ -47,9 +47,8 @@ class WebViewGuestDelegate : public content::BrowserPluginGuestDelegate, protected: // content::WebContentsObserver: - void DidCommitProvisionalLoadForFrame( - content::RenderFrameHost* render_frame_host, - const GURL& url, ui::PageTransition transition_type) override; + void DidFinishNavigation( + content::NavigationHandle* navigation_handle) override; // content::BrowserPluginGuestDelegate: void DidAttach(int guest_proxy_routing_id) final; diff --git a/atom/browser/window_list.cc b/atom/browser/window_list.cc index b3bec5d08c..83bf615aad 100644 --- a/atom/browser/window_list.cc +++ b/atom/browser/window_list.cc @@ -17,7 +17,7 @@ base::LazyInstance>::Leaky WindowList::observers_ = LAZY_INSTANCE_INITIALIZER; // static -WindowList* WindowList::instance_ = NULL; +WindowList* WindowList::instance_ = nullptr; // static WindowList* WindowList::GetInstance() { @@ -70,8 +70,8 @@ void WindowList::RemoveObserver(WindowListObserver* observer) { // static void WindowList::CloseAllWindows() { WindowVector windows = GetInstance()->windows_; - for (size_t i = 0; i < windows.size(); ++i) - windows[i]->Close(); + for (const auto& window : windows) + window->Close(); } WindowList::WindowList() { diff --git a/atom/common/api/api_messages.h b/atom/common/api/api_messages.h index ab27d5a251..7a9fdb04eb 100644 --- a/atom/common/api/api_messages.h +++ b/atom/common/api/api_messages.h @@ -39,5 +39,7 @@ IPC_MESSAGE_ROUTED3(AtomViewMsg_Message, IPC_MESSAGE_ROUTED1(AtomViewHostMsg_UpdateDraggableRegions, std::vector /* regions */) +IPC_MESSAGE_ROUTED0(AtomViewHostMsg_DidCommitCompositorFrame) + // Update renderer process preferences. IPC_MESSAGE_CONTROL1(AtomMsg_UpdatePreferences, base::ListValue) diff --git a/atom/common/api/atom_api_clipboard.cc b/atom/common/api/atom_api_clipboard.cc index cb413800be..01e670be92 100644 --- a/atom/common/api/atom_api_clipboard.cc +++ b/atom/common/api/atom_api_clipboard.cc @@ -54,12 +54,16 @@ std::string Read(const std::string& format_string, void Write(const mate::Dictionary& data, mate::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardType(args)); - base::string16 text, html; + base::string16 text, html, bookmark; gfx::Image image; - if (data.Get("text", &text)) + if (data.Get("text", &text)) { writer.WriteText(text); + if (data.Get("bookmark", &bookmark)) + writer.WriteBookmark(bookmark, base::UTF16ToUTF8(text)); + } + if (data.Get("rtf", &text)) { std::string rtf = base::UTF16ToUTF8(text); writer.WriteRTF(rtf); @@ -122,6 +126,23 @@ void WriteHtml(const base::string16& html, mate::Arguments* args) { writer.WriteHTML(html, std::string()); } +v8::Local ReadBookmark(mate::Arguments* args) { + base::string16 title; + std::string url; + mate::Dictionary dict = mate::Dictionary::CreateEmpty(args->isolate()); + ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); + clipboard->ReadBookmark(&title, &url); + dict.Set("title", title); + dict.Set("url", url); + return dict.GetHandle(); +} + +void WriteBookmark(const base::string16& title, const std::string& url, + mate::Arguments* args) { + ui::ScopedClipboardWriter writer(GetClipboardType(args)); + writer.WriteBookmark(title, url); +} + gfx::Image ReadImage(mate::Arguments* args) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); SkBitmap bitmap = clipboard->ReadImage(GetClipboardType(args)); @@ -150,6 +171,8 @@ void Initialize(v8::Local exports, v8::Local unused, dict.SetMethod("writeRTF", &WriteRtf); dict.SetMethod("readHTML", &ReadHtml); dict.SetMethod("writeHTML", &WriteHtml); + dict.SetMethod("readBookmark", &ReadBookmark); + dict.SetMethod("writeBookmark", &WriteBookmark); dict.SetMethod("readImage", &ReadImage); dict.SetMethod("writeImage", &WriteImage); dict.SetMethod("clear", &Clear); diff --git a/atom/common/api/atom_api_native_image.cc b/atom/common/api/atom_api_native_image.cc index c0b51ba2af..10a1c181b3 100644 --- a/atom/common/api/atom_api_native_image.cc +++ b/atom/common/api/atom_api_native_image.cc @@ -63,10 +63,10 @@ float GetScaleFactorFromPath(const base::FilePath& path) { // We don't try to convert string to float here because it is very very // expensive. - for (unsigned i = 0; i < node::arraysize(kScaleFactorPairs); ++i) { - if (base::EndsWith(filename, kScaleFactorPairs[i].name, + for (const auto& kScaleFactorPair : kScaleFactorPairs) { + if (base::EndsWith(filename, kScaleFactorPair.name, base::CompareCase::INSENSITIVE_ASCII)) - return kScaleFactorPairs[i].scale; + return kScaleFactorPair.scale; } return 1.0f; @@ -81,7 +81,7 @@ bool AddImageSkiaRep(gfx::ImageSkia* image, // Try PNG first. if (!gfx::PNGCodec::Decode(data, size, decoded.get())) // Try JPEG. - decoded.reset(gfx::JPEGCodec::Decode(data, size)); + decoded = gfx::JPEGCodec::Decode(data, size); if (!decoded) return false; @@ -160,10 +160,14 @@ base::win::ScopedHICON ReadICOFromPath(int size, const base::FilePath& path) { LR_LOADFROMFILE))); } -void ReadImageSkiaFromICO(gfx::ImageSkia* image, HICON icon) { +bool ReadImageSkiaFromICO(gfx::ImageSkia* image, HICON icon) { // Convert the icon from the Windows specific HICON to gfx::ImageSkia. std::unique_ptr bitmap(IconUtil::CreateSkBitmapFromHICON(icon)); + if (!bitmap) + return false; + image->AddRepresentation(gfx::ImageSkiaRep(*bitmap, 1.0f)); + return true; } #endif @@ -344,14 +348,17 @@ mate::Handle NativeImage::CreateFromDataURL( void NativeImage::BuildPrototype( v8::Isolate* isolate, v8::Local prototype) { mate::ObjectTemplateBuilder(isolate, prototype) - .SetMethod("toPng", &NativeImage::ToPNG) - .SetMethod("toJpeg", &NativeImage::ToJPEG) + .SetMethod("toPNG", &NativeImage::ToPNG) + .SetMethod("toJPEG", &NativeImage::ToJPEG) .SetMethod("getNativeHandle", &NativeImage::GetNativeHandle) .SetMethod("toDataURL", &NativeImage::ToDataURL) .SetMethod("isEmpty", &NativeImage::IsEmpty) .SetMethod("getSize", &NativeImage::GetSize) .SetMethod("setTemplateImage", &NativeImage::SetTemplateImage) - .SetMethod("isTemplateImage", &NativeImage::IsTemplateImage); + .SetMethod("isTemplateImage", &NativeImage::IsTemplateImage) + // TODO(kevinsawicki): Remove in 2.0, deprecate before then with warnings + .SetMethod("toPng", &NativeImage::ToPNG) + .SetMethod("toJpeg", &NativeImage::ToJPEG); } } // namespace api diff --git a/atom/common/api/atom_api_shell.cc b/atom/common/api/atom_api_shell.cc index f99e2ba185..2d9d6e0269 100644 --- a/atom/common/api/atom_api_shell.cc +++ b/atom/common/api/atom_api_shell.cc @@ -7,12 +7,47 @@ #include "atom/common/platform_util.h" #include "atom/common/native_mate_converters/file_path_converter.h" #include "atom/common/native_mate_converters/gurl_converter.h" +#include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/node_includes.h" #include "native_mate/dictionary.h" +#if defined(OS_WIN) +#include "base/win/scoped_com_initializer.h" +#include "base/win/shortcut.h" + +namespace mate { + +template<> +struct Converter { + static bool FromV8(v8::Isolate* isolate, v8::Handle val, + base::win::ShortcutOperation* out) { + std::string operation; + if (!ConvertFromV8(isolate, val, & operation)) + return false; + if (operation.empty() || operation == "create") + *out = base::win::SHORTCUT_CREATE_ALWAYS; + else if (operation == "update") + *out = base::win::SHORTCUT_UPDATE_EXISTING; + else if (operation == "replace") + *out = base::win::SHORTCUT_REPLACE_EXISTING; + else + return false; + return true; + } +}; + +} // namespace mate +#endif + namespace { -bool OpenExternal(const GURL& url, mate::Arguments* args) { +bool OpenExternal( +#if defined(OS_WIN) + const base::string16& url, +#else + const GURL& url, +#endif + mate::Arguments* args) { bool activate = true; if (args->Length() == 2) { mate::Dictionary options; @@ -23,6 +58,61 @@ bool OpenExternal(const GURL& url, mate::Arguments* args) { return platform_util::OpenExternal(url, activate); } +#if defined(OS_WIN) +bool WriteShortcutLink(const base::FilePath& shortcut_path, + mate::Arguments* args) { + base::win::ShortcutOperation operation = base::win::SHORTCUT_CREATE_ALWAYS; + args->GetNext(&operation); + mate::Dictionary options = mate::Dictionary::CreateEmpty(args->isolate()); + if (!args->GetNext(&options)) { + args->ThrowError(); + return false; + } + + base::win::ShortcutProperties properties; + base::FilePath path; + base::string16 str; + int index; + if (options.Get("target", &path)) + properties.set_target(path); + if (options.Get("cwd", &path)) + properties.set_working_dir(path); + if (options.Get("args", &str)) + properties.set_arguments(str); + if (options.Get("description", &str)) + properties.set_description(str); + if (options.Get("icon", &path) && options.Get("iconIndex", &index)) + properties.set_icon(path, index); + if (options.Get("appUserModelId", &str)) + properties.set_app_id(str); + + base::win::ScopedCOMInitializer com_initializer; + return base::win::CreateOrUpdateShortcutLink( + shortcut_path, properties, operation); +} + +v8::Local ReadShortcutLink(mate::Arguments* args, + const base::FilePath& path) { + using base::win::ShortcutProperties; + mate::Dictionary options = mate::Dictionary::CreateEmpty(args->isolate()); + base::win::ScopedCOMInitializer com_initializer; + base::win::ShortcutProperties properties; + if (!base::win::ResolveShortcutProperties( + path, ShortcutProperties::PROPERTIES_ALL, &properties)) { + args->ThrowError("Failed to read shortcut link"); + return v8::Null(args->isolate()); + } + options.Set("target", properties.target); + options.Set("cwd", properties.working_dir); + options.Set("args", properties.arguments); + options.Set("description", properties.description); + options.Set("icon", properties.icon); + options.Set("iconIndex", properties.icon_index); + options.Set("appUserModelId", properties.app_id); + return options.GetHandle(); +} +#endif + void Initialize(v8::Local exports, v8::Local unused, v8::Local context, void* priv) { mate::Dictionary dict(context->GetIsolate(), exports); @@ -31,6 +121,10 @@ void Initialize(v8::Local exports, v8::Local unused, dict.SetMethod("openExternal", &OpenExternal); dict.SetMethod("moveItemToTrash", &platform_util::MoveItemToTrash); dict.SetMethod("beep", &platform_util::Beep); +#if defined(OS_WIN) + dict.SetMethod("writeShortcutLink", &WriteShortcutLink); + dict.SetMethod("readShortcutLink", &ReadShortcutLink); +#endif } } // namespace diff --git a/atom/common/api/atom_bindings.cc b/atom/common/api/atom_bindings.cc index 599fc67498..b5a51ad507 100644 --- a/atom/common/api/atom_bindings.cc +++ b/atom/common/api/atom_bindings.cc @@ -25,7 +25,7 @@ namespace { struct DummyClass { bool crash; }; void Crash() { - static_cast(NULL)->crash = true; + static_cast(nullptr)->crash = true; } void Hang() { diff --git a/atom/common/api/event_emitter_caller.cc b/atom/common/api/event_emitter_caller.cc index 271ea705e0..40448cad10 100644 --- a/atom/common/api/event_emitter_caller.cc +++ b/atom/common/api/event_emitter_caller.cc @@ -6,7 +6,6 @@ #include "atom/common/api/locker.h" #include "atom/common/node_includes.h" -#include "base/memory/scoped_ptr.h" namespace mate { @@ -16,11 +15,8 @@ v8::Local CallEmitWithArgs(v8::Isolate* isolate, v8::Local obj, ValueVector* args) { // Perform microtask checkpoint after running JavaScript. - std::unique_ptr script_scope( - Locker::IsBrowserProcess() ? - nullptr : - new v8::MicrotasksScope(isolate, - v8::MicrotasksScope::kRunMicrotasks)); + v8::MicrotasksScope script_scope( + isolate, v8::MicrotasksScope::kRunMicrotasks); // Use node::MakeCallback to call the callback, and it will also run pending // tasks in Node.js. return node::MakeCallback( diff --git a/atom/common/asar/archive.cc b/atom/common/asar/archive.cc index c2306c3c8f..e622effe5d 100644 --- a/atom/common/asar/archive.cc +++ b/atom/common/asar/archive.cc @@ -41,7 +41,7 @@ bool GetFilesNode(const base::DictionaryValue* root, // Test for symbol linked directory. std::string link; if (dir->GetStringWithoutPathExpansion("link", &link)) { - const base::DictionaryValue* linked_node = NULL; + const base::DictionaryValue* linked_node = nullptr; if (!GetNodeFromPath(link, root, &linked_node)) return false; dir = linked_node; @@ -60,7 +60,7 @@ bool GetChildNode(const base::DictionaryValue* root, return true; } - const base::DictionaryValue* files = NULL; + const base::DictionaryValue* files = nullptr; return GetFilesNode(root, dir, &files) && files->GetDictionaryWithoutPathExpansion(name, out); } @@ -78,7 +78,7 @@ bool GetNodeFromPath(std::string path, for (size_t delimiter_position = path.find_first_of(kSeparators); delimiter_position != std::string::npos; delimiter_position = path.find_first_of(kSeparators)) { - const base::DictionaryValue* child = NULL; + const base::DictionaryValue* child = nullptr; if (!GetChildNode(root, path.substr(0, delimiter_position), dir, &child)) return false; diff --git a/atom/common/asar/archive.h b/atom/common/asar/archive.h index 5438776885..9e3abc3434 100644 --- a/atom/common/asar/archive.h +++ b/atom/common/asar/archive.h @@ -5,12 +5,12 @@ #ifndef ATOM_COMMON_ASAR_ARCHIVE_H_ #define ATOM_COMMON_ASAR_ARCHIVE_H_ +#include #include #include "base/containers/scoped_ptr_hash_map.h" #include "base/files/file.h" #include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" namespace base { class DictionaryValue; diff --git a/atom/common/atom_version.h b/atom/common/atom_version.h index d649af2a6e..ddf222faf1 100644 --- a/atom/common/atom_version.h +++ b/atom/common/atom_version.h @@ -6,8 +6,8 @@ #define ATOM_VERSION_H #define ATOM_MAJOR_VERSION 1 -#define ATOM_MINOR_VERSION 2 -#define ATOM_PATCH_VERSION 3 +#define ATOM_MINOR_VERSION 3 +#define ATOM_PATCH_VERSION 1 #define ATOM_VERSION_IS_RELEASE 1 diff --git a/atom/common/chrome_version.h b/atom/common/chrome_version.h index 3c3b780b9c..96186adc4f 100644 --- a/atom/common/chrome_version.h +++ b/atom/common/chrome_version.h @@ -8,7 +8,7 @@ #ifndef ATOM_COMMON_CHROME_VERSION_H_ #define ATOM_COMMON_CHROME_VERSION_H_ -#define CHROME_VERSION_STRING "51.0.2704.103" +#define CHROME_VERSION_STRING "52.0.2743.82" #define CHROME_VERSION "v" CHROME_VERSION_STRING #endif // ATOM_COMMON_CHROME_VERSION_H_ diff --git a/atom/common/crash_reporter/crash_reporter_linux.h b/atom/common/crash_reporter/crash_reporter_linux.h index b74103ccbf..de5a50e719 100644 --- a/atom/common/crash_reporter/crash_reporter_linux.h +++ b/atom/common/crash_reporter/crash_reporter_linux.h @@ -5,12 +5,12 @@ #ifndef ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_LINUX_H_ #define ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_LINUX_H_ +#include #include #include "atom/common/crash_reporter/crash_reporter.h" #include "atom/common/crash_reporter/linux/crash_dump_handler.h" #include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" namespace base { template struct DefaultSingletonTraits; diff --git a/atom/common/crash_reporter/crash_reporter_mac.h b/atom/common/crash_reporter/crash_reporter_mac.h index 5556263cd3..8acf50285d 100644 --- a/atom/common/crash_reporter/crash_reporter_mac.h +++ b/atom/common/crash_reporter/crash_reporter_mac.h @@ -10,7 +10,6 @@ #include "atom/common/crash_reporter/crash_reporter.h" #include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string_piece.h" #include "vendor/crashpad/client/simple_string_dictionary.h" diff --git a/atom/common/crash_reporter/crash_reporter_win.cc b/atom/common/crash_reporter/crash_reporter_win.cc index 4264f6af9d..3261f9c9c6 100644 --- a/atom/common/crash_reporter/crash_reporter_win.cc +++ b/atom/common/crash_reporter/crash_reporter_win.cc @@ -137,7 +137,9 @@ void UnregisterNonABICompliantCodeRange(void* start) { } // namespace -CrashReporterWin::CrashReporterWin() { +CrashReporterWin::CrashReporterWin() + : skip_system_crash_handler_(false), + code_range_registered_(false) { } CrashReporterWin::~CrashReporterWin() { @@ -188,19 +190,20 @@ void CrashReporterWin::InitBreakpad(const std::string& product_name, LOG(ERROR) << "Cannot initialize out-of-process crash handler"; #ifdef _WIN64 - bool registered = false; // Hook up V8 to breakpad. - { + if (!code_range_registered_) { + code_range_registered_ = true; // gin::Debug::SetCodeRangeCreatedCallback only runs the callback when // Isolate is just created, so we have to manually run following code here. void* code_range = nullptr; size_t size = 0; v8::Isolate::GetCurrent()->GetCodeRange(&code_range, &size); - if (code_range && size) - registered = RegisterNonABICompliantCodeRange(code_range, size); + if (code_range && size && + RegisterNonABICompliantCodeRange(code_range, size)) { + gin::Debug::SetCodeRangeDeletedCallback( + UnregisterNonABICompliantCodeRange); + } } - if (registered) - gin::Debug::SetCodeRangeDeletedCallback(UnregisterNonABICompliantCodeRange); #endif } diff --git a/atom/common/crash_reporter/crash_reporter_win.h b/atom/common/crash_reporter/crash_reporter_win.h index 0ab8f4bcfb..806c3de317 100644 --- a/atom/common/crash_reporter/crash_reporter_win.h +++ b/atom/common/crash_reporter/crash_reporter_win.h @@ -5,12 +5,12 @@ #ifndef ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_WIN_H_ #define ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_WIN_H_ +#include #include #include #include "atom/common/crash_reporter/crash_reporter.h" #include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" #include "vendor/breakpad/src/client/windows/handler/exception_handler.h" namespace base { @@ -62,6 +62,7 @@ class CrashReporterWin : public CrashReporter { google_breakpad::CustomClientInfo custom_info_; bool skip_system_crash_handler_; + bool code_range_registered_; std::unique_ptr breakpad_; DISALLOW_COPY_AND_ASSIGN(CrashReporterWin); diff --git a/atom/common/crash_reporter/win/crash_service.cc b/atom/common/crash_reporter/win/crash_service.cc index 4563a9202a..5782fd72a3 100644 --- a/atom/common/crash_reporter/win/crash_service.cc +++ b/atom/common/crash_reporter/win/crash_service.cc @@ -239,23 +239,17 @@ bool CrashService::Initialize(const base::string16& application_name, } SECURITY_ATTRIBUTES security_attributes = {0}; - SECURITY_ATTRIBUTES* security_attributes_actual = NULL; + SECURITY_DESCRIPTOR* security_descriptor = + reinterpret_cast( + GetSecurityDescriptorForLowIntegrity()); + DCHECK(security_descriptor != NULL); - if (base::win::GetVersion() >= base::win::VERSION_VISTA) { - SECURITY_DESCRIPTOR* security_descriptor = - reinterpret_cast( - GetSecurityDescriptorForLowIntegrity()); - DCHECK(security_descriptor != NULL); - - security_attributes.nLength = sizeof(security_attributes); - security_attributes.lpSecurityDescriptor = security_descriptor; - security_attributes.bInheritHandle = FALSE; - - security_attributes_actual = &security_attributes; - } + security_attributes.nLength = sizeof(security_attributes); + security_attributes.lpSecurityDescriptor = security_descriptor; + security_attributes.bInheritHandle = FALSE; // Create the OOP crash generator object. - dumper_ = new CrashGenerationServer(pipe_name, security_attributes_actual, + dumper_ = new CrashGenerationServer(pipe_name, &security_attributes, &CrashService::OnClientConnected, this, &CrashService::OnClientDumpRequest, this, &CrashService::OnClientExited, this, diff --git a/atom/common/native_mate_converters/callback.cc b/atom/common/native_mate_converters/callback.cc index 8bf5c459b0..dc6d30fd23 100644 --- a/atom/common/native_mate_converters/callback.cc +++ b/atom/common/native_mate_converters/callback.cc @@ -123,7 +123,7 @@ v8::Local CreateFunctionFromTranslater( v8::Local call_translater = v8::Local::New(isolate, g_call_translater); - TranslaterHolder* holder = new TranslaterHolder; + auto* holder = new TranslaterHolder; holder->translater = translater; return BindFunctionWith(isolate, isolate->GetCurrentContext(), diff --git a/atom/common/native_mate_converters/callback.h b/atom/common/native_mate_converters/callback.h index 43a1baf25f..decc36eb57 100644 --- a/atom/common/native_mate_converters/callback.h +++ b/atom/common/native_mate_converters/callback.h @@ -48,11 +48,8 @@ struct V8FunctionInvoker(ArgTypes...)> { v8::EscapableHandleScope handle_scope(isolate); if (!function.IsAlive()) return v8::Null(isolate); - std::unique_ptr script_scope( - Locker::IsBrowserProcess() ? - nullptr : - new v8::MicrotasksScope(isolate, - v8::MicrotasksScope::kRunMicrotasks)); + v8::MicrotasksScope script_scope(isolate, + v8::MicrotasksScope::kRunMicrotasks); v8::Local holder = function.NewHandle(isolate); v8::Local context = holder->CreationContext(); v8::Context::Scope context_scope(context); @@ -71,11 +68,8 @@ struct V8FunctionInvoker { v8::HandleScope handle_scope(isolate); if (!function.IsAlive()) return; - std::unique_ptr script_scope( - Locker::IsBrowserProcess() ? - nullptr : - new v8::MicrotasksScope(isolate, - v8::MicrotasksScope::kRunMicrotasks)); + v8::MicrotasksScope script_scope(isolate, + v8::MicrotasksScope::kRunMicrotasks); v8::Local holder = function.NewHandle(isolate); v8::Local context = holder->CreationContext(); v8::Context::Scope context_scope(context); @@ -94,11 +88,8 @@ struct V8FunctionInvoker { ReturnType ret = ReturnType(); if (!function.IsAlive()) return ret; - std::unique_ptr script_scope( - Locker::IsBrowserProcess() ? - nullptr : - new v8::MicrotasksScope(isolate, - v8::MicrotasksScope::kRunMicrotasks)); + v8::MicrotasksScope script_scope(isolate, + v8::MicrotasksScope::kRunMicrotasks); v8::Local holder = function.NewHandle(isolate); v8::Local context = holder->CreationContext(); v8::Context::Scope context_scope(context); diff --git a/atom/common/native_mate_converters/gfx_converter.cc b/atom/common/native_mate_converters/gfx_converter.cc index 37e7aeb3a4..db6a181cc9 100644 --- a/atom/common/native_mate_converters/gfx_converter.cc +++ b/atom/common/native_mate_converters/gfx_converter.cc @@ -7,8 +7,9 @@ #include "native_mate/dictionary.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" -#include "ui/gfx/screen.h" #include "ui/gfx/geometry/size.h" +#include "ui/display/display.h" +#include "ui/display/screen.h" namespace mate { @@ -35,7 +36,7 @@ bool Converter::FromV8(v8::Isolate* isolate, } v8::Local Converter::ToV8(v8::Isolate* isolate, - const gfx::Size& val) { + const gfx::Size& val) { mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.SetHidden("simple", true); dict.Set("width", val.width()); @@ -82,13 +83,13 @@ bool Converter::FromV8(v8::Isolate* isolate, } template<> -struct Converter { +struct Converter { static v8::Local ToV8(v8::Isolate* isolate, - const gfx::Display::TouchSupport& val) { + const display::Display::TouchSupport& val) { switch (val) { - case gfx::Display::TOUCH_SUPPORT_AVAILABLE: + case display::Display::TOUCH_SUPPORT_AVAILABLE: return StringToV8(isolate, "available"); - case gfx::Display::TOUCH_SUPPORT_UNAVAILABLE: + case display::Display::TOUCH_SUPPORT_UNAVAILABLE: return StringToV8(isolate, "unavailable"); default: return StringToV8(isolate, "unknown"); @@ -96,8 +97,8 @@ struct Converter { } }; -v8::Local Converter::ToV8(v8::Isolate* isolate, - const gfx::Display& val) { +v8::Local Converter::ToV8( + v8::Isolate* isolate, const display::Display& val) { mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.SetHidden("simple", true); dict.Set("id", val.id()); diff --git a/atom/common/native_mate_converters/gfx_converter.h b/atom/common/native_mate_converters/gfx_converter.h index c6da76a2d0..1797710962 100644 --- a/atom/common/native_mate_converters/gfx_converter.h +++ b/atom/common/native_mate_converters/gfx_converter.h @@ -7,11 +7,14 @@ #include "native_mate/converter.h" +namespace display { +class Display; +} + namespace gfx { class Point; class Size; class Rect; -class Display; } namespace mate { @@ -44,12 +47,12 @@ struct Converter { }; template<> -struct Converter { +struct Converter { static v8::Local ToV8(v8::Isolate* isolate, - const gfx::Display& val); + const display::Display& val); static bool FromV8(v8::Isolate* isolate, v8::Local val, - gfx::Display* out); + display::Display* out); }; } // namespace mate diff --git a/atom/common/native_mate_converters/net_converter.cc b/atom/common/native_mate_converters/net_converter.cc index 71bc50fde7..e79e09df10 100644 --- a/atom/common/native_mate_converters/net_converter.cc +++ b/atom/common/native_mate_converters/net_converter.cc @@ -11,6 +11,7 @@ #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "base/values.h" +#include "base/strings/string_number_conversions.h" #include "native_mate/dictionary.h" #include "net/base/upload_bytes_element_reader.h" #include "net/base/upload_data_stream.h" @@ -46,6 +47,15 @@ v8::Local Converter>::ToV8( encoded_data.size()).ToLocalChecked(); dict.Set("data", buffer); dict.Set("issuerName", val->issuer().GetDisplayName()); + dict.Set("subjectName", val->subject().GetDisplayName()); + dict.Set("serialNumber", base::HexEncode(val->serial_number().data(), + val->serial_number().size())); + dict.Set("validStart", val->valid_start().ToDoubleT()); + dict.Set("validExpiry", val->valid_expiry().ToDoubleT()); + dict.Set("fingerprint", + net::HashValue( + val->CalculateFingerprint256(val->os_cert_handle())).ToString()); + return dict.GetHandle(); } diff --git a/atom/common/native_mate_converters/v8_value_converter.cc b/atom/common/native_mate_converters/v8_value_converter.cc index ff96b727e0..6d159d4daf 100644 --- a/atom/common/native_mate_converters/v8_value_converter.cc +++ b/atom/common/native_mate_converters/v8_value_converter.cc @@ -5,14 +5,15 @@ #include "atom/common/native_mate_converters/v8_value_converter.h" #include +#include #include #include #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/values.h" #include "native_mate/dictionary.h" -#include "vendor/node/src/node_buffer.h" + +#include "atom/common/node_includes.h" namespace atom { @@ -55,7 +56,7 @@ class V8ValueConverter::FromV8ValueState { // hash. Different hash obviously means different objects, but two objects // in a couple of thousands could have the same identity hash. std::pair range = unique_map_.equal_range(hash); - for (Iterator it = range.first; it != range.second; ++it) { + for (auto it = range.first; it != range.second; ++it) { // Operator == for handles actually compares the underlying objects. if (it->second == handle) return false; @@ -110,32 +111,31 @@ base::Value* V8ValueConverter::FromV8Value( v8::Local V8ValueConverter::ToV8ValueImpl( v8::Isolate* isolate, const base::Value* value) const { - CHECK(value); switch (value->GetType()) { case base::Value::TYPE_NULL: return v8::Null(isolate); case base::Value::TYPE_BOOLEAN: { bool val = false; - CHECK(value->GetAsBoolean(&val)); + value->GetAsBoolean(&val); return v8::Boolean::New(isolate, val); } case base::Value::TYPE_INTEGER: { int val = 0; - CHECK(value->GetAsInteger(&val)); + value->GetAsInteger(&val); return v8::Integer::New(isolate, val); } case base::Value::TYPE_DOUBLE: { double val = 0.0; - CHECK(value->GetAsDouble(&val)); + value->GetAsDouble(&val); return v8::Number::New(isolate, val); } case base::Value::TYPE_STRING: { std::string val; - CHECK(value->GetAsString(&val)); + value->GetAsString(&val); return v8::String::NewFromUtf8( isolate, val.c_str(), v8::String::kNormalString, val.length()); } @@ -162,11 +162,10 @@ v8::Local V8ValueConverter::ToV8Array( v8::Local result(v8::Array::New(isolate, val->GetSize())); for (size_t i = 0; i < val->GetSize(); ++i) { - const base::Value* child = NULL; - CHECK(val->Get(i, &child)); + const base::Value* child = nullptr; + val->Get(i, &child); v8::Local child_v8 = ToV8ValueImpl(isolate, child); - CHECK(!child_v8.IsEmpty()); v8::TryCatch try_catch; result->Set(static_cast(i), child_v8); @@ -186,7 +185,6 @@ v8::Local V8ValueConverter::ToV8Object( !iter.IsAtEnd(); iter.Advance()) { const std::string& key = iter.key(); v8::Local child_v8 = ToV8ValueImpl(isolate, &iter.value()); - CHECK(!child_v8.IsEmpty()); v8::TryCatch try_catch; result.Set(key, child_v8); @@ -210,11 +208,9 @@ base::Value* V8ValueConverter::FromV8ValueImpl( FromV8ValueState* state, v8::Local val, v8::Isolate* isolate) const { - CHECK(!val.IsEmpty()); - FromV8ValueState::Level state_level(state); if (state->HasReachedMaxRecursionDepth()) - return NULL; + return nullptr; if (val->IsNull()) return base::Value::CreateNullValue().release(); @@ -235,7 +231,7 @@ base::Value* V8ValueConverter::FromV8ValueImpl( if (val->IsUndefined()) // JSON.stringify ignores undefined. - return NULL; + return nullptr; if (val->IsDate()) { v8::Date* date = v8::Date::Cast(*val); @@ -265,7 +261,7 @@ base::Value* V8ValueConverter::FromV8ValueImpl( if (val->IsFunction()) { if (!function_allowed_) // JSON.stringify refuses to convert function(){}. - return NULL; + return nullptr; return FromV8Object(val->ToObject(), state, isolate); } @@ -278,7 +274,7 @@ base::Value* V8ValueConverter::FromV8ValueImpl( } LOG(ERROR) << "Unexpected v8 value type encountered."; - return NULL; + return nullptr; } base::Value* V8ValueConverter::FromV8Array( @@ -295,7 +291,7 @@ base::Value* V8ValueConverter::FromV8Array( val->CreationContext() != isolate->GetCurrentContext()) scope.reset(new v8::Context::Scope(val->CreationContext())); - base::ListValue* result = new base::ListValue(); + auto* result = new base::ListValue(); // Only fields with integer keys are carried over to the ListValue. for (uint32_t i = 0; i < val->Length(); ++i) { diff --git a/atom/common/node_bindings.cc b/atom/common/node_bindings.cc index ed2ea01675..2a999ea79b 100644 --- a/atom/common/node_bindings.cc +++ b/atom/common/node_bindings.cc @@ -11,7 +11,6 @@ #include "atom/common/api/locker.h" #include "atom/common/atom_command_line.h" #include "atom/common/native_mate_converters/file_path_converter.h" -#include "atom/common/node_includes.h" #include "base/command_line.h" #include "base/base_paths.h" #include "base/environment.h" @@ -22,6 +21,8 @@ #include "content/public/common/content_paths.h" #include "native_mate/dictionary.h" +#include "atom/common/node_includes.h" + using content::BrowserThread; // Force all builtin modules to be referenced so they can actually run their @@ -216,7 +217,6 @@ void NodeBindings::UvRunOnce() { DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI)); node::Environment* env = uv_env(); - CHECK(env); // Use Locker in browser process. mate::Locker locker(env->isolate()); @@ -226,10 +226,8 @@ void NodeBindings::UvRunOnce() { v8::Context::Scope context_scope(env->context()); // Perform microtask checkpoint after running JavaScript. - std::unique_ptr script_scope(is_browser_ ? - nullptr : - new v8::MicrotasksScope(env->isolate(), - v8::MicrotasksScope::kRunMicrotasks)); + v8::MicrotasksScope script_scope(env->isolate(), + v8::MicrotasksScope::kRunMicrotasks); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); diff --git a/atom/common/node_bindings_mac.cc b/atom/common/node_bindings_mac.cc index 9e61d27f49..cbcbdba360 100644 --- a/atom/common/node_bindings_mac.cc +++ b/atom/common/node_bindings_mac.cc @@ -54,7 +54,8 @@ void NodeBindingsMac::PollEvents() { // Wait for new libuv events. int r; do { - r = select(fd + 1, &readset, NULL, NULL, timeout == -1 ? NULL : &tv); + r = select(fd + 1, &readset, nullptr, nullptr, + timeout == -1 ? nullptr : &tv); } while (r == -1 && errno == EINTR); } diff --git a/atom/common/node_includes.h b/atom/common/node_includes.h index 46b6fa058e..01efa6b154 100644 --- a/atom/common/node_includes.h +++ b/atom/common/node_includes.h @@ -19,6 +19,7 @@ #undef CHECK_GT #undef CHECK_LE #undef CHECK_LT +#undef UNLIKELY #undef DISALLOW_COPY_AND_ASSIGN #undef NO_RETURN #undef arraysize diff --git a/atom/common/options_switches.cc b/atom/common/options_switches.cc index 36ec19edb8..6b514599f0 100644 --- a/atom/common/options_switches.cc +++ b/atom/common/options_switches.cc @@ -96,9 +96,6 @@ const char kNodeIntegration[] = "nodeIntegration"; // Instancd ID of guest WebContents. const char kGuestInstanceID[] = "guestInstanceId"; -// Enable DirectWrite on Windows. -const char kDirectWrite[] = "directWrite"; - // Web runtime features. const char kExperimentalFeatures[] = "experimentalFeatures"; const char kExperimentalCanvasFeatures[] = "experimentalCanvasFeatures"; diff --git a/atom/common/options_switches.h b/atom/common/options_switches.h index 29fbc0e40f..54c6387728 100644 --- a/atom/common/options_switches.h +++ b/atom/common/options_switches.h @@ -48,7 +48,6 @@ extern const char kFocusable[]; extern const char kWebPreferences[]; // WebPreferences. -extern const char kDirectWrite[]; extern const char kZoomFactor[]; extern const char kPreloadScript[]; extern const char kPreloadURL[]; diff --git a/atom/common/platform_util.h b/atom/common/platform_util.h index 4565221e9d..262f0a2e6e 100644 --- a/atom/common/platform_util.h +++ b/atom/common/platform_util.h @@ -5,6 +5,12 @@ #ifndef ATOM_COMMON_PLATFORM_UTIL_H_ #define ATOM_COMMON_PLATFORM_UTIL_H_ +#include "build/build_config.h" + +#if defined(OS_WIN) +#include "base/strings/string16.h" +#endif + class GURL; namespace base { @@ -23,7 +29,13 @@ void OpenItem(const base::FilePath& full_path); // Open the given external protocol URL in the desktop's default manner. // (For example, mailto: URLs in the default mail user agent.) -bool OpenExternal(const GURL& url, bool activate); +bool OpenExternal( +#if defined(OS_WIN) + const base::string16& url, +#else + const GURL& url, +#endif + bool activate); // Move a file to trash. bool MoveItemToTrash(const base::FilePath& full_path); diff --git a/atom/common/platform_util_win.cc b/atom/common/platform_util_win.cc index 12591a94d5..0795fcb72b 100644 --- a/atom/common/platform_util_win.cc +++ b/atom/common/platform_util_win.cc @@ -24,8 +24,8 @@ #include "base/win/scoped_com_initializer.h" #include "base/win/scoped_comptr.h" #include "base/win/windows_version.h" -#include "url/gurl.h" #include "ui/base/win/shell.h" +#include "url/gurl.h" namespace { @@ -301,30 +301,13 @@ void OpenItem(const base::FilePath& full_path) { ui::win::OpenFileViaShell(full_path); } -bool OpenExternal(const GURL& url, bool activate) { +bool OpenExternal(const base::string16& url, bool activate) { // Quote the input scheme to be sure that the command does not have // parameters unexpected by the external program. This url should already // have been escaped. - std::string escaped_url = url.spec(); - escaped_url.insert(0, "\""); - escaped_url += "\""; + base::string16 escaped_url = L"\"" + url + L"\""; - // According to Mozilla in uriloader/exthandler/win/nsOSHelperAppService.cpp: - // "Some versions of windows (Win2k before SP3, Win XP before SP1) crash in - // ShellExecute on long URLs (bug 161357 on bugzilla.mozilla.org). IE 5 and 6 - // support URLS of 2083 chars in length, 2K is safe." - const size_t kMaxURLLength = 2048; - if (escaped_url.length() > kMaxURLLength) { - NOTREACHED(); - return false; - } - - if (base::win::GetVersion() < base::win::VERSION_WIN7) { - if (!ValidateShellCommandForScheme(url.scheme())) - return false; - } - - if (reinterpret_cast(ShellExecuteA(NULL, "open", + if (reinterpret_cast(ShellExecuteW(NULL, L"open", escaped_url.c_str(), NULL, NULL, SW_SHOWNORMAL)) <= 32) { // We fail to execute the call. We could display a message to the user. diff --git a/atom/node/osfhandle.h b/atom/node/osfhandle.h index 6ebb2ab11e..3933236e50 100644 --- a/atom/node/osfhandle.h +++ b/atom/node/osfhandle.h @@ -7,8 +7,6 @@ #include -#include "node_extern.h" - namespace node { // The _open_osfhandle and _close functions on Windows are provided by the @@ -20,8 +18,8 @@ namespace node { // we always create fd in one instance of VC++ library. // Followings wrappers are compiled in node.dll, and all code in electron.exe // should call these wrappers instead of calling _open_osfhandle directly. -NODE_EXTERN int open_osfhandle(intptr_t osfhandle, int flags); -NODE_EXTERN int close(int fd); +__declspec(dllexport) int open_osfhandle(intptr_t osfhandle, int flags); +__declspec(dllexport) int close(int fd); } // namespace node diff --git a/atom/renderer/api/atom_api_renderer_ipc.cc b/atom/renderer/api/atom_api_renderer_ipc.cc index a82562f936..49f917292b 100644 --- a/atom/renderer/api/atom_api_renderer_ipc.cc +++ b/atom/renderer/api/atom_api_renderer_ipc.cc @@ -20,11 +20,11 @@ namespace { RenderView* GetCurrentRenderView() { WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext(); if (!frame) - return NULL; + return nullptr; WebView* view = frame->view(); if (!view) - return NULL; // can happen during closing. + return nullptr; // can happen during closing. return RenderView::FromWebView(view); } @@ -33,7 +33,7 @@ void Send(mate::Arguments* args, const base::string16& channel, const base::ListValue& arguments) { RenderView* render_view = GetCurrentRenderView(); - if (render_view == NULL) + if (render_view == nullptr) return; bool success = render_view->Send(new AtomViewHostMsg_Message( @@ -49,7 +49,7 @@ base::string16 SendSync(mate::Arguments* args, base::string16 json; RenderView* render_view = GetCurrentRenderView(); - if (render_view == NULL) + if (render_view == nullptr) return json; IPC::SyncMessage* message = new AtomViewHostMsg_Message_Sync( diff --git a/atom/renderer/api/atom_api_web_frame.cc b/atom/renderer/api/atom_api_web_frame.cc index 0b291d3b55..dce72b5809 100644 --- a/atom/renderer/api/atom_api_web_frame.cc +++ b/atom/renderer/api/atom_api_web_frame.cc @@ -39,7 +39,7 @@ class ScriptExecutionCallback : public blink::WebScriptExecutionCallback { explicit ScriptExecutionCallback(const CompletionCallback& callback) : callback_(callback) {} - ~ScriptExecutionCallback() {} + ~ScriptExecutionCallback() override {} void completed( const blink::WebVector>& result) override { diff --git a/atom/renderer/api/atom_api_web_frame.h b/atom/renderer/api/atom_api_web_frame.h index df0392a933..852191fc76 100644 --- a/atom/renderer/api/atom_api_web_frame.h +++ b/atom/renderer/api/atom_api_web_frame.h @@ -5,10 +5,10 @@ #ifndef ATOM_RENDERER_API_ATOM_API_WEB_FRAME_H_ #define ATOM_RENDERER_API_ATOM_API_WEB_FRAME_H_ +#include #include #include "atom/renderer/guest_view_container.h" -#include "base/memory/scoped_ptr.h" #include "native_mate/handle.h" #include "native_mate/wrappable.h" #include "third_party/WebKit/public/web/WebCache.h" diff --git a/atom/renderer/atom_render_view_observer.cc b/atom/renderer/atom_render_view_observer.cc index 7ee93efb39..ea5727893d 100644 --- a/atom/renderer/atom_render_view_observer.cc +++ b/atom/renderer/atom_render_view_observer.cc @@ -132,15 +132,19 @@ void AtomRenderViewObserver::DraggableRegionsChanged(blink::WebFrame* frame) { blink::WebVector webregions = frame->document().draggableRegions(); std::vector regions; - for (size_t i = 0; i < webregions.size(); ++i) { + for (const auto& webregion : webregions) { DraggableRegion region; - region.bounds = webregions[i].bounds; - region.draggable = webregions[i].draggable; + region.bounds = webregion.bounds; + region.draggable = webregion.draggable; regions.push_back(region); } Send(new AtomViewHostMsg_UpdateDraggableRegions(routing_id(), regions)); } +void AtomRenderViewObserver::DidCommitCompositorFrame() { + Send(new AtomViewHostMsg_DidCommitCompositorFrame(routing_id())); +} + bool AtomRenderViewObserver::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(AtomRenderViewObserver, message) diff --git a/atom/renderer/atom_render_view_observer.h b/atom/renderer/atom_render_view_observer.h index 376138f084..2948896054 100644 --- a/atom/renderer/atom_render_view_observer.h +++ b/atom/renderer/atom_render_view_observer.h @@ -28,6 +28,7 @@ class AtomRenderViewObserver : public content::RenderViewObserver { // content::RenderViewObserver implementation. void DidCreateDocumentElement(blink::WebLocalFrame* frame) override; void DraggableRegionsChanged(blink::WebFrame* frame) override; + void DidCommitCompositorFrame() override; bool OnMessageReceived(const IPC::Message& message) override; void OnBrowserMessage(bool send_to_all, diff --git a/atom/renderer/atom_renderer_client.cc b/atom/renderer/atom_renderer_client.cc index 63a9a3eb26..d2c341fa27 100644 --- a/atom/renderer/atom_renderer_client.cc +++ b/atom/renderer/atom_renderer_client.cc @@ -20,7 +20,6 @@ #include "atom/renderer/node_array_buffer_bridge.h" #include "atom/renderer/preferences_manager.h" #include "base/command_line.h" -#include "base/strings/utf_string_conversions.h" #include "chrome/renderer/media/chrome_key_systems.h" #include "chrome/renderer/pepper/pepper_helper.h" #include "chrome/renderer/printing/print_web_view_helper.h" @@ -32,7 +31,6 @@ #include "content/public/renderer/render_view.h" #include "ipc/ipc_message_macros.h" #include "native_mate/dictionary.h" -#include "net/base/net_errors.h" #include "third_party/WebKit/public/web/WebCustomElement.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebFrameWidget.h" @@ -317,21 +315,9 @@ content::BrowserPluginDelegate* AtomRendererClient::CreateBrowserPluginDelegate( } } -void AtomRendererClient::AddKeySystems( - std::vector* key_systems) { +void AtomRendererClient::AddSupportedKeySystems( + std::vector>* key_systems) { AddChromeKeySystems(key_systems); } -void AtomRendererClient::GetNavigationErrorStrings( - content::RenderFrame* render_frame, - const blink::WebURLRequest& failed_request, - const blink::WebURLError& error, - std::string* error_html, - base::string16* error_description) { - if (!error_description) - return; - - *error_description = base::UTF8ToUTF16(net::ErrorToShortString(error.reason)); -} - } // namespace atom diff --git a/atom/renderer/atom_renderer_client.h b/atom/renderer/atom_renderer_client.h index f4a548908e..5419692d2a 100644 --- a/atom/renderer/atom_renderer_client.h +++ b/atom/renderer/atom_renderer_client.h @@ -57,12 +57,9 @@ class AtomRendererClient : public content::ContentRendererClient { content::RenderFrame* render_frame, const std::string& mime_type, const GURL& original_url) override; - void AddKeySystems(std::vector* key_systems) override; - void GetNavigationErrorStrings(content::RenderFrame* render_frame, - const blink::WebURLRequest& failed_request, - const blink::WebURLError& error, - std::string* error_html, - base::string16* error_description) override; + void AddSupportedKeySystems( + std::vector>* key_systems) + override; std::unique_ptr node_bindings_; std::unique_ptr atom_bindings_; diff --git a/atom/renderer/preferences_manager.h b/atom/renderer/preferences_manager.h index 451928085d..c531fe879a 100644 --- a/atom/renderer/preferences_manager.h +++ b/atom/renderer/preferences_manager.h @@ -8,11 +8,11 @@ #include #include "base/values.h" -#include "content/public/renderer/render_process_observer.h" +#include "content/public/renderer/render_thread_observer.h" namespace atom { -class PreferencesManager : public content::RenderProcessObserver { +class PreferencesManager : public content::RenderThreadObserver { public: PreferencesManager(); ~PreferencesManager() override; diff --git a/atom/utility/atom_content_utility_client.cc b/atom/utility/atom_content_utility_client.cc index aff567fbca..8d4ccf6289 100644 --- a/atom/utility/atom_content_utility_client.cc +++ b/atom/utility/atom_content_utility_client.cc @@ -58,8 +58,7 @@ bool AtomContentUtilityClient::OnMessageReceived( IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() - for (Handlers::iterator it = handlers_.begin(); - !handled && it != handlers_.end(); ++it) { + for (auto it = handlers_.begin(); !handled && it != handlers_.end(); ++it) { handled = (*it)->OnMessageReceived(message); } diff --git a/chromium_src/SkUserConfig.h b/chromium_src/SkUserConfig.h deleted file mode 100644 index 755b050de6..0000000000 --- a/chromium_src/SkUserConfig.h +++ /dev/null @@ -1,158 +0,0 @@ - -/* - * Copyright 2006 The Android Open Source Project - * - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. - */ - - -#ifndef SkUserConfig_DEFINED -#define SkUserConfig_DEFINED - -/* SkTypes.h, the root of the public header files, does the following trick: - - #include "SkPreConfig.h" - #include "SkUserConfig.h" - #include "SkPostConfig.h" - - SkPreConfig.h runs first, and it is responsible for initializing certain - skia defines. - - SkPostConfig.h runs last, and its job is to just check that the final - defines are consistent (i.e. that we don't have mutually conflicting - defines). - - SkUserConfig.h (this file) runs in the middle. It gets to change or augment - the list of flags initially set in preconfig, and then postconfig checks - that everything still makes sense. - - Below are optional defines that add, subtract, or change default behavior - in Skia. Your port can locally edit this file to enable/disable flags as - you choose, or these can be delared on your command line (i.e. -Dfoo). - - By default, this include file will always default to having all of the flags - commented out, so including it will have no effect. -*/ - -/////////////////////////////////////////////////////////////////////////////// - -/* Skia has lots of debug-only code. Often this is just null checks or other - parameter checking, but sometimes it can be quite intrusive (e.g. check that - each 32bit pixel is in premultiplied form). This code can be very useful - during development, but will slow things down in a shipping product. - - By default, these mutually exclusive flags are defined in SkPreConfig.h, - based on the presence or absence of NDEBUG, but that decision can be changed - here. - */ -//#define SK_DEBUG -//#define SK_RELEASE - -/* Skia has certain debug-only code that is extremely intensive even for debug - builds. This code is useful for diagnosing specific issues, but is not - generally applicable, therefore it must be explicitly enabled to avoid - the performance impact. By default these flags are undefined, but can be - enabled by uncommenting them below. - */ -//#define SK_DEBUG_GLYPH_CACHE -//#define SK_DEBUG_PATH - -/* If, in debugging mode, Skia needs to stop (presumably to invoke a debugger) - it will call SK_CRASH(). If this is not defined it, it is defined in - SkPostConfig.h to write to an illegal address - */ -//#define SK_CRASH() *(int *)(uintptr_t)0 = 0 - - -/* preconfig will have attempted to determine the endianness of the system, - but you can change these mutually exclusive flags here. - */ -//#define SK_CPU_BENDIAN -//#define SK_CPU_LENDIAN - -/* Most compilers use the same bit endianness for bit flags in a byte as the - system byte endianness, and this is the default. If for some reason this - needs to be overridden, specify which of the mutually exclusive flags to - use. For example, some atom processors in certain configurations have big - endian byte order but little endian bit orders. -*/ -//#define SK_UINT8_BITFIELD_BENDIAN -//#define SK_UINT8_BITFIELD_LENDIAN - - -/* To write debug messages to a console, skia will call SkDebugf(...) following - printf conventions (e.g. const char* format, ...). If you want to redirect - this to something other than printf, define yours here - */ -// Log the file and line number for assertions. -#define SkDebugf(...) - -/* - * To specify a different default font cache limit, define this. If this is - * undefined, skia will use a built-in value. - */ -//#define SK_DEFAULT_FONT_CACHE_LIMIT (1024 * 1024) - -/* - * To specify the default size of the image cache, undefine this and set it to - * the desired value (in bytes). SkGraphics.h as a runtime API to set this - * value as well. If this is undefined, a built-in value will be used. - */ -//#define SK_DEFAULT_IMAGE_CACHE_LIMIT (1024 * 1024) - -/* Define this to allow PDF scalars above 32k. The PDF/A spec doesn't allow - them, but modern PDF interpreters should handle them just fine. - */ -//#define SK_ALLOW_LARGE_PDF_SCALARS - -/* Define this to provide font subsetter in PDF generation. - */ -//#define SK_SFNTLY_SUBSETTER "sfntly/subsetter/font_subsetter.h" - -/* Define this to set the upper limit for text to support LCD. Values that - are very large increase the cost in the font cache and draw slower, without - improving readability. If this is undefined, Skia will use its default - value (e.g. 48) - */ -//#define SK_MAX_SIZE_FOR_LCDTEXT 48 - -/* If SK_DEBUG is defined, then you can optionally define SK_SUPPORT_UNITTEST - which will run additional self-tests at startup. These can take a long time, - so this flag is optional. - */ -#ifdef SK_DEBUG -//#define SK_SUPPORT_UNITTEST -#endif - -/* Change the ordering to work in X windows. - */ -#ifdef SK_SAMPLES_FOR_X - #define SK_R32_SHIFT 16 - #define SK_G32_SHIFT 8 - #define SK_B32_SHIFT 0 - #define SK_A32_SHIFT 24 -#endif - - -/* Determines whether to build code that supports the GPU backend. Some classes - that are not GPU-specific, such as SkShader subclasses, have optional code - that is used allows them to interact with the GPU backend. If you'd like to - omit this code set SK_SUPPORT_GPU to 0. This also allows you to omit the gpu - directories from your include search path when you're not building the GPU - backend. Defaults to 1 (build the GPU code). - */ -//#define SK_SUPPORT_GPU 1 - - -/* The PDF generation code uses Path Ops to handle complex clipping paths, - * but at this time, Path Ops is not release ready yet. So, the code is - * hidden behind this #define guard. If you are feeling adventurous and - * want the latest and greatest PDF generation code, uncomment the #define. - * When Path Ops is release ready, the define guards and this user config - * define should be removed entirely. - */ -//#define SK_PDF_USE_PATHOPS_CLIPPING - -#endif - diff --git a/chromium_src/chrome/browser/browser_process.h b/chromium_src/chrome/browser/browser_process.h index 53ec0ba75f..1459ca31a6 100644 --- a/chromium_src/chrome/browser/browser_process.h +++ b/chromium_src/chrome/browser/browser_process.h @@ -10,10 +10,10 @@ #ifndef CHROME_BROWSER_BROWSER_PROCESS_H_ #define CHROME_BROWSER_BROWSER_PROCESS_H_ +#include #include #include "base/macros.h" -#include "base/memory/scoped_ptr.h" namespace printing { class PrintJobManager; diff --git a/chromium_src/chrome/browser/certificate_manager_model.h b/chromium_src/chrome/browser/certificate_manager_model.h index 81c3b6c8a8..7646da5b9b 100644 --- a/chromium_src/chrome/browser/certificate_manager_model.h +++ b/chromium_src/chrome/browser/certificate_manager_model.h @@ -6,12 +6,12 @@ #define CHROME_BROWSER_CERTIFICATE_MANAGER_MODEL_H_ #include +#include #include #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "net/cert/nss_cert_database.h" diff --git a/chromium_src/chrome/browser/extensions/global_shortcut_listener_win.h b/chromium_src/chrome/browser/extensions/global_shortcut_listener_win.h index 1999e0e774..83e9fdff28 100644 --- a/chromium_src/chrome/browser/extensions/global_shortcut_listener_win.h +++ b/chromium_src/chrome/browser/extensions/global_shortcut_listener_win.h @@ -5,9 +5,10 @@ #ifndef CHROME_BROWSER_EXTENSIONS_GLOBAL_SHORTCUT_LISTENER_WIN_H_ #define CHROME_BROWSER_EXTENSIONS_GLOBAL_SHORTCUT_LISTENER_WIN_H_ +#include + #include -#include "base/memory/scoped_ptr.h" #include "chrome/browser/extensions/global_shortcut_listener.h" #include "ui/gfx/win/singleton_hwnd.h" #include "ui/gfx/win/singleton_hwnd_observer.h" diff --git a/chromium_src/chrome/browser/media/native_desktop_media_list.cc b/chromium_src/chrome/browser/media/native_desktop_media_list.cc index a524dfcf38..76170a473d 100644 --- a/chromium_src/chrome/browser/media/native_desktop_media_list.cc +++ b/chromium_src/chrome/browser/media/native_desktop_media_list.cc @@ -97,7 +97,6 @@ class NativeDesktopMediaList::Worker typedef std::map ImageHashesMap; // webrtc::DesktopCapturer::Callback interface. - webrtc::SharedMemory* CreateSharedMemory(size_t size) override; void OnCaptureCompleted(webrtc::DesktopFrame* frame) override; base::WeakPtr media_list_; @@ -218,11 +217,6 @@ void NativeDesktopMediaList::Worker::Refresh( base::Bind(&NativeDesktopMediaList::OnRefreshFinished, media_list_)); } -webrtc::SharedMemory* NativeDesktopMediaList::Worker::CreateSharedMemory( - size_t size) { - return NULL; -} - void NativeDesktopMediaList::Worker::OnCaptureCompleted( webrtc::DesktopFrame* frame) { current_frame_.reset(frame); diff --git a/chromium_src/chrome/browser/media/native_desktop_media_list.h b/chromium_src/chrome/browser/media/native_desktop_media_list.h index 8032439798..9814849a29 100644 --- a/chromium_src/chrome/browser/media/native_desktop_media_list.h +++ b/chromium_src/chrome/browser/media/native_desktop_media_list.h @@ -5,7 +5,6 @@ #ifndef CHROME_BROWSER_MEDIA_NATIVE_DESKTOP_MEDIA_LIST_H_ #define CHROME_BROWSER_MEDIA_NATIVE_DESKTOP_MEDIA_LIST_H_ -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/sequenced_task_runner.h" #include "chrome/browser/media/desktop_media_list.h" diff --git a/chromium_src/chrome/browser/printing/pdf_to_emf_converter.cc b/chromium_src/chrome/browser/printing/pdf_to_emf_converter.cc index e13effd64d..0d23a7c6d5 100644 --- a/chromium_src/chrome/browser/printing/pdf_to_emf_converter.cc +++ b/chromium_src/chrome/browser/printing/pdf_to_emf_converter.cc @@ -104,7 +104,7 @@ class PdfToEmfUtilityProcessHostClient // UtilityProcessHostClient implementation. virtual void OnProcessCrashed(int exit_code) override; - virtual void OnProcessLaunchFailed() override; + virtual void OnProcessLaunchFailed(int exit_code) override; virtual bool OnMessageReceived(const IPC::Message& message) override; private: @@ -423,7 +423,7 @@ void PdfToEmfUtilityProcessHostClient::OnProcessCrashed(int exit_code) { OnFailed(); } -void PdfToEmfUtilityProcessHostClient::OnProcessLaunchFailed() { +void PdfToEmfUtilityProcessHostClient::OnProcessLaunchFailed(int exit_code) { OnFailed(); } diff --git a/chromium_src/chrome/browser/printing/pdf_to_emf_converter.h b/chromium_src/chrome/browser/printing/pdf_to_emf_converter.h index 859d422931..bd292dd476 100644 --- a/chromium_src/chrome/browser/printing/pdf_to_emf_converter.h +++ b/chromium_src/chrome/browser/printing/pdf_to_emf_converter.h @@ -5,9 +5,10 @@ #ifndef CHROME_BROWSER_PRINTING_PDF_TO_EMF_CONVERTER_H_ #define CHROME_BROWSER_PRINTING_PDF_TO_EMF_CONVERTER_H_ +#include + #include "base/callback.h" #include "base/memory/ref_counted_memory.h" -#include "base/memory/scoped_ptr.h" namespace base { class FilePath; diff --git a/chromium_src/chrome/browser/printing/print_job.h b/chromium_src/chrome/browser/printing/print_job.h index 5569f87679..420622a7e9 100644 --- a/chromium_src/chrome/browser/printing/print_job.h +++ b/chromium_src/chrome/browser/printing/print_job.h @@ -5,7 +5,8 @@ #ifndef CHROME_BROWSER_PRINTING_PRINT_JOB_H_ #define CHROME_BROWSER_PRINTING_PRINT_JOB_H_ -#include "base/memory/scoped_ptr.h" +#include + #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop.h" #include "chrome/browser/printing/print_job_worker_owner.h" diff --git a/chromium_src/chrome/browser/printing/print_job_manager.h b/chromium_src/chrome/browser/printing/print_job_manager.h index 32d5b301b2..ddb4e97b42 100644 --- a/chromium_src/chrome/browser/printing/print_job_manager.h +++ b/chromium_src/chrome/browser/printing/print_job_manager.h @@ -5,12 +5,12 @@ #ifndef CHROME_BROWSER_PRINTING_PRINT_JOB_MANAGER_H_ #define CHROME_BROWSER_PRINTING_PRINT_JOB_MANAGER_H_ +#include #include #include #include "base/logging.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/synchronization/lock.h" #include "base/threading/non_thread_safe.h" #include "content/public/browser/notification_observer.h" diff --git a/chromium_src/chrome/browser/printing/print_job_worker.h b/chromium_src/chrome/browser/printing/print_job_worker.h index 6b15097b7a..343c0fa15f 100644 --- a/chromium_src/chrome/browser/printing/print_job_worker.h +++ b/chromium_src/chrome/browser/printing/print_job_worker.h @@ -5,8 +5,9 @@ #ifndef CHROME_BROWSER_PRINTING_PRINT_JOB_WORKER_H_ #define CHROME_BROWSER_PRINTING_PRINT_JOB_WORKER_H_ +#include + #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread.h" #include "content/public/browser/browser_thread.h" diff --git a/chromium_src/chrome/browser/printing/print_view_manager_base.cc b/chromium_src/chrome/browser/printing/print_view_manager_base.cc index 2bbafdd8e5..f771f6963d 100644 --- a/chromium_src/chrome/browser/printing/print_view_manager_base.cc +++ b/chromium_src/chrome/browser/printing/print_view_manager_base.cc @@ -4,8 +4,9 @@ #include "chrome/browser/printing/print_view_manager_base.h" +#include + #include "base/bind.h" -#include "base/memory/scoped_ptr.h" #include "components/prefs/pref_service.h" #include "base/strings/utf_string_conversions.h" #include "base/timer/timer.h" diff --git a/chromium_src/chrome/browser/printing/printer_query.h b/chromium_src/chrome/browser/printing/printer_query.h index 934c185926..d2f017d189 100644 --- a/chromium_src/chrome/browser/printing/printer_query.h +++ b/chromium_src/chrome/browser/printing/printer_query.h @@ -5,9 +5,10 @@ #ifndef CHROME_BROWSER_PRINTING_PRINTER_QUERY_H_ #define CHROME_BROWSER_PRINTING_PRINTER_QUERY_H_ +#include + #include "base/callback.h" #include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/printing/print_job_worker_owner.h" #include "printing/print_job_constants.h" diff --git a/chromium_src/chrome/browser/process_singleton_posix.cc b/chromium_src/chrome/browser/process_singleton_posix.cc index 5742b35852..bb999fb500 100644 --- a/chromium_src/chrome/browser/process_singleton_posix.cc +++ b/chromium_src/chrome/browser/process_singleton_posix.cc @@ -74,8 +74,8 @@ #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" -#include "base/thread_task_runner_handle.h" #include "base/threading/platform_thread.h" +#include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "content/public/browser/browser_thread.h" diff --git a/chromium_src/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc b/chromium_src/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc index 224b55d4ca..c77c8f00f8 100644 --- a/chromium_src/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc +++ b/chromium_src/chrome/browser/renderer_host/pepper/pepper_broker_message_filter.cc @@ -17,7 +17,6 @@ using content::BrowserPpapiHost; using content::BrowserThread; -using content::RenderProcessHost; namespace chrome { diff --git a/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc b/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc index 43179c68d4..96fe8dc8e3 100644 --- a/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc +++ b/chromium_src/chrome/browser/renderer_host/pepper/pepper_flash_browser_host.cc @@ -26,7 +26,6 @@ using content::BrowserPpapiHost; using content::BrowserThread; -using content::RenderProcessHost; namespace chrome { diff --git a/chromium_src/chrome/browser/speech/tts_controller.h b/chromium_src/chrome/browser/speech/tts_controller.h index f4dcd77470..0587a1b8cb 100644 --- a/chromium_src/chrome/browser/speech/tts_controller.h +++ b/chromium_src/chrome/browser/speech/tts_controller.h @@ -5,12 +5,12 @@ #ifndef CHROME_BROWSER_SPEECH_TTS_CONTROLLER_H_ #define CHROME_BROWSER_SPEECH_TTS_CONTROLLER_H_ +#include #include #include #include #include -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/memory/weak_ptr.h" #include "url/gurl.h" @@ -340,4 +340,4 @@ class TtsController { virtual ~TtsController() {} }; -#endif // CHROME_BROWSER_SPEECH_TTS_CONTROLLER_H_ \ No newline at end of file +#endif // CHROME_BROWSER_SPEECH_TTS_CONTROLLER_H_ diff --git a/chromium_src/chrome/browser/speech/tts_controller_impl.h b/chromium_src/chrome/browser/speech/tts_controller_impl.h index 6c8aa5747d..749c60ad6d 100644 --- a/chromium_src/chrome/browser/speech/tts_controller_impl.h +++ b/chromium_src/chrome/browser/speech/tts_controller_impl.h @@ -5,12 +5,12 @@ #ifndef CHROME_BROWSER_SPEECH_TTS_CONTROLLER_IMPL_H_ #define CHROME_BROWSER_SPEECH_TTS_CONTROLLER_IMPL_H_ +#include #include #include #include #include -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/speech/tts_controller.h" diff --git a/chromium_src/chrome/browser/speech/tts_linux.cc b/chromium_src/chrome/browser/speech/tts_linux.cc index b1e8bc4043..d0e0e2ee82 100644 --- a/chromium_src/chrome/browser/speech/tts_linux.cc +++ b/chromium_src/chrome/browser/speech/tts_linux.cc @@ -5,10 +5,10 @@ #include #include +#include #include "base/command_line.h" #include "base/debug/leak_annotations.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/synchronization/lock.h" #include "chrome/browser/speech/tts_platform.h" diff --git a/chromium_src/chrome/common/chrome_paths_linux.cc b/chromium_src/chrome/common/chrome_paths_linux.cc index e89ae822d9..745bc03adb 100644 --- a/chromium_src/chrome/common/chrome_paths_linux.cc +++ b/chromium_src/chrome/common/chrome_paths_linux.cc @@ -4,10 +4,11 @@ #include "chrome/common/chrome_paths_internal.h" +#include + #include "base/base_paths.h" #include "base/environment.h" #include "base/files/file_util.h" -#include "base/memory/scoped_ptr.h" #include "base/nix/xdg_util.h" #include "base/path_service.h" #include "chrome/common/chrome_paths.h" diff --git a/chromium_src/chrome/renderer/media/chrome_key_systems.cc b/chromium_src/chrome/renderer/media/chrome_key_systems.cc index 417a61fcda..79e1333a74 100644 --- a/chromium_src/chrome/renderer/media/chrome_key_systems.cc +++ b/chromium_src/chrome/renderer/media/chrome_key_systems.cc @@ -4,6 +4,8 @@ #include "chrome/renderer/media/chrome_key_systems.h" +#include + #include #include @@ -12,13 +14,10 @@ #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "chrome/common/widevine_cdm_messages.h" -#include "components/cdm/renderer/widevine_key_systems.h" +#include "components/cdm/renderer/widevine_key_system_properties.h" #include "content/public/renderer/render_thread.h" #include "media/base/eme_constants.h" - -#if defined(OS_ANDROID) -#include "components/cdm/renderer/android_key_systems.h" -#endif +#include "media/base/key_system_properties.h" // #include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR. #include "third_party/widevine/cdm/stub/widevine_cdm_version.h" @@ -30,10 +29,13 @@ #include "base/version.h" #endif -using media::KeySystemInfo; +using media::KeySystemProperties; using media::SupportedCodecs; #if defined(ENABLE_PEPPER_CDMS) +static const char kExternalClearKeyPepperType[] = + "application/x-ppapi-clearkey-cdm"; + static bool IsPepperCdmAvailable( const std::string& pepper_type, std::vector* additional_param_names, @@ -49,6 +51,120 @@ static bool IsPepperCdmAvailable( return is_available; } +// KeySystemProperties implementation for external Clear Key systems. +class ExternalClearKeyProperties : public KeySystemProperties { + public: + explicit ExternalClearKeyProperties(const std::string& key_system_name) + : key_system_name_(key_system_name) {} + + std::string GetKeySystemName() const override { return key_system_name_; } + bool IsSupportedInitDataType( + media::EmeInitDataType init_data_type) const override { + switch (init_data_type) { + case media::EmeInitDataType::WEBM: + case media::EmeInitDataType::KEYIDS: + return true; + + case media::EmeInitDataType::CENC: +#if defined(USE_PROPRIETARY_CODECS) + return true; +#else + return false; +#endif // defined(USE_PROPRIETARY_CODECS) + + case media::EmeInitDataType::UNKNOWN: + return false; + } + NOTREACHED(); + return false; + } + + SupportedCodecs GetSupportedCodecs() const override { +#if defined(USE_PROPRIETARY_CODECS) + return media::EME_CODEC_MP4_ALL | media::EME_CODEC_WEBM_ALL; +#else + return media::EME_CODEC_WEBM_ALL; +#endif + } + + media::EmeConfigRule GetRobustnessConfigRule( + media::EmeMediaType media_type, + const std::string& requested_robustness) const override { + return requested_robustness.empty() ? media::EmeConfigRule::SUPPORTED + : media::EmeConfigRule::NOT_SUPPORTED; + } + + // Persistent license sessions are faked. + media::EmeSessionTypeSupport GetPersistentLicenseSessionSupport() + const override { + return media::EmeSessionTypeSupport::SUPPORTED; + } + + media::EmeSessionTypeSupport GetPersistentReleaseMessageSessionSupport() + const override { + return media::EmeSessionTypeSupport::NOT_SUPPORTED; + } + + media::EmeFeatureSupport GetPersistentStateSupport() const override { + return media::EmeFeatureSupport::REQUESTABLE; + } + + media::EmeFeatureSupport GetDistinctiveIdentifierSupport() const override { + return media::EmeFeatureSupport::NOT_SUPPORTED; + } + + std::string GetPepperType() const override { + return kExternalClearKeyPepperType; + } + + private: + const std::string key_system_name_; +}; + +// External Clear Key (used for testing). +static void AddExternalClearKey( + std::vector>* concrete_key_systems) { + static const char kExternalClearKeyKeySystem[] = + "org.chromium.externalclearkey"; + static const char kExternalClearKeyDecryptOnlyKeySystem[] = + "org.chromium.externalclearkey.decryptonly"; + static const char kExternalClearKeyFileIOTestKeySystem[] = + "org.chromium.externalclearkey.fileiotest"; + static const char kExternalClearKeyInitializeFailKeySystem[] = + "org.chromium.externalclearkey.initializefail"; + static const char kExternalClearKeyCrashKeySystem[] = + "org.chromium.externalclearkey.crash"; + + std::vector additional_param_names; + std::vector additional_param_values; + if (!IsPepperCdmAvailable(kExternalClearKeyPepperType, + &additional_param_names, + &additional_param_values)) { + return; + } + + concrete_key_systems->emplace_back( + new ExternalClearKeyProperties(kExternalClearKeyKeySystem)); + + // Add support of decrypt-only mode in ClearKeyCdm. + concrete_key_systems->emplace_back( + new ExternalClearKeyProperties(kExternalClearKeyDecryptOnlyKeySystem)); + + // A key system that triggers FileIO test in ClearKeyCdm. + concrete_key_systems->emplace_back( + new ExternalClearKeyProperties(kExternalClearKeyFileIOTestKeySystem)); + + // A key system that Chrome thinks is supported by ClearKeyCdm, but actually + // will be refused by ClearKeyCdm. This is to test the CDM initialization + // failure case. + concrete_key_systems->emplace_back( + new ExternalClearKeyProperties(kExternalClearKeyInitializeFailKeySystem)); + + // A key system that triggers a crash in ClearKeyCdm. + concrete_key_systems->emplace_back( + new ExternalClearKeyProperties(kExternalClearKeyCrashKeySystem)); +} + #if defined(WIDEVINE_CDM_AVAILABLE) // This function finds "codecs" and parses the value into the vector |codecs|. // Converts the codec strings to UTF-8 since we only expect ASCII strings and @@ -79,11 +195,11 @@ void GetSupportedCodecsForPepperCdm( } static void AddPepperBasedWidevine( - std::vector* concrete_key_systems) { + std::vector>* concrete_key_systems) { #if defined(WIDEVINE_CDM_MIN_GLIBC_VERSION) Version glibc_version(gnu_get_libc_version()); DCHECK(glibc_version.IsValid()); - if (glibc_version.IsOlderThan(WIDEVINE_CDM_MIN_GLIBC_VERSION)) + if (glibc_version < base::Version(WIDEVINE_CDM_MIN_GLIBC_VERSION)) return; #endif // defined(WIDEVINE_CDM_MIN_GLIBC_VERSION) @@ -120,10 +236,12 @@ static void AddPepperBasedWidevine( #if defined(USE_PROPRIETARY_CODECS) if (codecs[i] == kCdmSupportedCodecAvc1) supported_codecs |= media::EME_CODEC_MP4_AVC1; + if (codecs[i] == kCdmSupportedCodecVp9) + supported_codecs |= media::EME_CODEC_MP4_VP9; #endif // defined(USE_PROPRIETARY_CODECS) } - cdm::AddWidevineWithCodecs( + concrete_key_systems->emplace_back(new cdm::WidevineKeySystemProperties( supported_codecs, #if defined(OS_CHROMEOS) media::EmeRobustness::HW_SECURE_ALL, // Maximum audio robustness. @@ -131,27 +249,29 @@ static void AddPepperBasedWidevine( media::EmeSessionTypeSupport:: SUPPORTED_WITH_IDENTIFIER, // Persistent-license. media::EmeSessionTypeSupport:: - NOT_SUPPORTED, // Persistent-release-message. - media::EmeFeatureSupport::REQUESTABLE, // Persistent state. - media::EmeFeatureSupport::REQUESTABLE, // Distinctive identifier. + NOT_SUPPORTED, // Persistent-release-message. + media::EmeFeatureSupport::REQUESTABLE, // Persistent state. + media::EmeFeatureSupport::REQUESTABLE)); // Distinctive identifier. #else // (Desktop) media::EmeRobustness::SW_SECURE_CRYPTO, // Maximum audio robustness. media::EmeRobustness::SW_SECURE_DECODE, // Maximum video robustness. media::EmeSessionTypeSupport::NOT_SUPPORTED, // persistent-license. media::EmeSessionTypeSupport:: - NOT_SUPPORTED, // persistent-release-message. - media::EmeFeatureSupport::REQUESTABLE, // Persistent state. - media::EmeFeatureSupport::NOT_SUPPORTED, // Distinctive identifier. + NOT_SUPPORTED, // persistent-release-message. + media::EmeFeatureSupport::REQUESTABLE, // Persistent state. + media::EmeFeatureSupport::NOT_SUPPORTED)); // Distinctive identifier. #endif // defined(OS_CHROMEOS) - concrete_key_systems); } #endif // defined(WIDEVINE_CDM_AVAILABLE) #endif // defined(ENABLE_PEPPER_CDMS) -void AddChromeKeySystems(std::vector* key_systems_info) { +void AddChromeKeySystems( + std::vector>* key_systems_properties) { #if defined(ENABLE_PEPPER_CDMS) + AddExternalClearKey(key_systems_properties); + #if defined(WIDEVINE_CDM_AVAILABLE) - AddPepperBasedWidevine(key_systems_info); + AddPepperBasedWidevine(key_systems_properties); #endif // defined(WIDEVINE_CDM_AVAILABLE) #endif // defined(ENABLE_PEPPER_CDMS) } diff --git a/chromium_src/chrome/renderer/media/chrome_key_systems.h b/chromium_src/chrome/renderer/media/chrome_key_systems.h index dfec84f3b3..3e82ee70e2 100644 --- a/chromium_src/chrome/renderer/media/chrome_key_systems.h +++ b/chromium_src/chrome/renderer/media/chrome_key_systems.h @@ -5,10 +5,16 @@ #ifndef CHROME_RENDERER_MEDIA_CHROME_KEY_SYSTEMS_H_ #define CHROME_RENDERER_MEDIA_CHROME_KEY_SYSTEMS_H_ +#include #include -#include "media/base/key_system_info.h" +namespace media { +class KeySystemProperties; +} -void AddChromeKeySystems(std::vector* key_systems_info); +// Register the key systems supported by populating |key_systems_properties|. +void AddChromeKeySystems( + std::vector>* + key_systems_properties); #endif // CHROME_RENDERER_MEDIA_CHROME_KEY_SYSTEMS_H_ diff --git a/chromium_src/chrome/renderer/pepper/pepper_shared_memory_message_filter.cc b/chromium_src/chrome/renderer/pepper/pepper_shared_memory_message_filter.cc index 7c219f60b8..9919fb47b0 100644 --- a/chromium_src/chrome/renderer/pepper/pepper_shared_memory_message_filter.cc +++ b/chromium_src/chrome/renderer/pepper/pepper_shared_memory_message_filter.cc @@ -4,7 +4,8 @@ #include "chrome/renderer/pepper/pepper_shared_memory_message_filter.h" -#include "base/memory/scoped_ptr.h" +#include + #include "base/memory/shared_memory.h" #include "base/process/process_handle.h" #include "content/public/common/content_client.h" diff --git a/chromium_src/chrome/renderer/printing/print_web_view_helper.h b/chromium_src/chrome/renderer/printing/print_web_view_helper.h index e3e6448809..0a00f2ebb1 100644 --- a/chromium_src/chrome/renderer/printing/print_web_view_helper.h +++ b/chromium_src/chrome/renderer/printing/print_web_view_helper.h @@ -5,11 +5,11 @@ #ifndef CHROME_RENDERER_PRINTING_PRINT_WEB_VIEW_HELPER_H_ #define CHROME_RENDERER_PRINTING_PRINT_WEB_VIEW_HELPER_H_ +#include #include #include "base/callback.h" #include "base/gtest_prod_util.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/shared_memory.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" diff --git a/chromium_src/chrome/renderer/printing/print_web_view_helper_linux.cc b/chromium_src/chrome/renderer/printing/print_web_view_helper_linux.cc index 608f406e62..216d8236a8 100644 --- a/chromium_src/chrome/renderer/printing/print_web_view_helper_linux.cc +++ b/chromium_src/chrome/renderer/printing/print_web_view_helper_linux.cc @@ -4,8 +4,9 @@ #include "chrome/renderer/printing/print_web_view_helper.h" +#include + #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "chrome/common/print_messages.h" #include "content/public/renderer/render_thread.h" #include "printing/metafile_skia_wrapper.h" diff --git a/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc b/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc index 7ff17a388b..96a128652a 100644 --- a/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc +++ b/chromium_src/chrome/renderer/printing/print_web_view_helper_pdf_win.cc @@ -4,8 +4,9 @@ #include "chrome/renderer/printing/print_web_view_helper.h" +#include + #include "base/logging.h" -#include "base/memory/scoped_ptr.h" #include "base/process/process_handle.h" #include "chrome/common/print_messages.h" #include "content/public/renderer/render_thread.h" diff --git a/chromium_src/chrome/renderer/spellchecker/spellcheck_worditerator.h b/chromium_src/chrome/renderer/spellchecker/spellcheck_worditerator.h index 4490c7a90e..7e07d29273 100644 --- a/chromium_src/chrome/renderer/spellchecker/spellcheck_worditerator.h +++ b/chromium_src/chrome/renderer/spellchecker/spellcheck_worditerator.h @@ -9,10 +9,10 @@ #ifndef CHROME_RENDERER_SPELLCHECKER_SPELLCHECK_WORDITERATOR_H_ #define CHROME_RENDERER_SPELLCHECKER_SPELLCHECK_WORDITERATOR_H_ +#include #include #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" #include "third_party/icu/source/common/unicode/uscript.h" diff --git a/chromium_src/chrome/renderer/tts_dispatcher.h b/chromium_src/chrome/renderer/tts_dispatcher.h index 0a770d7218..45db9751c8 100644 --- a/chromium_src/chrome/renderer/tts_dispatcher.h +++ b/chromium_src/chrome/renderer/tts_dispatcher.h @@ -8,7 +8,7 @@ #include #include "base/containers/hash_tables.h" -#include "content/public/renderer/render_process_observer.h" +#include "content/public/renderer/render_thread_observer.h" #include "third_party/WebKit/public/platform/WebSpeechSynthesizer.h" #include "third_party/WebKit/public/platform/WebSpeechSynthesizerClient.h" @@ -27,7 +27,7 @@ struct TtsVoice; // the utterance id (which is globally unique) matches. class TtsDispatcher : public blink::WebSpeechSynthesizer, - public content::RenderProcessObserver { + public content::RenderThreadObserver { public: explicit TtsDispatcher(blink::WebSpeechSynthesizerClient* client); diff --git a/chromium_src/net/test/embedded_test_server/stream_listen_socket.cc b/chromium_src/net/test/embedded_test_server/stream_listen_socket.cc index 2514c636cb..0b16c1395e 100644 --- a/chromium_src/net/test/embedded_test_server/stream_listen_socket.cc +++ b/chromium_src/net/test/embedded_test_server/stream_listen_socket.cc @@ -4,6 +4,8 @@ #include "net/test/embedded_test_server/stream_listen_socket.h" +#include + #if defined(OS_WIN) // winsock2.h must be included first in order to ensure it is included before // windows.h. @@ -20,7 +22,6 @@ #include "base/files/file_util.h" #include "base/logging.h" #include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" #include "base/posix/eintr_wrapper.h" #include "base/sys_byteorder.h" #include "base/threading/platform_thread.h" diff --git a/chromium_src/net/test/embedded_test_server/stream_listen_socket.h b/chromium_src/net/test/embedded_test_server/stream_listen_socket.h index 7ad25437ec..00d4b58dcf 100644 --- a/chromium_src/net/test/embedded_test_server/stream_listen_socket.h +++ b/chromium_src/net/test/embedded_test_server/stream_listen_socket.h @@ -16,6 +16,8 @@ #ifndef NET_TEST_EMBEDDED_TEST_SERVER_STREAM_LISTEN_SOCKET_H_ #define NET_TEST_EMBEDDED_TEST_SERVER_STREAM_LISTEN_SOCKET_H_ +#include + #include "build/build_config.h" #if defined(OS_WIN) @@ -30,7 +32,6 @@ #include "base/macros.h" #include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" #include "net/base/net_export.h" #include "net/socket/socket_descriptor.h" diff --git a/common.gypi b/common.gypi index 3389e18690..2a22c957c9 100644 --- a/common.gypi +++ b/common.gypi @@ -14,11 +14,14 @@ 'python': 'python', 'openssl_fips': '', 'openssl_no_asm': 1, + 'use_openssl_def': 0, + 'OPENSSL_PRODUCT': 'libopenssl.a', 'node_release_urlbase': 'https://atom.io/download/atom-shell', 'node_byteorder': ' { @@ -9,13 +10,18 @@ app.on('window-all-closed', () => { exports.load = (appUrl) => { app.on('ready', () => { - mainWindow = new BrowserWindow({ + const options = { width: 800, height: 600, autoHideMenuBar: true, backgroundColor: '#FFFFFF', useContentSize: true - }) + } + if (process.platform === 'linux') { + options.icon = path.join(__dirname, 'icon.png') + } + + mainWindow = new BrowserWindow(options) mainWindow.loadURL(appUrl) mainWindow.focus() }) diff --git a/default_app/icon.png b/default_app/icon.png new file mode 100644 index 0000000000..ac3a6547d9 Binary files /dev/null and b/default_app/icon.png differ diff --git a/default_app/index.html b/default_app/index.html index edfb3e6ddc..67e3e249e3 100644 --- a/default_app/index.html +++ b/default_app/index.html @@ -1,9 +1,9 @@ - + Electron