ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / content / browser / web_contents / web_contents_impl.cc
blob7d3766006456ddf20376ef8faee2abcfb4eae3a1
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 "content/browser/web_contents/web_contents_impl.h"
7 #include <utility>
9 #include "base/command_line.h"
10 #include "base/lazy_instance.h"
11 #include "base/logging.h"
12 #include "base/metrics/histogram.h"
13 #include "base/process/process.h"
14 #include "base/strings/string16.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/time/time.h"
19 #include "base/trace_event/trace_event.h"
20 #include "content/browser/accessibility/accessibility_mode_helper.h"
21 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
22 #include "content/browser/browser_plugin/browser_plugin_embedder.h"
23 #include "content/browser/browser_plugin/browser_plugin_guest.h"
24 #include "content/browser/child_process_security_policy_impl.h"
25 #include "content/browser/devtools/devtools_manager.h"
26 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
27 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
28 #include "content/browser/download/download_stats.h"
29 #include "content/browser/download/mhtml_generation_manager.h"
30 #include "content/browser/download/save_package.h"
31 #include "content/browser/frame_host/cross_process_frame_connector.h"
32 #include "content/browser/frame_host/interstitial_page_impl.h"
33 #include "content/browser/frame_host/navigation_entry_impl.h"
34 #include "content/browser/frame_host/navigator_impl.h"
35 #include "content/browser/frame_host/render_frame_host_impl.h"
36 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
37 #include "content/browser/geolocation/geolocation_service_context.h"
38 #include "content/browser/host_zoom_map_impl.h"
39 #include "content/browser/loader/resource_dispatcher_host_impl.h"
40 #include "content/browser/manifest/manifest_manager_host.h"
41 #include "content/browser/media/audio_stream_monitor.h"
42 #include "content/browser/media/capture/web_contents_audio_muter.h"
43 #include "content/browser/message_port_message_filter.h"
44 #include "content/browser/plugin_content_origin_whitelist.h"
45 #include "content/browser/power_save_blocker_impl.h"
46 #include "content/browser/renderer_host/render_process_host_impl.h"
47 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
48 #include "content/browser/renderer_host/render_view_host_impl.h"
49 #include "content/browser/renderer_host/render_widget_host_impl.h"
50 #include "content/browser/renderer_host/render_widget_host_view_base.h"
51 #include "content/browser/screen_orientation/screen_orientation_dispatcher_host_impl.h"
52 #include "content/browser/site_instance_impl.h"
53 #include "content/browser/web_contents/web_contents_view_guest.h"
54 #include "content/browser/webui/generic_handler.h"
55 #include "content/browser/webui/web_ui_controller_factory_registry.h"
56 #include "content/browser/webui/web_ui_impl.h"
57 #include "content/common/browser_plugin/browser_plugin_constants.h"
58 #include "content/common/browser_plugin/browser_plugin_messages.h"
59 #include "content/common/frame_messages.h"
60 #include "content/common/image_messages.h"
61 #include "content/common/input_messages.h"
62 #include "content/common/ssl_status_serialization.h"
63 #include "content/common/view_messages.h"
64 #include "content/public/browser/ax_event_notification_details.h"
65 #include "content/public/browser/browser_context.h"
66 #include "content/public/browser/browser_plugin_guest_manager.h"
67 #include "content/public/browser/content_browser_client.h"
68 #include "content/public/browser/devtools_agent_host.h"
69 #include "content/public/browser/download_manager.h"
70 #include "content/public/browser/download_url_parameters.h"
71 #include "content/public/browser/invalidate_type.h"
72 #include "content/public/browser/javascript_dialog_manager.h"
73 #include "content/public/browser/load_from_memory_cache_details.h"
74 #include "content/public/browser/load_notification_details.h"
75 #include "content/public/browser/navigation_details.h"
76 #include "content/public/browser/notification_details.h"
77 #include "content/public/browser/notification_service.h"
78 #include "content/public/browser/render_widget_host_iterator.h"
79 #include "content/public/browser/resource_request_details.h"
80 #include "content/public/browser/screen_orientation_dispatcher_host.h"
81 #include "content/public/browser/storage_partition.h"
82 #include "content/public/browser/user_metrics.h"
83 #include "content/public/browser/web_contents_delegate.h"
84 #include "content/public/browser/web_contents_observer.h"
85 #include "content/public/common/bindings_policy.h"
86 #include "content/public/common/content_constants.h"
87 #include "content/public/common/content_switches.h"
88 #include "content/public/common/page_zoom.h"
89 #include "content/public/common/result_codes.h"
90 #include "content/public/common/url_constants.h"
91 #include "content/public/common/url_utils.h"
92 #include "content/public/common/web_preferences.h"
93 #include "net/base/mime_util.h"
94 #include "net/base/net_util.h"
95 #include "net/http/http_cache.h"
96 #include "net/http/http_transaction_factory.h"
97 #include "net/url_request/url_request_context.h"
98 #include "net/url_request/url_request_context_getter.h"
99 #include "ui/base/layout.h"
100 #include "ui/gfx/display.h"
101 #include "ui/gfx/screen.h"
102 #include "ui/gl/gl_switches.h"
104 #if defined(ENABLE_BROWSER_CDMS)
105 #include "content/browser/media/media_web_contents_observer.h"
106 #endif
108 #if defined(OS_ANDROID)
109 #include "content/browser/android/content_video_view.h"
110 #include "content/browser/android/date_time_chooser_android.h"
111 #include "content/browser/media/android/browser_media_player_manager.h"
112 #include "content/browser/web_contents/web_contents_android.h"
113 #endif
115 #if defined(OS_MACOSX)
116 #include "base/mac/foundation_util.h"
117 #endif
119 namespace content {
120 namespace {
122 const int kMinimumDelayBetweenLoadingUpdatesMS = 100;
124 // This matches what Blink's ProgressTracker has traditionally used for a
125 // minimum progress value.
126 const double kMinimumLoadingProgress = 0.1;
128 const char kDotGoogleDotCom[] = ".google.com";
130 #if defined(OS_ANDROID)
131 const char kWebContentsAndroidKey[] = "web_contents_android";
132 #endif // OS_ANDROID
134 base::LazyInstance<std::vector<WebContentsImpl::CreatedCallback> >
135 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
137 static int StartDownload(RenderFrameHost* rfh,
138 const GURL& url,
139 bool is_favicon,
140 uint32_t max_bitmap_size) {
141 static int g_next_image_download_id = 0;
142 rfh->Send(new ImageMsg_DownloadImage(rfh->GetRoutingID(),
143 ++g_next_image_download_id,
144 url,
145 is_favicon,
146 max_bitmap_size));
147 return g_next_image_download_id;
150 void NotifyCacheOnIO(
151 scoped_refptr<net::URLRequestContextGetter> request_context,
152 const GURL& url,
153 const std::string& http_method) {
154 request_context->GetURLRequestContext()->http_transaction_factory()->
155 GetCache()->OnExternalCacheHit(url, http_method);
158 // Helper function for retrieving all the sites in a frame tree.
159 bool CollectSites(BrowserContext* context,
160 std::set<GURL>* sites,
161 FrameTreeNode* node) {
162 sites->insert(SiteInstance::GetSiteForURL(context, node->current_url()));
163 return true;
166 bool ForEachFrameInternal(
167 const base::Callback<void(RenderFrameHost*)>& on_frame,
168 FrameTreeNode* node) {
169 on_frame.Run(node->current_frame_host());
170 return true;
173 bool ForEachPendingFrameInternal(
174 const base::Callback<void(RenderFrameHost*)>& on_frame,
175 FrameTreeNode* node) {
176 RenderFrameHost* pending_frame_host =
177 node->render_manager()->pending_frame_host();
178 if (pending_frame_host)
179 on_frame.Run(pending_frame_host);
180 return true;
183 void SendToAllFramesInternal(IPC::Message* message, RenderFrameHost* rfh) {
184 IPC::Message* message_copy = new IPC::Message(*message);
185 message_copy->set_routing_id(rfh->GetRoutingID());
186 rfh->Send(message_copy);
189 void AddRenderWidgetHostViewToSet(std::set<RenderWidgetHostView*>* set,
190 RenderFrameHost* rfh) {
191 RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
192 ->frame_tree_node()
193 ->render_manager()
194 ->GetRenderWidgetHostView();
195 set->insert(rwhv);
198 void SetAccessibilityModeOnFrame(AccessibilityMode mode,
199 RenderFrameHost* frame_host) {
200 static_cast<RenderFrameHostImpl*>(frame_host)->SetAccessibilityMode(mode);
203 // Enable sudden termination for the current RenderFrameHost of
204 // |frame_tree_node| if the ID of its SiteInstance is |site_instance_id|. Used
205 // with FrameTree::ForEach.
206 bool EnableSuddenTermination(int32 site_instance_id,
207 FrameTreeNode* frame_tree_node) {
208 if (frame_tree_node->current_frame_host()->GetSiteInstance()->GetId()
209 == site_instance_id) {
210 frame_tree_node->current_frame_host()
211 ->set_override_sudden_termination_status(true);
213 return true;
216 // Returns false and sets |sudden_termination_allowed| to false if sudden
217 // termination is not allowed for the current RenderFrameHost of
218 // |frame_tree_node|. Used with FrameTree::ForEach.
219 bool SuddenTerminationAllowed(bool* sudden_termination_allowed,
220 FrameTreeNode* frame_tree_node) {
221 if (frame_tree_node->current_frame_host()->SuddenTerminationAllowed())
222 return true;
223 *sudden_termination_allowed = false;
224 return false;
227 } // namespace
229 WebContents* WebContents::Create(const WebContents::CreateParams& params) {
230 return WebContentsImpl::CreateWithOpener(
231 params, static_cast<WebContentsImpl*>(params.opener));
234 WebContents* WebContents::CreateWithSessionStorage(
235 const WebContents::CreateParams& params,
236 const SessionStorageNamespaceMap& session_storage_namespace_map) {
237 WebContentsImpl* new_contents = new WebContentsImpl(
238 params.browser_context, NULL);
240 for (SessionStorageNamespaceMap::const_iterator it =
241 session_storage_namespace_map.begin();
242 it != session_storage_namespace_map.end();
243 ++it) {
244 new_contents->GetController()
245 .SetSessionStorageNamespace(it->first, it->second.get());
248 new_contents->Init(params);
249 return new_contents;
252 void WebContentsImpl::FriendZone::AddCreatedCallbackForTesting(
253 const CreatedCallback& callback) {
254 g_created_callbacks.Get().push_back(callback);
257 void WebContentsImpl::FriendZone::RemoveCreatedCallbackForTesting(
258 const CreatedCallback& callback) {
259 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
260 if (g_created_callbacks.Get().at(i).Equals(callback)) {
261 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
262 return;
267 WebContents* WebContents::FromRenderViewHost(const RenderViewHost* rvh) {
268 return rvh->GetDelegate()->GetAsWebContents();
271 WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
272 RenderFrameHostImpl* rfh_impl = static_cast<RenderFrameHostImpl*>(rfh);
273 if (!rfh_impl)
274 return NULL;
275 return rfh_impl->delegate()->GetAsWebContents();
278 // WebContentsImpl::DestructionObserver ----------------------------------------
280 class WebContentsImpl::DestructionObserver : public WebContentsObserver {
281 public:
282 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
283 : WebContentsObserver(watched_contents),
284 owner_(owner) {
287 // WebContentsObserver:
288 void WebContentsDestroyed() override {
289 owner_->OnWebContentsDestroyed(
290 static_cast<WebContentsImpl*>(web_contents()));
293 private:
294 WebContentsImpl* owner_;
296 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
299 WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id,
300 int render_frame_id,
301 ColorChooser* chooser,
302 int identifier)
303 : render_process_id(render_process_id),
304 render_frame_id(render_frame_id),
305 chooser(chooser),
306 identifier(identifier) {
309 WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
312 // WebContentsImpl -------------------------------------------------------------
314 WebContentsImpl::WebContentsImpl(BrowserContext* browser_context,
315 WebContentsImpl* opener)
316 : delegate_(NULL),
317 controller_(this, browser_context),
318 render_view_host_delegate_view_(NULL),
319 opener_(opener),
320 created_with_opener_(!!opener),
321 #if defined(OS_WIN)
322 accessible_parent_(NULL),
323 #endif
324 frame_tree_(new NavigatorImpl(&controller_, this),
325 this,
326 this,
327 this,
328 this),
329 is_loading_(false),
330 is_load_to_different_document_(false),
331 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
332 crashed_error_code_(0),
333 waiting_for_response_(false),
334 load_state_(net::LOAD_STATE_IDLE, base::string16()),
335 loading_total_progress_(0.0),
336 loading_frames_in_progress_(0),
337 upload_size_(0),
338 upload_position_(0),
339 displayed_insecure_content_(false),
340 has_accessed_initial_document_(false),
341 capturer_count_(0),
342 should_normally_be_visible_(true),
343 is_being_destroyed_(false),
344 notify_disconnection_(false),
345 dialog_manager_(NULL),
346 is_showing_before_unload_dialog_(false),
347 last_active_time_(base::TimeTicks::Now()),
348 closed_by_user_gesture_(false),
349 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)),
350 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)),
351 render_view_message_source_(NULL),
352 render_frame_message_source_(NULL),
353 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
354 fullscreen_widget_had_focus_at_shutdown_(false),
355 is_subframe_(false),
356 force_disable_overscroll_content_(false),
357 last_dialog_suppressed_(false),
358 geolocation_service_context_(new GeolocationServiceContext()),
359 accessibility_mode_(
360 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
361 audio_stream_monitor_(this),
362 virtual_keyboard_requested_(false),
363 loading_weak_factory_(this) {
364 frame_tree_.SetFrameRemoveListener(
365 base::Bind(&WebContentsImpl::OnFrameRemoved,
366 base::Unretained(this)));
367 #if defined(ENABLE_BROWSER_CDMS)
368 media_web_contents_observer_.reset(new MediaWebContentsObserver(this));
369 #endif
372 WebContentsImpl::~WebContentsImpl() {
373 is_being_destroyed_ = true;
375 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
376 // shutdown and be deleted as well.
377 frame_tree_.ForEach(
378 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown));
380 ClearAllPowerSaveBlockers();
382 for (std::set<RenderWidgetHostImpl*>::iterator iter =
383 created_widgets_.begin(); iter != created_widgets_.end(); ++iter) {
384 (*iter)->DetachDelegate();
386 created_widgets_.clear();
388 // Clear out any JavaScript state.
389 if (dialog_manager_)
390 dialog_manager_->WebContentsDestroyed(this);
392 if (color_chooser_info_.get())
393 color_chooser_info_->chooser->End();
395 NotifyDisconnected();
397 // Notify any observer that have a reference on this WebContents.
398 NotificationService::current()->Notify(
399 NOTIFICATION_WEB_CONTENTS_DESTROYED,
400 Source<WebContents>(this),
401 NotificationService::NoDetails());
403 // Destroy all frame tree nodes except for the root; this notifies observers.
404 frame_tree_.ResetForMainFrameSwap();
405 GetRenderManager()->ResetProxyHosts();
407 // Manually call the observer methods for the root frame tree node.
408 RenderFrameHostManager* root = GetRenderManager();
410 if (root->pending_frame_host())
411 root->pending_frame_host()->SetRenderFrameCreated(false);
412 root->current_frame_host()->SetRenderFrameCreated(false);
414 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
415 FrameDeleted(root->current_frame_host()));
417 if (root->pending_render_view_host()) {
418 FOR_EACH_OBSERVER(WebContentsObserver,
419 observers_,
420 RenderViewDeleted(root->pending_render_view_host()));
423 FOR_EACH_OBSERVER(WebContentsObserver,
424 observers_,
425 RenderViewDeleted(root->current_host()));
427 FOR_EACH_OBSERVER(WebContentsObserver,
428 observers_,
429 WebContentsDestroyed());
431 FOR_EACH_OBSERVER(WebContentsObserver,
432 observers_,
433 ResetWebContents());
435 SetDelegate(NULL);
437 STLDeleteContainerPairSecondPointers(destruction_observers_.begin(),
438 destruction_observers_.end());
441 WebContentsImpl* WebContentsImpl::CreateWithOpener(
442 const WebContents::CreateParams& params,
443 WebContentsImpl* opener) {
444 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
445 WebContentsImpl* new_contents = new WebContentsImpl(
446 params.browser_context, params.opener_suppressed ? NULL : opener);
448 if (params.guest_delegate) {
449 // This makes |new_contents| act as a guest.
450 // For more info, see comment above class BrowserPluginGuest.
451 BrowserPluginGuest::Create(new_contents, params.guest_delegate);
452 // We are instantiating a WebContents for browser plugin. Set its subframe
453 // bit to true.
454 new_contents->is_subframe_ = true;
456 new_contents->Init(params);
457 return new_contents;
460 // static
461 std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
462 std::vector<WebContentsImpl*> result;
463 scoped_ptr<RenderWidgetHostIterator> widgets(
464 RenderWidgetHostImpl::GetRenderWidgetHosts());
465 std::set<WebContentsImpl*> web_contents_set;
466 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
467 if (!rwh->IsRenderView())
468 continue;
469 RenderViewHost* rvh = RenderViewHost::From(rwh);
470 if (!rvh)
471 continue;
472 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
473 if (!web_contents)
474 continue;
475 WebContentsImpl* wci = static_cast<WebContentsImpl*>(web_contents);
476 if (web_contents_set.find(wci) == web_contents_set.end()) {
477 web_contents_set.insert(wci);
478 result.push_back(wci);
481 return result;
484 RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
485 return GetRenderManager();
488 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
489 const IPC::Message& message) {
490 return OnMessageReceived(render_view_host, NULL, message);
493 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
494 RenderFrameHost* render_frame_host,
495 const IPC::Message& message) {
496 DCHECK(render_view_host || render_frame_host);
497 if (GetWebUI() &&
498 static_cast<WebUIImpl*>(GetWebUI())->OnMessageReceived(message)) {
499 return true;
502 ObserverListBase<WebContentsObserver>::Iterator it(observers_);
503 WebContentsObserver* observer;
504 if (render_frame_host) {
505 while ((observer = it.GetNext()) != NULL)
506 if (observer->OnMessageReceived(message, render_frame_host))
507 return true;
508 } else {
509 while ((observer = it.GetNext()) != NULL)
510 if (observer->OnMessageReceived(message))
511 return true;
514 // Message handlers should be aware of which
515 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
516 // stored in render_(view|frame)_message_source_.
517 if (render_frame_host)
518 render_frame_message_source_ = render_frame_host;
519 else
520 render_view_message_source_ = render_view_host;
522 bool handled = true;
523 IPC_BEGIN_MESSAGE_MAP(WebContentsImpl, message)
524 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse,
525 OnDomOperationResponse)
526 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor,
527 OnThemeColorChanged)
528 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad,
529 OnDocumentLoadedInFrame)
530 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad, OnDidFinishLoad)
531 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading)
532 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
533 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
534 OnDidChangeLoadProgress)
535 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser, OnOpenColorChooser)
536 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser, OnEndColorChooser)
537 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser,
538 OnSetSelectedColorInColorChooser)
539 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification,
540 OnMediaPlayingNotification)
541 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification,
542 OnMediaPausedNotification)
543 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFirstVisuallyNonEmptyPaint,
544 OnFirstVisuallyNonEmptyPaint)
545 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache,
546 OnDidLoadResourceFromMemoryCache)
547 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent,
548 OnDidDisplayInsecureContent)
549 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent,
550 OnDidRunInsecureContent)
551 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset)
552 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits, OnUpdateZoomLimits)
553 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory, OnEnumerateDirectory)
554 IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler,
555 OnRegisterProtocolHandler)
556 IPC_MESSAGE_HANDLER(ViewHostMsg_UnregisterProtocolHandler,
557 OnUnregisterProtocolHandler)
558 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply, OnFindReply)
559 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed, OnAppCacheAccessed)
560 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend, OnWebUISend)
561 #if defined(ENABLE_PLUGINS)
562 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
563 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
564 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
565 OnRequestPpapiBrokerPermission)
566 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach,
567 OnBrowserPluginMessage(render_frame_host,
568 message))
569 #endif
570 IPC_MESSAGE_HANDLER(ImageHostMsg_DidDownloadImage, OnDidDownloadImage)
571 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL, OnUpdateFaviconURL)
572 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage,
573 OnShowValidationMessage)
574 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage,
575 OnHideValidationMessage)
576 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage,
577 OnMoveValidationMessage)
578 #if defined(OS_ANDROID)
579 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply,
580 OnFindMatchRectsReply)
581 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog,
582 OnOpenDateTimeDialog)
583 #endif
584 IPC_MESSAGE_UNHANDLED(handled = false)
585 IPC_END_MESSAGE_MAP()
586 render_view_message_source_ = NULL;
587 render_frame_message_source_ = NULL;
589 return handled;
592 bool WebContentsImpl::HasValidFrameSource() {
593 if (!render_frame_message_source_) {
594 DCHECK(render_view_message_source_);
595 RecordAction(base::UserMetricsAction("BadMessageTerminate_WC"));
596 GetRenderProcessHost()->ReceivedBadMessage();
597 return false;
600 return true;
603 void WebContentsImpl::RunFileChooser(
604 RenderViewHost* render_view_host,
605 const FileChooserParams& params) {
606 if (delegate_)
607 delegate_->RunFileChooser(this, params);
610 NavigationControllerImpl& WebContentsImpl::GetController() {
611 return controller_;
614 const NavigationControllerImpl& WebContentsImpl::GetController() const {
615 return controller_;
618 BrowserContext* WebContentsImpl::GetBrowserContext() const {
619 return controller_.GetBrowserContext();
622 const GURL& WebContentsImpl::GetURL() const {
623 // We may not have a navigation entry yet.
624 NavigationEntry* entry = controller_.GetVisibleEntry();
625 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
628 const GURL& WebContentsImpl::GetVisibleURL() const {
629 // We may not have a navigation entry yet.
630 NavigationEntry* entry = controller_.GetVisibleEntry();
631 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
634 const GURL& WebContentsImpl::GetLastCommittedURL() const {
635 // We may not have a navigation entry yet.
636 NavigationEntry* entry = controller_.GetLastCommittedEntry();
637 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
640 WebContentsDelegate* WebContentsImpl::GetDelegate() {
641 return delegate_;
644 void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
645 // TODO(cbentzel): remove this debugging code?
646 if (delegate == delegate_)
647 return;
648 if (delegate_)
649 delegate_->Detach(this);
650 delegate_ = delegate;
651 if (delegate_) {
652 delegate_->Attach(this);
653 // Ensure the visible RVH reflects the new delegate's preferences.
654 if (view_)
655 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
659 RenderProcessHost* WebContentsImpl::GetRenderProcessHost() const {
660 RenderViewHostImpl* host = GetRenderManager()->current_host();
661 return host ? host->GetProcess() : NULL;
664 RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
665 return frame_tree_.root()->current_frame_host();
668 RenderFrameHost* WebContentsImpl::GetFocusedFrame() {
669 if (!frame_tree_.GetFocusedFrame())
670 return NULL;
671 return frame_tree_.GetFocusedFrame()->current_frame_host();
674 void WebContentsImpl::ForEachFrame(
675 const base::Callback<void(RenderFrameHost*)>& on_frame) {
676 frame_tree_.ForEach(base::Bind(&ForEachFrameInternal, on_frame));
679 void WebContentsImpl::SendToAllFrames(IPC::Message* message) {
680 ForEachFrame(base::Bind(&SendToAllFramesInternal, message));
681 delete message;
684 RenderViewHost* WebContentsImpl::GetRenderViewHost() const {
685 return GetRenderManager()->current_host();
688 int WebContentsImpl::GetRoutingID() const {
689 if (!GetRenderViewHost())
690 return MSG_ROUTING_NONE;
692 return GetRenderViewHost()->GetRoutingID();
695 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
696 return fullscreen_widget_routing_id_;
699 RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() const {
700 return GetRenderManager()->GetRenderWidgetHostView();
703 RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView()
704 const {
705 RenderWidgetHost* const widget_host =
706 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
707 GetFullscreenWidgetRoutingID());
708 return widget_host ? widget_host->GetView() : NULL;
711 WebContentsView* WebContentsImpl::GetView() const {
712 return view_.get();
715 void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode) {
716 if (mode == accessibility_mode_)
717 return;
719 accessibility_mode_ = mode;
720 frame_tree_.ForEach(
721 base::Bind(&ForEachFrameInternal,
722 base::Bind(&SetAccessibilityModeOnFrame, mode)));
723 frame_tree_.ForEach(
724 base::Bind(&ForEachPendingFrameInternal,
725 base::Bind(&SetAccessibilityModeOnFrame, mode)));
728 void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode) {
729 SetAccessibilityMode(AddAccessibilityModeTo(accessibility_mode_, mode));
732 void WebContentsImpl::RemoveAccessibilityMode(AccessibilityMode mode) {
733 SetAccessibilityMode(RemoveAccessibilityModeFrom(accessibility_mode_, mode));
736 void WebContentsImpl::ClearNavigationTransitionData() {
737 FrameTreeNode* node = frame_tree_.root();
738 node->render_manager()->ClearNavigationTransitionData();
741 WebUI* WebContentsImpl::CreateWebUI(const GURL& url) {
742 WebUIImpl* web_ui = new WebUIImpl(this);
743 WebUIController* controller = WebUIControllerFactoryRegistry::GetInstance()->
744 CreateWebUIControllerForURL(web_ui, url);
745 if (controller) {
746 web_ui->AddMessageHandler(new GenericHandler());
747 web_ui->SetController(controller);
748 return web_ui;
751 delete web_ui;
752 return NULL;
755 WebUI* WebContentsImpl::GetWebUI() const {
756 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
757 : GetRenderManager()->pending_web_ui();
760 WebUI* WebContentsImpl::GetCommittedWebUI() const {
761 return GetRenderManager()->web_ui();
764 void WebContentsImpl::SetUserAgentOverride(const std::string& override) {
765 if (GetUserAgentOverride() == override)
766 return;
768 renderer_preferences_.user_agent_override = override;
770 // Send the new override string to the renderer.
771 RenderViewHost* host = GetRenderViewHost();
772 if (host)
773 host->SyncRendererPrefs();
775 // Reload the page if a load is currently in progress to avoid having
776 // different parts of the page loaded using different user agents.
777 NavigationEntry* entry = controller_.GetVisibleEntry();
778 if (is_loading_ && entry != NULL && entry->GetIsOverridingUserAgent())
779 controller_.ReloadIgnoringCache(true);
781 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
782 UserAgentOverrideSet(override));
785 const std::string& WebContentsImpl::GetUserAgentOverride() const {
786 return renderer_preferences_.user_agent_override;
789 void WebContentsImpl::EnableTreeOnlyAccessibilityMode() {
790 AddAccessibilityMode(AccessibilityModeTreeOnly);
793 bool WebContentsImpl::IsTreeOnlyAccessibilityModeForTesting() const {
794 return accessibility_mode_ == AccessibilityModeTreeOnly;
797 bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
798 return accessibility_mode_ == AccessibilityModeComplete;
801 #if defined(OS_WIN)
802 void WebContentsImpl::SetParentNativeViewAccessible(
803 gfx::NativeViewAccessible accessible_parent) {
804 accessible_parent_ = accessible_parent;
805 RenderFrameHostImpl* rfh = GetMainFrame();
806 if (rfh)
807 rfh->SetParentNativeViewAccessible(accessible_parent);
809 #endif
811 const base::string16& WebContentsImpl::GetTitle() const {
812 // Transient entries take precedence. They are used for interstitial pages
813 // that are shown on top of existing pages.
814 NavigationEntry* entry = controller_.GetTransientEntry();
815 std::string accept_languages =
816 GetContentClient()->browser()->GetAcceptLangs(
817 GetBrowserContext());
818 if (entry) {
819 return entry->GetTitleForDisplay(accept_languages);
821 WebUI* our_web_ui = GetRenderManager()->pending_web_ui() ?
822 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
823 if (our_web_ui) {
824 // Don't override the title in view source mode.
825 entry = controller_.GetVisibleEntry();
826 if (!(entry && entry->IsViewSourceMode())) {
827 // Give the Web UI the chance to override our title.
828 const base::string16& title = our_web_ui->GetOverriddenTitle();
829 if (!title.empty())
830 return title;
834 // We use the title for the last committed entry rather than a pending
835 // navigation entry. For example, when the user types in a URL, we want to
836 // keep the old page's title until the new load has committed and we get a new
837 // title.
838 entry = controller_.GetLastCommittedEntry();
840 // We make an exception for initial navigations.
841 if (controller_.IsInitialNavigation()) {
842 // We only want to use the title from the visible entry in one of two cases:
843 // 1. There's already a committed entry for an initial navigation, in which
844 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
845 // 2. The pending entry has been explicitly assigned a title to display.
847 // If there's no last committed entry and no assigned title, we should fall
848 // back to |page_title_when_no_navigation_entry_| rather than showing the
849 // URL.
850 if (entry ||
851 (controller_.GetVisibleEntry() &&
852 !controller_.GetVisibleEntry()->GetTitle().empty())) {
853 entry = controller_.GetVisibleEntry();
857 if (entry) {
858 return entry->GetTitleForDisplay(accept_languages);
861 // |page_title_when_no_navigation_entry_| is finally used
862 // if no title cannot be retrieved.
863 return page_title_when_no_navigation_entry_;
866 int32 WebContentsImpl::GetMaxPageID() {
867 return GetMaxPageIDForSiteInstance(GetSiteInstance());
870 int32 WebContentsImpl::GetMaxPageIDForSiteInstance(
871 SiteInstance* site_instance) {
872 if (max_page_ids_.find(site_instance->GetId()) == max_page_ids_.end())
873 max_page_ids_[site_instance->GetId()] = -1;
875 return max_page_ids_[site_instance->GetId()];
878 void WebContentsImpl::UpdateMaxPageID(int32 page_id) {
879 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id);
882 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
883 SiteInstance* site_instance, int32 page_id) {
884 if (GetMaxPageIDForSiteInstance(site_instance) < page_id)
885 max_page_ids_[site_instance->GetId()] = page_id;
888 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents* web_contents) {
889 WebContentsImpl* contents = static_cast<WebContentsImpl*>(web_contents);
890 max_page_ids_ = contents->max_page_ids_;
893 SiteInstanceImpl* WebContentsImpl::GetSiteInstance() const {
894 return GetRenderManager()->current_host()->GetSiteInstance();
897 SiteInstanceImpl* WebContentsImpl::GetPendingSiteInstance() const {
898 RenderViewHostImpl* dest_rvh =
899 GetRenderManager()->pending_render_view_host() ?
900 GetRenderManager()->pending_render_view_host() :
901 GetRenderManager()->current_host();
902 return dest_rvh->GetSiteInstance();
905 bool WebContentsImpl::IsLoading() const {
906 return is_loading_;
909 bool WebContentsImpl::IsLoadingToDifferentDocument() const {
910 return is_loading_ && is_load_to_different_document_;
913 bool WebContentsImpl::IsWaitingForResponse() const {
914 return waiting_for_response_ && is_load_to_different_document_;
917 const net::LoadStateWithParam& WebContentsImpl::GetLoadState() const {
918 return load_state_;
921 const base::string16& WebContentsImpl::GetLoadStateHost() const {
922 return load_state_host_;
925 uint64 WebContentsImpl::GetUploadSize() const {
926 return upload_size_;
929 uint64 WebContentsImpl::GetUploadPosition() const {
930 return upload_position_;
933 std::set<GURL> WebContentsImpl::GetSitesInTab() const {
934 std::set<GURL> sites;
935 frame_tree_.ForEach(base::Bind(&CollectSites,
936 base::Unretained(GetBrowserContext()),
937 base::Unretained(&sites)));
938 return sites;
941 const std::string& WebContentsImpl::GetEncoding() const {
942 return canonical_encoding_;
945 bool WebContentsImpl::DisplayedInsecureContent() const {
946 return displayed_insecure_content_;
949 void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size) {
950 DCHECK(!is_being_destroyed_);
951 ++capturer_count_;
952 DVLOG(1) << "There are now " << capturer_count_
953 << " capturing(s) of WebContentsImpl@" << this;
955 // Note: This provides a hint to upstream code to size the views optimally
956 // for quality (e.g., to avoid scaling).
957 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
958 preferred_size_for_capture_ = capture_size;
959 OnPreferredSizeChanged(preferred_size_);
962 // Ensure that all views are un-occluded before capture begins.
963 WasUnOccluded();
966 void WebContentsImpl::DecrementCapturerCount() {
967 --capturer_count_;
968 DVLOG(1) << "There are now " << capturer_count_
969 << " capturing(s) of WebContentsImpl@" << this;
970 DCHECK_LE(0, capturer_count_);
972 if (is_being_destroyed_)
973 return;
975 if (capturer_count_ == 0) {
976 const gfx::Size old_size = preferred_size_for_capture_;
977 preferred_size_for_capture_ = gfx::Size();
978 OnPreferredSizeChanged(old_size);
981 if (IsHidden()) {
982 DVLOG(1) << "Executing delayed WasHidden().";
983 WasHidden();
987 int WebContentsImpl::GetCapturerCount() const {
988 return capturer_count_;
991 bool WebContentsImpl::IsAudioMuted() const {
992 return audio_muter_.get() && audio_muter_->is_muting();
995 void WebContentsImpl::SetAudioMuted(bool mute) {
996 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
997 << " for WebContentsImpl@" << this;
999 if (mute == IsAudioMuted())
1000 return;
1002 if (mute) {
1003 if (!audio_muter_)
1004 audio_muter_.reset(new WebContentsAudioMuter(this));
1005 audio_muter_->StartMuting();
1006 } else {
1007 DCHECK(audio_muter_);
1008 audio_muter_->StopMuting();
1011 // Notification for UI updates in response to the changed muting state.
1012 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1015 bool WebContentsImpl::IsCrashed() const {
1016 return (crashed_status_ == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1017 crashed_status_ == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
1018 crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
1021 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1022 int error_code) {
1023 if (status == crashed_status_)
1024 return;
1026 crashed_status_ = status;
1027 crashed_error_code_ = error_code;
1028 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
1031 base::TerminationStatus WebContentsImpl::GetCrashedStatus() const {
1032 return crashed_status_;
1035 bool WebContentsImpl::IsBeingDestroyed() const {
1036 return is_being_destroyed_;
1039 void WebContentsImpl::NotifyNavigationStateChanged(
1040 InvalidateTypes changed_flags) {
1041 // Create and release the audio power save blocker depending on whether the
1042 // tab is actively producing audio or not.
1043 if ((changed_flags & INVALIDATE_TYPE_TAB) &&
1044 AudioStreamMonitor::monitoring_available()) {
1045 if (WasRecentlyAudible()) {
1046 if (!audio_power_save_blocker_)
1047 CreateAudioPowerSaveBlocker();
1048 } else {
1049 audio_power_save_blocker_.reset();
1053 if (delegate_)
1054 delegate_->NavigationStateChanged(this, changed_flags);
1057 base::TimeTicks WebContentsImpl::GetLastActiveTime() const {
1058 return last_active_time_;
1061 void WebContentsImpl::WasShown() {
1062 controller_.SetActive(true);
1064 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1065 if (view) {
1066 view->Show();
1067 #if defined(OS_MACOSX)
1068 view->SetActive(true);
1069 #endif
1073 last_active_time_ = base::TimeTicks::Now();
1075 // The resize rect might have changed while this was inactive -- send the new
1076 // one to make sure it's up to date.
1077 RenderViewHostImpl* rvh =
1078 static_cast<RenderViewHostImpl*>(GetRenderViewHost());
1079 if (rvh) {
1080 rvh->ResizeRectChanged(GetRootWindowResizerRect());
1083 // Restore power save blocker if there are active video players running.
1084 if (!active_video_players_.empty() && !video_power_save_blocker_)
1085 CreateVideoPowerSaveBlocker();
1087 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasShown());
1089 should_normally_be_visible_ = true;
1092 void WebContentsImpl::WasHidden() {
1093 // If there are entities capturing screenshots or video (e.g., mirroring),
1094 // don't activate the "disable rendering" optimization.
1095 if (capturer_count_ == 0) {
1096 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1097 // open a tab in the background, then closes the tab before selecting it.
1098 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1099 // removes the |GetRenderViewHost()|; then when we actually destroy the
1100 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1101 // calls us).
1102 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1103 if (view)
1104 view->Hide();
1107 // Release any video power save blockers held as video is not visible.
1108 video_power_save_blocker_.reset();
1111 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasHidden());
1113 should_normally_be_visible_ = false;
1116 void WebContentsImpl::WasOccluded() {
1117 if (capturer_count_ > 0)
1118 return;
1120 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1121 if (view)
1122 view->WasOccluded();
1126 void WebContentsImpl::WasUnOccluded() {
1127 for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
1128 if (view)
1129 view->WasUnOccluded();
1133 bool WebContentsImpl::NeedToFireBeforeUnload() {
1134 bool sudden_termination_allowed = true;
1135 frame_tree_.ForEach(base::Bind(
1136 &SuddenTerminationAllowed, &sudden_termination_allowed));
1137 // TODO(creis): Should we fire even for interstitial pages?
1138 return WillNotifyDisconnection() &&
1139 !ShowingInterstitialPage() &&
1140 !sudden_termination_allowed;
1143 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition) {
1144 GetMainFrame()->DispatchBeforeUnload(for_cross_site_transition);
1147 void WebContentsImpl::Stop() {
1148 GetRenderManager()->Stop();
1149 FOR_EACH_OBSERVER(WebContentsObserver, observers_, NavigationStopped());
1152 WebContents* WebContentsImpl::Clone() {
1153 // We use our current SiteInstance since the cloned entry will use it anyway.
1154 // We pass our own opener so that the cloned page can access it if it was
1155 // before.
1156 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
1157 create_params.initial_size = GetContainerBounds().size();
1158 WebContentsImpl* tc = CreateWithOpener(create_params, opener_);
1159 tc->GetController().CopyStateFrom(controller_);
1160 FOR_EACH_OBSERVER(WebContentsObserver,
1161 observers_,
1162 DidCloneToNewWebContents(this, tc));
1163 return tc;
1166 void WebContentsImpl::Observe(int type,
1167 const NotificationSource& source,
1168 const NotificationDetails& details) {
1169 switch (type) {
1170 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
1171 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
1172 RenderWidgetHostView* view = host->GetView();
1173 if (view == GetFullscreenRenderWidgetHostView()) {
1174 // We cannot just call view_->RestoreFocus() here. On some platforms,
1175 // attempting to focus the currently-invisible WebContentsView will be
1176 // flat-out ignored. Therefore, this boolean is used to track whether
1177 // we will request focus after the fullscreen widget has been
1178 // destroyed.
1179 fullscreen_widget_had_focus_at_shutdown_ = (view && view->HasFocus());
1180 } else {
1181 for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
1182 i != pending_widget_views_.end(); ++i) {
1183 if (host->GetView() == i->second) {
1184 pending_widget_views_.erase(i);
1185 break;
1189 break;
1191 default:
1192 NOTREACHED();
1196 WebContents* WebContentsImpl::GetWebContents() {
1197 return this;
1200 void WebContentsImpl::Init(const WebContents::CreateParams& params) {
1201 // This is set before initializing the render manager since
1202 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
1203 // it should be hidden.
1204 should_normally_be_visible_ = !params.initially_hidden;
1206 // Either both routing ids can be given, or neither can be.
1207 DCHECK((params.routing_id == MSG_ROUTING_NONE &&
1208 params.main_frame_routing_id == MSG_ROUTING_NONE) ||
1209 (params.routing_id != MSG_ROUTING_NONE &&
1210 params.main_frame_routing_id != MSG_ROUTING_NONE));
1211 GetRenderManager()->Init(
1212 params.browser_context, params.site_instance, params.routing_id,
1213 params.main_frame_routing_id);
1215 WebContentsViewDelegate* delegate =
1216 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1218 if (browser_plugin_guest_) {
1219 scoped_ptr<WebContentsView> platform_view(CreateWebContentsView(
1220 this, delegate, &render_view_host_delegate_view_));
1222 WebContentsViewGuest* rv = new WebContentsViewGuest(
1223 this, browser_plugin_guest_.get(), platform_view.Pass(),
1224 render_view_host_delegate_view_);
1225 render_view_host_delegate_view_ = rv;
1226 view_.reset(rv);
1227 } else {
1228 // Regular WebContentsView.
1229 view_.reset(CreateWebContentsView(
1230 this, delegate, &render_view_host_delegate_view_));
1232 CHECK(render_view_host_delegate_view_);
1233 CHECK(view_.get());
1235 gfx::Size initial_size = params.initial_size;
1236 view_->CreateView(initial_size, params.context);
1238 // Listen for whether our opener gets destroyed.
1239 if (opener_)
1240 AddDestructionObserver(opener_);
1242 #if defined(ENABLE_PLUGINS)
1243 plugin_content_origin_whitelist_.reset(
1244 new PluginContentOriginWhitelist(this));
1245 #endif
1247 registrar_.Add(this,
1248 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1249 NotificationService::AllBrowserContextsAndSources());
1251 screen_orientation_dispatcher_host_.reset(
1252 new ScreenOrientationDispatcherHostImpl(this));
1254 manifest_manager_host_.reset(new ManifestManagerHost(this));
1256 #if defined(OS_ANDROID)
1257 date_time_chooser_.reset(new DateTimeChooserAndroid());
1258 #endif
1260 // BrowserPluginGuest::Init needs to be called after this WebContents has
1261 // a RenderWidgetHostViewGuest. That is, |view_->CreateView| above.
1262 if (browser_plugin_guest_)
1263 browser_plugin_guest_->Init();
1265 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
1266 g_created_callbacks.Get().at(i).Run(this);
1268 // If the WebContents creation was renderer-initiated, it means that the
1269 // corresponding RenderView and main RenderFrame have already been created.
1270 // Ensure observers are notified about this.
1271 if (params.renderer_initiated_creation) {
1272 RenderViewCreated(GetRenderViewHost());
1273 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
1276 // Ensure that observers are notified of the creation of this WebContents's
1277 // main RenderFrameHost. It must be done here for main frames, since the
1278 // NotifySwappedFromRenderManager expects view_ to already be created and that
1279 // happens after RenderFrameHostManager::Init.
1280 NotifySwappedFromRenderManager(
1281 nullptr, GetRenderManager()->current_frame_host(), true);
1284 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
1285 RemoveDestructionObserver(web_contents);
1287 // Clear the opener if it has been closed.
1288 if (web_contents == opener_) {
1289 opener_ = NULL;
1290 return;
1292 // Clear a pending contents that has been closed before being shown.
1293 for (PendingContents::iterator iter = pending_contents_.begin();
1294 iter != pending_contents_.end();
1295 ++iter) {
1296 if (iter->second != web_contents)
1297 continue;
1298 pending_contents_.erase(iter);
1299 return;
1301 NOTREACHED();
1304 void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
1305 if (!ContainsKey(destruction_observers_, web_contents)) {
1306 destruction_observers_[web_contents] =
1307 new DestructionObserver(this, web_contents);
1311 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
1312 DestructionObservers::iterator iter =
1313 destruction_observers_.find(web_contents);
1314 if (iter != destruction_observers_.end()) {
1315 delete destruction_observers_[web_contents];
1316 destruction_observers_.erase(iter);
1320 void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
1321 observers_.AddObserver(observer);
1324 void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
1325 observers_.RemoveObserver(observer);
1328 std::set<RenderWidgetHostView*>
1329 WebContentsImpl::GetRenderWidgetHostViewsInTree() {
1330 std::set<RenderWidgetHostView*> set;
1331 if (ShowingInterstitialPage()) {
1332 set.insert(GetRenderWidgetHostView());
1333 } else {
1334 ForEachFrame(
1335 base::Bind(&AddRenderWidgetHostViewToSet, base::Unretained(&set)));
1337 return set;
1340 void WebContentsImpl::Activate() {
1341 if (delegate_)
1342 delegate_->ActivateContents(this);
1345 void WebContentsImpl::Deactivate() {
1346 if (delegate_)
1347 delegate_->DeactivateContents(this);
1350 void WebContentsImpl::LostCapture() {
1351 if (delegate_)
1352 delegate_->LostCapture();
1355 void WebContentsImpl::RenderWidgetDeleted(
1356 RenderWidgetHostImpl* render_widget_host) {
1357 if (is_being_destroyed_) {
1358 // |created_widgets_| might have been destroyed.
1359 return;
1362 std::set<RenderWidgetHostImpl*>::iterator iter =
1363 created_widgets_.find(render_widget_host);
1364 if (iter != created_widgets_.end())
1365 created_widgets_.erase(iter);
1367 if (render_widget_host &&
1368 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_) {
1369 if (delegate_ && delegate_->EmbedsFullscreenWidget())
1370 delegate_->ExitFullscreenModeForTab(this);
1371 FOR_EACH_OBSERVER(WebContentsObserver,
1372 observers_,
1373 DidDestroyFullscreenWidget(
1374 fullscreen_widget_routing_id_));
1375 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
1376 if (fullscreen_widget_had_focus_at_shutdown_)
1377 view_->RestoreFocus();
1381 void WebContentsImpl::RenderWidgetGotFocus(
1382 RenderWidgetHostImpl* render_widget_host) {
1383 // Notify the delegate if an embedded fullscreen widget was focused.
1384 if (delegate_ && render_widget_host &&
1385 delegate_->EmbedsFullscreenWidget() &&
1386 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView())
1387 delegate_->WebContentsFocused(this);
1390 void WebContentsImpl::RenderWidgetWasResized(
1391 RenderWidgetHostImpl* render_widget_host,
1392 bool width_changed) {
1393 RenderFrameHostImpl* rfh = GetMainFrame();
1394 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
1395 return;
1397 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1398 MainFrameWasResized(width_changed));
1401 void WebContentsImpl::ScreenInfoChanged() {
1402 if (browser_plugin_embedder_)
1403 browser_plugin_embedder_->ScreenInfoChanged();
1406 bool WebContentsImpl::PreHandleKeyboardEvent(
1407 const NativeWebKeyboardEvent& event,
1408 bool* is_keyboard_shortcut) {
1409 return delegate_ &&
1410 delegate_->PreHandleKeyboardEvent(this, event, is_keyboard_shortcut);
1413 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1414 if (browser_plugin_embedder_ &&
1415 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
1416 return;
1418 if (delegate_)
1419 delegate_->HandleKeyboardEvent(this, event);
1422 bool WebContentsImpl::HandleWheelEvent(
1423 const blink::WebMouseWheelEvent& event) {
1424 #if !defined(OS_MACOSX)
1425 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
1426 // this isn't done for two reasons:
1427 // -the OS already has a gesture to do this through pinch-zoom
1428 // -if a user starts an inertial scroll, let's go, and presses control
1429 // (i.e. control+tab) then the OS's buffered scroll events will come in
1430 // with control key set which isn't what the user wants
1431 if (delegate_ && event.wheelTicksY &&
1432 (event.modifiers & blink::WebInputEvent::ControlKey) &&
1433 !event.canScroll) {
1434 delegate_->ContentsZoomChange(event.wheelTicksY > 0);
1435 return true;
1437 #endif
1438 return false;
1441 bool WebContentsImpl::PreHandleGestureEvent(
1442 const blink::WebGestureEvent& event) {
1443 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
1446 void WebContentsImpl::HandleMouseDown() {
1447 if (delegate_)
1448 delegate_->HandleMouseDown();
1451 void WebContentsImpl::HandleMouseUp() {
1452 if (delegate_)
1453 delegate_->HandleMouseUp();
1456 void WebContentsImpl::HandlePointerActivate() {
1457 if (delegate_)
1458 delegate_->HandlePointerActivate();
1461 void WebContentsImpl::HandleGestureBegin() {
1462 if (delegate_)
1463 delegate_->HandleGestureBegin();
1466 void WebContentsImpl::HandleGestureEnd() {
1467 if (delegate_)
1468 delegate_->HandleGestureEnd();
1471 void WebContentsImpl::EnterFullscreenMode(const GURL& origin) {
1472 // This method is being called to enter renderer-initiated fullscreen mode.
1473 // Make sure any existing fullscreen widget is shut down first.
1474 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1475 if (widget_view)
1476 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1478 if (delegate_)
1479 delegate_->EnterFullscreenModeForTab(this, origin);
1481 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1482 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1485 void WebContentsImpl::ExitFullscreenMode() {
1486 // This method is being called to leave renderer-initiated fullscreen mode.
1487 // Make sure any existing fullscreen widget is shut down first.
1488 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1489 if (widget_view)
1490 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1492 #if defined(OS_ANDROID)
1493 ContentVideoView* video_view = ContentVideoView::GetInstance();
1494 if (video_view != NULL)
1495 video_view->OnExitFullscreen();
1496 #endif
1498 if (delegate_)
1499 delegate_->ExitFullscreenModeForTab(this);
1501 // Ensure web contents exit fullscreen state by sending a resize message,
1502 // which includes the fullscreen state. This is required for the situation
1503 // of the browser moving the view into a fullscreen state "browser fullscreen"
1504 // and then the contents entering "tab fullscreen". Exiting the contents
1505 // "tab fullscreen" then won't have the side effect of the view resizing,
1506 // hence the explicit call here is required.
1507 if (RenderWidgetHostView* rwh_view = GetRenderWidgetHostView()) {
1508 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
1509 render_widget_host->WasResized();
1512 FOR_EACH_OBSERVER(WebContentsObserver,
1513 observers_,
1514 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1517 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1518 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
1521 void WebContentsImpl::RequestToLockMouse(bool user_gesture,
1522 bool last_unlocked_by_target) {
1523 if (delegate_) {
1524 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
1525 } else {
1526 GotResponseToLockMouseRequest(false);
1530 void WebContentsImpl::LostMouseLock() {
1531 if (delegate_)
1532 delegate_->LostMouseLock();
1535 void WebContentsImpl::CreateNewWindow(
1536 int render_process_id,
1537 int route_id,
1538 int main_frame_route_id,
1539 const ViewHostMsg_CreateWindow_Params& params,
1540 SessionStorageNamespace* session_storage_namespace) {
1541 // We usually create the new window in the same BrowsingInstance (group of
1542 // script-related windows), by passing in the current SiteInstance. However,
1543 // if the opener is being suppressed (in a non-guest), we create a new
1544 // SiteInstance in its own BrowsingInstance.
1545 bool is_guest = BrowserPluginGuest::IsGuest(this);
1547 // If the opener is to be suppressed, the new window can be in any process.
1548 // Since routing ids are process specific, we must not have one passed in
1549 // as argument here.
1550 DCHECK(!params.opener_suppressed || route_id == MSG_ROUTING_NONE);
1552 scoped_refptr<SiteInstance> site_instance =
1553 params.opener_suppressed && !is_guest ?
1554 SiteInstance::CreateForURL(GetBrowserContext(), params.target_url) :
1555 GetSiteInstance();
1557 // A message to create a new window can only come from the active process for
1558 // this WebContentsImpl instance. If any other process sends the request,
1559 // it is invalid and the process must be terminated.
1560 if (GetRenderProcessHost()->GetID() != render_process_id) {
1561 RenderProcessHost* rph = RenderProcessHost::FromID(render_process_id);
1562 base::ProcessHandle process_handle = rph->GetHandle();
1563 if (process_handle != base::kNullProcessHandle) {
1564 RecordAction(
1565 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1566 rph->Shutdown(RESULT_CODE_KILLED, false);
1568 return;
1571 // We must assign the SessionStorageNamespace before calling Init().
1573 // http://crbug.com/142685
1574 const std::string& partition_id =
1575 GetContentClient()->browser()->
1576 GetStoragePartitionIdForSite(GetBrowserContext(),
1577 site_instance->GetSiteURL());
1578 StoragePartition* partition = BrowserContext::GetStoragePartition(
1579 GetBrowserContext(), site_instance.get());
1580 DOMStorageContextWrapper* dom_storage_context =
1581 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
1582 SessionStorageNamespaceImpl* session_storage_namespace_impl =
1583 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
1584 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
1586 if (delegate_ &&
1587 !delegate_->ShouldCreateWebContents(this,
1588 route_id,
1589 main_frame_route_id,
1590 params.window_container_type,
1591 params.frame_name,
1592 params.target_url,
1593 partition_id,
1594 session_storage_namespace)) {
1595 if (route_id != MSG_ROUTING_NONE &&
1596 !RenderViewHost::FromID(render_process_id, route_id)) {
1597 // If the embedder didn't create a WebContents for this route, we need to
1598 // delete the RenderView that had already been created.
1599 Send(new ViewMsg_Close(route_id));
1601 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id);
1602 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1603 main_frame_route_id);
1604 return;
1607 // Create the new web contents. This will automatically create the new
1608 // WebContentsView. In the future, we may want to create the view separately.
1609 CreateParams create_params(GetBrowserContext(), site_instance.get());
1610 create_params.routing_id = route_id;
1611 create_params.main_frame_routing_id = main_frame_route_id;
1612 create_params.opener = this;
1613 create_params.opener_suppressed = params.opener_suppressed;
1614 if (params.disposition == NEW_BACKGROUND_TAB)
1615 create_params.initially_hidden = true;
1616 create_params.renderer_initiated_creation = true;
1618 WebContentsImpl* new_contents = NULL;
1619 if (!is_guest) {
1620 create_params.context = view_->GetNativeView();
1621 create_params.initial_size = GetContainerBounds().size();
1622 new_contents = static_cast<WebContentsImpl*>(
1623 WebContents::Create(create_params));
1624 } else {
1625 new_contents = GetBrowserPluginGuest()->CreateNewGuestWindow(create_params);
1627 new_contents->GetController().SetSessionStorageNamespace(
1628 partition_id,
1629 session_storage_namespace);
1631 // Save the window for later if we're not suppressing the opener (since it
1632 // will be shown immediately).
1633 if (!params.opener_suppressed) {
1634 if (!is_guest) {
1635 WebContentsView* new_view = new_contents->view_.get();
1637 // TODO(brettw): It seems bogus that we have to call this function on the
1638 // newly created object and give it one of its own member variables.
1639 new_view->CreateViewForWidget(new_contents->GetRenderViewHost(), false);
1641 // Save the created window associated with the route so we can show it
1642 // later.
1643 DCHECK_NE(MSG_ROUTING_NONE, route_id);
1644 pending_contents_[route_id] = new_contents;
1645 AddDestructionObserver(new_contents);
1648 if (delegate_) {
1649 delegate_->WebContentsCreated(
1650 this, params.opener_render_frame_id, params.frame_name,
1651 params.target_url, new_contents);
1654 if (params.opener_suppressed) {
1655 // When the opener is suppressed, the original renderer cannot access the
1656 // new window. As a result, we need to show and navigate the window here.
1657 bool was_blocked = false;
1658 if (delegate_) {
1659 gfx::Rect initial_rect;
1660 delegate_->AddNewContents(
1661 this, new_contents, params.disposition, initial_rect,
1662 params.user_gesture, &was_blocked);
1664 if (!was_blocked) {
1665 OpenURLParams open_params(params.target_url,
1666 Referrer(),
1667 CURRENT_TAB,
1668 ui::PAGE_TRANSITION_LINK,
1669 true /* is_renderer_initiated */);
1670 open_params.user_gesture = params.user_gesture;
1671 new_contents->OpenURL(open_params);
1676 void WebContentsImpl::CreateNewWidget(int render_process_id,
1677 int route_id,
1678 blink::WebPopupType popup_type) {
1679 CreateNewWidget(render_process_id, route_id, false, popup_type);
1682 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id,
1683 int route_id) {
1684 CreateNewWidget(render_process_id, route_id, true, blink::WebPopupTypeNone);
1687 void WebContentsImpl::CreateNewWidget(int render_process_id,
1688 int route_id,
1689 bool is_fullscreen,
1690 blink::WebPopupType popup_type) {
1691 RenderProcessHost* process = GetRenderProcessHost();
1692 // A message to create a new widget can only come from the active process for
1693 // this WebContentsImpl instance. If any other process sends the request,
1694 // it is invalid and the process must be terminated.
1695 if (process->GetID() != render_process_id) {
1696 RenderProcessHost* rph = RenderProcessHost::FromID(render_process_id);
1697 base::ProcessHandle process_handle = rph->GetHandle();
1698 if (process_handle != base::kNullProcessHandle) {
1699 RecordAction(
1700 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1701 rph->Shutdown(RESULT_CODE_KILLED, false);
1703 return;
1706 RenderWidgetHostImpl* widget_host =
1707 new RenderWidgetHostImpl(this, process, route_id, IsHidden());
1708 created_widgets_.insert(widget_host);
1710 RenderWidgetHostViewBase* widget_view =
1711 static_cast<RenderWidgetHostViewBase*>(
1712 view_->CreateViewForPopupWidget(widget_host));
1713 if (!widget_view)
1714 return;
1715 if (!is_fullscreen) {
1716 // Popups should not get activated.
1717 widget_view->SetPopupType(popup_type);
1719 // Save the created widget associated with the route so we can show it later.
1720 pending_widget_views_[route_id] = widget_view;
1722 #if defined(OS_MACOSX)
1723 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1724 // to allow it to survive the trip without being hosted.
1725 base::mac::NSObjectRetain(widget_view->GetNativeView());
1726 #endif
1729 void WebContentsImpl::ShowCreatedWindow(int route_id,
1730 WindowOpenDisposition disposition,
1731 const gfx::Rect& initial_rect,
1732 bool user_gesture) {
1733 WebContentsImpl* contents = GetCreatedWindow(route_id);
1734 if (contents) {
1735 WebContentsDelegate* delegate = GetDelegate();
1736 if (delegate) {
1737 delegate->AddNewContents(
1738 this, contents, disposition, initial_rect, user_gesture, NULL);
1743 void WebContentsImpl::ShowCreatedWidget(int route_id,
1744 const gfx::Rect& initial_rect) {
1745 ShowCreatedWidget(route_id, false, initial_rect);
1748 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id) {
1749 ShowCreatedWidget(route_id, true, gfx::Rect());
1752 void WebContentsImpl::ShowCreatedWidget(int route_id,
1753 bool is_fullscreen,
1754 const gfx::Rect& initial_rect) {
1755 RenderWidgetHostViewBase* widget_host_view =
1756 static_cast<RenderWidgetHostViewBase*>(GetCreatedWidget(route_id));
1757 if (!widget_host_view)
1758 return;
1760 RenderWidgetHostView* view = NULL;
1761 BrowserPluginGuest* guest = GetBrowserPluginGuest();
1762 if (guest && guest->embedder_web_contents()) {
1763 view = guest->embedder_web_contents()->GetRenderWidgetHostView();
1764 } else {
1765 view = GetRenderWidgetHostView();
1768 if (is_fullscreen) {
1769 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
1770 view_->StoreFocus();
1771 fullscreen_widget_routing_id_ = route_id;
1772 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
1773 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1774 delegate_->EnterFullscreenModeForTab(this, GURL());
1775 } else {
1776 widget_host_view->InitAsFullscreen(view);
1778 FOR_EACH_OBSERVER(WebContentsObserver,
1779 observers_,
1780 DidShowFullscreenWidget(route_id));
1781 if (!widget_host_view->HasFocus())
1782 widget_host_view->Focus();
1783 } else {
1784 widget_host_view->InitAsPopup(view, initial_rect);
1787 RenderWidgetHostImpl* render_widget_host_impl =
1788 RenderWidgetHostImpl::From(widget_host_view->GetRenderWidgetHost());
1789 render_widget_host_impl->Init();
1790 // Only allow privileged mouse lock for fullscreen render widget, which is
1791 // used to implement Pepper Flash fullscreen.
1792 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
1794 #if defined(OS_MACOSX)
1795 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1796 // properly embedded (or purposefully ignored) we can release the retain we
1797 // took in CreateNewWidget().
1798 base::mac::NSObjectRelease(widget_host_view->GetNativeView());
1799 #endif
1802 WebContentsImpl* WebContentsImpl::GetCreatedWindow(int route_id) {
1803 PendingContents::iterator iter = pending_contents_.find(route_id);
1805 // Certain systems can block the creation of new windows. If we didn't succeed
1806 // in creating one, just return NULL.
1807 if (iter == pending_contents_.end()) {
1808 return NULL;
1811 WebContentsImpl* new_contents = iter->second;
1812 pending_contents_.erase(route_id);
1813 RemoveDestructionObserver(new_contents);
1815 // Don't initialize the guest WebContents immediately.
1816 if (BrowserPluginGuest::IsGuest(new_contents))
1817 return new_contents;
1819 if (!new_contents->GetRenderProcessHost()->HasConnection() ||
1820 !new_contents->GetRenderViewHost()->GetView())
1821 return NULL;
1823 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
1824 // TODO(brettw): It seems bogus to reach into here and initialize the host.
1825 static_cast<RenderViewHostImpl*>(new_contents->GetRenderViewHost())->Init();
1826 new_contents->GetMainFrame()->Init();
1828 return new_contents;
1831 RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int route_id) {
1832 PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
1833 if (iter == pending_widget_views_.end()) {
1834 DCHECK(false);
1835 return NULL;
1838 RenderWidgetHostView* widget_host_view = iter->second;
1839 pending_widget_views_.erase(route_id);
1841 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
1842 if (!widget_host->GetProcess()->HasConnection()) {
1843 // The view has gone away or the renderer crashed. Nothing to do.
1844 return NULL;
1847 return widget_host_view;
1850 void WebContentsImpl::RequestMediaAccessPermission(
1851 const MediaStreamRequest& request,
1852 const MediaResponseCallback& callback) {
1853 if (delegate_) {
1854 delegate_->RequestMediaAccessPermission(this, request, callback);
1855 } else {
1856 callback.Run(MediaStreamDevices(),
1857 MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN,
1858 scoped_ptr<MediaStreamUI>());
1862 bool WebContentsImpl::CheckMediaAccessPermission(const GURL& security_origin,
1863 MediaStreamType type) {
1864 DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
1865 type == MEDIA_DEVICE_VIDEO_CAPTURE);
1866 return delegate_ &&
1867 delegate_->CheckMediaAccessPermission(this, security_origin, type);
1870 SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
1871 SiteInstance* instance) {
1872 return controller_.GetSessionStorageNamespace(instance);
1875 SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
1876 return controller_.GetSessionStorageNamespaceMap();
1879 FrameTree* WebContentsImpl::GetFrameTree() {
1880 return &frame_tree_;
1883 void WebContentsImpl::SetIsVirtualKeyboardRequested(bool requested) {
1884 virtual_keyboard_requested_ = requested;
1887 bool WebContentsImpl::IsVirtualKeyboardRequested() {
1888 return virtual_keyboard_requested_;
1891 AccessibilityMode WebContentsImpl::GetAccessibilityMode() const {
1892 return accessibility_mode_;
1895 void WebContentsImpl::AccessibilityEventReceived(
1896 const std::vector<AXEventNotificationDetails>& details) {
1897 FOR_EACH_OBSERVER(
1898 WebContentsObserver, observers_, AccessibilityEventReceived(details));
1901 RenderFrameHost* WebContentsImpl::GetGuestByInstanceID(
1902 RenderFrameHost* render_frame_host,
1903 int browser_plugin_instance_id) {
1904 BrowserPluginGuestManager* guest_manager =
1905 GetBrowserContext()->GetGuestManager();
1906 WebContents* guest = guest_manager->GetGuestByInstanceID(
1907 render_frame_host->GetProcess()->GetID(), browser_plugin_instance_id);
1908 if (!guest)
1909 return NULL;
1910 return guest->GetMainFrame();
1913 GeolocationServiceContext* WebContentsImpl::GetGeolocationServiceContext() {
1914 return geolocation_service_context_.get();
1917 void WebContentsImpl::OnShowValidationMessage(
1918 const gfx::Rect& anchor_in_root_view,
1919 const base::string16& main_text,
1920 const base::string16& sub_text) {
1921 if (delegate_)
1922 delegate_->ShowValidationMessage(
1923 this, anchor_in_root_view, main_text, sub_text);
1926 void WebContentsImpl::OnHideValidationMessage() {
1927 if (delegate_)
1928 delegate_->HideValidationMessage(this);
1931 void WebContentsImpl::OnMoveValidationMessage(
1932 const gfx::Rect& anchor_in_root_view) {
1933 if (delegate_)
1934 delegate_->MoveValidationMessage(this, anchor_in_root_view);
1937 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl* rwh) {
1938 if (browser_plugin_embedder_)
1939 browser_plugin_embedder_->DidSendScreenRects();
1942 BrowserAccessibilityManager*
1943 WebContentsImpl::GetRootBrowserAccessibilityManager() {
1944 RenderFrameHostImpl* rfh = GetMainFrame();
1945 return rfh ? rfh->browser_accessibility_manager() : NULL;
1948 BrowserAccessibilityManager*
1949 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
1950 RenderFrameHostImpl* rfh = GetMainFrame();
1951 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : NULL;
1954 void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
1955 const gfx::Size old_size = GetPreferredSize();
1956 preferred_size_ = pref_size;
1957 OnPreferredSizeChanged(old_size);
1960 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size& new_size) {
1961 if (delegate_)
1962 delegate_->ResizeDueToAutoResize(this, new_size);
1965 WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
1966 if (!delegate_)
1967 return NULL;
1969 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
1970 return new_contents;
1973 bool WebContentsImpl::Send(IPC::Message* message) {
1974 if (!GetRenderViewHost()) {
1975 delete message;
1976 return false;
1979 return GetRenderViewHost()->Send(message);
1982 bool WebContentsImpl::NavigateToPendingEntry(
1983 NavigationController::ReloadType reload_type) {
1984 FrameTreeNode* node = frame_tree_.root();
1986 // Navigate in the FrameTreeNode specified in the pending entry, if any. This
1987 // is currently only used in --site-per-process and tests.
1988 // TODO(creis): Remove this method and NavigationEntryImpl::frame_tree_node_id
1989 // by using FrameNavigationEntries instead. See https://crbug.com/236848.
1990 NavigationEntryImpl* pending_entry = controller_.GetPendingEntry();
1991 if (pending_entry->frame_tree_node_id() != -1) {
1992 FrameTreeNode* subframe =
1993 frame_tree_.FindByID(pending_entry->frame_tree_node_id());
1994 DCHECK(subframe);
1995 if (subframe)
1996 node = subframe;
1999 return node->navigator()->NavigateToPendingEntry(node, reload_type);
2002 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
2003 RenderFrameHost* render_frame_host) {
2004 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2005 RenderFrameForInterstitialPageCreated(render_frame_host));
2008 void WebContentsImpl::AttachInterstitialPage(
2009 InterstitialPageImpl* interstitial_page) {
2010 DCHECK(interstitial_page);
2011 GetRenderManager()->set_interstitial_page(interstitial_page);
2013 // Cancel any visible dialogs so that they don't interfere with the
2014 // interstitial.
2015 if (dialog_manager_)
2016 dialog_manager_->CancelActiveAndPendingDialogs(this);
2018 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2019 DidAttachInterstitialPage());
2022 void WebContentsImpl::DetachInterstitialPage() {
2023 if (ShowingInterstitialPage())
2024 GetRenderManager()->remove_interstitial_page();
2025 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2026 DidDetachInterstitialPage());
2029 void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
2030 int history_length) {
2031 SetHistoryOffsetAndLengthForView(
2032 GetRenderViewHost(), history_offset, history_length);
2035 void WebContentsImpl::SetHistoryOffsetAndLengthForView(
2036 RenderViewHost* render_view_host,
2037 int history_offset,
2038 int history_length) {
2039 render_view_host->Send(new ViewMsg_SetHistoryOffsetAndLength(
2040 render_view_host->GetRoutingID(), history_offset, history_length));
2043 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache) {
2044 RenderFrameHost* focused_frame = GetFocusedFrame();
2045 if (!focused_frame)
2046 return;
2048 focused_frame->Send(new FrameMsg_Reload(
2049 focused_frame->GetRoutingID(), ignore_cache));
2052 void WebContentsImpl::Undo() {
2053 RenderFrameHost* focused_frame = GetFocusedFrame();
2054 if (!focused_frame)
2055 return;
2057 focused_frame->Send(new InputMsg_Undo(focused_frame->GetRoutingID()));
2058 RecordAction(base::UserMetricsAction("Undo"));
2061 void WebContentsImpl::Redo() {
2062 RenderFrameHost* focused_frame = GetFocusedFrame();
2063 if (!focused_frame)
2064 return;
2065 focused_frame->Send(new InputMsg_Redo(focused_frame->GetRoutingID()));
2066 RecordAction(base::UserMetricsAction("Redo"));
2069 void WebContentsImpl::Cut() {
2070 RenderFrameHost* focused_frame = GetFocusedFrame();
2071 if (!focused_frame)
2072 return;
2074 focused_frame->Send(new InputMsg_Cut(focused_frame->GetRoutingID()));
2075 RecordAction(base::UserMetricsAction("Cut"));
2078 void WebContentsImpl::Copy() {
2079 RenderFrameHost* focused_frame = GetFocusedFrame();
2080 if (!focused_frame)
2081 return;
2083 focused_frame->Send(new InputMsg_Copy(focused_frame->GetRoutingID()));
2084 RecordAction(base::UserMetricsAction("Copy"));
2087 void WebContentsImpl::CopyToFindPboard() {
2088 #if defined(OS_MACOSX)
2089 RenderFrameHost* focused_frame = GetFocusedFrame();
2090 if (!focused_frame)
2091 return;
2093 // Windows/Linux don't have the concept of a find pasteboard.
2094 focused_frame->Send(
2095 new InputMsg_CopyToFindPboard(focused_frame->GetRoutingID()));
2096 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
2097 #endif
2100 void WebContentsImpl::Paste() {
2101 RenderFrameHost* focused_frame = GetFocusedFrame();
2102 if (!focused_frame)
2103 return;
2105 focused_frame->Send(new InputMsg_Paste(focused_frame->GetRoutingID()));
2106 RecordAction(base::UserMetricsAction("Paste"));
2109 void WebContentsImpl::PasteAndMatchStyle() {
2110 RenderFrameHost* focused_frame = GetFocusedFrame();
2111 if (!focused_frame)
2112 return;
2114 focused_frame->Send(new InputMsg_PasteAndMatchStyle(
2115 focused_frame->GetRoutingID()));
2116 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
2119 void WebContentsImpl::Delete() {
2120 RenderFrameHost* focused_frame = GetFocusedFrame();
2121 if (!focused_frame)
2122 return;
2124 focused_frame->Send(new InputMsg_Delete(focused_frame->GetRoutingID()));
2125 RecordAction(base::UserMetricsAction("DeleteSelection"));
2128 void WebContentsImpl::SelectAll() {
2129 RenderFrameHost* focused_frame = GetFocusedFrame();
2130 if (!focused_frame)
2131 return;
2133 focused_frame->Send(new InputMsg_SelectAll(focused_frame->GetRoutingID()));
2134 RecordAction(base::UserMetricsAction("SelectAll"));
2137 void WebContentsImpl::Unselect() {
2138 RenderFrameHost* focused_frame = GetFocusedFrame();
2139 if (!focused_frame)
2140 return;
2142 focused_frame->Send(new InputMsg_Unselect(focused_frame->GetRoutingID()));
2143 RecordAction(base::UserMetricsAction("Unselect"));
2146 void WebContentsImpl::Replace(const base::string16& word) {
2147 RenderFrameHost* focused_frame = GetFocusedFrame();
2148 if (!focused_frame)
2149 return;
2151 focused_frame->Send(new InputMsg_Replace(
2152 focused_frame->GetRoutingID(), word));
2155 void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
2156 RenderFrameHost* focused_frame = GetFocusedFrame();
2157 if (!focused_frame)
2158 return;
2160 focused_frame->Send(new InputMsg_ReplaceMisspelling(
2161 focused_frame->GetRoutingID(), word));
2164 void WebContentsImpl::NotifyContextMenuClosed(
2165 const CustomContextMenuContext& context) {
2166 RenderFrameHost* focused_frame = GetFocusedFrame();
2167 if (!focused_frame)
2168 return;
2170 focused_frame->Send(new FrameMsg_ContextMenuClosed(
2171 focused_frame->GetRoutingID(), context));
2174 void WebContentsImpl::ExecuteCustomContextMenuCommand(
2175 int action, const CustomContextMenuContext& context) {
2176 RenderFrameHost* focused_frame = GetFocusedFrame();
2177 if (!focused_frame)
2178 return;
2180 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
2181 focused_frame->GetRoutingID(), context, action));
2184 gfx::NativeView WebContentsImpl::GetNativeView() {
2185 return view_->GetNativeView();
2188 gfx::NativeView WebContentsImpl::GetContentNativeView() {
2189 return view_->GetContentNativeView();
2192 gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
2193 return view_->GetTopLevelNativeWindow();
2196 gfx::Rect WebContentsImpl::GetViewBounds() {
2197 return view_->GetViewBounds();
2200 gfx::Rect WebContentsImpl::GetContainerBounds() {
2201 gfx::Rect rv;
2202 view_->GetContainerBounds(&rv);
2203 return rv;
2206 DropData* WebContentsImpl::GetDropData() {
2207 return view_->GetDropData();
2210 void WebContentsImpl::Focus() {
2211 view_->Focus();
2214 void WebContentsImpl::SetInitialFocus() {
2215 view_->SetInitialFocus();
2218 void WebContentsImpl::StoreFocus() {
2219 view_->StoreFocus();
2222 void WebContentsImpl::RestoreFocus() {
2223 view_->RestoreFocus();
2226 void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
2227 if (ShowingInterstitialPage()) {
2228 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse);
2229 return;
2231 RenderWidgetHostView* const fullscreen_view =
2232 GetFullscreenRenderWidgetHostView();
2233 if (fullscreen_view) {
2234 fullscreen_view->Focus();
2235 return;
2237 GetRenderViewHostImpl()->SetInitialFocus(reverse);
2240 bool WebContentsImpl::ShowingInterstitialPage() const {
2241 return GetRenderManager()->interstitial_page() != NULL;
2244 InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
2245 return GetRenderManager()->interstitial_page();
2248 bool WebContentsImpl::IsSavable() {
2249 // WebKit creates Document object when MIME type is application/xhtml+xml,
2250 // so we also support this MIME type.
2251 return contents_mime_type_ == "text/html" ||
2252 contents_mime_type_ == "text/xml" ||
2253 contents_mime_type_ == "application/xhtml+xml" ||
2254 contents_mime_type_ == "text/plain" ||
2255 contents_mime_type_ == "text/css" ||
2256 net::IsSupportedJavascriptMimeType(contents_mime_type_.c_str());
2259 void WebContentsImpl::OnSavePage() {
2260 // If we can not save the page, try to download it.
2261 if (!IsSavable()) {
2262 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML);
2263 SaveFrame(GetURL(), Referrer());
2264 return;
2267 Stop();
2269 // Create the save package and possibly prompt the user for the name to save
2270 // the page as. The user prompt is an asynchronous operation that runs on
2271 // another thread.
2272 save_package_ = new SavePackage(this);
2273 save_package_->GetSaveInfo();
2276 // Used in automated testing to bypass prompting the user for file names.
2277 // Instead, the names and paths are hard coded rather than running them through
2278 // file name sanitation and extension / mime checking.
2279 bool WebContentsImpl::SavePage(const base::FilePath& main_file,
2280 const base::FilePath& dir_path,
2281 SavePageType save_type) {
2282 // Stop the page from navigating.
2283 Stop();
2285 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
2286 return save_package_->Init(SavePackageDownloadCreatedCallback());
2289 void WebContentsImpl::SaveFrame(const GURL& url,
2290 const Referrer& referrer) {
2291 if (!GetURL().is_valid())
2292 return;
2293 if (delegate_ && delegate_->SaveFrame(url, referrer))
2294 return;
2296 bool is_main_frame = (url == GetURL());
2298 DownloadManager* dlm =
2299 BrowserContext::GetDownloadManager(GetBrowserContext());
2300 if (!dlm)
2301 return;
2302 int64 post_id = -1;
2303 if (is_main_frame) {
2304 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2305 if (entry)
2306 post_id = entry->GetPostID();
2308 scoped_ptr<DownloadUrlParameters> params(
2309 DownloadUrlParameters::FromWebContents(this, url));
2310 params->set_referrer(referrer);
2311 params->set_post_id(post_id);
2312 params->set_prefer_cache(true);
2313 if (post_id >= 0)
2314 params->set_method("POST");
2315 params->set_prompt(true);
2316 dlm->DownloadUrl(params.Pass());
2319 void WebContentsImpl::GenerateMHTML(
2320 const base::FilePath& file,
2321 const base::Callback<void(int64)>& callback) {
2322 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file, callback);
2325 const std::string& WebContentsImpl::GetContentsMimeType() const {
2326 return contents_mime_type_;
2329 bool WebContentsImpl::WillNotifyDisconnection() const {
2330 return notify_disconnection_;
2333 void WebContentsImpl::SetOverrideEncoding(const std::string& encoding) {
2334 SetEncoding(encoding);
2335 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding));
2338 void WebContentsImpl::ResetOverrideEncoding() {
2339 canonical_encoding_.clear();
2340 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2343 RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
2344 return &renderer_preferences_;
2347 void WebContentsImpl::Close() {
2348 Close(GetRenderViewHost());
2351 void WebContentsImpl::DragSourceEndedAt(int client_x, int client_y,
2352 int screen_x, int screen_y, blink::WebDragOperation operation) {
2353 if (browser_plugin_embedder_.get())
2354 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y,
2355 screen_x, screen_y, operation);
2356 if (GetRenderViewHost())
2357 GetRenderViewHostImpl()->DragSourceEndedAt(client_x, client_y,
2358 screen_x, screen_y, operation);
2361 void WebContentsImpl::DidGetResourceResponseStart(
2362 const ResourceRequestDetails& details) {
2363 controller_.ssl_manager()->DidStartResourceResponse(details);
2365 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2366 DidGetResourceResponseStart(details));
2368 // TODO(avi): Remove. http://crbug.com/170921
2369 NotificationService::current()->Notify(
2370 NOTIFICATION_RESOURCE_RESPONSE_STARTED,
2371 Source<WebContents>(this),
2372 Details<const ResourceRequestDetails>(&details));
2375 void WebContentsImpl::DidGetRedirectForResourceRequest(
2376 RenderFrameHost* render_frame_host,
2377 const ResourceRedirectDetails& details) {
2378 controller_.ssl_manager()->DidReceiveResourceRedirect(details);
2380 FOR_EACH_OBSERVER(
2381 WebContentsObserver,
2382 observers_,
2383 DidGetRedirectForResourceRequest(render_frame_host, details));
2385 // TODO(avi): Remove. http://crbug.com/170921
2386 NotificationService::current()->Notify(
2387 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
2388 Source<WebContents>(this),
2389 Details<const ResourceRedirectDetails>(&details));
2392 void WebContentsImpl::SystemDragEnded() {
2393 if (GetRenderViewHost())
2394 GetRenderViewHostImpl()->DragSourceSystemDragEnded();
2395 if (delegate_)
2396 delegate_->DragEnded();
2397 if (browser_plugin_embedder_.get())
2398 browser_plugin_embedder_->SystemDragEnded();
2401 void WebContentsImpl::UserGestureDone() {
2402 OnUserGesture();
2405 void WebContentsImpl::SetClosedByUserGesture(bool value) {
2406 closed_by_user_gesture_ = value;
2409 bool WebContentsImpl::GetClosedByUserGesture() const {
2410 return closed_by_user_gesture_;
2413 void WebContentsImpl::ViewSource() {
2414 if (!delegate_)
2415 return;
2417 NavigationEntry* entry = GetController().GetLastCommittedEntry();
2418 if (!entry)
2419 return;
2421 delegate_->ViewSourceForTab(this, entry->GetURL());
2424 void WebContentsImpl::ViewFrameSource(const GURL& url,
2425 const PageState& page_state) {
2426 if (!delegate_)
2427 return;
2429 delegate_->ViewSourceForFrame(this, url, page_state);
2432 int WebContentsImpl::GetMinimumZoomPercent() const {
2433 return minimum_zoom_percent_;
2436 int WebContentsImpl::GetMaximumZoomPercent() const {
2437 return maximum_zoom_percent_;
2440 gfx::Size WebContentsImpl::GetPreferredSize() const {
2441 return capturer_count_ == 0 ? preferred_size_ : preferred_size_for_capture_;
2444 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed) {
2445 if (GetBrowserPluginGuest())
2446 return GetBrowserPluginGuest()->LockMouse(allowed);
2448 return GetRenderViewHost() ?
2449 GetRenderViewHostImpl()->GotResponseToLockMouseRequest(allowed) : false;
2452 bool WebContentsImpl::HasOpener() const {
2453 return opener_ != NULL;
2456 WebContents* WebContentsImpl::GetOpener() const {
2457 return static_cast<WebContents*>(opener_);
2460 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
2461 if (!color_chooser_info_.get())
2462 return;
2463 RenderFrameHost* rfh = RenderFrameHost::FromID(
2464 color_chooser_info_->render_process_id,
2465 color_chooser_info_->render_frame_id);
2466 if (!rfh)
2467 return;
2469 rfh->Send(new FrameMsg_DidChooseColorResponse(
2470 rfh->GetRoutingID(), color_chooser_info_->identifier, color));
2473 void WebContentsImpl::DidEndColorChooser() {
2474 if (!color_chooser_info_.get())
2475 return;
2476 RenderFrameHost* rfh = RenderFrameHost::FromID(
2477 color_chooser_info_->render_process_id,
2478 color_chooser_info_->render_frame_id);
2479 if (!rfh)
2480 return;
2482 rfh->Send(new FrameMsg_DidEndColorChooser(
2483 rfh->GetRoutingID(), color_chooser_info_->identifier));
2484 color_chooser_info_.reset();
2487 int WebContentsImpl::DownloadImage(const GURL& url,
2488 bool is_favicon,
2489 uint32_t max_bitmap_size,
2490 const ImageDownloadCallback& callback) {
2491 int id = StartDownload(GetMainFrame(), url, is_favicon, max_bitmap_size);
2492 image_download_map_[id] = callback;
2493 return id;
2496 bool WebContentsImpl::IsSubframe() const {
2497 return is_subframe_;
2500 void WebContentsImpl::Find(int request_id,
2501 const base::string16& search_text,
2502 const blink::WebFindOptions& options) {
2503 // See if a top level browser plugin handles the find request first.
2504 if (browser_plugin_embedder_ &&
2505 browser_plugin_embedder_->Find(request_id, search_text, options)) {
2506 return;
2508 Send(new ViewMsg_Find(GetRoutingID(), request_id, search_text, options));
2511 void WebContentsImpl::StopFinding(StopFindAction action) {
2512 // See if a top level browser plugin handles the stop finding request first.
2513 if (browser_plugin_embedder_ &&
2514 browser_plugin_embedder_->StopFinding(action)) {
2515 return;
2517 Send(new ViewMsg_StopFinding(GetRoutingID(), action));
2520 void WebContentsImpl::InsertCSS(const std::string& css) {
2521 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2522 GetMainFrame()->GetRoutingID(), css));
2525 bool WebContentsImpl::WasRecentlyAudible() {
2526 return audio_stream_monitor_.WasRecentlyAudible();
2529 void WebContentsImpl::GetManifest(const GetManifestCallback& callback) {
2530 manifest_manager_host_->GetManifest(GetMainFrame(), callback);
2533 void WebContentsImpl::ExitFullscreen() {
2534 // Clean up related state and initiate the fullscreen exit.
2535 GetRenderViewHostImpl()->RejectMouseLockOrUnlockIfNecessary();
2536 ExitFullscreenMode();
2539 bool WebContentsImpl::FocusLocationBarByDefault() {
2540 NavigationEntry* entry = controller_.GetVisibleEntry();
2541 if (entry && entry->GetURL() == GURL(url::kAboutBlankURL))
2542 return true;
2543 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
2546 void WebContentsImpl::SetFocusToLocationBar(bool select_all) {
2547 if (delegate_)
2548 delegate_->SetFocusToLocationBar(select_all);
2551 void WebContentsImpl::DidStartProvisionalLoad(
2552 RenderFrameHostImpl* render_frame_host,
2553 const GURL& validated_url,
2554 bool is_error_page,
2555 bool is_iframe_srcdoc) {
2556 // Notify observers about the start of the provisional load.
2557 FOR_EACH_OBSERVER(
2558 WebContentsObserver,
2559 observers_,
2560 DidStartProvisionalLoadForFrame(
2561 render_frame_host, validated_url, is_error_page, is_iframe_srcdoc));
2563 // Notify accessibility if this is a reload.
2564 NavigationEntry* entry = controller_.GetVisibleEntry();
2565 if (entry && ui::PageTransitionCoreTypeIs(
2566 entry->GetTransitionType(), ui::PAGE_TRANSITION_RELOAD)) {
2567 FrameTreeNode* ftn = render_frame_host->frame_tree_node();
2568 BrowserAccessibilityManager* manager =
2569 ftn->current_frame_host()->browser_accessibility_manager();
2570 if (manager)
2571 manager->UserIsReloading();
2575 void WebContentsImpl::DidStartNavigationTransition(
2576 RenderFrameHostImpl* render_frame_host) {
2577 #if defined(OS_ANDROID)
2578 int render_frame_id = render_frame_host->GetRoutingID();
2579 GetWebContentsAndroid()->DidStartNavigationTransitionForFrame(
2580 render_frame_id);
2581 #endif
2584 void WebContentsImpl::DidFailProvisionalLoadWithError(
2585 RenderFrameHostImpl* render_frame_host,
2586 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
2587 GURL validated_url(params.url);
2588 FOR_EACH_OBSERVER(WebContentsObserver,
2589 observers_,
2590 DidFailProvisionalLoad(render_frame_host,
2591 validated_url,
2592 params.error_code,
2593 params.error_description));
2595 FrameTreeNode* ftn = render_frame_host->frame_tree_node();
2596 BrowserAccessibilityManager* manager =
2597 ftn->current_frame_host()->browser_accessibility_manager();
2598 if (manager)
2599 manager->NavigationFailed();
2602 void WebContentsImpl::DidFailLoadWithError(
2603 RenderFrameHostImpl* render_frame_host,
2604 const GURL& url,
2605 int error_code,
2606 const base::string16& error_description) {
2607 FOR_EACH_OBSERVER(
2608 WebContentsObserver,
2609 observers_,
2610 DidFailLoad(render_frame_host, url, error_code, error_description));
2613 void WebContentsImpl::NotifyChangedNavigationState(
2614 InvalidateTypes changed_flags) {
2615 NotifyNavigationStateChanged(changed_flags);
2618 void WebContentsImpl::AboutToNavigateRenderFrame(
2619 RenderFrameHostImpl* old_host,
2620 RenderFrameHostImpl* new_host) {
2621 // Notify observers that we will navigate in this RenderFrame.
2622 FOR_EACH_OBSERVER(
2623 WebContentsObserver,
2624 observers_,
2625 AboutToNavigateRenderFrame(old_host, new_host));
2628 void WebContentsImpl::DidStartNavigationToPendingEntry(
2629 const GURL& url,
2630 NavigationController::ReloadType reload_type) {
2631 // Notify observers about navigation.
2632 FOR_EACH_OBSERVER(
2633 WebContentsObserver,
2634 observers_,
2635 DidStartNavigationToPendingEntry(url, reload_type));
2638 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
2639 const OpenURLParams& params) {
2640 // OpenURL can blow away the source RFH. Use the process/frame routing ID as a
2641 // weak pointer of sorts.
2642 const int32_t process_id = render_frame_host->GetProcess()->GetID();
2643 const int32_t frame_id = render_frame_host->GetRoutingID();
2645 WebContents* new_contents = OpenURL(params);
2647 if (new_contents && RenderFrameHost::FromID(process_id, frame_id)) {
2648 // Notify observers.
2649 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2650 DidOpenRequestedURL(new_contents,
2651 render_frame_host,
2652 params.url,
2653 params.referrer,
2654 params.disposition,
2655 params.transition));
2659 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2660 if (!delegate_)
2661 return false;
2662 return delegate_->ShouldPreserveAbortedURLs(this);
2665 void WebContentsImpl::DidCommitProvisionalLoad(
2666 RenderFrameHostImpl* render_frame_host,
2667 const GURL& url,
2668 ui::PageTransition transition_type) {
2669 // Notify observers about the commit of the provisional load.
2670 FOR_EACH_OBSERVER(WebContentsObserver,
2671 observers_,
2672 DidCommitProvisionalLoadForFrame(
2673 render_frame_host, url, transition_type));
2675 BrowserAccessibilityManager* manager =
2676 render_frame_host->browser_accessibility_manager();
2677 if (manager)
2678 manager->NavigationSucceeded();
2681 void WebContentsImpl::DidNavigateMainFramePreCommit(
2682 bool navigation_is_within_page) {
2683 // Ensure fullscreen mode is exited before committing the navigation to a
2684 // different page. The next page will not start out assuming it is in
2685 // fullscreen mode.
2686 if (navigation_is_within_page) {
2687 // No page change? Then, the renderer and browser can remain in fullscreen.
2688 return;
2690 if (IsFullscreenForCurrentTab())
2691 ExitFullscreen();
2692 DCHECK(!IsFullscreenForCurrentTab());
2695 void WebContentsImpl::DidNavigateMainFramePostCommit(
2696 RenderFrameHostImpl* render_frame_host,
2697 const LoadCommittedDetails& details,
2698 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2699 if (details.is_navigation_to_different_page()) {
2700 // Clear the status bubble. This is a workaround for a bug where WebKit
2701 // doesn't let us know that the cursor left an element during a
2702 // transition (this is also why the mouse cursor remains as a hand after
2703 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2704 // clear the bubble when a user navigates to a named anchor in the same
2705 // page.
2706 UpdateTargetURL(render_frame_host->GetRenderViewHost(), GURL());
2708 RenderWidgetHostViewBase* rwhvb =
2709 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
2710 if (rwhvb)
2711 rwhvb->OnDidNavigateMainFrameToNewPage();
2714 if (!details.is_in_page) {
2715 // Once the main frame is navigated, we're no longer considered to have
2716 // displayed insecure content.
2717 displayed_insecure_content_ = false;
2718 SSLManager::NotifySSLInternalStateChanged(
2719 GetController().GetBrowserContext());
2722 // Notify observers about navigation.
2723 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2724 DidNavigateMainFrame(details, params));
2726 if (delegate_)
2727 delegate_->DidNavigateMainFramePostCommit(this);
2728 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
2731 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2732 RenderFrameHostImpl* render_frame_host,
2733 const LoadCommittedDetails& details,
2734 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2735 // Now that something has committed, we don't need to track whether the
2736 // initial page has been accessed.
2737 has_accessed_initial_document_ = false;
2739 // If we navigate off the page, close all JavaScript dialogs.
2740 if (dialog_manager_ && !details.is_in_page)
2741 dialog_manager_->CancelActiveAndPendingDialogs(this);
2743 // Notify observers about navigation.
2744 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2745 DidNavigateAnyFrame(render_frame_host, details, params));
2748 void WebContentsImpl::SetMainFrameMimeType(const std::string& mime_type) {
2749 contents_mime_type_ = mime_type;
2752 bool WebContentsImpl::CanOverscrollContent() const {
2753 // Disable overscroll when touch emulation is on. See crbug.com/369938.
2754 if (force_disable_overscroll_content_)
2755 return false;
2757 if (delegate_)
2758 return delegate_->CanOverscrollContent();
2760 return false;
2763 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color) {
2764 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2765 DidChangeThemeColor(theme_color));
2768 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2769 const GURL& url,
2770 const std::string& security_info,
2771 const std::string& http_method,
2772 const std::string& mime_type,
2773 ResourceType resource_type) {
2775 // Send out a notification that we loaded a resource from our memory cache.
2776 int cert_id = 0;
2777 net::CertStatus cert_status = 0;
2778 int security_bits = -1;
2779 int connection_status = 0;
2780 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids;
2781 DeserializeSecurityInfo(security_info, &cert_id, &cert_status,
2782 &security_bits, &connection_status,
2783 &signed_certificate_timestamp_ids);
2784 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details
2785 LoadFromMemoryCacheDetails details(
2786 url, GetRenderProcessHost()->GetID(), cert_id, cert_status, http_method,
2787 mime_type, resource_type);
2789 controller_.ssl_manager()->DidLoadFromMemoryCache(details);
2791 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2792 DidLoadResourceFromMemoryCache(details));
2794 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
2795 scoped_refptr<net::URLRequestContextGetter> request_context(
2796 resource_type == RESOURCE_TYPE_MEDIA ?
2797 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2798 GetRenderProcessHost()->GetID()) :
2799 GetBrowserContext()->GetRequestContextForRenderProcess(
2800 GetRenderProcessHost()->GetID()));
2801 BrowserThread::PostTask(
2802 BrowserThread::IO,
2803 FROM_HERE,
2804 base::Bind(&NotifyCacheOnIO, request_context, url, http_method));
2808 void WebContentsImpl::OnDidDisplayInsecureContent() {
2809 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
2810 displayed_insecure_content_ = true;
2811 SSLManager::NotifySSLInternalStateChanged(
2812 GetController().GetBrowserContext());
2815 void WebContentsImpl::OnDidRunInsecureContent(
2816 const std::string& security_origin, const GURL& target_url) {
2817 LOG(WARNING) << security_origin << " ran insecure content from "
2818 << target_url.possibly_invalid_spec();
2819 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
2820 if (EndsWith(security_origin, kDotGoogleDotCom, false))
2821 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
2822 controller_.ssl_manager()->DidRunInsecureContent(security_origin);
2823 displayed_insecure_content_ = true;
2824 SSLManager::NotifySSLInternalStateChanged(
2825 GetController().GetBrowserContext());
2828 void WebContentsImpl::OnDocumentLoadedInFrame() {
2829 if (!HasValidFrameSource())
2830 return;
2832 RenderFrameHostImpl* rfh =
2833 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2834 FOR_EACH_OBSERVER(
2835 WebContentsObserver, observers_, DocumentLoadedInFrame(rfh));
2838 void WebContentsImpl::OnDidFinishLoad(const GURL& url) {
2839 if (!HasValidFrameSource())
2840 return;
2842 GURL validated_url(url);
2843 RenderProcessHost* render_process_host =
2844 render_frame_message_source_->GetProcess();
2845 render_process_host->FilterURL(false, &validated_url);
2847 RenderFrameHostImpl* rfh =
2848 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2849 FOR_EACH_OBSERVER(
2850 WebContentsObserver, observers_, DidFinishLoad(rfh, validated_url));
2853 void WebContentsImpl::OnDidStartLoading(bool to_different_document) {
2854 if (!HasValidFrameSource())
2855 return;
2857 RenderFrameHostImpl* rfh =
2858 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2859 int64 render_frame_id = rfh->frame_tree_node()->frame_tree_node_id();
2861 // Any main frame load to a new document should reset the load progress, since
2862 // it will replace the current page and any frames.
2863 if (to_different_document && !rfh->GetParent()) {
2864 ResetLoadProgressState();
2865 loading_frames_in_progress_ = 0;
2866 rfh->frame_tree_node()->set_is_loading(false);
2869 // It is possible to get multiple calls to OnDidStartLoading that don't have
2870 // corresponding calls to OnDidStopLoading:
2871 // - With "swappedout://" URLs, this happens when a RenderView gets swapped
2872 // out for a cross-process navigation, and it turns into a placeholder for
2873 // one being rendered in a different process.
2874 // - Also, there might be more than one RenderFrameHost sharing the same
2875 // FrameTreeNode (and thus sharing its ID) each sending a start.
2876 // - But in the future, once clamy@ moves navigation network requests to the
2877 // browser process, there's a good chance that callbacks about starting and
2878 // stopping will all be handled by the browser. When that happens, there
2879 // should no longer be a start/stop call imbalance. TODO(avi): When this
2880 // future arrives, update this code to not allow this case.
2881 if (rfh->frame_tree_node()->is_loading())
2882 return;
2884 DCHECK_GE(loading_frames_in_progress_, 0);
2885 if (loading_frames_in_progress_ == 0)
2886 DidStartLoading(rfh, to_different_document);
2888 ++loading_frames_in_progress_;
2889 rfh->frame_tree_node()->set_is_loading(true);
2891 // Notify the RenderFrameHostManager of the event.
2892 rfh->frame_tree_node()->render_manager()->OnDidStartLoading();
2894 loading_progresses_[render_frame_id] = kMinimumLoadingProgress;
2895 SendLoadProgressChanged();
2898 void WebContentsImpl::OnDidStopLoading() {
2899 if (!HasValidFrameSource())
2900 return;
2902 RenderFrameHostImpl* rfh =
2903 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2904 int64 render_frame_id = rfh->frame_tree_node()->frame_tree_node_id();
2905 rfh->frame_tree_node()->set_is_loading(false);
2907 if (loading_progresses_.find(render_frame_id) != loading_progresses_.end()) {
2908 // Load stopped while we were still tracking load. Make sure we update
2909 // progress based on this frame's completion.
2910 loading_progresses_[render_frame_id] = 1.0;
2911 SendLoadProgressChanged();
2912 // Then we clean-up our states.
2913 if (loading_total_progress_ == 1.0)
2914 ResetLoadProgressState();
2917 // Notify the RenderFrameHostManager of the event.
2918 rfh->frame_tree_node()->render_manager()->OnDidStopLoading();
2920 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
2921 // calls DidStopLoading() without a matching DidStartLoading().
2922 if (loading_frames_in_progress_ == 0)
2923 return;
2924 --loading_frames_in_progress_;
2925 if (loading_frames_in_progress_ == 0)
2926 DidStopLoading(rfh);
2929 void WebContentsImpl::OnDidChangeLoadProgress(double load_progress) {
2930 if (!HasValidFrameSource())
2931 return;
2933 RenderFrameHostImpl* rfh =
2934 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2935 int64 render_frame_id = rfh->frame_tree_node()->frame_tree_node_id();
2937 loading_progresses_[render_frame_id] = load_progress;
2939 // We notify progress change immediately for the first and last updates.
2940 // Also, since the message loop may be pretty busy when a page is loaded, it
2941 // might not execute a posted task in a timely manner so we make sure to
2942 // immediately send progress report if enough time has passed.
2943 base::TimeDelta min_delay =
2944 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
2945 if (load_progress == 1.0 || loading_last_progress_update_.is_null() ||
2946 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay) {
2947 // If there is a pending task to send progress, it is now obsolete.
2948 loading_weak_factory_.InvalidateWeakPtrs();
2949 SendLoadProgressChanged();
2950 if (loading_total_progress_ == 1.0)
2951 ResetLoadProgressState();
2952 return;
2955 if (loading_weak_factory_.HasWeakPtrs())
2956 return;
2958 base::MessageLoop::current()->PostDelayedTask(
2959 FROM_HERE,
2960 base::Bind(&WebContentsImpl::SendLoadProgressChanged,
2961 loading_weak_factory_.GetWeakPtr()),
2962 min_delay);
2965 void WebContentsImpl::OnGoToEntryAtOffset(int offset) {
2966 if (!delegate_ || delegate_->OnGoToEntryOffset(offset))
2967 controller_.GoToOffset(offset);
2970 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent,
2971 int maximum_percent) {
2972 minimum_zoom_percent_ = minimum_percent;
2973 maximum_zoom_percent_ = maximum_percent;
2976 void WebContentsImpl::OnEnumerateDirectory(int request_id,
2977 const base::FilePath& path) {
2978 if (!delegate_)
2979 return;
2981 ChildProcessSecurityPolicyImpl* policy =
2982 ChildProcessSecurityPolicyImpl::GetInstance();
2983 if (policy->CanReadFile(GetRenderProcessHost()->GetID(), path))
2984 delegate_->EnumerateDirectory(this, request_id, path);
2987 void WebContentsImpl::OnRegisterProtocolHandler(const std::string& protocol,
2988 const GURL& url,
2989 const base::string16& title,
2990 bool user_gesture) {
2991 if (!delegate_)
2992 return;
2994 ChildProcessSecurityPolicyImpl* policy =
2995 ChildProcessSecurityPolicyImpl::GetInstance();
2996 if (policy->IsPseudoScheme(protocol))
2997 return;
2999 delegate_->RegisterProtocolHandler(this, protocol, url, user_gesture);
3002 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string& protocol,
3003 const GURL& url,
3004 bool user_gesture) {
3005 if (!delegate_)
3006 return;
3008 ChildProcessSecurityPolicyImpl* policy =
3009 ChildProcessSecurityPolicyImpl::GetInstance();
3010 if (policy->IsPseudoScheme(protocol))
3011 return;
3013 delegate_->UnregisterProtocolHandler(this, protocol, url, user_gesture);
3016 void WebContentsImpl::OnFindReply(int request_id,
3017 int number_of_matches,
3018 const gfx::Rect& selection_rect,
3019 int active_match_ordinal,
3020 bool final_update) {
3021 if (delegate_) {
3022 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
3023 active_match_ordinal, final_update);
3027 #if defined(OS_ANDROID)
3028 void WebContentsImpl::OnFindMatchRectsReply(
3029 int version,
3030 const std::vector<gfx::RectF>& rects,
3031 const gfx::RectF& active_rect) {
3032 if (delegate_)
3033 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
3036 void WebContentsImpl::OnOpenDateTimeDialog(
3037 const ViewHostMsg_DateTimeDialogValue_Params& value) {
3038 date_time_chooser_->ShowDialog(GetTopLevelNativeWindow(),
3039 GetRenderViewHost(),
3040 value.dialog_type,
3041 value.dialog_value,
3042 value.minimum,
3043 value.maximum,
3044 value.step,
3045 value.suggestions);
3047 #endif
3049 void WebContentsImpl::OnDomOperationResponse(const std::string& json_string,
3050 int automation_id) {
3051 DomOperationNotificationDetails details(json_string, automation_id);
3052 NotificationService::current()->Notify(
3053 NOTIFICATION_DOM_OPERATION_RESPONSE,
3054 Source<WebContents>(this),
3055 Details<DomOperationNotificationDetails>(&details));
3058 void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
3059 bool blocked_by_policy) {
3060 // Notify observers about navigation.
3061 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3062 AppCacheAccessed(manifest_url, blocked_by_policy));
3065 void WebContentsImpl::OnOpenColorChooser(
3066 int color_chooser_id,
3067 SkColor color,
3068 const std::vector<ColorSuggestion>& suggestions) {
3069 if (!HasValidFrameSource())
3070 return;
3072 ColorChooser* new_color_chooser = delegate_ ?
3073 delegate_->OpenColorChooser(this, color, suggestions) :
3074 NULL;
3075 if (!new_color_chooser)
3076 return;
3077 if (color_chooser_info_.get())
3078 color_chooser_info_->chooser->End();
3080 color_chooser_info_.reset(new ColorChooserInfo(
3081 render_frame_message_source_->GetProcess()->GetID(),
3082 render_frame_message_source_->GetRoutingID(),
3083 new_color_chooser,
3084 color_chooser_id));
3087 void WebContentsImpl::OnEndColorChooser(int color_chooser_id) {
3088 if (color_chooser_info_ &&
3089 color_chooser_id == color_chooser_info_->identifier)
3090 color_chooser_info_->chooser->End();
3093 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id,
3094 SkColor color) {
3095 if (color_chooser_info_ &&
3096 color_chooser_id == color_chooser_info_->identifier)
3097 color_chooser_info_->chooser->SetSelectedColor(color);
3100 // This exists for render views that don't have a WebUI, but do have WebUI
3101 // bindings enabled.
3102 void WebContentsImpl::OnWebUISend(const GURL& source_url,
3103 const std::string& name,
3104 const base::ListValue& args) {
3105 if (delegate_)
3106 delegate_->WebUISend(this, source_url, name, args);
3109 #if defined(ENABLE_PLUGINS)
3110 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id,
3111 const base::FilePath& path,
3112 bool is_hung) {
3113 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
3115 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3116 PluginHungStatusChanged(plugin_child_id, path, is_hung));
3119 void WebContentsImpl::OnPluginCrashed(const base::FilePath& plugin_path,
3120 base::ProcessId plugin_pid) {
3121 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3122 PluginCrashed(plugin_path, plugin_pid));
3125 void WebContentsImpl::OnRequestPpapiBrokerPermission(
3126 int routing_id,
3127 const GURL& url,
3128 const base::FilePath& plugin_path) {
3129 if (!delegate_) {
3130 OnPpapiBrokerPermissionResult(routing_id, false);
3131 return;
3134 if (!delegate_->RequestPpapiBrokerPermission(
3135 this, url, plugin_path,
3136 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult,
3137 base::Unretained(this), routing_id))) {
3138 NOTIMPLEMENTED();
3139 OnPpapiBrokerPermissionResult(routing_id, false);
3143 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id,
3144 bool result) {
3145 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id, result));
3148 void WebContentsImpl::OnBrowserPluginMessage(RenderFrameHost* render_frame_host,
3149 const IPC::Message& message) {
3150 // This creates a BrowserPluginEmbedder, which handles all the BrowserPlugin
3151 // specific messages for this WebContents. This means that any message from
3152 // a BrowserPlugin prior to this will be ignored.
3153 // For more info, see comment above classes BrowserPluginEmbedder and
3154 // BrowserPluginGuest.
3155 CHECK(!browser_plugin_embedder_.get());
3156 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
3157 browser_plugin_embedder_->OnMessageReceived(message, render_frame_host);
3159 #endif // defined(ENABLE_PLUGINS)
3161 void WebContentsImpl::OnDidDownloadImage(
3162 int id,
3163 int http_status_code,
3164 const GURL& image_url,
3165 const std::vector<SkBitmap>& bitmaps,
3166 const std::vector<gfx::Size>& original_bitmap_sizes) {
3167 if (bitmaps.size() != original_bitmap_sizes.size())
3168 return;
3170 ImageDownloadMap::iterator iter = image_download_map_.find(id);
3171 if (iter == image_download_map_.end()) {
3172 // Currently WebContents notifies us of ANY downloads so that it is
3173 // possible to get here.
3174 return;
3176 if (!iter->second.is_null()) {
3177 iter->second.Run(
3178 id, http_status_code, image_url, bitmaps, original_bitmap_sizes);
3180 image_download_map_.erase(id);
3183 void WebContentsImpl::OnUpdateFaviconURL(
3184 const std::vector<FaviconURL>& candidates) {
3185 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3186 DidUpdateFaviconURL(candidates));
3189 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3190 DCHECK(!audio_power_save_blocker_);
3191 audio_power_save_blocker_ = PowerSaveBlocker::Create(
3192 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension,
3193 PowerSaveBlocker::kReasonAudioPlayback, "Playing audio");
3196 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3197 DCHECK(!video_power_save_blocker_);
3198 DCHECK(!active_video_players_.empty());
3199 video_power_save_blocker_ = PowerSaveBlocker::Create(
3200 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
3201 PowerSaveBlocker::kReasonVideoPlayback, "Playing video");
3202 #if defined(OS_ANDROID)
3203 static_cast<PowerSaveBlockerImpl*>(video_power_save_blocker_.get())
3204 ->InitDisplaySleepBlocker(GetView()->GetNativeView());
3205 #endif
3208 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3209 // If there are no more audio players and we don't have audio stream
3210 // monitoring, release the audio power save blocker here instead of during
3211 // NotifyNavigationStateChanged().
3212 if (active_audio_players_.empty() &&
3213 !AudioStreamMonitor::monitoring_available()) {
3214 audio_power_save_blocker_.reset();
3217 // If there are no more video players, clear the video power save blocker.
3218 if (active_video_players_.empty())
3219 video_power_save_blocker_.reset();
3222 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie,
3223 bool has_video,
3224 bool has_audio,
3225 bool is_remote) {
3226 // Ignore the videos playing remotely and don't hold the wake lock for the
3227 // screen.
3228 if (is_remote) return;
3230 if (has_audio) {
3231 AddMediaPlayerEntry(player_cookie, &active_audio_players_);
3233 // If we don't have audio stream monitoring, allocate the audio power save
3234 // blocker here instead of during NotifyNavigationStateChanged().
3235 if (!audio_power_save_blocker_ &&
3236 !AudioStreamMonitor::monitoring_available()) {
3237 CreateAudioPowerSaveBlocker();
3241 if (has_video) {
3242 AddMediaPlayerEntry(player_cookie, &active_video_players_);
3244 // If we're not hidden and have just created a player, create a blocker.
3245 if (!video_power_save_blocker_ && !IsHidden())
3246 CreateVideoPowerSaveBlocker();
3250 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie) {
3251 RemoveMediaPlayerEntry(player_cookie, &active_audio_players_);
3252 RemoveMediaPlayerEntry(player_cookie, &active_video_players_);
3253 MaybeReleasePowerSaveBlockers();
3256 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3257 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3258 DidFirstVisuallyNonEmptyPaint());
3261 void WebContentsImpl::DidChangeVisibleSSLState() {
3262 if (delegate_)
3263 delegate_->VisibleSSLStateChanged(this);
3266 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3267 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3268 BeforeFormRepostWarningShow());
3271 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3272 Activate();
3273 if (delegate_)
3274 delegate_->ShowRepostFormWarningDialog(this);
3277 bool WebContentsImpl::HasAccessedInitialDocument() {
3278 return has_accessed_initial_document_;
3281 // Notifies the RenderWidgetHost instance about the fact that the page is
3282 // loading, or done loading.
3283 void WebContentsImpl::SetIsLoading(RenderViewHost* render_view_host,
3284 bool is_loading,
3285 bool to_different_document,
3286 LoadNotificationDetails* details) {
3287 if (is_loading == is_loading_)
3288 return;
3290 if (!is_loading) {
3291 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
3292 base::string16());
3293 load_state_host_.clear();
3294 upload_size_ = 0;
3295 upload_position_ = 0;
3298 GetRenderManager()->SetIsLoading(is_loading);
3300 is_loading_ = is_loading;
3301 waiting_for_response_ = is_loading;
3302 is_load_to_different_document_ = to_different_document;
3304 if (delegate_)
3305 delegate_->LoadingStateChanged(this, to_different_document);
3306 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
3308 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
3309 if (is_loading) {
3310 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3311 this, "URL", url);
3312 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3313 DidStartLoading(render_view_host));
3314 } else {
3315 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3316 this, "URL", url);
3317 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3318 DidStopLoading(render_view_host));
3321 // TODO(avi): Remove. http://crbug.com/170921
3322 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
3323 NotificationDetails det = NotificationService::NoDetails();
3324 if (details)
3325 det = Details<LoadNotificationDetails>(details);
3326 NotificationService::current()->Notify(
3327 type, Source<NavigationController>(&controller_), det);
3330 void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
3331 RenderFrameHost* focused_frame = GetFocusedFrame();
3332 if (!focused_frame)
3333 return;
3335 focused_frame->Send(new InputMsg_MoveRangeSelectionExtent(
3336 focused_frame->GetRoutingID(), extent));
3339 void WebContentsImpl::SelectRange(const gfx::Point& base,
3340 const gfx::Point& extent) {
3341 RenderFrameHost* focused_frame = GetFocusedFrame();
3342 if (!focused_frame)
3343 return;
3345 focused_frame->Send(
3346 new InputMsg_SelectRange(focused_frame->GetRoutingID(), base, extent));
3349 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost* rvh) {
3350 // If we are creating a RVH for a restored controller, then we need to make
3351 // sure the RenderView starts with a next_page_id_ larger than the number
3352 // of restored entries. This must be called before the RenderView starts
3353 // navigating (to avoid a race between the browser updating max_page_id and
3354 // the renderer updating next_page_id_). Because of this, we only call this
3355 // from CreateRenderView and allow that to notify the RenderView for us.
3356 int max_restored_page_id = controller_.GetMaxRestoredPageID();
3357 if (max_restored_page_id >
3358 GetMaxPageIDForSiteInstance(rvh->GetSiteInstance()))
3359 UpdateMaxPageIDForSiteInstance(rvh->GetSiteInstance(),
3360 max_restored_page_id);
3363 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl* entry,
3364 const base::string16& title) {
3365 // For file URLs without a title, use the pathname instead. In the case of a
3366 // synthesized title, we don't want the update to count toward the "one set
3367 // per page of the title to history."
3368 base::string16 final_title;
3369 bool explicit_set;
3370 if (entry && entry->GetURL().SchemeIsFile() && title.empty()) {
3371 final_title = base::UTF8ToUTF16(entry->GetURL().ExtractFileName());
3372 explicit_set = false; // Don't count synthetic titles toward the set limit.
3373 } else {
3374 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
3375 explicit_set = true;
3378 // If a page is created via window.open and never navigated,
3379 // there will be no navigation entry. In this situation,
3380 // |page_title_when_no_navigation_entry_| will be used for page title.
3381 if (entry) {
3382 if (final_title == entry->GetTitle())
3383 return false; // Nothing changed, don't bother.
3385 entry->SetTitle(final_title);
3386 } else {
3387 if (page_title_when_no_navigation_entry_ == final_title)
3388 return false; // Nothing changed, don't bother.
3390 page_title_when_no_navigation_entry_ = final_title;
3393 // Lastly, set the title for the view.
3394 view_->SetPageTitle(final_title);
3396 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3397 TitleWasSet(entry, explicit_set));
3399 // TODO(avi): Remove. http://crbug.com/170921
3400 std::pair<NavigationEntry*, bool> details =
3401 std::make_pair(entry, explicit_set);
3402 NotificationService::current()->Notify(
3403 NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,
3404 Source<WebContents>(this),
3405 Details<std::pair<NavigationEntry*, bool> >(&details));
3407 return true;
3410 void WebContentsImpl::SendLoadProgressChanged() {
3411 loading_last_progress_update_ = base::TimeTicks::Now();
3412 double progress = 0.0;
3413 int frame_count = 0;
3415 for (LoadingProgressMap::iterator it = loading_progresses_.begin();
3416 it != loading_progresses_.end();
3417 ++it) {
3418 progress += it->second;
3419 ++frame_count;
3421 if (frame_count == 0)
3422 return;
3423 progress /= frame_count;
3424 DCHECK(progress <= 1.0);
3426 if (progress <= loading_total_progress_)
3427 return;
3428 loading_total_progress_ = progress;
3430 if (delegate_)
3431 delegate_->LoadProgressChanged(this, progress);
3434 void WebContentsImpl::ResetLoadProgressState() {
3435 loading_progresses_.clear();
3436 loading_total_progress_ = 0.0;
3437 loading_weak_factory_.InvalidateWeakPtrs();
3438 loading_last_progress_update_ = base::TimeTicks();
3441 void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_host,
3442 RenderViewHost* new_host) {
3443 // After sending out a swap notification, we need to send a disconnect
3444 // notification so that clients that pick up a pointer to |this| can NULL the
3445 // pointer. See Bug 1230284.
3446 notify_disconnection_ = true;
3447 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3448 RenderViewHostChanged(old_host, new_host));
3450 // TODO(avi): Remove. http://crbug.com/170921
3451 std::pair<RenderViewHost*, RenderViewHost*> details =
3452 std::make_pair(old_host, new_host);
3453 NotificationService::current()->Notify(
3454 NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
3455 Source<WebContents>(this),
3456 Details<std::pair<RenderViewHost*, RenderViewHost*> >(&details));
3458 // Ensure that the associated embedder gets cleared after a RenderViewHost
3459 // gets swapped, so we don't reuse the same embedder next time a
3460 // RenderViewHost is attached to this WebContents.
3461 RemoveBrowserPluginEmbedder();
3464 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_host,
3465 RenderFrameHost* new_host) {
3466 FOR_EACH_OBSERVER(WebContentsObserver,
3467 observers_,
3468 RenderFrameHostChanged(old_host, new_host));
3471 // TODO(avi): Remove this entire function because this notification is already
3472 // covered by two observer functions. http://crbug.com/170921
3473 void WebContentsImpl::NotifyDisconnected() {
3474 if (!notify_disconnection_)
3475 return;
3477 notify_disconnection_ = false;
3478 NotificationService::current()->Notify(
3479 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
3480 Source<WebContents>(this),
3481 NotificationService::NoDetails());
3484 void WebContentsImpl::NotifyNavigationEntryCommitted(
3485 const LoadCommittedDetails& load_details) {
3486 FOR_EACH_OBSERVER(
3487 WebContentsObserver, observers_, NavigationEntryCommitted(load_details));
3490 bool WebContentsImpl::OnMessageReceived(RenderFrameHost* render_frame_host,
3491 const IPC::Message& message) {
3492 return OnMessageReceived(NULL, render_frame_host, message);
3495 const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3496 return GetLastCommittedURL();
3499 void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
3500 // Note this is only for subframes, the notification for the main frame
3501 // happens in RenderViewCreated.
3502 FOR_EACH_OBSERVER(WebContentsObserver,
3503 observers_,
3504 RenderFrameCreated(render_frame_host));
3505 SetAccessibilityModeOnFrame(accessibility_mode_, render_frame_host);
3508 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
3509 ClearPowerSaveBlockers(render_frame_host);
3510 FOR_EACH_OBSERVER(WebContentsObserver,
3511 observers_,
3512 RenderFrameDeleted(render_frame_host));
3515 void WebContentsImpl::WorkerCrashed(RenderFrameHost* render_frame_host) {
3516 if (delegate_)
3517 delegate_->WorkerCrashed(this);
3520 void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
3521 const ContextMenuParams& params) {
3522 ContextMenuParams context_menu_params(params);
3523 // Allow WebContentsDelegates to handle the context menu operation first.
3524 if (GetBrowserPluginGuest()) {
3525 WebContentsViewGuest* view_guest =
3526 static_cast<WebContentsViewGuest*>(GetView());
3527 context_menu_params = view_guest->ConvertContextMenuParams(params);
3529 if (delegate_ && delegate_->HandleContextMenu(context_menu_params))
3530 return;
3532 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
3533 context_menu_params);
3536 void WebContentsImpl::RunJavaScriptMessage(
3537 RenderFrameHost* render_frame_host,
3538 const base::string16& message,
3539 const base::string16& default_prompt,
3540 const GURL& frame_url,
3541 JavaScriptMessageType javascript_message_type,
3542 IPC::Message* reply_msg) {
3543 // Suppress JavaScript dialogs when requested. Also suppress messages when
3544 // showing an interstitial as it's shown over the previous page and we don't
3545 // want the hidden page's dialogs to interfere with the interstitial.
3546 bool suppress_this_message =
3547 static_cast<RenderFrameHostImpl*>(render_frame_host)->is_swapped_out() ||
3548 ShowingInterstitialPage() || !delegate_ ||
3549 delegate_->ShouldSuppressDialogs(this) ||
3550 !delegate_->GetJavaScriptDialogManager(this);
3552 if (!suppress_this_message) {
3553 std::string accept_lang = GetContentClient()->browser()->
3554 GetAcceptLangs(GetBrowserContext());
3555 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3556 dialog_manager_->RunJavaScriptDialog(
3557 this,
3558 frame_url.GetOrigin(),
3559 accept_lang,
3560 javascript_message_type,
3561 message,
3562 default_prompt,
3563 base::Bind(&WebContentsImpl::OnDialogClosed,
3564 base::Unretained(this),
3565 render_frame_host->GetProcess()->GetID(),
3566 render_frame_host->GetRoutingID(),
3567 reply_msg,
3568 false),
3569 &suppress_this_message);
3572 if (suppress_this_message) {
3573 // If we are suppressing messages, just reply as if the user immediately
3574 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3575 OnDialogClosed(render_frame_host->GetProcess()->GetID(),
3576 render_frame_host->GetRoutingID(), reply_msg,
3577 true, false, base::string16());
3580 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3581 // http://crbug.com/288961 ). The only safe thing to do here is return.
3584 void WebContentsImpl::RunBeforeUnloadConfirm(
3585 RenderFrameHost* render_frame_host,
3586 const base::string16& message,
3587 bool is_reload,
3588 IPC::Message* reply_msg) {
3589 RenderFrameHostImpl* rfhi =
3590 static_cast<RenderFrameHostImpl*>(render_frame_host);
3591 if (delegate_)
3592 delegate_->WillRunBeforeUnloadConfirm();
3594 bool suppress_this_message =
3595 rfhi->rfh_state() != RenderFrameHostImpl::STATE_DEFAULT || !delegate_ ||
3596 delegate_->ShouldSuppressDialogs(this) ||
3597 !delegate_->GetJavaScriptDialogManager(this);
3598 if (suppress_this_message) {
3599 rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16(), true);
3600 return;
3603 is_showing_before_unload_dialog_ = true;
3604 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3605 dialog_manager_->RunBeforeUnloadDialog(
3606 this, message, is_reload,
3607 base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
3608 render_frame_host->GetProcess()->GetID(),
3609 render_frame_host->GetRoutingID(), reply_msg,
3610 false));
3613 WebContents* WebContentsImpl::GetAsWebContents() {
3614 return this;
3617 bool WebContentsImpl::IsNeverVisible() {
3618 if (!delegate_)
3619 return false;
3620 return delegate_->IsNeverVisible(this);
3623 #if defined(OS_WIN)
3624 gfx::NativeViewAccessible WebContentsImpl::GetParentNativeViewAccessible() {
3625 return accessible_parent_;
3627 #endif
3629 RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
3630 return render_view_host_delegate_view_;
3633 RendererPreferences WebContentsImpl::GetRendererPrefs(
3634 BrowserContext* browser_context) const {
3635 return renderer_preferences_;
3638 gfx::Rect WebContentsImpl::GetRootWindowResizerRect() const {
3639 if (delegate_)
3640 return delegate_->GetRootWindowResizerRect();
3641 return gfx::Rect();
3644 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3645 if (browser_plugin_embedder_)
3646 browser_plugin_embedder_.reset();
3649 void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
3650 // Don't send notifications if we are just creating a swapped-out RVH for
3651 // the opener chain. These won't be used for view-source or WebUI, so it's
3652 // ok to return early.
3653 if (!static_cast<RenderViewHostImpl*>(render_view_host)->is_active())
3654 return;
3656 if (delegate_)
3657 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
3659 NotificationService::current()->Notify(
3660 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
3661 Source<WebContents>(this),
3662 Details<RenderViewHost>(render_view_host));
3664 // When we're creating views, we're still doing initial setup, so we always
3665 // use the pending Web UI rather than any possibly existing committed one.
3666 if (GetRenderManager()->pending_web_ui())
3667 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host);
3669 NavigationEntry* entry = controller_.GetPendingEntry();
3670 if (entry && entry->IsViewSourceMode()) {
3671 // Put the renderer in view source mode.
3672 render_view_host->Send(
3673 new ViewMsg_EnableViewSourceMode(render_view_host->GetRoutingID()));
3676 view_->RenderViewCreated(render_view_host);
3678 FOR_EACH_OBSERVER(
3679 WebContentsObserver, observers_, RenderViewCreated(render_view_host));
3681 DevToolsManager::GetInstance()->RenderViewCreated(this, render_view_host);
3684 void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
3685 if (rvh != GetRenderViewHost()) {
3686 // Don't notify the world, since this came from a renderer in the
3687 // background.
3688 return;
3691 notify_disconnection_ = true;
3692 // TODO(avi): Remove. http://crbug.com/170921
3693 NotificationService::current()->Notify(
3694 NOTIFICATION_WEB_CONTENTS_CONNECTED,
3695 Source<WebContents>(this),
3696 NotificationService::NoDetails());
3698 bool was_crashed = IsCrashed();
3699 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
3701 // Restore the focus to the tab (otherwise the focus will be on the top
3702 // window).
3703 if (was_crashed && !FocusLocationBarByDefault() &&
3704 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
3705 view_->Focus();
3708 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewReady());
3711 void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
3712 base::TerminationStatus status,
3713 int error_code) {
3714 if (rvh != GetRenderViewHost()) {
3715 // The pending page's RenderViewHost is gone.
3716 return;
3719 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3720 // renderer may not have made a clean exit.
3721 if (IsFullscreenForCurrentTab())
3722 ExitFullscreenMode();
3724 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3725 if (dialog_manager_)
3726 dialog_manager_->CancelActiveAndPendingDialogs(this);
3728 if (delegate_)
3729 delegate_->HideValidationMessage(this);
3731 SetIsLoading(rvh, false, true, NULL);
3732 NotifyDisconnected();
3733 SetIsCrashed(status, error_code);
3735 // Reset the loading progress. TODO(avi): What does it mean to have a
3736 // "renderer crash" when there is more than one renderer process serving a
3737 // webpage? Once this function is called at a more granular frame level, we
3738 // probably will need to more granularly reset the state here.
3739 ResetLoadProgressState();
3740 loading_frames_in_progress_ = 0;
3742 FOR_EACH_OBSERVER(WebContentsObserver,
3743 observers_,
3744 RenderProcessGone(GetCrashedStatus()));
3747 void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
3748 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewDeleted(rvh));
3751 void WebContentsImpl::UpdateState(RenderViewHost* rvh,
3752 int32 page_id,
3753 const PageState& page_state) {
3754 // Ensure that this state update comes from a RenderViewHost that belongs to
3755 // this WebContents.
3756 // TODO(nasko): This should go through RenderFrameHost.
3757 // TODO(creis): We can't update state for cross-process subframes until we
3758 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
3759 if (rvh->GetDelegate()->GetAsWebContents() != this)
3760 return;
3762 // We must be prepared to handle state updates for any page, these occur
3763 // when the user is scrolling and entering form data, as well as when we're
3764 // leaving a page, in which case our state may have already been moved to
3765 // the next page. The navigation controller will look up the appropriate
3766 // NavigationEntry and update it when it is notified via the delegate.
3768 int entry_index = controller_.GetEntryIndexWithPageID(
3769 rvh->GetSiteInstance(), page_id);
3770 if (entry_index < 0)
3771 return;
3772 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
3774 if (page_state == entry->GetPageState())
3775 return; // Nothing to update.
3776 entry->SetPageState(page_state);
3777 controller_.NotifyEntryChanged(entry, entry_index);
3780 void WebContentsImpl::UpdateTargetURL(RenderViewHost* render_view_host,
3781 const GURL& url) {
3782 if (fullscreen_widget_routing_id_ != MSG_ROUTING_NONE) {
3783 // If we're fullscreen only update the url if it's from the fullscreen
3784 // renderer.
3785 RenderWidgetHostView* fs = GetFullscreenRenderWidgetHostView();
3786 if (fs && fs->GetRenderWidgetHost() != render_view_host)
3787 return;
3789 if (delegate_)
3790 delegate_->UpdateTargetURL(this, url);
3793 void WebContentsImpl::Close(RenderViewHost* rvh) {
3794 #if defined(OS_MACOSX)
3795 // The UI may be in an event-tracking loop, such as between the
3796 // mouse-down and mouse-up in text selection or a button click.
3797 // Defer the close until after tracking is complete, so that we
3798 // don't free objects out from under the UI.
3799 // TODO(shess): This could get more fine-grained. For instance,
3800 // closing a tab in another window while selecting text in the
3801 // current window's Omnibox should be just fine.
3802 if (view_->IsEventTracking()) {
3803 view_->CloseTabAfterEventTracking();
3804 return;
3806 #endif
3808 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3809 if (delegate_ && rvh == GetRenderViewHost())
3810 delegate_->CloseContents(this);
3813 void WebContentsImpl::SwappedOut(RenderFrameHost* rfh) {
3814 if (delegate_ && rfh->GetRenderViewHost() == GetRenderViewHost())
3815 delegate_->SwappedOut(this);
3818 void WebContentsImpl::DidDeferAfterResponseStarted(
3819 const TransitionLayerData& transition_data) {
3820 #if defined(OS_ANDROID)
3821 GetWebContentsAndroid()->DidDeferAfterResponseStarted(transition_data);
3822 #endif
3825 bool WebContentsImpl::WillHandleDeferAfterResponseStarted() {
3826 #if defined(OS_ANDROID)
3827 return GetWebContentsAndroid()->WillHandleDeferAfterResponseStarted();
3828 #else
3829 return false;
3830 #endif
3833 void WebContentsImpl::RequestMove(const gfx::Rect& new_bounds) {
3834 if (delegate_ && delegate_->IsPopupOrPanel(this))
3835 delegate_->MoveContents(this, new_bounds);
3838 void WebContentsImpl::DidStartLoading(RenderFrameHost* render_frame_host,
3839 bool to_different_document) {
3840 SetIsLoading(render_frame_host->GetRenderViewHost(), true,
3841 to_different_document, NULL);
3843 // Notify accessibility that the user is navigating away from the
3844 // current document.
3846 // TODO(dmazzoni): do this using a WebContentsObserver.
3847 FrameTreeNode* ftn = static_cast<RenderFrameHostImpl*>(render_frame_host)->
3848 frame_tree_node();
3849 BrowserAccessibilityManager* manager =
3850 ftn->current_frame_host()->browser_accessibility_manager();
3851 if (manager)
3852 manager->UserIsNavigatingAway();
3855 void WebContentsImpl::DidStopLoading(RenderFrameHost* render_frame_host) {
3856 scoped_ptr<LoadNotificationDetails> details;
3858 // Use the last committed entry rather than the active one, in case a
3859 // pending entry has been created.
3860 NavigationEntry* entry = controller_.GetLastCommittedEntry();
3861 Navigator* navigator = frame_tree_.root()->navigator();
3863 // An entry may not exist for a stop when loading an initial blank page or
3864 // if an iframe injected by script into a blank page finishes loading.
3865 if (entry) {
3866 base::TimeDelta elapsed =
3867 base::TimeTicks::Now() - navigator->GetCurrentLoadStart();
3869 details.reset(new LoadNotificationDetails(
3870 entry->GetVirtualURL(),
3871 entry->GetTransitionType(),
3872 elapsed,
3873 &controller_,
3874 controller_.GetCurrentEntryIndex()));
3877 SetIsLoading(render_frame_host->GetRenderViewHost(), false, true,
3878 details.get());
3881 void WebContentsImpl::DidCancelLoading() {
3882 controller_.DiscardNonCommittedEntries();
3884 // Update the URL display.
3885 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3888 void WebContentsImpl::DidAccessInitialDocument() {
3889 has_accessed_initial_document_ = true;
3891 // We may have left a failed browser-initiated navigation in the address bar
3892 // to let the user edit it and try again. Clear it now that content might
3893 // show up underneath it.
3894 if (!IsLoading() && controller_.GetPendingEntry())
3895 controller_.DiscardPendingEntry();
3897 // Update the URL display.
3898 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3901 void WebContentsImpl::DidDisownOpener(RenderFrameHost* render_frame_host) {
3902 // No action is necessary if the opener has already been cleared.
3903 if (!opener_)
3904 return;
3906 // Clear our opener so that future cross-process navigations don't have an
3907 // opener assigned.
3908 RemoveDestructionObserver(opener_);
3909 opener_ = NULL;
3911 // Notify all swapped out RenderViewHosts for this tab. This is important
3912 // in case we go back to them, or if another window in those processes tries
3913 // to access window.opener.
3914 GetRenderManager()->DidDisownOpener(render_frame_host);
3917 void WebContentsImpl::DocumentOnLoadCompleted(
3918 RenderFrameHost* render_frame_host) {
3919 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3920 DocumentOnLoadCompletedInMainFrame());
3922 // TODO(avi): Remove. http://crbug.com/170921
3923 NotificationService::current()->Notify(
3924 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
3925 Source<WebContents>(this),
3926 NotificationService::NoDetails());
3929 void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
3930 int32 page_id,
3931 const base::string16& title,
3932 base::i18n::TextDirection title_direction) {
3933 RenderViewHost* rvh = render_frame_host->GetRenderViewHost();
3935 // If we have a title, that's a pretty good indication that we've started
3936 // getting useful data.
3937 SetNotWaitingForResponse();
3939 // Try to find the navigation entry, which might not be the current one.
3940 // For example, it might be from a pending RVH for the pending entry.
3941 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
3942 rvh->GetSiteInstance(), page_id);
3944 // We can handle title updates when we don't have an entry in
3945 // UpdateTitleForEntry, but only if the update is from the current RVH.
3946 // TODO(avi): Change to make decisions based on the RenderFrameHost.
3947 if (!entry && rvh != GetRenderViewHost())
3948 return;
3950 // TODO(evan): make use of title_direction.
3951 // http://code.google.com/p/chromium/issues/detail?id=27094
3952 if (!UpdateTitleForEntry(entry, title))
3953 return;
3955 // Broadcast notifications when the UI should be updated.
3956 if (entry == controller_.GetEntryAtOffset(0))
3957 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
3960 void WebContentsImpl::UpdateEncoding(RenderFrameHost* render_frame_host,
3961 const std::string& encoding) {
3962 SetEncoding(encoding);
3965 void WebContentsImpl::DocumentAvailableInMainFrame(
3966 RenderViewHost* render_view_host) {
3967 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3968 DocumentAvailableInMainFrame());
3970 void WebContentsImpl::RouteCloseEvent(RenderViewHost* rvh) {
3971 // Tell the active RenderViewHost to run unload handlers and close, as long
3972 // as the request came from a RenderViewHost in the same BrowsingInstance.
3973 // In most cases, we receive this from a swapped out RenderViewHost.
3974 // It is possible to receive it from one that has just been swapped in,
3975 // in which case we might as well deliver the message anyway.
3976 if (rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3977 GetRenderViewHost()->ClosePage();
3980 void WebContentsImpl::RouteMessageEvent(
3981 RenderViewHost* rvh,
3982 const ViewMsg_PostMessage_Params& params) {
3983 // Only deliver the message to the active RenderViewHost if the request
3984 // came from a RenderViewHost in the same BrowsingInstance or if this
3985 // WebContents is dedicated to a browser plugin guest.
3986 // Note: This check means that an embedder could theoretically receive a
3987 // postMessage from anyone (not just its own guests). However, this is
3988 // probably not a risk for apps since other pages won't have references
3989 // to App windows.
3990 if (!rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()) &&
3991 !GetBrowserPluginGuest() && !GetBrowserPluginEmbedder())
3992 return;
3994 ViewMsg_PostMessage_Params new_params(params);
3996 // If there is a source_routing_id, translate it to the routing ID for
3997 // the equivalent swapped out RVH in the target process. If we need
3998 // to create a swapped out RVH for the source tab, we create its opener
3999 // chain as well, since those will also be accessible to the target page.
4000 if (new_params.source_routing_id != MSG_ROUTING_NONE) {
4001 // Try to look up the WebContents for the source page.
4002 WebContentsImpl* source_contents = NULL;
4003 RenderViewHostImpl* source_rvh = RenderViewHostImpl::FromID(
4004 rvh->GetProcess()->GetID(), params.source_routing_id);
4005 if (source_rvh) {
4006 source_contents = static_cast<WebContentsImpl*>(
4007 source_rvh->GetDelegate()->GetAsWebContents());
4010 if (source_contents) {
4011 if (GetBrowserPluginGuest()) {
4012 // We create a swapped out RenderView for the embedder in the guest's
4013 // render process but we intentionally do not expose the embedder's
4014 // opener chain to it.
4015 new_params.source_routing_id =
4016 source_contents->CreateSwappedOutRenderView(GetSiteInstance());
4017 } else {
4018 new_params.source_routing_id =
4019 source_contents->CreateOpenerRenderViews(GetSiteInstance());
4021 } else {
4022 // We couldn't find it, so don't pass a source frame.
4023 new_params.source_routing_id = MSG_ROUTING_NONE;
4027 // In most cases, we receive this from a swapped out RenderViewHost.
4028 // It is possible to receive it from one that has just been swapped in,
4029 // in which case we might as well deliver the message anyway.
4030 if (!params.message_ports.empty()) {
4031 // Updating the message port information has to be done in the IO thread;
4032 // MessagePortMessageFilter::RouteMessageEventWithMessagePorts will send
4033 // ViewMsg_PostMessageEvent after it's done. Note that a trivial solution
4034 // would've been to post a task on the IO thread to do the IO-thread-bound
4035 // work, and make that post a task back to WebContentsImpl in the UI
4036 // thread. But we cannot do that, since there's nothing to guarantee that
4037 // WebContentsImpl stays alive during the round trip.
4038 scoped_refptr<MessagePortMessageFilter> message_port_message_filter(
4039 static_cast<RenderProcessHostImpl*>(GetRenderProcessHost())
4040 ->message_port_message_filter());
4041 BrowserThread::PostTask(
4042 BrowserThread::IO, FROM_HERE,
4043 base::Bind(&MessagePortMessageFilter::RouteMessageEventWithMessagePorts,
4044 message_port_message_filter, GetRoutingID(), new_params));
4045 } else {
4046 Send(new ViewMsg_PostMessageEvent(GetRoutingID(), new_params));
4050 bool WebContentsImpl::AddMessageToConsole(int32 level,
4051 const base::string16& message,
4052 int32 line_no,
4053 const base::string16& source_id) {
4054 if (!delegate_)
4055 return false;
4056 return delegate_->AddMessageToConsole(this, level, message, line_no,
4057 source_id);
4060 int WebContentsImpl::CreateSwappedOutRenderView(
4061 SiteInstance* instance) {
4062 int render_view_routing_id = MSG_ROUTING_NONE;
4063 GetRenderManager()->CreateRenderFrame(
4064 instance, nullptr, MSG_ROUTING_NONE,
4065 CREATE_RF_SWAPPED_OUT | CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
4066 CREATE_RF_HIDDEN,
4067 &render_view_routing_id);
4068 return render_view_routing_id;
4071 void WebContentsImpl::OnUserGesture() {
4072 // Notify observers.
4073 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetUserGesture());
4075 ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
4076 if (rdh) // NULL in unittests.
4077 rdh->OnUserGesture(this);
4080 void WebContentsImpl::OnIgnoredUIEvent() {
4081 // Notify observers.
4082 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetIgnoredUIEvent());
4085 void WebContentsImpl::RendererUnresponsive(RenderViewHost* render_view_host) {
4086 // Don't show hung renderer dialog for a swapped out RVH.
4087 if (render_view_host != GetRenderViewHost())
4088 return;
4090 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(render_view_host);
4091 RenderFrameHostImpl* rfhi =
4092 static_cast<RenderFrameHostImpl*>(rvhi->GetMainFrame());
4094 // Ignore renderer unresponsive event if debugger is attached to the tab
4095 // since the event may be a result of the renderer sitting on a breakpoint.
4096 // See http://crbug.com/65458
4097 if (DevToolsAgentHost::IsDebuggerAttached(this))
4098 return;
4100 if (rfhi->IsWaitingForBeforeUnloadACK() ||
4101 rfhi->IsWaitingForUnloadACK()) {
4102 // Hang occurred while firing the beforeunload/unload handler.
4103 // Pretend the handler fired so tab closing continues as if it had.
4104 frame_tree_.ForEach(base::Bind(
4105 &EnableSuddenTermination, rvhi->GetSiteInstance()->GetId()));
4107 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
4108 return;
4110 // If the tab hangs in the beforeunload/unload handler there's really
4111 // nothing we can do to recover. If the hang is in the beforeunload handler,
4112 // pretend the beforeunload listeners have all fired and allow the delegate
4113 // to continue closing; the user will not have the option of cancelling the
4114 // close. Otherwise, pretend the unload listeners have all fired and close
4115 // the tab.
4116 bool close = true;
4117 if (rfhi->IsWaitingForBeforeUnloadACK() && delegate_) {
4118 delegate_->BeforeUnloadFired(this, true, &close);
4120 if (close)
4121 Close(rvhi);
4122 return;
4125 if (!GetRenderViewHostImpl() || !GetRenderViewHostImpl()->IsRenderViewLive())
4126 return;
4128 if (delegate_)
4129 delegate_->RendererUnresponsive(this);
4132 void WebContentsImpl::RendererResponsive(RenderViewHost* render_view_host) {
4133 if (delegate_)
4134 delegate_->RendererResponsive(this);
4137 void WebContentsImpl::LoadStateChanged(
4138 const GURL& url,
4139 const net::LoadStateWithParam& load_state,
4140 uint64 upload_position,
4141 uint64 upload_size) {
4142 load_state_ = load_state;
4143 upload_position_ = upload_position;
4144 upload_size_ = upload_size;
4145 load_state_host_ = net::IDNToUnicode(url.host(),
4146 GetContentClient()->browser()->GetAcceptLangs(
4147 GetBrowserContext()));
4148 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
4149 SetNotWaitingForResponse();
4150 if (IsLoading()) {
4151 NotifyNavigationStateChanged(static_cast<InvalidateTypes>(
4152 INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB));
4156 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
4157 bool proceed, const base::TimeTicks& proceed_time,
4158 bool* proceed_to_fire_unload) {
4159 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4160 BeforeUnloadFired(proceed_time));
4161 if (delegate_)
4162 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
4163 // Note: |this| might be deleted at this point.
4166 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4167 RenderViewHost* render_view_host) {
4168 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
4169 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
4172 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4173 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4174 gfx::Size size = GetSizeForNewRenderView();
4175 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4176 // here during container initialization and normal window size will be set
4177 // later. In case of tab duplication this resizing to 0x0 prevents setting
4178 // normal size later so just ignore it.
4179 if (!size.IsEmpty())
4180 view_->SizeContents(size);
4183 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4184 // We need to cancel modal dialogs when doing a process swap, since the load
4185 // deferrer would prevent us from swapping out.
4186 if (dialog_manager_)
4187 dialog_manager_->CancelActiveAndPendingDialogs(this);
4190 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_host,
4191 RenderFrameHost* new_host,
4192 bool is_main_frame) {
4193 if (is_main_frame) {
4194 NotifyViewSwapped(old_host ? old_host->GetRenderViewHost() : nullptr,
4195 new_host->GetRenderViewHost());
4197 // Make sure the visible RVH reflects the new delegate's preferences.
4198 if (delegate_)
4199 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4201 view_->RenderViewSwappedIn(new_host->GetRenderViewHost());
4204 NotifyFrameSwapped(old_host, new_host);
4207 void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
4208 RenderViewHost* old_host,
4209 RenderViewHost* new_host) {
4210 NotifyViewSwapped(old_host, new_host);
4213 int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
4214 SiteInstance* instance) {
4215 if (!opener_)
4216 return MSG_ROUTING_NONE;
4218 // Recursively create RenderViews for anything else in the opener chain.
4219 return opener_->CreateOpenerRenderViews(instance);
4222 int WebContentsImpl::CreateOpenerRenderViews(SiteInstance* instance) {
4223 int opener_route_id = MSG_ROUTING_NONE;
4225 // If this tab has an opener, ensure it has a RenderView in the given
4226 // SiteInstance as well.
4227 if (opener_)
4228 opener_route_id = opener_->CreateOpenerRenderViews(instance);
4230 // If any of the renderers (current, pending, or swapped out) for this
4231 // WebContents has the same SiteInstance, use it.
4232 if (GetRenderManager()->current_host()->GetSiteInstance() == instance)
4233 return GetRenderManager()->current_host()->GetRoutingID();
4235 if (GetRenderManager()->pending_render_view_host() &&
4236 GetRenderManager()->pending_render_view_host()->GetSiteInstance() ==
4237 instance)
4238 return GetRenderManager()->pending_render_view_host()->GetRoutingID();
4240 RenderViewHostImpl* rvh = GetRenderManager()->GetSwappedOutRenderViewHost(
4241 instance);
4242 if (rvh)
4243 return rvh->GetRoutingID();
4245 // Create a swapped out RenderView in the given SiteInstance if none exists,
4246 // setting its opener to the given route_id. Return the new view's route_id.
4247 int render_view_routing_id = MSG_ROUTING_NONE;
4248 GetRenderManager()->CreateRenderFrame(instance, nullptr, opener_route_id,
4249 CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
4250 CREATE_RF_SWAPPED_OUT |
4251 CREATE_RF_HIDDEN,
4252 &render_view_routing_id);
4253 return render_view_routing_id;
4256 NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
4257 return GetController();
4260 scoped_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderManager(
4261 const GURL& url) {
4262 return scoped_ptr<WebUIImpl>(static_cast<WebUIImpl*>(CreateWebUI(url)));
4265 NavigationEntry*
4266 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4267 return controller_.GetLastCommittedEntry();
4270 bool WebContentsImpl::CreateRenderViewForRenderManager(
4271 RenderViewHost* render_view_host,
4272 int opener_route_id,
4273 int proxy_routing_id,
4274 bool for_main_frame_navigation) {
4275 TRACE_EVENT0("browser,navigation",
4276 "WebContentsImpl::CreateRenderViewForRenderManager");
4277 // Can be NULL during tests.
4278 RenderWidgetHostViewBase* rwh_view;
4279 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
4280 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
4281 // case this because RWH is still a base class of RenderViewHost, and child
4282 // frame RWHVs are unique in that they do not have their own WebContents.
4283 if (!for_main_frame_navigation) {
4284 RenderWidgetHostViewChildFrame* rwh_view_child =
4285 new RenderWidgetHostViewChildFrame(render_view_host);
4286 rwh_view = rwh_view_child;
4287 } else {
4288 rwh_view = view_->CreateViewForWidget(render_view_host, false);
4291 // Now that the RenderView has been created, we need to tell it its size.
4292 if (rwh_view)
4293 rwh_view->SetSize(GetSizeForNewRenderView());
4295 // Make sure we use the correct starting page_id in the new RenderView.
4296 UpdateMaxPageIDIfNecessary(render_view_host);
4297 int32 max_page_id =
4298 GetMaxPageIDForSiteInstance(render_view_host->GetSiteInstance());
4300 if (!static_cast<RenderViewHostImpl*>(
4301 render_view_host)->CreateRenderView(base::string16(),
4302 opener_route_id,
4303 proxy_routing_id,
4304 max_page_id,
4305 created_with_opener_)) {
4306 return false;
4309 SetHistoryOffsetAndLengthForView(render_view_host,
4310 controller_.GetLastCommittedEntryIndex(),
4311 controller_.GetEntryCount());
4313 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4314 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4315 // linux. See crbug.com/83941.
4316 if (rwh_view) {
4317 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
4318 render_widget_host->WasResized();
4320 #endif
4322 return true;
4325 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4326 RenderFrameHost* render_frame_host,
4327 int parent_routing_id,
4328 int proxy_routing_id) {
4329 TRACE_EVENT0("browser,navigation",
4330 "WebContentsImpl::CreateRenderFrameForRenderManager");
4332 RenderFrameHostImpl* rfh =
4333 static_cast<RenderFrameHostImpl*>(render_frame_host);
4334 if (!rfh->CreateRenderFrame(parent_routing_id, proxy_routing_id))
4335 return false;
4337 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4338 // RenderFrameHost will have to be associated with the appropriate
4339 // RenderWidgetHostView or a new one should be created here.
4341 return true;
4344 #if defined(OS_ANDROID)
4346 base::android::ScopedJavaLocalRef<jobject>
4347 WebContentsImpl::GetJavaWebContents() {
4348 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
4349 return GetWebContentsAndroid()->GetJavaObject();
4352 WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
4353 WebContentsAndroid* web_contents_android =
4354 static_cast<WebContentsAndroid*>(GetUserData(kWebContentsAndroidKey));
4355 if (!web_contents_android) {
4356 web_contents_android = new WebContentsAndroid(this);
4357 SetUserData(kWebContentsAndroidKey, web_contents_android);
4359 return web_contents_android;
4362 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4363 return CreateRenderViewForRenderManager(GetRenderViewHost(),
4364 MSG_ROUTING_NONE,
4365 MSG_ROUTING_NONE,
4366 true);
4369 #elif defined(OS_MACOSX)
4371 void WebContentsImpl::SetAllowOtherViews(bool allow) {
4372 view_->SetAllowOtherViews(allow);
4375 bool WebContentsImpl::GetAllowOtherViews() {
4376 return view_->GetAllowOtherViews();
4379 #endif
4381 void WebContentsImpl::OnDialogClosed(int render_process_id,
4382 int render_frame_id,
4383 IPC::Message* reply_msg,
4384 bool dialog_was_suppressed,
4385 bool success,
4386 const base::string16& user_input) {
4387 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
4388 render_frame_id);
4389 last_dialog_suppressed_ = dialog_was_suppressed;
4391 if (is_showing_before_unload_dialog_ && !success) {
4392 // If a beforeunload dialog is canceled, we need to stop the throbber from
4393 // spinning, since we forced it to start spinning in Navigate.
4394 if (rfh)
4395 DidStopLoading(rfh);
4396 controller_.DiscardNonCommittedEntries();
4398 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4399 BeforeUnloadDialogCancelled());
4402 is_showing_before_unload_dialog_ = false;
4403 if (rfh) {
4404 rfh->JavaScriptDialogClosed(reply_msg, success, user_input,
4405 dialog_was_suppressed);
4406 } else {
4407 // Don't leak the sync IPC reply if the RFH or process is gone.
4408 delete reply_msg;
4412 void WebContentsImpl::SetEncoding(const std::string& encoding) {
4413 if (encoding == last_reported_encoding_)
4414 return;
4415 last_reported_encoding_ = encoding;
4417 canonical_encoding_ = GetContentClient()->browser()->
4418 GetCanonicalEncodingNameByAliasName(encoding);
4421 bool WebContentsImpl::IsHidden() {
4422 return capturer_count_ == 0 && !should_normally_be_visible_;
4425 RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
4426 return frame_tree_.root()->render_manager();
4429 RenderViewHostImpl* WebContentsImpl::GetRenderViewHostImpl() {
4430 return static_cast<RenderViewHostImpl*>(GetRenderViewHost());
4433 BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
4434 return browser_plugin_guest_.get();
4437 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest* guest) {
4438 CHECK(!browser_plugin_guest_);
4439 browser_plugin_guest_.reset(guest);
4442 BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
4443 return browser_plugin_embedder_.get();
4446 void WebContentsImpl::ClearPowerSaveBlockers(
4447 RenderFrameHost* render_frame_host) {
4448 RemoveAllMediaPlayerEntries(render_frame_host, &active_audio_players_);
4449 RemoveAllMediaPlayerEntries(render_frame_host, &active_video_players_);
4450 MaybeReleasePowerSaveBlockers();
4453 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4454 active_audio_players_.clear();
4455 active_video_players_.clear();
4456 audio_power_save_blocker_.reset();
4457 video_power_save_blocker_.reset();
4460 gfx::Size WebContentsImpl::GetSizeForNewRenderView() {
4461 gfx::Size size;
4462 if (delegate_)
4463 size = delegate_->GetSizeForNewRenderView(this);
4464 if (size.IsEmpty())
4465 size = GetContainerBounds().size();
4466 return size;
4469 void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
4470 FOR_EACH_OBSERVER(
4471 WebContentsObserver, observers_, FrameDeleted(render_frame_host));
4474 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
4475 if (!delegate_)
4476 return;
4477 const gfx::Size new_size = GetPreferredSize();
4478 if (new_size != old_size)
4479 delegate_->UpdatePreferredSize(this, new_size);
4482 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie,
4483 ActiveMediaPlayerMap* player_map) {
4484 if (!HasValidFrameSource())
4485 return;
4487 const uintptr_t key =
4488 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4489 DCHECK(std::find((*player_map)[key].begin(),
4490 (*player_map)[key].end(),
4491 player_cookie) == (*player_map)[key].end());
4492 (*player_map)[key].push_back(player_cookie);
4495 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie,
4496 ActiveMediaPlayerMap* player_map) {
4497 if (!HasValidFrameSource())
4498 return;
4500 const uintptr_t key =
4501 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4502 ActiveMediaPlayerMap::iterator it = player_map->find(key);
4503 if (it == player_map->end())
4504 return;
4506 // Remove the player.
4507 PlayerList::iterator player_it =
4508 std::find(it->second.begin(), it->second.end(), player_cookie);
4509 if (player_it != it->second.end())
4510 it->second.erase(player_it);
4512 // If there are no players left, remove the map entry.
4513 if (it->second.empty())
4514 player_map->erase(it);
4517 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4518 RenderFrameHost* render_frame_host,
4519 ActiveMediaPlayerMap* player_map) {
4520 ActiveMediaPlayerMap::iterator it =
4521 player_map->find(reinterpret_cast<uintptr_t>(render_frame_host));
4522 if (it == player_map->end())
4523 return;
4524 player_map->erase(it);
4527 void WebContentsImpl::ResumeResponseDeferredAtStart() {
4528 FrameTreeNode* node = frame_tree_.root();
4529 node->render_manager()->ResumeResponseDeferredAtStart();
4532 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
4533 force_disable_overscroll_content_ = force_disable;
4534 if (view_)
4535 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4538 } // namespace content