Merge pull request #1874 from atom/fewer-code

Remove duplicate code between api::WebContents and NativeWindow
This commit is contained in:
Cheng Zhao 2015-06-05 18:40:38 +08:00
commit cd7b3dd291
13 changed files with 687 additions and 676 deletions

View file

@ -8,9 +8,7 @@
#include "atom/browser/atom_browser_client.h" #include "atom/browser/atom_browser_client.h"
#include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_javascript_dialog_manager.h"
#include "atom/browser/native_window.h" #include "atom/browser/native_window.h"
#include "atom/browser/web_dialog_helper.h"
#include "atom/browser/web_view_manager.h" #include "atom/browser/web_view_manager.h"
#include "atom/common/api/api_messages.h" #include "atom/common/api/api_messages.h"
#include "atom/common/native_mate_converters/gfx_converter.h" #include "atom/common/native_mate_converters/gfx_converter.h"
@ -21,7 +19,6 @@
#include "base/strings/string_util.h" #include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h" #include "base/strings/utf_string_conversions.h"
#include "brightray/browser/inspectable_web_contents.h" #include "brightray/browser/inspectable_web_contents.h"
#include "brightray/browser/media/media_stream_devices_controller.h"
#include "content/public/browser/favicon_status.h" #include "content/public/browser/favicon_status.h"
#include "content/public/browser/guest_host.h" #include "content/public/browser/guest_host.h"
#include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_details.h"
@ -82,6 +79,10 @@ const int kDefaultHeight = 300;
v8::Persistent<v8::ObjectTemplate> template_; v8::Persistent<v8::ObjectTemplate> template_;
// The wrapWebContents funtion which is implemented in JavaScript
using WrapWebContentsCallback = base::Callback<void(v8::Local<v8::Value>)>;
WrapWebContentsCallback g_wrap_web_contents;
// Get the window that has the |guest| embedded. // Get the window that has the |guest| embedded.
NativeWindow* GetWindowFromGuest(const content::WebContents* guest) { NativeWindow* GetWindowFromGuest(const content::WebContents* guest) {
WebViewManager::WebViewInfo info; WebViewManager::WebViewInfo info;
@ -98,28 +99,35 @@ content::ServiceWorkerContext* GetServiceWorkerContext(
if (!context || !site_instance) if (!context || !site_instance)
return nullptr; return nullptr;
content::StoragePartition* storage_partition = auto storage_partition =
content::BrowserContext::GetStoragePartition( content::BrowserContext::GetStoragePartition(context, site_instance);
context, site_instance); if (!storage_partition)
return nullptr;
DCHECK(storage_partition);
return storage_partition->GetServiceWorkerContext(); return storage_partition->GetServiceWorkerContext();
} }
} // namespace } // namespace
WebContents::WebContents(brightray::InspectableWebContents* web_contents)
: WebContents(web_contents->GetWebContents()) {
inspectable_web_contents_ = web_contents;
}
WebContents::WebContents(content::WebContents* web_contents) WebContents::WebContents(content::WebContents* web_contents)
: content::WebContentsObserver(web_contents), : CommonWebContentsDelegate(false),
content::WebContentsObserver(web_contents),
guest_instance_id_(-1), guest_instance_id_(-1),
guest_opaque_(true), guest_opaque_(true),
guest_host_(nullptr), guest_host_(nullptr),
auto_size_enabled_(false), auto_size_enabled_(false),
is_full_page_plugin_(false) { is_full_page_plugin_(false),
inspectable_web_contents_(nullptr) {
} }
WebContents::WebContents(const mate::Dictionary& options) WebContents::WebContents(const mate::Dictionary& options)
: guest_instance_id_(-1), : CommonWebContentsDelegate(true),
guest_instance_id_(-1),
guest_opaque_(true), guest_opaque_(true),
guest_host_(nullptr), guest_host_(nullptr),
auto_size_enabled_(false), auto_size_enabled_(false),
@ -135,9 +143,11 @@ WebContents::WebContents(const mate::Dictionary& options)
if (options.Get("isGuest", &is_guest) && is_guest) if (options.Get("isGuest", &is_guest) && is_guest)
params.guest_delegate = this; params.guest_delegate = this;
storage_.reset(brightray::InspectableWebContents::Create(params)); auto web_contents = content::WebContents::Create(params);
Observe(storage_->GetWebContents()); InitWithWebContents(web_contents, GetWindowFromGuest(web_contents));
web_contents()->SetDelegate(this); inspectable_web_contents_ = managed_web_contents();
Observe(GetWebContents());
} }
WebContents::~WebContents() { WebContents::~WebContents() {
@ -185,56 +195,7 @@ content::WebContents* WebContents::OpenURLFromTab(
if (Emit("will-navigate", params.url)) if (Emit("will-navigate", params.url))
return nullptr; return nullptr;
content::NavigationController::LoadURLParams load_url_params(params.url); return CommonWebContentsDelegate::OpenURLFromTab(source, params);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.transferred_global_request_id =
params.transferred_global_request_id;
load_url_params.should_clear_history_list = true;
web_contents()->GetController().LoadURLWithParams(load_url_params);
return web_contents();
}
content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
content::WebContents* source) {
if (!dialog_manager_)
dialog_manager_.reset(new AtomJavaScriptDialogManager);
return dialog_manager_.get();
}
void WebContents::RunFileChooser(content::WebContents* guest,
const content::FileChooserParams& params) {
if (!web_dialog_helper_)
web_dialog_helper_.reset(new WebDialogHelper(GetWindowFromGuest(guest)));
web_dialog_helper_->RunFileChooser(guest, params);
}
void WebContents::EnumerateDirectory(content::WebContents* guest,
int request_id,
const base::FilePath& path) {
if (!web_dialog_helper_)
web_dialog_helper_.reset(new WebDialogHelper(GetWindowFromGuest(guest)));
web_dialog_helper_->EnumerateDirectory(guest, request_id, path);
}
bool WebContents::CheckMediaAccessPermission(content::WebContents* web_contents,
const GURL& security_origin,
content::MediaStreamType type) {
return true;
}
void WebContents::RequestMediaAccessPermission(
content::WebContents*,
const content::MediaStreamRequest& request,
const content::MediaResponseCallback& callback) {
brightray::MediaStreamDevicesController controller(request, callback);
controller.TakeAction();
} }
void WebContents::HandleKeyboardEvent( void WebContents::HandleKeyboardEvent(
@ -250,32 +211,13 @@ void WebContents::HandleKeyboardEvent(
void WebContents::EnterFullscreenModeForTab(content::WebContents* source, void WebContents::EnterFullscreenModeForTab(content::WebContents* source,
const GURL& origin) { const GURL& origin) {
auto window = GetWindowFromGuest(source); CommonWebContentsDelegate::EnterFullscreenModeForTab(source, origin);
if (window) { Emit("enter-html-full-screen");
window->SetHtmlApiFullscreen(true);
window->NotifyWindowEnterHtmlFullScreen();
source->GetRenderViewHost()->WasResized();
Emit("enter-html-full-screen");
}
} }
void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
auto window = GetWindowFromGuest(source); CommonWebContentsDelegate::ExitFullscreenModeForTab(source);
if (window) { Emit("leave-html-full-screen");
window->SetHtmlApiFullscreen(false);
window->NotifyWindowLeaveHtmlFullScreen();
source->GetRenderViewHost()->WasResized();
Emit("leave-html-full-screen");
}
}
bool WebContents::IsFullscreenForTabOrPending(
const content::WebContents* source) const {
auto window = GetWindowFromGuest(source);
if (window)
return window->is_html_api_fullscreen();
else
return false;
} }
void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
@ -421,15 +363,11 @@ void WebContents::RenderViewReady() {
// WebContents::GetRenderWidgetHostView will return the RWHV of an // WebContents::GetRenderWidgetHostView will return the RWHV of an
// interstitial page if one is showing at this time. We only want opacity // interstitial page if one is showing at this time. We only want opacity
// to apply to web pages. // to apply to web pages.
if (guest_opaque_) { auto render_view_host_view = web_contents()->GetRenderViewHost()->GetView();
web_contents() if (guest_opaque_)
->GetRenderViewHost() render_view_host_view->SetBackgroundColorToDefault();
->GetView() else
->SetBackgroundColorToDefault(); render_view_host_view->SetBackgroundColor(SK_ColorTRANSPARENT);
} else {
web_contents()->GetRenderViewHost()->GetView()->SetBackgroundColor(
SK_ColorTRANSPARENT);
}
} }
void WebContents::WebContentsDestroyed() { void WebContents::WebContentsDestroyed() {
@ -471,7 +409,7 @@ void WebContents::WillAttach(content::WebContents* embedder_web_contents,
} }
void WebContents::Destroy() { void WebContents::Destroy() {
if (storage_) { if (is_guest() && managed_web_contents()) {
// When force destroying the "destroyed" event is not emitted. // When force destroying the "destroyed" event is not emitted.
WebContentsDestroyed(); WebContentsDestroyed();
@ -480,7 +418,7 @@ void WebContents::Destroy() {
guest_host_ = nullptr; guest_host_ = nullptr;
Observe(nullptr); Observe(nullptr);
storage_.reset(); DestroyWebContents();
} }
} }
@ -565,26 +503,82 @@ void WebContents::ExecuteJavaScript(const base::string16& code) {
web_contents()->GetMainFrame()->ExecuteJavaScript(code); web_contents()->GetMainFrame()->ExecuteJavaScript(code);
} }
void WebContents::OpenDevTools() { void WebContents::OpenDevTools(mate::Arguments* args) {
storage_->SetCanDock(false); if (!inspectable_web_contents())
storage_->ShowDevTools(); return;
bool detach = false;
if (is_guest()) {
detach = true;
} else if (args && args->Length() == 1) {
mate::Dictionary options;
args->GetNext(&options) && options.Get("detach", &detach);
}
inspectable_web_contents()->SetCanDock(!detach);
inspectable_web_contents()->ShowDevTools();
} }
void WebContents::CloseDevTools() { void WebContents::CloseDevTools() {
storage_->CloseDevTools(); if (!inspectable_web_contents())
return;
inspectable_web_contents()->CloseDevTools();
} }
bool WebContents::IsDevToolsOpened() { bool WebContents::IsDevToolsOpened() {
return storage_->IsDevToolsViewShowing(); if (!inspectable_web_contents())
return false;
return inspectable_web_contents()->IsDevToolsViewShowing();
}
void WebContents::ToggleDevTools() {
if (IsDevToolsOpened())
CloseDevTools();
else
OpenDevTools(nullptr);
} }
void WebContents::InspectElement(int x, int y) { void WebContents::InspectElement(int x, int y) {
OpenDevTools(); if (!inspectable_web_contents())
return;
OpenDevTools(nullptr);
scoped_refptr<content::DevToolsAgentHost> agent( scoped_refptr<content::DevToolsAgentHost> agent(
content::DevToolsAgentHost::GetOrCreateFor(storage_->GetWebContents())); content::DevToolsAgentHost::GetOrCreateFor(web_contents()));
agent->InspectElement(x, y); agent->InspectElement(x, y);
} }
void WebContents::InspectServiceWorker() {
if (!inspectable_web_contents())
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::TYPE_SERVICE_WORKER) {
OpenDevTools(nullptr);
inspectable_web_contents()->AttachTo(agent_host);
break;
}
}
}
void WebContents::HasServiceWorker(
const base::Callback<void(bool)>& callback) {
auto context = GetServiceWorkerContext(web_contents());
if (!context)
return;
context->CheckHasServiceWorker(web_contents()->GetLastCommittedURL(),
GURL::EmptyGURL(),
callback);
}
void WebContents::UnregisterServiceWorker(
const base::Callback<void(bool)>& callback) {
auto context = GetServiceWorkerContext(web_contents());
if (!context)
return;
context->UnregisterServiceWorker(web_contents()->GetLastCommittedURL(),
callback);
}
void WebContents::Undo() { void WebContents::Undo() {
web_contents()->Undo(); web_contents()->Undo();
} }
@ -706,36 +700,8 @@ void WebContents::SetAllowTransparency(bool allow) {
} }
} }
void WebContents::HasServiceWorker( bool WebContents::IsGuest() const {
const base::Callback<void(bool)>& callback) { return is_guest();
auto context = GetServiceWorkerContext(web_contents());
if (!context)
return;
context->CheckHasServiceWorker(web_contents()->GetLastCommittedURL(),
GURL::EmptyGURL(),
callback);
}
void WebContents::UnregisterServiceWorker(
const base::Callback<void(bool)>& callback) {
auto context = GetServiceWorkerContext(web_contents());
if (!context)
return;
context->UnregisterServiceWorker(web_contents()->GetLastCommittedURL(),
callback);
}
void WebContents::InspectServiceWorker() {
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::TYPE_SERVICE_WORKER) {
OpenDevTools();
storage_->AttachTo(agent_host);
break;
}
}
} }
mate::ObjectTemplateBuilder WebContents::GetObjectTemplateBuilder( mate::ObjectTemplateBuilder WebContents::GetObjectTemplateBuilder(
@ -762,6 +728,7 @@ mate::ObjectTemplateBuilder WebContents::GetObjectTemplateBuilder(
.SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("openDevTools", &WebContents::OpenDevTools)
.SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools)
.SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
.SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
.SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("inspectElement", &WebContents::InspectElement)
.SetMethod("undo", &WebContents::Undo) .SetMethod("undo", &WebContents::Undo)
.SetMethod("redo", &WebContents::Redo) .SetMethod("redo", &WebContents::Redo)
@ -777,7 +744,7 @@ mate::ObjectTemplateBuilder WebContents::GetObjectTemplateBuilder(
.SetMethod("_send", &WebContents::SendIPCMessage) .SetMethod("_send", &WebContents::SendIPCMessage)
.SetMethod("setSize", &WebContents::SetSize) .SetMethod("setSize", &WebContents::SetSize)
.SetMethod("setAllowTransparency", &WebContents::SetAllowTransparency) .SetMethod("setAllowTransparency", &WebContents::SetAllowTransparency)
.SetMethod("isGuest", &WebContents::is_guest) .SetMethod("isGuest", &WebContents::IsGuest)
.SetMethod("hasServiceWorker", &WebContents::HasServiceWorker) .SetMethod("hasServiceWorker", &WebContents::HasServiceWorker)
.SetMethod("unregisterServiceWorker", .SetMethod("unregisterServiceWorker",
&WebContents::UnregisterServiceWorker) &WebContents::UnregisterServiceWorker)
@ -818,16 +785,36 @@ gfx::Size WebContents::GetDefaultSize() const {
} }
} }
// static
mate::Handle<WebContents> WebContents::CreateFrom(
v8::Isolate* isolate, brightray::InspectableWebContents* web_contents) {
auto handle = mate::CreateHandle(isolate, new WebContents(web_contents));
g_wrap_web_contents.Run(handle.ToV8());
return handle;
}
// static // static
mate::Handle<WebContents> WebContents::CreateFrom( mate::Handle<WebContents> WebContents::CreateFrom(
v8::Isolate* isolate, content::WebContents* web_contents) { v8::Isolate* isolate, content::WebContents* web_contents) {
return mate::CreateHandle(isolate, new WebContents(web_contents)); auto handle = mate::CreateHandle(isolate, new WebContents(web_contents));
g_wrap_web_contents.Run(handle.ToV8());
return handle;
} }
// static // static
mate::Handle<WebContents> WebContents::Create( mate::Handle<WebContents> WebContents::Create(
v8::Isolate* isolate, const mate::Dictionary& options) { v8::Isolate* isolate, const mate::Dictionary& options) {
return mate::CreateHandle(isolate, new WebContents(options)); auto handle = mate::CreateHandle(isolate, new WebContents(options));
g_wrap_web_contents.Run(handle.ToV8());
return handle;
}
void SetWrapWebContents(const WrapWebContentsCallback& callback) {
g_wrap_web_contents = callback;
}
void ClearWrapWebContents() {
g_wrap_web_contents.Reset();
} }
} // namespace api } // namespace api
@ -842,6 +829,8 @@ void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Isolate* isolate = context->GetIsolate(); v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports); mate::Dictionary dict(isolate, exports);
dict.SetMethod("create", &atom::api::WebContents::Create); dict.SetMethod("create", &atom::api::WebContents::Create);
dict.SetMethod("_setWrapWebContents", &atom::api::SetWrapWebContents);
dict.SetMethod("_clearWrapWebContents", &atom::api::ClearWrapWebContents);
} }
} // namespace } // namespace

