NaCl: Update revision in DEPS, r12770 -> r12773
[chromium-blink-merge.git] / chrome / browser / extensions / extension_host.cc
blobfa3e2f0034759969de5f2852485cbbc9b4b1ab13
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/extensions/extension_host.h"
7 #include <list>
9 #include "base/bind.h"
10 #include "base/logging.h"
11 #include "base/memory/singleton.h"
12 #include "base/memory/weak_ptr.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/histogram.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "chrome/browser/chrome_notification_types.h"
18 #include "chrome/browser/extensions/error_console/error_console.h"
19 #include "chrome/browser/extensions/extension_service.h"
20 #include "chrome/browser/extensions/extension_tab_util.h"
21 #include "chrome/browser/extensions/extension_web_contents_observer.h"
22 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
23 #include "chrome/common/chrome_constants.h"
24 #include "chrome/common/extensions/extension_constants.h"
25 #include "chrome/common/extensions/extension_messages.h"
26 #include "chrome/common/render_messages.h"
27 #include "chrome/common/url_constants.h"
28 #include "content/public/browser/browser_context.h"
29 #include "content/public/browser/content_browser_client.h"
30 #include "content/public/browser/native_web_keyboard_event.h"
31 #include "content/public/browser/notification_service.h"
32 #include "content/public/browser/notification_source.h"
33 #include "content/public/browser/notification_types.h"
34 #include "content/public/browser/render_process_host.h"
35 #include "content/public/browser/render_view_host.h"
36 #include "content/public/browser/render_widget_host_view.h"
37 #include "content/public/browser/site_instance.h"
38 #include "content/public/browser/web_contents.h"
39 #include "extensions/browser/event_router.h"
40 #include "extensions/browser/extension_error.h"
41 #include "extensions/browser/extension_system.h"
42 #include "extensions/browser/extensions_browser_client.h"
43 #include "extensions/browser/process_manager.h"
44 #include "extensions/browser/runtime_data.h"
45 #include "extensions/browser/view_type_utils.h"
46 #include "extensions/common/extension.h"
47 #include "extensions/common/extension_urls.h"
48 #include "extensions/common/feature_switch.h"
49 #include "extensions/common/manifest_handlers/background_info.h"
50 #include "third_party/WebKit/public/web/WebInputEvent.h"
51 #include "ui/base/l10n/l10n_util.h"
52 #include "ui/base/window_open_disposition.h"
54 using content::BrowserContext;
55 using content::OpenURLParams;
56 using content::RenderProcessHost;
57 using content::RenderViewHost;
58 using content::SiteInstance;
59 using content::WebContents;
61 namespace extensions {
63 // Helper class that rate-limits the creation of renderer processes for
64 // ExtensionHosts, to avoid blocking the UI.
65 class ExtensionHost::ProcessCreationQueue {
66 public:
67 static ProcessCreationQueue* GetInstance() {
68 return Singleton<ProcessCreationQueue>::get();
71 // Add a host to the queue for RenderView creation.
72 void CreateSoon(ExtensionHost* host) {
73 queue_.push_back(host);
74 PostTask();
77 // Remove a host from the queue (in case it's being deleted).
78 void Remove(ExtensionHost* host) {
79 Queue::iterator it = std::find(queue_.begin(), queue_.end(), host);
80 if (it != queue_.end())
81 queue_.erase(it);
84 private:
85 friend class Singleton<ProcessCreationQueue>;
86 friend struct DefaultSingletonTraits<ProcessCreationQueue>;
87 ProcessCreationQueue()
88 : pending_create_(false),
89 ptr_factory_(this) {}
91 // Queue up a delayed task to process the next ExtensionHost in the queue.
92 void PostTask() {
93 if (!pending_create_) {
94 base::MessageLoop::current()->PostTask(FROM_HERE,
95 base::Bind(&ProcessCreationQueue::ProcessOneHost,
96 ptr_factory_.GetWeakPtr()));
97 pending_create_ = true;
101 // Create the RenderView for the next host in the queue.
102 void ProcessOneHost() {
103 pending_create_ = false;
104 if (queue_.empty())
105 return; // can happen on shutdown
107 queue_.front()->CreateRenderViewNow();
108 queue_.pop_front();
110 if (!queue_.empty())
111 PostTask();
114 typedef std::list<ExtensionHost*> Queue;
115 Queue queue_;
116 bool pending_create_;
117 base::WeakPtrFactory<ProcessCreationQueue> ptr_factory_;
120 ////////////////
121 // ExtensionHost
123 ExtensionHost::ExtensionHost(const Extension* extension,
124 SiteInstance* site_instance,
125 const GURL& url,
126 ViewType host_type)
127 : extension_(extension),
128 extension_id_(extension->id()),
129 browser_context_(site_instance->GetBrowserContext()),
130 render_view_host_(NULL),
131 did_stop_loading_(false),
132 document_element_available_(false),
133 initial_url_(url),
134 extension_function_dispatcher_(browser_context_, this),
135 extension_host_type_(host_type) {
136 // Not used for panels, see PanelHost.
137 DCHECK(host_type == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE ||
138 host_type == VIEW_TYPE_EXTENSION_DIALOG ||
139 host_type == VIEW_TYPE_EXTENSION_INFOBAR ||
140 host_type == VIEW_TYPE_EXTENSION_POPUP);
141 host_contents_.reset(WebContents::Create(
142 WebContents::CreateParams(browser_context_, site_instance))),
143 content::WebContentsObserver::Observe(host_contents_.get());
144 host_contents_->SetDelegate(this);
145 SetViewType(host_contents_.get(), host_type);
147 ExtensionWebContentsObserver::CreateForWebContents(host_contents());
149 render_view_host_ = host_contents_->GetRenderViewHost();
151 // Listen for when an extension is unloaded from the same profile, as it may
152 // be the same extension that this points to.
153 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED,
154 content::Source<BrowserContext>(browser_context_));
156 ExtensionsBrowserClient::Get()->OnExtensionHostCreated(host_contents());
159 ExtensionHost::~ExtensionHost() {
160 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE &&
161 extension_ && BackgroundInfo::HasLazyBackgroundPage(extension_)) {
162 UMA_HISTOGRAM_LONG_TIMES("Extensions.EventPageActiveTime",
163 since_created_.Elapsed());
165 content::NotificationService::current()->Notify(
166 chrome::NOTIFICATION_EXTENSION_HOST_DESTROYED,
167 content::Source<BrowserContext>(browser_context_),
168 content::Details<ExtensionHost>(this));
169 ProcessCreationQueue::GetInstance()->Remove(this);
172 content::RenderProcessHost* ExtensionHost::render_process_host() const {
173 return render_view_host()->GetProcess();
176 RenderViewHost* ExtensionHost::render_view_host() const {
177 // TODO(mpcomplete): This can be NULL. How do we handle that?
178 return render_view_host_;
181 bool ExtensionHost::IsRenderViewLive() const {
182 return render_view_host()->IsRenderViewLive();
185 void ExtensionHost::CreateRenderViewSoon() {
186 if ((render_process_host() && render_process_host()->HasConnection())) {
187 // If the process is already started, go ahead and initialize the RenderView
188 // synchronously. The process creation is the real meaty part that we want
189 // to defer.
190 CreateRenderViewNow();
191 } else {
192 ProcessCreationQueue::GetInstance()->CreateSoon(this);
196 void ExtensionHost::CreateRenderViewNow() {
197 LoadInitialURL();
198 if (!IsBackgroundPage()) {
199 DCHECK(IsRenderViewLive());
200 ExtensionsBrowserClient::Get()->OnRenderViewCreatedForBackgroundPage(this);
204 const GURL& ExtensionHost::GetURL() const {
205 return host_contents()->GetURL();
208 void ExtensionHost::LoadInitialURL() {
209 host_contents_->GetController().LoadURL(
210 initial_url_, content::Referrer(), content::PAGE_TRANSITION_LINK,
211 std::string());
214 bool ExtensionHost::IsBackgroundPage() const {
215 DCHECK(extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
216 return true;
219 void ExtensionHost::Close() {
220 content::NotificationService::current()->Notify(
221 chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
222 content::Source<BrowserContext>(browser_context_),
223 content::Details<ExtensionHost>(this));
226 void ExtensionHost::Observe(int type,
227 const content::NotificationSource& source,
228 const content::NotificationDetails& details) {
229 switch (type) {
230 case chrome::NOTIFICATION_EXTENSION_UNLOADED:
231 // The extension object will be deleted after this notification has been
232 // sent. NULL it out so that dirty pointer issues don't arise in cases
233 // when multiple ExtensionHost objects pointing to the same Extension are
234 // present.
235 if (extension_ == content::Details<UnloadedExtensionInfo>(details)->
236 extension) {
237 extension_ = NULL;
239 break;
240 default:
241 NOTREACHED() << "Unexpected notification sent.";
242 break;
246 void ExtensionHost::RenderProcessGone(base::TerminationStatus status) {
247 // During browser shutdown, we may use sudden termination on an extension
248 // process, so it is expected to lose our connection to the render view.
249 // Do nothing.
250 RenderProcessHost* process_host = host_contents_->GetRenderProcessHost();
251 if (process_host && process_host->FastShutdownStarted())
252 return;
254 // In certain cases, multiple ExtensionHost objects may have pointed to
255 // the same Extension at some point (one with a background page and a
256 // popup, for example). When the first ExtensionHost goes away, the extension
257 // is unloaded, and any other host that pointed to that extension will have
258 // its pointer to it NULLed out so that any attempt to unload a dirty pointer
259 // will be averted.
260 if (!extension_)
261 return;
263 // TODO(aa): This is suspicious. There can be multiple views in an extension,
264 // and they aren't all going to use ExtensionHost. This should be in someplace
265 // more central, like EPM maybe.
266 content::NotificationService::current()->Notify(
267 chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
268 content::Source<BrowserContext>(browser_context_),
269 content::Details<ExtensionHost>(this));
272 void ExtensionHost::DidStopLoading(content::RenderViewHost* render_view_host) {
273 bool notify = !did_stop_loading_;
274 did_stop_loading_ = true;
275 OnDidStopLoading();
276 if (notify) {
277 if (extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
278 if (extension_ && BackgroundInfo::HasLazyBackgroundPage(extension_)) {
279 UMA_HISTOGRAM_TIMES("Extensions.EventPageLoadTime",
280 since_created_.Elapsed());
281 } else {
282 UMA_HISTOGRAM_TIMES("Extensions.BackgroundPageLoadTime",
283 since_created_.Elapsed());
285 } else if (extension_host_type_ == VIEW_TYPE_EXTENSION_DIALOG) {
286 UMA_HISTOGRAM_TIMES("Extensions.DialogLoadTime",
287 since_created_.Elapsed());
288 } else if (extension_host_type_ == VIEW_TYPE_EXTENSION_POPUP) {
289 UMA_HISTOGRAM_TIMES("Extensions.PopupLoadTime",
290 since_created_.Elapsed());
291 } else if (extension_host_type_ == VIEW_TYPE_EXTENSION_INFOBAR) {
292 UMA_HISTOGRAM_TIMES("Extensions.InfobarLoadTime",
293 since_created_.Elapsed());
296 // Send the notification last, because it might result in this being
297 // deleted.
298 content::NotificationService::current()->Notify(
299 chrome::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING,
300 content::Source<BrowserContext>(browser_context_),
301 content::Details<ExtensionHost>(this));
305 void ExtensionHost::OnDidStopLoading() {
306 DCHECK(extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
307 // Nothing to do for background pages.
310 void ExtensionHost::DocumentAvailableInMainFrame() {
311 // If the document has already been marked as available for this host, then
312 // bail. No need for the redundant setup. http://crbug.com/31170
313 if (document_element_available_)
314 return;
315 document_element_available_ = true;
316 OnDocumentAvailable();
319 void ExtensionHost::OnDocumentAvailable() {
320 DCHECK(extension_host_type_ == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
321 ExtensionSystem::Get(browser_context_)
322 ->runtime_data()
323 ->SetBackgroundPageReady(extension_, true);
324 content::NotificationService::current()->Notify(
325 chrome::NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY,
326 content::Source<const Extension>(extension_),
327 content::NotificationService::NoDetails());
330 void ExtensionHost::CloseContents(WebContents* contents) {
331 Close();
334 bool ExtensionHost::OnMessageReceived(const IPC::Message& message) {
335 bool handled = true;
336 IPC_BEGIN_MESSAGE_MAP(ExtensionHost, message)
337 IPC_MESSAGE_HANDLER(ExtensionHostMsg_Request, OnRequest)
338 IPC_MESSAGE_HANDLER(ExtensionHostMsg_EventAck, OnEventAck)
339 IPC_MESSAGE_HANDLER(ExtensionHostMsg_IncrementLazyKeepaliveCount,
340 OnIncrementLazyKeepaliveCount)
341 IPC_MESSAGE_HANDLER(ExtensionHostMsg_DecrementLazyKeepaliveCount,
342 OnDecrementLazyKeepaliveCount)
343 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_DetailedConsoleMessageAdded,
344 OnDetailedConsoleMessageAdded)
345 IPC_MESSAGE_UNHANDLED(handled = false)
346 IPC_END_MESSAGE_MAP()
347 return handled;
350 void ExtensionHost::OnRequest(const ExtensionHostMsg_Request_Params& params) {
351 extension_function_dispatcher_.Dispatch(params, render_view_host());
354 void ExtensionHost::OnEventAck() {
355 EventRouter* router = ExtensionSystem::Get(browser_context_)->event_router();
356 if (router)
357 router->OnEventAck(browser_context_, extension_id());
360 void ExtensionHost::OnIncrementLazyKeepaliveCount() {
361 ProcessManager* pm = ExtensionSystem::Get(
362 browser_context_)->process_manager();
363 if (pm)
364 pm->IncrementLazyKeepaliveCount(extension());
367 void ExtensionHost::OnDecrementLazyKeepaliveCount() {
368 ProcessManager* pm = ExtensionSystem::Get(
369 browser_context_)->process_manager();
370 if (pm)
371 pm->DecrementLazyKeepaliveCount(extension());
374 void ExtensionHost::OnDetailedConsoleMessageAdded(
375 const base::string16& message,
376 const base::string16& source,
377 const StackTrace& stack_trace,
378 int32 severity_level) {
379 if (!IsSourceFromAnExtension(source))
380 return;
382 GURL context_url;
383 WebContents* associated_contents = GetAssociatedWebContents();
384 if (associated_contents)
385 context_url = associated_contents->GetLastCommittedURL();
386 else if (host_contents_.get())
387 context_url = host_contents_->GetLastCommittedURL();
389 ErrorConsole* console =
390 ExtensionSystem::Get(browser_context_)->error_console();
391 if (!console)
392 return;
394 console->ReportError(
395 scoped_ptr<ExtensionError>(new RuntimeError(
396 extension_id_,
397 browser_context_->IsOffTheRecord(),
398 source,
399 message,
400 stack_trace,
401 context_url,
402 static_cast<logging::LogSeverity>(severity_level),
403 render_view_host_->GetRoutingID(),
404 render_view_host_->GetProcess()->GetID())));
407 // content::WebContentsObserver
409 void ExtensionHost::RenderViewCreated(RenderViewHost* render_view_host) {
410 render_view_host_ = render_view_host;
413 void ExtensionHost::RenderViewDeleted(RenderViewHost* render_view_host) {
414 // If our RenderViewHost is deleted, fall back to the host_contents' current
415 // RVH. There is sometimes a small gap between the pending RVH being deleted
416 // and RenderViewCreated being called, so we update it here.
417 if (render_view_host == render_view_host_)
418 render_view_host_ = host_contents_->GetRenderViewHost();
421 content::JavaScriptDialogManager* ExtensionHost::GetJavaScriptDialogManager() {
422 return ExtensionsBrowserClient::Get()->GetJavaScriptDialogManager();
425 void ExtensionHost::AddNewContents(WebContents* source,
426 WebContents* new_contents,
427 WindowOpenDisposition disposition,
428 const gfx::Rect& initial_pos,
429 bool user_gesture,
430 bool* was_blocked) {
431 // First, if the creating extension view was associated with a tab contents,
432 // use that tab content's delegate. We must be careful here that the
433 // associated tab contents has the same profile as the new tab contents. In
434 // the case of extensions in 'spanning' incognito mode, they can mismatch.
435 // We don't want to end up putting a normal tab into an incognito window, or
436 // vice versa.
437 // Note that we don't do this for popup windows, because we need to associate
438 // those with their extension_app_id.
439 if (disposition != NEW_POPUP) {
440 WebContents* associated_contents = GetAssociatedWebContents();
441 if (associated_contents &&
442 associated_contents->GetBrowserContext() ==
443 new_contents->GetBrowserContext()) {
444 WebContentsDelegate* delegate = associated_contents->GetDelegate();
445 if (delegate) {
446 delegate->AddNewContents(
447 associated_contents, new_contents, disposition, initial_pos,
448 user_gesture, was_blocked);
449 return;
454 ExtensionTabUtil::CreateTab(new_contents, extension_id_, disposition,
455 initial_pos, user_gesture);
458 void ExtensionHost::RenderViewReady() {
459 content::NotificationService::current()->Notify(
460 chrome::NOTIFICATION_EXTENSION_HOST_CREATED,
461 content::Source<BrowserContext>(browser_context_),
462 content::Details<ExtensionHost>(this));
465 void ExtensionHost::RequestMediaAccessPermission(
466 content::WebContents* web_contents,
467 const content::MediaStreamRequest& request,
468 const content::MediaResponseCallback& callback) {
469 MediaCaptureDevicesDispatcher::GetInstance()->ProcessMediaAccessRequest(
470 web_contents, request, callback, extension());
473 bool ExtensionHost::PreHandleGestureEvent(
474 content::WebContents* source,
475 const blink::WebGestureEvent& event) {
476 // Disable pinch zooming.
477 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
478 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
479 event.type == blink::WebGestureEvent::GesturePinchEnd;
482 } // namespace extensions