View file

@ -9,10 +9,9 @@
#include <vector> #include <vector>
#include "atom/browser/api/event_emitter.h" #include "atom/browser/api/event_emitter.h"
#include "brightray/browser/default_web_contents_delegate.h" #include "atom/browser/common_web_contents_delegate.h"
#include "content/public/browser/browser_plugin_guest_delegate.h" #include "content/public/browser/browser_plugin_guest_delegate.h"
#include "content/public/common/favicon_url.h" #include "content/public/common/favicon_url.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/gpu_data_manager_observer.h" #include "content/public/browser/gpu_data_manager_observer.h"
#include "native_mate/handle.h" #include "native_mate/handle.h"
@ -23,14 +22,12 @@ class InspectableWebContents;
} }
namespace mate { namespace mate {
class Arguments;
class Dictionary; class Dictionary;
} }
namespace atom { namespace atom {
class AtomJavaScriptDialogManager;
class WebDialogHelper;
namespace api { namespace api {
// A struct of parameters for SetSize(). The parameters are all declared as // A struct of parameters for SetSize(). The parameters are all declared as
@ -51,11 +48,13 @@ struct SetSizeParams {
class WebContents : public mate::EventEmitter, class WebContents : public mate::EventEmitter,
public content::BrowserPluginGuestDelegate, public content::BrowserPluginGuestDelegate,
public content::WebContentsDelegate, public CommonWebContentsDelegate,
public content::WebContentsObserver, public content::WebContentsObserver,
public content::GpuDataManagerObserver { public content::GpuDataManagerObserver {
public: public:
// Create from an existing WebContents. // Create from an existing WebContents.
static mate::Handle<WebContents> CreateFrom(
v8::Isolate* isolate, brightray::InspectableWebContents* web_contents);
static mate::Handle<WebContents> CreateFrom( static mate::Handle<WebContents> CreateFrom(
v8::Isolate* isolate, content::WebContents* web_contents); v8::Isolate* isolate, content::WebContents* web_contents);
@ -80,13 +79,14 @@ class WebContents : public mate::EventEmitter,
void SetUserAgent(const std::string& user_agent); void SetUserAgent(const std::string& user_agent);
void InsertCSS(const std::string& css); void InsertCSS(const std::string& css);
void ExecuteJavaScript(const base::string16& code); void ExecuteJavaScript(const base::string16& code);
void OpenDevTools(); void OpenDevTools(mate::Arguments* args);
void CloseDevTools(); void CloseDevTools();
bool IsDevToolsOpened(); bool IsDevToolsOpened();
void ToggleDevTools();
void InspectElement(int x, int y); void InspectElement(int x, int y);
void InspectServiceWorker();
void HasServiceWorker(const base::Callback<void(bool)>&); void HasServiceWorker(const base::Callback<void(bool)>&);
void UnregisterServiceWorker(const base::Callback<void(bool)>&); void UnregisterServiceWorker(const base::Callback<void(bool)>&);
void InspectServiceWorker();
// Editing commands. // Editing commands.
void Undo(); void Undo();
@ -112,17 +112,19 @@ class WebContents : public mate::EventEmitter,
// Sets the transparency of the guest. // Sets the transparency of the guest.
void SetAllowTransparency(bool allow); void SetAllowTransparency(bool allow);
// Returns whether this is a guest view. bool IsGuest() const;
bool is_guest() const { return guest_instance_id_ != -1; }
// Returns whether this guest has an associated embedder. // Returns whether this guest has an associated embedder.
bool attached() const { return !!embedder_web_contents_; } bool attached() const { return !!embedder_web_contents_; }
content::WebContents* web_contents() const { // Returns the current InspectableWebContents object, nullptr will be returned
return content::WebContentsObserver::web_contents(); // if current WebContents can not beinspected, e.g. it is the devtools.
brightray::InspectableWebContents* inspectable_web_contents() const {
return inspectable_web_contents_;
} }
protected: protected:
explicit WebContents(brightray::InspectableWebContents* web_contents);
explicit WebContents(content::WebContents* web_contents); explicit WebContents(content::WebContents* web_contents);
explicit WebContents(const mate::Dictionary& options); explicit WebContents(const mate::Dictionary& options);
~WebContents(); ~WebContents();
@ -150,28 +152,12 @@ class WebContents : public mate::EventEmitter,
content::WebContents* OpenURLFromTab( content::WebContents* OpenURLFromTab(
content::WebContents* source, content::WebContents* source,
const content::OpenURLParams& params) override; const content::OpenURLParams& params) override;
content::JavaScriptDialogManager* GetJavaScriptDialogManager(
content::WebContents* source) override;
void RunFileChooser(content::WebContents* web_contents,
const content::FileChooserParams& params) override;
void EnumerateDirectory(content::WebContents* web_contents,
int request_id,
const base::FilePath& path) override;
bool CheckMediaAccessPermission(content::WebContents* web_contents,
const GURL& security_origin,
content::MediaStreamType type) override;
void RequestMediaAccessPermission(
content::WebContents*,
const content::MediaStreamRequest&,
const content::MediaResponseCallback&) override;
void HandleKeyboardEvent( void HandleKeyboardEvent(
content::WebContents* source, content::WebContents* source,
const content::NativeWebKeyboardEvent& event) override; const content::NativeWebKeyboardEvent& event) override;
void EnterFullscreenModeForTab(content::WebContents* source, void EnterFullscreenModeForTab(content::WebContents* source,
const GURL& origin) override; const GURL& origin) override;
void ExitFullscreenModeForTab(content::WebContents* source) override; void ExitFullscreenModeForTab(content::WebContents* source) override;
bool IsFullscreenForTabOrPending(
const content::WebContents* source) const override;
// content::WebContentsObserver: // content::WebContentsObserver:
void RenderViewDeleted(content::RenderViewHost*) override; void RenderViewDeleted(content::RenderViewHost*) override;
@ -242,18 +228,12 @@ class WebContents : public mate::EventEmitter,
// Returns the default size of the guestview. // Returns the default size of the guestview.
gfx::Size GetDefaultSize() const; gfx::Size GetDefaultSize() const;
scoped_ptr<WebDialogHelper> web_dialog_helper_;
scoped_ptr<AtomJavaScriptDialogManager> dialog_manager_;
// Unique ID for a guest WebContents. // Unique ID for a guest WebContents.
int guest_instance_id_; int guest_instance_id_;
// Stores whether the contents of the guest can be transparent. // Stores whether the contents of the guest can be transparent.
bool guest_opaque_; bool guest_opaque_;
// Stores the WebContents that managed by this class.
scoped_ptr<brightray::InspectableWebContents> storage_;
// The WebContents that attaches this guest view. // The WebContents that attaches this guest view.
content::WebContents* embedder_web_contents_; content::WebContents* embedder_web_contents_;
@ -282,6 +262,10 @@ class WebContents : public mate::EventEmitter,
// Whether the guest view is inside a plugin document. // Whether the guest view is inside a plugin document.
bool is_full_page_plugin_; bool is_full_page_plugin_;
// Current InspectableWebContents object, can be nullptr for WebContents of
// devtools. It is a weak reference.
brightray::InspectableWebContents* inspectable_web_contents_;
DISALLOW_COPY_AND_ASSIGN(WebContents); DISALLOW_COPY_AND_ASSIGN(WebContents);
}; };

View file

@ -165,6 +165,26 @@ void Window::OnDevToolsFocus() {
Emit("devtools-focused"); Emit("devtools-focused");
} }
void Window::OnDevToolsOpened() {
Emit("devtools-opened");
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
auto handle =
WebContents::CreateFrom(isolate, window_->GetDevToolsWebContents());
devtools_web_contents_.Reset(isolate, handle.ToV8());
}
void Window::OnDevToolsClosed() {
Emit("devtools-closed");
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
devtools_web_contents_.Reset();
}
// static // static
mate::Wrappable* Window::New(v8::Isolate* isolate, mate::Wrappable* Window::New(v8::Isolate* isolate,
const mate::Dictionary& options) { const mate::Dictionary& options) {
@ -356,26 +376,6 @@ bool Window::IsKiosk() {
return window_->IsKiosk(); return window_->IsKiosk();
} }
void Window::OpenDevTools(bool can_dock) {
window_->OpenDevTools(can_dock);
}
void Window::CloseDevTools() {
window_->CloseDevTools();
}
bool Window::IsDevToolsOpened() {
return window_->IsDevToolsOpened();
}
void Window::InspectElement(int x, int y) {
window_->InspectElement(x, y);
}
void Window::InspectServiceWorker() {
window_->InspectServiceWorker();
}
void Window::FocusOnWebView() { void Window::FocusOnWebView() {
window_->FocusOnWebView(); window_->FocusOnWebView();
} }
@ -472,13 +472,20 @@ bool Window::IsVisibleOnAllWorkspaces() {
return window_->IsVisibleOnAllWorkspaces(); return window_->IsVisibleOnAllWorkspaces();
} }
mate::Handle<WebContents> Window::GetWebContents(v8::Isolate* isolate) const { v8::Local<v8::Value> Window::WebContents(v8::Isolate* isolate) {
return WebContents::CreateFrom(isolate, window_->GetWebContents()); if (web_contents_.IsEmpty()) {
auto handle =
WebContents::CreateFrom(isolate, window_->managed_web_contents());
web_contents_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, web_contents_);
} }
mate::Handle<WebContents> Window::GetDevToolsWebContents( v8::Local<v8::Value> Window::DevToolsWebContents(v8::Isolate* isolate) {
v8::Isolate* isolate) const { if (devtools_web_contents_.IsEmpty())
return WebContents::CreateFrom(isolate, window_->GetDevToolsWebContents()); return v8::Null(isolate);
else
return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
} }
// static // static
@ -529,10 +536,6 @@ void Window::BuildPrototype(v8::Isolate* isolate,
.SetMethod("getRepresentedFilename", &Window::GetRepresentedFilename) .SetMethod("getRepresentedFilename", &Window::GetRepresentedFilename)
.SetMethod("setDocumentEdited", &Window::SetDocumentEdited) .SetMethod("setDocumentEdited", &Window::SetDocumentEdited)
.SetMethod("isDocumentEdited", &Window::IsDocumentEdited) .SetMethod("isDocumentEdited", &Window::IsDocumentEdited)
.SetMethod("_openDevTools", &Window::OpenDevTools)
.SetMethod("closeDevTools", &Window::CloseDevTools)
.SetMethod("isDevToolsOpened", &Window::IsDevToolsOpened)
.SetMethod("_inspectElement", &Window::InspectElement)
.SetMethod("focusOnWebView", &Window::FocusOnWebView) .SetMethod("focusOnWebView", &Window::FocusOnWebView)
.SetMethod("blurWebView", &Window::BlurWebView) .SetMethod("blurWebView", &Window::BlurWebView)
.SetMethod("isWebViewFocused", &Window::IsWebViewFocused) .SetMethod("isWebViewFocused", &Window::IsWebViewFocused)
@ -553,9 +556,8 @@ void Window::BuildPrototype(v8::Isolate* isolate,
.SetMethod("showDefinitionForSelection", .SetMethod("showDefinitionForSelection",
&Window::ShowDefinitionForSelection) &Window::ShowDefinitionForSelection)
#endif #endif
.SetMethod("_getWebContents", &Window::GetWebContents) .SetProperty("webContents", &Window::WebContents)
.SetMethod("_getDevToolsWebContents", &Window::GetDevToolsWebContents) .SetProperty("devToolsWebContents", &Window::DevToolsWebContents);
.SetMethod("_inspectServiceWorker", &Window::InspectServiceWorker);
} }
} // namespace api } // namespace api

View file

@ -78,6 +78,8 @@ class Window : public mate::EventEmitter,
void OnRendererUnresponsive() override; void OnRendererUnresponsive() override;
void OnRendererResponsive() override; void OnRendererResponsive() override;
void OnDevToolsFocus() override; void OnDevToolsFocus() override;
void OnDevToolsOpened() override;
void OnDevToolsClosed() override;
private: private:
// APIs for NativeWindow. // APIs for NativeWindow.
@ -121,11 +123,6 @@ class Window : public mate::EventEmitter,
void SetSkipTaskbar(bool skip); void SetSkipTaskbar(bool skip);
void SetKiosk(bool kiosk); void SetKiosk(bool kiosk);
bool IsKiosk(); bool IsKiosk();
void OpenDevTools(bool can_dock);
void CloseDevTools();
bool IsDevToolsOpened();
void InspectElement(int x, int y);
void InspectServiceWorker();
void FocusOnWebView(); void FocusOnWebView();
void BlurWebView(); void BlurWebView();
bool IsWebViewFocused(); bool IsWebViewFocused();
@ -151,9 +148,11 @@ class Window : public mate::EventEmitter,
void SetVisibleOnAllWorkspaces(bool visible); void SetVisibleOnAllWorkspaces(bool visible);
bool IsVisibleOnAllWorkspaces(); bool IsVisibleOnAllWorkspaces();
// APIs for WebContents. v8::Local<v8::Value> WebContents(v8::Isolate* isolate);
mate::Handle<WebContents> GetWebContents(v8::Isolate* isolate) const; v8::Local<v8::Value> DevToolsWebContents(v8::Isolate* isolate);
mate::Handle<WebContents> GetDevToolsWebContents(v8::Isolate* isolate) const;
v8::Global<v8::Value> web_contents_;
v8::Global<v8::Value> devtools_web_contents_;
scoped_ptr<NativeWindow> window_; scoped_ptr<NativeWindow> window_;

View file

@ -2,7 +2,6 @@ EventEmitter = require('events').EventEmitter
IDWeakMap = require 'id-weak-map' IDWeakMap = require 'id-weak-map'
app = require 'app' app = require 'app'
ipc = require 'ipc' ipc = require 'ipc'
wrapWebContents = require('web-contents').wrap
BrowserWindow = process.atomBinding('window').BrowserWindow BrowserWindow = process.atomBinding('window').BrowserWindow
BrowserWindow::__proto__ = EventEmitter.prototype BrowserWindow::__proto__ = EventEmitter.prototype
@ -16,10 +15,6 @@ BrowserWindow::_init = ->
menu = app.getApplicationMenu() menu = app.getApplicationMenu()
@setMenu menu if menu? @setMenu menu if menu?
@webContents = @getWebContents()
@devToolsWebContents = null
@webContents.once 'destroyed', => @webContents = null
# Remember the window ID. # Remember the window ID.
Object.defineProperty this, 'id', Object.defineProperty this, 'id',
value: BrowserWindow.windows.add(this) value: BrowserWindow.windows.add(this)
@ -40,35 +35,6 @@ BrowserWindow::_init = ->
@once 'closed', => @once 'closed', =>
BrowserWindow.windows.remove @id if BrowserWindow.windows.has @id BrowserWindow.windows.remove @id if BrowserWindow.windows.has @id
BrowserWindow::openDevTools = (options={}) ->
options.detach ?= false
@_openDevTools !options.detach
# Force devToolsWebContents to be created.
@devToolsWebContents = @getDevToolsWebContents()
@devToolsWebContents.once 'destroyed', => @devToolsWebContents = null
# Emit devtools events.
@devToolsWebContents.once 'did-finish-load', => @emit 'devtools-opened'
@devToolsWebContents.once 'destroyed', => @emit 'devtools-closed'
BrowserWindow::toggleDevTools = ->
if @isDevToolsOpened() then @closeDevTools() else @openDevTools()
BrowserWindow::inspectElement = (x, y) ->
@openDevTools true
@_inspectElement x, y
BrowserWindow::inspectServiceWorker = ->
@openDevTools true
@_inspectServiceWorker()
BrowserWindow::getWebContents = ->
wrapWebContents @_getWebContents()
BrowserWindow::getDevToolsWebContents = ->
wrapWebContents @_getDevToolsWebContents()
BrowserWindow::setMenu = (menu) -> BrowserWindow::setMenu = (menu) ->
throw new TypeError('Invalid menu') unless menu is null or menu?.constructor?.name is 'Menu' throw new TypeError('Invalid menu') unless menu is null or menu?.constructor?.name is 'Menu'
@ -110,7 +76,12 @@ BrowserWindow::stop = -> @webContents.stop()
BrowserWindow::getRoutingId = -> @webContents.getRoutingId() BrowserWindow::getRoutingId = -> @webContents.getRoutingId()
BrowserWindow::getProcessId = -> @webContents.getProcessId() BrowserWindow::getProcessId = -> @webContents.getProcessId()
BrowserWindow::isCrashed = -> @webContents.isCrashed() BrowserWindow::isCrashed = -> @webContents.isCrashed()
BrowserWindow::executeJavaScriptInDevTools = (code) -> BrowserWindow::executeJavaScriptInDevTools = (code) -> @devToolsWebContents?.executeJavaScript code
@devToolsWebContents.executeJavaScript code BrowserWindow::openDevTools = -> @webContents.openDevTools.apply @webContents, arguments
BrowserWindow::closeDevTools = -> @webContents.closeDevTools()
BrowserWindow::isDevToolsOpened = -> @webContents.isDevToolsOpened()
BrowserWindow::toggleDevTools = -> @webContents.toggleDevTools()
BrowserWindow::inspectElement = -> @webContents.inspectElement.apply @webContents, arguments
BrowserWindow::inspectServiceWorker = -> @webContents.inspectServiceWorker()
module.exports = BrowserWindow module.exports = BrowserWindow

View file

@ -3,9 +3,7 @@ NavigationController = require './navigation-controller'
binding = process.atomBinding 'web_contents' binding = process.atomBinding 'web_contents'
ipc = require 'ipc' ipc = require 'ipc'
module.exports.wrap = (webContents) -> wrapWebContents = (webContents) ->
return null unless webContents.isAlive()
# webContents is an EventEmitter. # webContents is an EventEmitter.
webContents.__proto__ = EventEmitter.prototype webContents.__proto__ = EventEmitter.prototype
@ -62,5 +60,8 @@ module.exports.wrap = (webContents) ->
webContents webContents
binding._setWrapWebContents wrapWebContents
process.once 'exit', binding._clearWrapWebContents
module.exports.create = (options={}) -> module.exports.create = (options={}) ->
@wrap binding.create(options) binding.create(options)

View file

@ -0,0 +1,341 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/common_web_contents_delegate.h"
#include <string>
#include <vector>
#include "atom/browser/atom_javascript_dialog_manager.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/file_dialog.h"
#include "atom/browser/web_dialog_helper.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/common/renderer_preferences.h"
#include "storage/browser/fileapi/isolated_context.h"
namespace atom {
namespace {
struct FileSystem {
FileSystem() {
}
FileSystem(const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {
}
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path,
std::string* registered_name) {
auto isolated_context = storage::IsolatedContext::GetInstance();
std::string file_system_id = isolated_context->RegisterFileSystemForPath(
storage::kFileSystemTypeNativeLocal,
std::string(),
path,
registered_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system_id);
policy->GrantWriteFileSystem(renderer_id, file_system_id);
policy->GrantCreateFileForFileSystem(renderer_id, file_system_id);
policy->GrantDeleteFromFileSystem(renderer_id, file_system_id);
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system_id;
}
FileSystem CreateFileSystemStruct(
content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& registered_name,
const std::string& file_system_path) {
const GURL origin = web_contents->GetURL().GetOrigin();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, registered_name);
return FileSystem(file_system_name, root_url, file_system_path);
}
base::DictionaryValue* CreateFileSystemValue(const FileSystem& file_system) {
base::DictionaryValue* 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);
return file_system_value;
}
} // namespace
CommonWebContentsDelegate::CommonWebContentsDelegate(bool is_guest)
: is_guest_(is_guest),
owner_window_(nullptr),
html_fullscreen_(false),
native_fullscreen_(false) {
}
CommonWebContentsDelegate::~CommonWebContentsDelegate() {
}
void CommonWebContentsDelegate::InitWithWebContents(
content::WebContents* web_contents,
NativeWindow* owner_window) {
owner_window_ = owner_window;
web_contents->SetDelegate(this);
// Tell renderer to handle all navigations in browser.
auto preferences = web_contents->GetMutableRendererPrefs();
preferences->browser_handles_non_local_top_level_requests = true;
preferences->browser_handles_all_top_level_requests = true;
web_contents->GetRenderViewHost()->SyncRendererPrefs();
// Create InspectableWebContents.
web_contents_.reset(brightray::InspectableWebContents::Create(web_contents));
web_contents_->SetDelegate(this);
}
void CommonWebContentsDelegate::DestroyWebContents() {
web_contents_.reset();
}
content::WebContents* CommonWebContentsDelegate::GetWebContents() const {
if (!web_contents_)
return nullptr;
return web_contents_->GetWebContents();
}
content::WebContents*
CommonWebContentsDelegate::GetDevToolsWebContents() const {
if (!web_contents_)
return nullptr;
return web_contents_->GetDevToolsWebContents();
}
content::WebContents* CommonWebContentsDelegate::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
content::NavigationController::LoadURLParams load_url_params(params.url);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.transferred_global_request_id =
params.transferred_global_request_id;
load_url_params.should_clear_history_list = true;
source->GetController().LoadURLWithParams(load_url_params);
return source;
}
void CommonWebContentsDelegate::RequestToLockMouse(
content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) {
GetWebContents()->GotResponseToLockMouseRequest(true);
}
bool CommonWebContentsDelegate::CanOverscrollContent() const {
return false;
}
bool CommonWebContentsDelegate::IsPopupOrPanel(
const content::WebContents* source) const {
return !is_guest_;
}
content::JavaScriptDialogManager*
CommonWebContentsDelegate::GetJavaScriptDialogManager(
content::WebContents* source) {
if (!dialog_manager_)
dialog_manager_.reset(new AtomJavaScriptDialogManager);
return dialog_manager_.get();
}
content::ColorChooser* CommonWebContentsDelegate::OpenColorChooser(
content::WebContents* web_contents,
SkColor color,
const std::vector<content::ColorSuggestion>& suggestions) {
return chrome::ShowColorChooser(web_contents, color);
}
void CommonWebContentsDelegate::RunFileChooser(
content::WebContents* guest,
const content::FileChooserParams& params) {
if (!web_dialog_helper_)
web_dialog_helper_.reset(new WebDialogHelper(owner_window_));
web_dialog_helper_->RunFileChooser(guest, params);
}
void CommonWebContentsDelegate::EnumerateDirectory(content::WebContents* guest,
int request_id,
const base::FilePath& path) {
if (!web_dialog_helper_)
web_dialog_helper_.reset(new WebDialogHelper(owner_window_));
web_dialog_helper_->EnumerateDirectory(guest, request_id, path);
}
void CommonWebContentsDelegate::EnterFullscreenModeForTab(
content::WebContents* source, const GURL& origin) {
if (!owner_window_)
return;
SetHtmlApiFullscreen(true);
owner_window_->NotifyWindowEnterHtmlFullScreen();
source->GetRenderViewHost()->WasResized();
}
void CommonWebContentsDelegate::ExitFullscreenModeForTab(
content::WebContents* source) {
if (!owner_window_)
return;
SetHtmlApiFullscreen(false);
owner_window_->NotifyWindowLeaveHtmlFullScreen();
source->GetRenderViewHost()->WasResized();
}
bool CommonWebContentsDelegate::IsFullscreenForTabOrPending(
const content::WebContents* source) const {
return html_fullscreen_;
}
void CommonWebContentsDelegate::DevToolsSaveToFile(
const std::string& url, const std::string& content, bool save_as) {
base::FilePath path;
PathsMap::iterator it = saved_files_.find(url);
if (it != saved_files_.end() && !save_as) {
path = it->second;
} else {
file_dialog::Filters filters;
base::FilePath default_path(base::FilePath::FromUTF8Unsafe(url));
if (!file_dialog::ShowSaveDialog(owner_window_, url, default_path,
filters, &path)) {
base::StringValue url_value(url);
web_contents_->CallClientFunction(
"DevToolsAPI.canceledSaveURL", &url_value, nullptr, nullptr);
return;
}
}
saved_files_[url] = path;
base::WriteFile(path, content.data(), content.size());
// Notify devtools.
base::StringValue url_value(url);
web_contents_->CallClientFunction(
"DevToolsAPI.savedURL", &url_value, nullptr, nullptr);
}
void CommonWebContentsDelegate::DevToolsAppendToFile(
const std::string& url, const std::string& content) {
PathsMap::iterator it = saved_files_.find(url);
if (it == saved_files_.end())
return;
base::AppendToFile(it->second, content.data(), content.size());
// Notify devtools.
base::StringValue url_value(url);
web_contents_->CallClientFunction(
"DevToolsAPI.appendedToURL", &url_value, nullptr, nullptr);
}
void CommonWebContentsDelegate::DevToolsAddFileSystem() {
file_dialog::Filters filters;
base::FilePath default_path;
std::vector<base::FilePath> paths;
int flag = file_dialog::FILE_DIALOG_OPEN_DIRECTORY;
if (!file_dialog::ShowOpenDialog(owner_window_, "", default_path,
filters, flag, &paths))
return;
base::FilePath path = paths[0];
std::string registered_name;
std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(),
path,
&registered_name);
WorkspaceMap::iterator it = saved_paths_.find(file_system_id);
if (it != saved_paths_.end())
return;
saved_paths_[file_system_id] = path;
FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(),
file_system_id,
registered_name,
path.AsUTF8Unsafe());
scoped_ptr<base::StringValue> error_string_value(
new base::StringValue(std::string()));
scoped_ptr<base::DictionaryValue> file_system_value;
if (!file_system.file_system_path.empty())
file_system_value.reset(CreateFileSystemValue(file_system));
web_contents_->CallClientFunction(
"DevToolsAPI.fileSystemAdded",
error_string_value.get(),
file_system_value.get(),
nullptr);
}
void CommonWebContentsDelegate::DevToolsRemoveFileSystem(
const std::string& file_system_path) {
if (!web_contents_)
return;
base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path);
storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath(path);
for (auto it = saved_paths_.begin(); it != saved_paths_.end(); ++it)
if (it->second == path) {
saved_paths_.erase(it);
break;
}
base::StringValue file_system_path_value(file_system_path);
web_contents_->CallClientFunction(
"DevToolsAPI.fileSystemRemoved",
&file_system_path_value,
nullptr,
nullptr);
}
void CommonWebContentsDelegate::SetHtmlApiFullscreen(bool enter_fullscreen) {
// Window is already in fullscreen mode, save the state.
if (enter_fullscreen && owner_window_->IsFullscreen()) {
native_fullscreen_ = true;
html_fullscreen_ = true;
return;
}
// Exit html fullscreen state but not window's fullscreen mode.
if (!enter_fullscreen && native_fullscreen_) {
html_fullscreen_ = false;
return;
}
owner_window_->SetFullScreen(enter_fullscreen);
html_fullscreen_ = enter_fullscreen;
native_fullscreen_ = false;
}
} // namespace atom

View file

@ -0,0 +1,124 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_COMMON_WEB_CONTENTS_DELEGATE_H_
#define ATOM_BROWSER_COMMON_WEB_CONTENTS_DELEGATE_H_
#include <map>
#include <string>
#include <vector>
#include "brightray/browser/default_web_contents_delegate.h"
#include "brightray/browser/inspectable_web_contents_impl.h"
#include "brightray/browser/inspectable_web_contents_delegate.h"
namespace atom {
class AtomJavaScriptDialogManager;
class NativeWindow;
class WebDialogHelper;
class CommonWebContentsDelegate
: public brightray::DefaultWebContentsDelegate,
public brightray::InspectableWebContentsDelegate {
public:
explicit CommonWebContentsDelegate(bool is_guest);
virtual ~CommonWebContentsDelegate();
// Create a InspectableWebContents object and takes onwership of
// |web_contents|.
void InitWithWebContents(content::WebContents* web_contents,
NativeWindow* owner_window);
// Destroy the managed InspectableWebContents object.
void DestroyWebContents();
// Returns the WebContents managed by this delegate.
content::WebContents* GetWebContents() const;
// Returns the WebContents of devtools.
content::WebContents* GetDevToolsWebContents() const;
brightray::InspectableWebContents* managed_web_contents() const {
return web_contents_.get();
}
bool is_guest() const { return is_guest_; }
protected:
// content::WebContentsDelegate:
content::WebContents* OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) override;
void RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) override;
bool CanOverscrollContent() const override;
bool IsPopupOrPanel(const content::WebContents* source) const override;
content::JavaScriptDialogManager* GetJavaScriptDialogManager(
content::WebContents* source) override;
content::ColorChooser* OpenColorChooser(
content::WebContents* web_contents,
SkColor color,
const std::vector<content::ColorSuggestion>& suggestions) override;
void RunFileChooser(content::WebContents* web_contents,
const content::FileChooserParams& params) override;
void EnumerateDirectory(content::WebContents* web_contents,
int request_id,
const base::FilePath& path) override;
void EnterFullscreenModeForTab(content::WebContents* source,
const GURL& origin) override;
void ExitFullscreenModeForTab(content::WebContents* source) override;
bool IsFullscreenForTabOrPending(
const content::WebContents* source) const override;
// brightray::InspectableWebContentsDelegate:
void DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) override;
void DevToolsAppendToFile(const std::string& url,
const std::string& content) override;
void DevToolsAddFileSystem() override;
void DevToolsRemoveFileSystem(const std::string& file_system_path) override;
private:
// Set fullscreen mode triggered by html api.
void SetHtmlApiFullscreen(bool enter_fullscreen);
// Whether this is guest WebContents or NativeWindow.
const bool is_guest_;
// The window that this WebContents belongs to.
NativeWindow* owner_window_;
// Whether window is fullscreened by HTML5 api.
bool html_fullscreen_;
// Whether window is fullscreened by window api.
bool native_fullscreen_;
scoped_ptr<WebDialogHelper> web_dialog_helper_;
scoped_ptr<AtomJavaScriptDialogManager> dialog_manager_;
// The stored InspectableWebContents object.
// Notice that web_contents_ must be placed after dialog_manager_, so we can
// make sure web_contents_ is destroyed before dialog_manager_, otherwise a
// crash would happen.
scoped_ptr<brightray::InspectableWebContents> web_contents_;
// Maps url to file path, used by the file requests sent from devtools.
typedef std::map<std::string, base::FilePath> PathsMap;
PathsMap saved_files_;
// Maps file system id to file path, used by the file system requests
// sent from devtools.
typedef std::map<std::string, base::FilePath> WorkspaceMap;
WorkspaceMap saved_paths_;
DISALLOW_COPY_AND_ASSIGN(CommonWebContentsDelegate);
};
} // namespace atom
#endif // ATOM_BROWSER_COMMON_WEB_CONTENTS_DELEGATE_H_

View file

@ -9,10 +9,7 @@
#include <vector> #include <vector>
#include "atom/browser/atom_browser_context.h" #include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_javascript_dialog_manager.h"
#include "atom/browser/browser.h" #include "atom/browser/browser.h"
#include "atom/browser/ui/file_dialog.h"
#include "atom/browser/web_dialog_helper.h"
#include "atom/browser/window_list.h" #include "atom/browser/window_list.h"
#include "atom/common/api/api_messages.h" #include "atom/common/api/api_messages.h"
#include "atom/common/atom_version.h" #include "atom/common/atom_version.h"
@ -31,17 +28,12 @@
#include "brightray/browser/inspectable_web_contents.h" #include "brightray/browser/inspectable_web_contents.h"
#include "brightray/browser/inspectable_web_contents_view.h" #include "brightray/browser/inspectable_web_contents_view.h"
#include "chrome/browser/printing/print_view_manager_basic.h" #include "chrome/browser/printing/print_view_manager_basic.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/invalidate_type.h"
#include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_entry.h"
#include "content/public/browser/notification_details.h" #include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h" #include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h" #include "content/public/browser/notification_types.h"
#include "content/public/browser/plugin_service.h" #include "content/public/browser/plugin_service.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h" #include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h" #include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/render_widget_host_view.h"
@ -51,7 +43,6 @@
#include "content/public/common/web_preferences.h" #include "content/public/common/web_preferences.h"
#include "ipc/ipc_message_macros.h" #include "ipc/ipc_message_macros.h"
#include "native_mate/dictionary.h" #include "native_mate/dictionary.h"
#include "storage/browser/fileapi/isolated_context.h"
#include "ui/gfx/codec/png_codec.h" #include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/geometry/size_conversions.h" #include "ui/gfx/geometry/size_conversions.h"
#include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/point.h"
@ -91,81 +82,24 @@ std::string RemoveWhitespace(const std::string& str) {
return str; return str;
} }
storage::IsolatedContext* isolated_context() {
storage::IsolatedContext* context =
storage::IsolatedContext::GetInstance();
DCHECK(context);
return context;
}
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path,
std::string* registered_name) {
std::string file_system_id = isolated_context()->RegisterFileSystemForPath(
storage::kFileSystemTypeNativeLocal,
std::string(),
path,
registered_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system_id);
policy->GrantWriteFileSystem(renderer_id, file_system_id);
policy->GrantCreateFileForFileSystem(renderer_id, file_system_id);
policy->GrantDeleteFromFileSystem(renderer_id, file_system_id);
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system_id;
}
NativeWindow::FileSystem CreateFileSystemStruct(
content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& registered_name,
const std::string& file_system_path) {
const GURL origin = web_contents->GetURL().GetOrigin();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, registered_name);
return NativeWindow::FileSystem(file_system_name,
root_url,
file_system_path);
}
base::DictionaryValue* CreateFileSystemValue(
NativeWindow::FileSystem file_system) {
base::DictionaryValue* 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);
return file_system_value;
}
} // namespace } // namespace
NativeWindow::NativeWindow(content::WebContents* web_contents, NativeWindow::NativeWindow(content::WebContents* web_contents,
const mate::Dictionary& options) const mate::Dictionary& options)
: content::WebContentsObserver(web_contents), : CommonWebContentsDelegate(false),
content::WebContentsObserver(web_contents),
has_frame_(true), has_frame_(true),
transparent_(false), transparent_(false),
enable_larger_than_screen_(false), enable_larger_than_screen_(false),
is_closed_(false), is_closed_(false),
node_integration_(true), node_integration_(true),
has_dialog_attached_(false), has_dialog_attached_(false),
html_fullscreen_(false),
native_fullscreen_(false),
zoom_factor_(1.0), zoom_factor_(1.0),
weak_factory_(this), weak_factory_(this) {
inspectable_web_contents_(
brightray::InspectableWebContents::Create(web_contents)) {
printing::PrintViewManagerBasic::CreateForWebContents(web_contents); printing::PrintViewManagerBasic::CreateForWebContents(web_contents);
InitWithWebContents(web_contents, this);
options.Get(switches::kFrame, &has_frame_); options.Get(switches::kFrame, &has_frame_);
options.Get(switches::kTransparent, &transparent_); options.Get(switches::kTransparent, &transparent_);
options.Get(switches::kEnableLargerThanScreen, &enable_larger_than_screen_); options.Get(switches::kEnableLargerThanScreen, &enable_larger_than_screen_);
@ -197,9 +131,6 @@ NativeWindow::NativeWindow(content::WebContents* web_contents,
// Read the zoom factor before any navigation. // Read the zoom factor before any navigation.
options.Get(switches::kZoomFactor, &zoom_factor_); options.Get(switches::kZoomFactor, &zoom_factor_);
web_contents->SetDelegate(this);
inspectable_web_contents()->SetDelegate(this);
WindowList::AddWindow(this); WindowList::AddWindow(this);
// Override the user agent to contain application and atom-shell's version. // Override the user agent to contain application and atom-shell's version.
@ -353,35 +284,6 @@ bool NativeWindow::HasModalDialog() {
return has_dialog_attached_; return has_dialog_attached_;
} }
void NativeWindow::OpenDevTools(bool can_dock) {
inspectable_web_contents()->SetCanDock(can_dock);
inspectable_web_contents()->ShowDevTools();
}
void NativeWindow::CloseDevTools() {
inspectable_web_contents()->CloseDevTools();
}
bool NativeWindow::IsDevToolsOpened() {
return inspectable_web_contents()->IsDevToolsViewShowing();
}
void NativeWindow::InspectElement(int x, int y) {
scoped_refptr<content::DevToolsAgentHost> agent(
content::DevToolsAgentHost::GetOrCreateFor(GetWebContents()));
agent->InspectElement(x, y);
}
void NativeWindow::InspectServiceWorker() {
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::TYPE_SERVICE_WORKER) {
inspectable_web_contents()->AttachTo(agent_host);
break;
}
}
}
void NativeWindow::FocusOnWebView() { void NativeWindow::FocusOnWebView() {
GetWebContents()->GetRenderViewHost()->Focus(); GetWebContents()->GetRenderViewHost()->Focus();
} }
@ -430,13 +332,6 @@ void NativeWindow::CapturePage(const gfx::Rect& rect,
kBGRA_8888_SkColorType); kBGRA_8888_SkColorType);
} }
void NativeWindow::DestroyWebContents() {
if (!inspectable_web_contents_)
return;
inspectable_web_contents_.reset();
}
void NativeWindow::CloseWebContents() { void NativeWindow::CloseWebContents() {
bool prevent_default = false; bool prevent_default = false;
FOR_EACH_OBSERVER(NativeWindowObserver, FOR_EACH_OBSERVER(NativeWindowObserver,
@ -466,18 +361,6 @@ void NativeWindow::CloseWebContents() {
web_contents->Close(); web_contents->Close();
} }
content::WebContents* NativeWindow::GetWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents()->GetWebContents();
}
content::WebContents* NativeWindow::GetDevToolsWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents()->devtools_web_contents();
}
void NativeWindow::AppendExtraCommandLineSwitches( void NativeWindow::AppendExtraCommandLineSwitches(
base::CommandLine* command_line) { base::CommandLine* command_line) {
// Append --node-integration to renderer process. // Append --node-integration to renderer process.
@ -546,25 +429,6 @@ void NativeWindow::OverrideWebkitPrefs(content::WebPreferences* prefs) {
} }
} }
void NativeWindow::SetHtmlApiFullscreen(bool enter_fullscreen) {
// Window is already in fullscreen mode, save the state.
if (enter_fullscreen && IsFullscreen()) {
native_fullscreen_ = true;
html_fullscreen_ = true;
return;
}
// Exit html fullscreen state but not window's fullscreen mode.
if (!enter_fullscreen && native_fullscreen_) {
html_fullscreen_ = false;
return;
}
SetFullScreen(enter_fullscreen);
html_fullscreen_ = enter_fullscreen;
native_fullscreen_ = false;
}
void NativeWindow::NotifyWindowClosed() { void NativeWindow::NotifyWindowClosed() {
if (is_closed_) if (is_closed_)
return; return;
@ -678,27 +542,7 @@ content::WebContents* NativeWindow::OpenURLFromTab(
if (prevent_default) if (prevent_default)
return nullptr; return nullptr;
content::NavigationController::LoadURLParams load_url_params(params.url); return CommonWebContentsDelegate::OpenURLFromTab(source, params);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.transferred_global_request_id =
params.transferred_global_request_id;
load_url_params.should_clear_history_list = true;
source->GetController().LoadURLWithParams(load_url_params);
return source;
}
content::JavaScriptDialogManager* NativeWindow::GetJavaScriptDialogManager(
content::WebContents* source) {
if (!dialog_manager_)
dialog_manager_.reset(new AtomJavaScriptDialogManager);
return dialog_manager_.get();
} }
void NativeWindow::RenderViewCreated( void NativeWindow::RenderViewCreated(
@ -726,38 +570,6 @@ void NativeWindow::BeforeUnloadFired(content::WebContents* tab,
} }
} }
content::ColorChooser* NativeWindow::OpenColorChooser(
content::WebContents* web_contents,
SkColor color,
const std::vector<content::ColorSuggestion>& suggestions) {
return chrome::ShowColorChooser(web_contents, color);
}
void NativeWindow::RunFileChooser(content::WebContents* web_contents,
const content::FileChooserParams& params) {
if (!web_dialog_helper_)
web_dialog_helper_.reset(new WebDialogHelper(this));
web_dialog_helper_->RunFileChooser(web_contents, params);
}
void NativeWindow::EnumerateDirectory(content::WebContents* web_contents,
int request_id,
const base::FilePath& path) {
if (!web_dialog_helper_)
web_dialog_helper_.reset(new WebDialogHelper(this));
web_dialog_helper_->EnumerateDirectory(web_contents, request_id, path);
}
void NativeWindow::RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) {
GetWebContents()->GotResponseToLockMouseRequest(true);
}
bool NativeWindow::CanOverscrollContent() const {
return false;
}
void NativeWindow::ActivateContents(content::WebContents* contents) { void NativeWindow::ActivateContents(content::WebContents* contents) {
FocusOnWebView(); FocusOnWebView();
} }
@ -786,11 +598,6 @@ void NativeWindow::CloseContents(content::WebContents* source) {
window_unresposive_closure_.Cancel(); window_unresposive_closure_.Cancel();
} }
bool NativeWindow::IsPopupOrPanel(const content::WebContents* source) const {
// Only popup window can use things like window.moveTo.
return true;
}
void NativeWindow::RendererUnresponsive(content::WebContents* source) { void NativeWindow::RendererUnresponsive(content::WebContents* source) {
// Schedule the unresponsive shortly later, since we may receive the // Schedule the unresponsive shortly later, since we may receive the
// responsive event soon. This could happen after the whole application had // responsive event soon. This could happen after the whole application had
@ -807,20 +614,6 @@ void NativeWindow::RendererResponsive(content::WebContents* source) {
FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnRendererResponsive()); FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnRendererResponsive());
} }
void NativeWindow::EnterFullscreenModeForTab(content::WebContents* source,
const GURL& origin) {
SetHtmlApiFullscreen(true);
}
void NativeWindow::ExitFullscreenModeForTab(content::WebContents* source) {
SetHtmlApiFullscreen(false);
}
bool NativeWindow::IsFullscreenForTabOrPending(
const content::WebContents* source) const {
return is_html_api_fullscreen();
}
void NativeWindow::BeforeUnloadFired(const base::TimeTicks& proceed_time) { void NativeWindow::BeforeUnloadFired(const base::TimeTicks& proceed_time) {
// Do nothing, we override this method just to avoid compilation error since // Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired. // there are two virtual functions named BeforeUnloadFired.
@ -857,96 +650,16 @@ void NativeWindow::Observe(int type,
} }
} }
void NativeWindow::DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
base::FilePath path;
PathsMap::iterator it = saved_files_.find(url);
if (it != saved_files_.end() && !save_as) {
path = it->second;
} else {
file_dialog::Filters filters;
base::FilePath default_path(base::FilePath::FromUTF8Unsafe(url));
if (!file_dialog::ShowSaveDialog(this, url, default_path, filters, &path)) {
base::StringValue url_value(url);
CallDevToolsFunction("DevToolsAPI.canceledSaveURL", &url_value);
return;
}
}
saved_files_[url] = path;
base::WriteFile(path, content.data(), content.size());
// Notify devtools.
base::StringValue url_value(url);
CallDevToolsFunction("DevToolsAPI.savedURL", &url_value);
}
void NativeWindow::DevToolsAppendToFile(const std::string& url,
const std::string& content) {
PathsMap::iterator it = saved_files_.find(url);
if (it == saved_files_.end())
return;
base::AppendToFile(it->second, content.data(), content.size());
// Notify devtools.
base::StringValue url_value(url);
CallDevToolsFunction("DevToolsAPI.appendedToURL", &url_value);
}
void NativeWindow::DevToolsFocused() { void NativeWindow::DevToolsFocused() {
FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnDevToolsFocus()); FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnDevToolsFocus());
} }
void NativeWindow::DevToolsAddFileSystem() { void NativeWindow::DevToolsOpened() {
file_dialog::Filters filters; FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnDevToolsOpened());
base::FilePath default_path;
std::vector<base::FilePath> paths;
int flag = file_dialog::FILE_DIALOG_OPEN_DIRECTORY;
if (!file_dialog::ShowOpenDialog(this, "", default_path,
filters, flag, &paths))
return;
base::FilePath path = paths[0];
std::string registered_name;
std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(),
path,
&registered_name);
WorkspaceMap::iterator it = saved_paths_.find(file_system_id);
if (it != saved_paths_.end())
return;
saved_paths_[file_system_id] = path;
FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(),
file_system_id,
registered_name,
path.AsUTF8Unsafe());
scoped_ptr<base::StringValue> error_string_value(
new base::StringValue(std::string()));
scoped_ptr<base::DictionaryValue> file_system_value;
if (!file_system.file_system_path.empty())
file_system_value.reset(CreateFileSystemValue(file_system));
CallDevToolsFunction("DevToolsAPI.fileSystemAdded", error_string_value.get(),
file_system_value.get(), nullptr);
} }
void NativeWindow::DevToolsRemoveFileSystem( void NativeWindow::DevToolsClosed() {
const std::string& file_system_path) { FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnDevToolsClosed());
base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path);
isolated_context()->RevokeFileSystemByPath(path);
for (auto it = saved_paths_.begin(); it != saved_paths_.end(); ++it)
if (it->second == path) {
saved_paths_.erase(it);
break;
}
base::StringValue file_system_path_value(file_system_path);
CallDevToolsFunction("DevToolsAPI.fileSystemRemoved",
&file_system_path_value, nullptr, nullptr);
} }
void NativeWindow::ScheduleUnresponsiveEvent(int ms) { void NativeWindow::ScheduleUnresponsiveEvent(int ms) {
@ -977,27 +690,4 @@ void NativeWindow::OnCapturePageDone(const CapturePageCallback& callback,
callback.Run(bitmap); callback.Run(bitmap);
} }
void NativeWindow::CallDevToolsFunction(const std::string& function_name,
const base::Value* arg1,
const base::Value* arg2,
const base::Value* arg3) {
std::string params;
if (arg1) {
std::string json;
base::JSONWriter::Write(arg1, &json);
params.append(json);
if (arg2) {
base::JSONWriter::Write(arg2, &json);
params.append(", " + json);
if (arg3) {
base::JSONWriter::Write(arg3, &json);
params.append(", " + json);
}
}
}
base::string16 javascript =
base::UTF8ToUTF16(function_name + "(" + params + ");");
GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript(javascript);
}
} // namespace atom } // namespace atom

View file

@ -9,15 +9,13 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include "atom/browser/common_web_contents_delegate.h"
#include "atom/browser/native_window_observer.h" #include "atom/browser/native_window_observer.h"
#include "atom/browser/ui/accelerator_util.h" #include "atom/browser/ui/accelerator_util.h"
#include "base/cancelable_callback.h" #include "base/cancelable_callback.h"
#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h" #include "base/memory/weak_ptr.h"
#include "base/observer_list.h" #include "base/observer_list.h"
#include "brightray/browser/default_web_contents_delegate.h"
#include "brightray/browser/inspectable_web_contents_delegate.h"
#include "brightray/browser/inspectable_web_contents_impl.h"
#include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_observer.h"
#include "content/public/browser/readback_types.h" #include "content/public/browser/readback_types.h"
@ -50,33 +48,14 @@ class MenuModel;
namespace atom { namespace atom {
class AtomJavaScriptDialogManager;
struct DraggableRegion; struct DraggableRegion;
class WebDialogHelper;
class NativeWindow : public brightray::DefaultWebContentsDelegate, class NativeWindow : public CommonWebContentsDelegate,
public brightray::InspectableWebContentsDelegate,
public content::WebContentsObserver, public content::WebContentsObserver,
public content::NotificationObserver { public content::NotificationObserver {
public: public:
typedef base::Callback<void(const SkBitmap& bitmap)> CapturePageCallback; typedef base::Callback<void(const SkBitmap& bitmap)> CapturePageCallback;
struct FileSystem {
FileSystem() {
}
FileSystem(const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {
}
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
class DialogScope { class DialogScope {
public: public:
explicit DialogScope(NativeWindow* window) explicit DialogScope(NativeWindow* window)
@ -165,11 +144,6 @@ class NativeWindow : public brightray::DefaultWebContentsDelegate,
virtual bool IsVisibleOnAllWorkspaces() = 0; virtual bool IsVisibleOnAllWorkspaces() = 0;
virtual bool IsClosed() const { return is_closed_; } virtual bool IsClosed() const { return is_closed_; }
virtual void OpenDevTools(bool can_dock);
virtual void CloseDevTools();
virtual bool IsDevToolsOpened();
virtual void InspectElement(int x, int y);
virtual void InspectServiceWorker();
virtual void FocusOnWebView(); virtual void FocusOnWebView();
virtual void BlurWebView(); virtual void BlurWebView();
@ -197,23 +171,14 @@ class NativeWindow : public brightray::DefaultWebContentsDelegate,
// Should be called by platform code when user want to close the window. // Should be called by platform code when user want to close the window.
virtual void CloseWebContents(); virtual void CloseWebContents();
// Destroy the WebContents immediately.
virtual void DestroyWebContents();
base::WeakPtr<NativeWindow> GetWeakPtr() { base::WeakPtr<NativeWindow> GetWeakPtr() {
return weak_factory_.GetWeakPtr(); return weak_factory_.GetWeakPtr();
} }
content::WebContents* GetWebContents() const;
content::WebContents* GetDevToolsWebContents() const;
// Called when renderer process is going to be started. // Called when renderer process is going to be started.
void AppendExtraCommandLineSwitches(base::CommandLine* command_line); void AppendExtraCommandLineSwitches(base::CommandLine* command_line);
void OverrideWebkitPrefs(content::WebPreferences* prefs); void OverrideWebkitPrefs(content::WebPreferences* prefs);
// Set fullscreen mode triggered by html api.
void SetHtmlApiFullscreen(bool enter_fullscreen);
// Public API used by platform-dependent delegates and observers to send UI // Public API used by platform-dependent delegates and observers to send UI
// related notifications. // related notifications.
void NotifyWindowClosed(); void NotifyWindowClosed();
@ -239,9 +204,11 @@ class NativeWindow : public brightray::DefaultWebContentsDelegate,
observers_.RemoveObserver(obs); observers_.RemoveObserver(obs);
} }
bool has_frame() const { return has_frame_; } brightray::InspectableWebContents* inspectable_web_contents() const {
return managed_web_contents();
}
bool is_html_api_fullscreen() const { return html_fullscreen_; } bool has_frame() const { return has_frame_; }
void set_has_dialog_attached(bool has_dialog_attached) { void set_has_dialog_attached(bool has_dialog_attached) {
has_dialog_attached_ = has_dialog_attached; has_dialog_attached_ = has_dialog_attached;
@ -251,11 +218,6 @@ class NativeWindow : public brightray::DefaultWebContentsDelegate,
explicit NativeWindow(content::WebContents* web_contents, explicit NativeWindow(content::WebContents* web_contents,
const mate::Dictionary& options); const mate::Dictionary& options);
brightray::InspectableWebContentsImpl* inspectable_web_contents() const {
return static_cast<brightray::InspectableWebContentsImpl*>(
inspectable_web_contents_.get());
}
// Called when the window needs to update its draggable region. // Called when the window needs to update its draggable region.
virtual void UpdateDraggableRegions( virtual void UpdateDraggableRegions(
const std::vector<DraggableRegion>& regions) = 0; const std::vector<DraggableRegion>& regions) = 0;
@ -273,38 +235,16 @@ class NativeWindow : public brightray::DefaultWebContentsDelegate,
content::WebContents* OpenURLFromTab( content::WebContents* OpenURLFromTab(
content::WebContents* source, content::WebContents* source,
const content::OpenURLParams& params) override; const content::OpenURLParams& params) override;
content::JavaScriptDialogManager* GetJavaScriptDialogManager(
content::WebContents* source) override;
void BeforeUnloadFired(content::WebContents* tab, void BeforeUnloadFired(content::WebContents* tab,
bool proceed, bool proceed,
bool* proceed_to_fire_unload) override; bool* proceed_to_fire_unload) override;
content::ColorChooser* OpenColorChooser(
content::WebContents* web_contents,
SkColor color,
const std::vector<content::ColorSuggestion>& suggestions) override;
void RunFileChooser(content::WebContents* web_contents,
const content::FileChooserParams& params) override;
void EnumerateDirectory(content::WebContents* web_contents,
int request_id,
const base::FilePath& path) override;
void RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) override;
bool CanOverscrollContent() const override;
void ActivateContents(content::WebContents* contents) override; void ActivateContents(content::WebContents* contents) override;
void DeactivateContents(content::WebContents* contents) override; void DeactivateContents(content::WebContents* contents) override;
void MoveContents(content::WebContents* source, void MoveContents(content::WebContents* source,
const gfx::Rect& pos) override; const gfx::Rect& pos) override;
void CloseContents(content::WebContents* source) override; void CloseContents(content::WebContents* source) override;
bool IsPopupOrPanel(
const content::WebContents* source) const override;
void RendererUnresponsive(content::WebContents* source) override; void RendererUnresponsive(content::WebContents* source) override;
void RendererResponsive(content::WebContents* source) override; void RendererResponsive(content::WebContents* source) override;
void EnterFullscreenModeForTab(content::WebContents* source,
const GURL& origin) override;
void ExitFullscreenModeForTab(content::WebContents* source) override;
bool IsFullscreenForTabOrPending(
const content::WebContents* source) const override;
// Implementations of content::WebContentsObserver. // Implementations of content::WebContentsObserver.
void RenderViewCreated(content::RenderViewHost* render_view_host) override; void RenderViewCreated(content::RenderViewHost* render_view_host) override;
@ -317,14 +257,9 @@ class NativeWindow : public brightray::DefaultWebContentsDelegate,
const content::NotificationDetails& details) override; const content::NotificationDetails& details) override;
// Implementations of brightray::InspectableWebContentsDelegate. // Implementations of brightray::InspectableWebContentsDelegate.
void DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) override;
void DevToolsAppendToFile(const std::string& url,
const std::string& content) override;
void DevToolsFocused() override; void DevToolsFocused() override;
void DevToolsAddFileSystem() override; void DevToolsOpened() override;
void DevToolsRemoveFileSystem(const std::string& file_system_path) override; void DevToolsClosed() override;
// Whether window has standard frame. // Whether window has standard frame.
bool has_frame_; bool has_frame_;
@ -345,12 +280,6 @@ class NativeWindow : public brightray::DefaultWebContentsDelegate,
// Dispatch unresponsive event to observers. // Dispatch unresponsive event to observers.
void NotifyWindowUnresponsive(); void NotifyWindowUnresponsive();
// Call a function in devtools.
void CallDevToolsFunction(const std::string& function_name,
const base::Value* arg1 = NULL,
const base::Value* arg2 = NULL,
const base::Value* arg3 = NULL);
// Called when CapturePage has done. // Called when CapturePage has done.
void OnCapturePageDone(const CapturePageCallback& callback, void OnCapturePageDone(const CapturePageCallback& callback,
const SkBitmap& bitmap, const SkBitmap& bitmap,
@ -371,12 +300,6 @@ class NativeWindow : public brightray::DefaultWebContentsDelegate,
// There is a dialog that has been attached to window. // There is a dialog that has been attached to window.
bool has_dialog_attached_; bool has_dialog_attached_;
// Whether window is fullscreened by HTML5 api.
bool html_fullscreen_;
// Whether window is fullscreened by window api.
bool native_fullscreen_;
// Closure that would be called when window is unresponsive when closing, // Closure that would be called when window is unresponsive when closing,
// it should be cancelled when we can prove that the window is responsive. // it should be cancelled when we can prove that the window is responsive.
base::CancelableClosure window_unresposive_closure_; base::CancelableClosure window_unresposive_closure_;
@ -392,23 +315,6 @@ class NativeWindow : public brightray::DefaultWebContentsDelegate,
base::WeakPtrFactory<NativeWindow> weak_factory_; base::WeakPtrFactory<NativeWindow> weak_factory_;
scoped_ptr<WebDialogHelper> web_dialog_helper_;
scoped_ptr<AtomJavaScriptDialogManager> dialog_manager_;
// Notice that inspectable_web_contents_ must be placed after dialog_manager_,
// so we can make sure inspectable_web_contents_ is destroyed before
// dialog_manager_, otherwise a crash would happen.
scoped_ptr<brightray::InspectableWebContents> inspectable_web_contents_;
// Maps url to file path, used by the file requests sent from devtools.
typedef std::map<std::string, base::FilePath> PathsMap;
PathsMap saved_files_;
// Maps file system id to file path, used by the file system requests
// sent from devtools.
typedef std::map<std::string, base::FilePath> WorkspaceMap;
WorkspaceMap saved_paths_;
DISALLOW_COPY_AND_ASSIGN(NativeWindow); DISALLOW_COPY_AND_ASSIGN(NativeWindow);
}; };

View file

@ -55,8 +55,10 @@ class NativeWindowObserver {
virtual void OnWindowEnterHtmlFullScreen() {} virtual void OnWindowEnterHtmlFullScreen() {}
virtual void OnWindowLeaveHtmlFullScreen() {} virtual void OnWindowLeaveHtmlFullScreen() {}
// Called when devtools window gets focused. // Redirect devtools events.
virtual void OnDevToolsFocus() {} virtual void OnDevToolsFocus() {}
virtual void OnDevToolsOpened() {}
virtual void OnDevToolsClosed() {}
// Called when renderer is hung. // Called when renderer is hung.
virtual void OnRendererUnresponsive() {} virtual void OnRendererUnresponsive() {}

View file

@ -123,6 +123,8 @@
'atom/browser/browser_mac.mm', 'atom/browser/browser_mac.mm',
'atom/browser/browser_win.cc', 'atom/browser/browser_win.cc',
'atom/browser/browser_observer.h', 'atom/browser/browser_observer.h',
'atom/browser/common_web_contents_delegate.cc',
'atom/browser/common_web_contents_delegate.h',
'atom/browser/javascript_environment.cc', 'atom/browser/javascript_environment.cc',
'atom/browser/javascript_environment.h', 'atom/browser/javascript_environment.h',
'atom/browser/mac/atom_application.h', 'atom/browser/mac/atom_application.h',

2
vendor/brightray vendored

@ -1 +1 @@
Subproject commit e9f49690e3f2d16c6bc4f70fca6b11987745ceac Subproject commit 20af087dd3ba01b601f8ad176899610c9479b382