Convert RenderFrameHost creation booleans to flags
[chromium-blink-merge.git] / content / browser / web_contents / web_contents_impl.cc
blobe6f8713fdb8985d0631ca19b12868461d106921c
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/debug/trace_event.h"
11 #include "base/lazy_instance.h"
12 #include "base/logging.h"
13 #include "base/metrics/histogram.h"
14 #include "base/metrics/stats_counters.h"
15 #include "base/process/process.h"
16 #include "base/strings/string16.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/time/time.h"
21 #include "content/browser/accessibility/accessibility_mode_helper.h"
22 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
23 #include "content/browser/browser_plugin/browser_plugin_embedder.h"
24 #include "content/browser/browser_plugin/browser_plugin_guest.h"
25 #include "content/browser/child_process_security_policy_impl.h"
26 #include "content/browser/devtools/devtools_manager.h"
27 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
28 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
29 #include "content/browser/download/download_stats.h"
30 #include "content/browser/download/mhtml_generation_manager.h"
31 #include "content/browser/download/save_package.h"
32 #include "content/browser/frame_host/cross_process_frame_connector.h"
33 #include "content/browser/frame_host/interstitial_page_impl.h"
34 #include "content/browser/frame_host/navigation_entry_impl.h"
35 #include "content/browser/frame_host/navigator_impl.h"
36 #include "content/browser/frame_host/render_frame_host_impl.h"
37 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
38 #include "content/browser/geolocation/geolocation_service_context.h"
39 #include "content/browser/host_zoom_map_impl.h"
40 #include "content/browser/loader/resource_dispatcher_host_impl.h"
41 #include "content/browser/manifest/manifest_manager_host.h"
42 #include "content/browser/media/audio_stream_monitor.h"
43 #include "content/browser/media/capture/web_contents_audio_muter.h"
44 #include "content/browser/media/midi_dispatcher_host.h"
45 #include "content/browser/message_port_message_filter.h"
46 #include "content/browser/message_port_service.h"
47 #include "content/browser/plugin_content_origin_whitelist.h"
48 #include "content/browser/power_save_blocker_impl.h"
49 #include "content/browser/renderer_host/render_process_host_impl.h"
50 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
51 #include "content/browser/renderer_host/render_view_host_impl.h"
52 #include "content/browser/renderer_host/render_widget_host_impl.h"
53 #include "content/browser/renderer_host/render_widget_host_view_base.h"
54 #include "content/browser/screen_orientation/screen_orientation_dispatcher_host_impl.h"
55 #include "content/browser/site_instance_impl.h"
56 #include "content/browser/web_contents/web_contents_view_guest.h"
57 #include "content/browser/webui/generic_handler.h"
58 #include "content/browser/webui/web_ui_controller_factory_registry.h"
59 #include "content/browser/webui/web_ui_impl.h"
60 #include "content/common/browser_plugin/browser_plugin_constants.h"
61 #include "content/common/browser_plugin/browser_plugin_messages.h"
62 #include "content/common/frame_messages.h"
63 #include "content/common/image_messages.h"
64 #include "content/common/input_messages.h"
65 #include "content/common/ssl_status_serialization.h"
66 #include "content/common/view_messages.h"
67 #include "content/public/browser/ax_event_notification_details.h"
68 #include "content/public/browser/browser_context.h"
69 #include "content/public/browser/browser_plugin_guest_manager.h"
70 #include "content/public/browser/content_browser_client.h"
71 #include "content/public/browser/devtools_agent_host.h"
72 #include "content/public/browser/download_manager.h"
73 #include "content/public/browser/download_url_parameters.h"
74 #include "content/public/browser/invalidate_type.h"
75 #include "content/public/browser/javascript_dialog_manager.h"
76 #include "content/public/browser/load_from_memory_cache_details.h"
77 #include "content/public/browser/load_notification_details.h"
78 #include "content/public/browser/navigation_details.h"
79 #include "content/public/browser/notification_details.h"
80 #include "content/public/browser/notification_service.h"
81 #include "content/public/browser/render_widget_host_iterator.h"
82 #include "content/public/browser/resource_request_details.h"
83 #include "content/public/browser/screen_orientation_dispatcher_host.h"
84 #include "content/public/browser/storage_partition.h"
85 #include "content/public/browser/user_metrics.h"
86 #include "content/public/browser/web_contents_delegate.h"
87 #include "content/public/browser/web_contents_observer.h"
88 #include "content/public/common/bindings_policy.h"
89 #include "content/public/common/content_constants.h"
90 #include "content/public/common/content_switches.h"
91 #include "content/public/common/page_zoom.h"
92 #include "content/public/common/result_codes.h"
93 #include "content/public/common/url_constants.h"
94 #include "content/public/common/url_utils.h"
95 #include "content/public/common/web_preferences.h"
96 #include "net/base/mime_util.h"
97 #include "net/base/net_util.h"
98 #include "net/http/http_cache.h"
99 #include "net/http/http_transaction_factory.h"
100 #include "net/url_request/url_request_context.h"
101 #include "net/url_request/url_request_context_getter.h"
102 #include "ui/base/layout.h"
103 #include "ui/gfx/display.h"
104 #include "ui/gfx/screen.h"
105 #include "ui/gl/gl_switches.h"
107 #if defined(OS_ANDROID)
108 #include "content/browser/android/date_time_chooser_android.h"
109 #include "content/browser/media/android/browser_media_player_manager.h"
110 #include "content/browser/web_contents/web_contents_android.h"
111 #endif
113 #if defined(OS_MACOSX)
114 #include "base/mac/foundation_util.h"
115 #endif
117 namespace content {
118 namespace {
120 const int kMinimumDelayBetweenLoadingUpdatesMS = 100;
122 // This matches what Blink's ProgressTracker has traditionally used for a
123 // minimum progress value.
124 const double kMinimumLoadingProgress = 0.1;
126 const char kDotGoogleDotCom[] = ".google.com";
128 #if defined(OS_ANDROID)
129 const char kWebContentsAndroidKey[] = "web_contents_android";
130 #endif // OS_ANDROID
132 base::LazyInstance<std::vector<WebContentsImpl::CreatedCallback> >
133 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
135 static int StartDownload(RenderFrameHost* rfh,
136 const GURL& url,
137 bool is_favicon,
138 uint32_t max_bitmap_size) {
139 static int g_next_image_download_id = 0;
140 rfh->Send(new ImageMsg_DownloadImage(rfh->GetRoutingID(),
141 ++g_next_image_download_id,
142 url,
143 is_favicon,
144 max_bitmap_size));
145 return g_next_image_download_id;
148 void NotifyCacheOnIO(
149 scoped_refptr<net::URLRequestContextGetter> request_context,
150 const GURL& url,
151 const std::string& http_method) {
152 request_context->GetURLRequestContext()->http_transaction_factory()->
153 GetCache()->OnExternalCacheHit(url, http_method);
156 // Helper function for retrieving all the sites in a frame tree.
157 bool CollectSites(BrowserContext* context,
158 std::set<GURL>* sites,
159 FrameTreeNode* node) {
160 sites->insert(SiteInstance::GetSiteForURL(context, node->current_url()));
161 return true;
164 bool ForEachFrameInternal(
165 const base::Callback<void(RenderFrameHost*)>& on_frame,
166 FrameTreeNode* node) {
167 on_frame.Run(node->current_frame_host());
168 return true;
171 bool ForEachPendingFrameInternal(
172 const base::Callback<void(RenderFrameHost*)>& on_frame,
173 FrameTreeNode* node) {
174 RenderFrameHost* pending_frame_host =
175 node->render_manager()->pending_frame_host();
176 if (pending_frame_host)
177 on_frame.Run(pending_frame_host);
178 return true;
181 void SendToAllFramesInternal(IPC::Message* message, RenderFrameHost* rfh) {
182 IPC::Message* message_copy = new IPC::Message(*message);
183 message_copy->set_routing_id(rfh->GetRoutingID());
184 rfh->Send(message_copy);
187 void AddRenderWidgetHostViewToSet(std::set<RenderWidgetHostView*>* set,
188 RenderFrameHost* rfh) {
189 RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
190 ->frame_tree_node()
191 ->render_manager()
192 ->GetRenderWidgetHostView();
193 set->insert(rwhv);
196 void SetAccessibilityModeOnFrame(AccessibilityMode mode,
197 RenderFrameHost* frame_host) {
198 static_cast<RenderFrameHostImpl*>(frame_host)->SetAccessibilityMode(mode);
201 } // namespace
203 WebContents* WebContents::Create(const WebContents::CreateParams& params) {
204 return WebContentsImpl::CreateWithOpener(
205 params, static_cast<WebContentsImpl*>(params.opener));
208 WebContents* WebContents::CreateWithSessionStorage(
209 const WebContents::CreateParams& params,
210 const SessionStorageNamespaceMap& session_storage_namespace_map) {
211 WebContentsImpl* new_contents = new WebContentsImpl(
212 params.browser_context, NULL);
214 for (SessionStorageNamespaceMap::const_iterator it =
215 session_storage_namespace_map.begin();
216 it != session_storage_namespace_map.end();
217 ++it) {
218 new_contents->GetController()
219 .SetSessionStorageNamespace(it->first, it->second.get());
222 new_contents->Init(params);
223 return new_contents;
226 void WebContentsImpl::AddCreatedCallback(const CreatedCallback& callback) {
227 g_created_callbacks.Get().push_back(callback);
230 void WebContentsImpl::RemoveCreatedCallback(const CreatedCallback& callback) {
231 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
232 if (g_created_callbacks.Get().at(i).Equals(callback)) {
233 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
234 return;
239 WebContents* WebContents::FromRenderViewHost(const RenderViewHost* rvh) {
240 return rvh->GetDelegate()->GetAsWebContents();
243 WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
244 RenderFrameHostImpl* rfh_impl = static_cast<RenderFrameHostImpl*>(rfh);
245 if (!rfh_impl)
246 return NULL;
247 return rfh_impl->delegate()->GetAsWebContents();
250 // WebContentsImpl::DestructionObserver ----------------------------------------
252 class WebContentsImpl::DestructionObserver : public WebContentsObserver {
253 public:
254 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
255 : WebContentsObserver(watched_contents),
256 owner_(owner) {
259 // WebContentsObserver:
260 void WebContentsDestroyed() override {
261 owner_->OnWebContentsDestroyed(
262 static_cast<WebContentsImpl*>(web_contents()));
265 private:
266 WebContentsImpl* owner_;
268 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
271 WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id,
272 int render_frame_id,
273 ColorChooser* chooser,
274 int identifier)
275 : render_process_id(render_process_id),
276 render_frame_id(render_frame_id),
277 chooser(chooser),
278 identifier(identifier) {
281 WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
284 // WebContentsImpl -------------------------------------------------------------
286 WebContentsImpl::WebContentsImpl(BrowserContext* browser_context,
287 WebContentsImpl* opener)
288 : delegate_(NULL),
289 controller_(this, browser_context),
290 render_view_host_delegate_view_(NULL),
291 opener_(opener),
292 created_with_opener_(!!opener),
293 #if defined(OS_WIN)
294 accessible_parent_(NULL),
295 #endif
296 frame_tree_(new NavigatorImpl(&controller_, this),
297 this,
298 this,
299 this,
300 this),
301 is_loading_(false),
302 is_load_to_different_document_(false),
303 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
304 crashed_error_code_(0),
305 waiting_for_response_(false),
306 load_state_(net::LOAD_STATE_IDLE, base::string16()),
307 loading_total_progress_(0.0),
308 loading_frames_in_progress_(0),
309 upload_size_(0),
310 upload_position_(0),
311 displayed_insecure_content_(false),
312 has_accessed_initial_document_(false),
313 capturer_count_(0),
314 should_normally_be_visible_(true),
315 is_being_destroyed_(false),
316 notify_disconnection_(false),
317 dialog_manager_(NULL),
318 is_showing_before_unload_dialog_(false),
319 last_active_time_(base::TimeTicks::Now()),
320 closed_by_user_gesture_(false),
321 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)),
322 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)),
323 totalPinchGestureAmount_(0),
324 currentPinchZoomStepDelta_(0),
325 render_view_message_source_(NULL),
326 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
327 fullscreen_widget_had_focus_at_shutdown_(false),
328 is_subframe_(false),
329 force_disable_overscroll_content_(false),
330 last_dialog_suppressed_(false),
331 geolocation_service_context_(new GeolocationServiceContext()),
332 accessibility_mode_(
333 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
334 audio_stream_monitor_(this),
335 loading_weak_factory_(this) {
336 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
337 g_created_callbacks.Get().at(i).Run(this);
338 frame_tree_.SetFrameRemoveListener(
339 base::Bind(&WebContentsImpl::OnFrameRemoved,
340 base::Unretained(this)));
343 WebContentsImpl::~WebContentsImpl() {
344 is_being_destroyed_ = true;
346 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
347 // shutdown and be deleted as well.
348 frame_tree_.ForEach(
349 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown));
351 ClearAllPowerSaveBlockers();
353 for (std::set<RenderWidgetHostImpl*>::iterator iter =
354 created_widgets_.begin(); iter != created_widgets_.end(); ++iter) {
355 (*iter)->DetachDelegate();
357 created_widgets_.clear();
359 // Clear out any JavaScript state.
360 if (dialog_manager_)
361 dialog_manager_->WebContentsDestroyed(this);
363 if (color_chooser_info_.get())
364 color_chooser_info_->chooser->End();
366 NotifyDisconnected();
368 // Notify any observer that have a reference on this WebContents.
369 NotificationService::current()->Notify(
370 NOTIFICATION_WEB_CONTENTS_DESTROYED,
371 Source<WebContents>(this),
372 NotificationService::NoDetails());
374 // Destroy all frame tree nodes except for the root; this notifies observers.
375 frame_tree_.ResetForMainFrameSwap();
376 GetRenderManager()->ResetProxyHosts();
378 // Manually call the observer methods for the root frame tree node.
379 RenderFrameHostManager* root = GetRenderManager();
380 if (root->pending_frame_host()) {
381 FOR_EACH_OBSERVER(WebContentsObserver,
382 observers_,
383 RenderFrameDeleted(root->pending_frame_host()));
385 FOR_EACH_OBSERVER(WebContentsObserver,
386 observers_,
387 RenderFrameDeleted(root->current_frame_host()));
389 if (root->pending_render_view_host()) {
390 FOR_EACH_OBSERVER(WebContentsObserver,
391 observers_,
392 RenderViewDeleted(root->pending_render_view_host()));
395 FOR_EACH_OBSERVER(WebContentsObserver,
396 observers_,
397 RenderViewDeleted(root->current_host()));
399 FOR_EACH_OBSERVER(WebContentsObserver,
400 observers_,
401 WebContentsDestroyed());
403 FOR_EACH_OBSERVER(WebContentsObserver,
404 observers_,
405 ResetWebContents());
407 SetDelegate(NULL);
409 STLDeleteContainerPairSecondPointers(destruction_observers_.begin(),
410 destruction_observers_.end());
413 WebContentsImpl* WebContentsImpl::CreateWithOpener(
414 const WebContents::CreateParams& params,
415 WebContentsImpl* opener) {
416 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
417 WebContentsImpl* new_contents = new WebContentsImpl(
418 params.browser_context, params.opener_suppressed ? NULL : opener);
420 if (params.guest_delegate) {
421 // This makes |new_contents| act as a guest.
422 // For more info, see comment above class BrowserPluginGuest.
423 BrowserPluginGuest::Create(new_contents, params.guest_delegate);
424 // We are instantiating a WebContents for browser plugin. Set its subframe
425 // bit to true.
426 new_contents->is_subframe_ = true;
428 new_contents->Init(params);
429 return new_contents;
432 // static
433 std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
434 std::vector<WebContentsImpl*> result;
435 scoped_ptr<RenderWidgetHostIterator> widgets(
436 RenderWidgetHostImpl::GetRenderWidgetHosts());
437 std::set<WebContentsImpl*> web_contents_set;
438 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
439 if (!rwh->IsRenderView())
440 continue;
441 RenderViewHost* rvh = RenderViewHost::From(rwh);
442 if (!rvh)
443 continue;
444 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
445 if (!web_contents)
446 continue;
447 WebContentsImpl* wci = static_cast<WebContentsImpl*>(web_contents);
448 if (web_contents_set.find(wci) == web_contents_set.end()) {
449 web_contents_set.insert(wci);
450 result.push_back(wci);
453 return result;
456 RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
457 return GetRenderManager();
460 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
461 const IPC::Message& message) {
462 return OnMessageReceived(render_view_host, NULL, message);
465 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
466 RenderFrameHost* render_frame_host,
467 const IPC::Message& message) {
468 DCHECK(render_view_host || render_frame_host);
469 if (GetWebUI() &&
470 static_cast<WebUIImpl*>(GetWebUI())->OnMessageReceived(message)) {
471 return true;
474 ObserverListBase<WebContentsObserver>::Iterator it(observers_);
475 WebContentsObserver* observer;
476 if (render_frame_host) {
477 while ((observer = it.GetNext()) != NULL)
478 if (observer->OnMessageReceived(message, render_frame_host))
479 return true;
480 } else {
481 while ((observer = it.GetNext()) != NULL)
482 if (observer->OnMessageReceived(message))
483 return true;
486 // Message handlers should be aware of which
487 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
488 // stored in render_(view|frame)_message_source_.
489 if (render_frame_host)
490 render_frame_message_source_ = render_frame_host;
491 else
492 render_view_message_source_ = render_view_host;
494 bool handled = true;
495 IPC_BEGIN_MESSAGE_MAP(WebContentsImpl, message)
496 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse,
497 OnDomOperationResponse)
498 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor,
499 OnThemeColorChanged)
500 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad,
501 OnDocumentLoadedInFrame)
502 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad, OnDidFinishLoad)
503 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading)
504 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
505 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
506 OnDidChangeLoadProgress)
507 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser, OnOpenColorChooser)
508 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser, OnEndColorChooser)
509 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser,
510 OnSetSelectedColorInColorChooser)
511 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification,
512 OnMediaPlayingNotification)
513 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification,
514 OnMediaPausedNotification)
515 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFirstVisuallyNonEmptyPaint,
516 OnFirstVisuallyNonEmptyPaint)
517 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache,
518 OnDidLoadResourceFromMemoryCache)
519 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent,
520 OnDidDisplayInsecureContent)
521 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent,
522 OnDidRunInsecureContent)
523 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset)
524 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits, OnUpdateZoomLimits)
525 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory, OnEnumerateDirectory)
526 IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler,
527 OnRegisterProtocolHandler)
528 IPC_MESSAGE_HANDLER(ViewHostMsg_UnregisterProtocolHandler,
529 OnUnregisterProtocolHandler)
530 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply, OnFindReply)
531 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed, OnAppCacheAccessed)
532 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend, OnWebUISend)
533 #if defined(ENABLE_PLUGINS)
534 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
535 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
536 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
537 OnRequestPpapiBrokerPermission)
538 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach,
539 OnBrowserPluginMessage(message))
540 #endif
541 IPC_MESSAGE_HANDLER(ImageHostMsg_DidDownloadImage, OnDidDownloadImage)
542 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL, OnUpdateFaviconURL)
543 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage,
544 OnShowValidationMessage)
545 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage,
546 OnHideValidationMessage)
547 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage,
548 OnMoveValidationMessage)
549 #if defined(OS_ANDROID)
550 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply,
551 OnFindMatchRectsReply)
552 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog,
553 OnOpenDateTimeDialog)
554 #endif
555 IPC_MESSAGE_UNHANDLED(handled = false)
556 IPC_END_MESSAGE_MAP()
557 render_view_message_source_ = NULL;
558 render_frame_message_source_ = NULL;
560 return handled;
563 void WebContentsImpl::RunFileChooser(
564 RenderViewHost* render_view_host,
565 const FileChooserParams& params) {
566 if (delegate_)
567 delegate_->RunFileChooser(this, params);
570 NavigationControllerImpl& WebContentsImpl::GetController() {
571 return controller_;
574 const NavigationControllerImpl& WebContentsImpl::GetController() const {
575 return controller_;
578 BrowserContext* WebContentsImpl::GetBrowserContext() const {
579 return controller_.GetBrowserContext();
582 const GURL& WebContentsImpl::GetURL() const {
583 // We may not have a navigation entry yet.
584 NavigationEntry* entry = controller_.GetVisibleEntry();
585 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
588 const GURL& WebContentsImpl::GetVisibleURL() const {
589 // We may not have a navigation entry yet.
590 NavigationEntry* entry = controller_.GetVisibleEntry();
591 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
594 const GURL& WebContentsImpl::GetLastCommittedURL() const {
595 // We may not have a navigation entry yet.
596 NavigationEntry* entry = controller_.GetLastCommittedEntry();
597 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
600 WebContentsDelegate* WebContentsImpl::GetDelegate() {
601 return delegate_;
604 void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
605 // TODO(cbentzel): remove this debugging code?
606 if (delegate == delegate_)
607 return;
608 if (delegate_)
609 delegate_->Detach(this);
610 delegate_ = delegate;
611 if (delegate_) {
612 delegate_->Attach(this);
613 // Ensure the visible RVH reflects the new delegate's preferences.
614 if (view_)
615 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
619 RenderProcessHost* WebContentsImpl::GetRenderProcessHost() const {
620 RenderViewHostImpl* host = GetRenderManager()->current_host();
621 return host ? host->GetProcess() : NULL;
624 RenderFrameHost* WebContentsImpl::GetMainFrame() {
625 return frame_tree_.root()->current_frame_host();
628 RenderFrameHost* WebContentsImpl::GetFocusedFrame() {
629 if (!frame_tree_.GetFocusedFrame())
630 return NULL;
631 return frame_tree_.GetFocusedFrame()->current_frame_host();
634 void WebContentsImpl::ForEachFrame(
635 const base::Callback<void(RenderFrameHost*)>& on_frame) {
636 frame_tree_.ForEach(base::Bind(&ForEachFrameInternal, on_frame));
639 void WebContentsImpl::SendToAllFrames(IPC::Message* message) {
640 ForEachFrame(base::Bind(&SendToAllFramesInternal, message));
641 delete message;
644 RenderViewHost* WebContentsImpl::GetRenderViewHost() const {
645 return GetRenderManager()->current_host();
648 int WebContentsImpl::GetRoutingID() const {
649 if (!GetRenderViewHost())
650 return MSG_ROUTING_NONE;
652 return GetRenderViewHost()->GetRoutingID();
655 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
656 return fullscreen_widget_routing_id_;
659 RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() const {
660 return GetRenderManager()->GetRenderWidgetHostView();
663 RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView()
664 const {
665 RenderWidgetHost* const widget_host =
666 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
667 GetFullscreenWidgetRoutingID());
668 return widget_host ? widget_host->GetView() : NULL;
671 WebContentsView* WebContentsImpl::GetView() const {
672 return view_.get();
675 void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode) {
676 if (mode == accessibility_mode_)
677 return;
679 accessibility_mode_ = mode;
680 frame_tree_.ForEach(
681 base::Bind(&ForEachFrameInternal,
682 base::Bind(&SetAccessibilityModeOnFrame, mode)));
683 frame_tree_.ForEach(
684 base::Bind(&ForEachPendingFrameInternal,
685 base::Bind(&SetAccessibilityModeOnFrame, mode)));
688 void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode) {
689 SetAccessibilityMode(AddAccessibilityModeTo(accessibility_mode_, mode));
692 void WebContentsImpl::RemoveAccessibilityMode(AccessibilityMode mode) {
693 SetAccessibilityMode(RemoveAccessibilityModeFrom(accessibility_mode_, mode));
696 void WebContentsImpl::ClearNavigationTransitionData() {
697 FrameTreeNode* node = frame_tree_.root();
698 node->render_manager()->ClearNavigationTransitionData();
701 WebUI* WebContentsImpl::CreateWebUI(const GURL& url) {
702 WebUIImpl* web_ui = new WebUIImpl(this);
703 WebUIController* controller = WebUIControllerFactoryRegistry::GetInstance()->
704 CreateWebUIControllerForURL(web_ui, url);
705 if (controller) {
706 web_ui->AddMessageHandler(new GenericHandler());
707 web_ui->SetController(controller);
708 return web_ui;
711 delete web_ui;
712 return NULL;
715 WebUI* WebContentsImpl::GetWebUI() const {
716 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
717 : GetRenderManager()->pending_web_ui();
720 WebUI* WebContentsImpl::GetCommittedWebUI() const {
721 return GetRenderManager()->web_ui();
724 void WebContentsImpl::SetUserAgentOverride(const std::string& override) {
725 if (GetUserAgentOverride() == override)
726 return;
728 renderer_preferences_.user_agent_override = override;
730 // Send the new override string to the renderer.
731 RenderViewHost* host = GetRenderViewHost();
732 if (host)
733 host->SyncRendererPrefs();
735 // Reload the page if a load is currently in progress to avoid having
736 // different parts of the page loaded using different user agents.
737 NavigationEntry* entry = controller_.GetVisibleEntry();
738 if (is_loading_ && entry != NULL && entry->GetIsOverridingUserAgent())
739 controller_.ReloadIgnoringCache(true);
741 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
742 UserAgentOverrideSet(override));
745 const std::string& WebContentsImpl::GetUserAgentOverride() const {
746 return renderer_preferences_.user_agent_override;
749 void WebContentsImpl::EnableTreeOnlyAccessibilityMode() {
750 AddAccessibilityMode(AccessibilityModeTreeOnly);
753 bool WebContentsImpl::IsTreeOnlyAccessibilityModeForTesting() const {
754 return accessibility_mode_ == AccessibilityModeTreeOnly;
757 bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
758 return accessibility_mode_ == AccessibilityModeComplete;
761 #if defined(OS_WIN)
762 void WebContentsImpl::SetParentNativeViewAccessible(
763 gfx::NativeViewAccessible accessible_parent) {
764 accessible_parent_ = accessible_parent;
765 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
766 if (rfh)
767 rfh->SetParentNativeViewAccessible(accessible_parent);
769 #endif
771 const base::string16& WebContentsImpl::GetTitle() const {
772 // Transient entries take precedence. They are used for interstitial pages
773 // that are shown on top of existing pages.
774 NavigationEntry* entry = controller_.GetTransientEntry();
775 std::string accept_languages =
776 GetContentClient()->browser()->GetAcceptLangs(
777 GetBrowserContext());
778 if (entry) {
779 return entry->GetTitleForDisplay(accept_languages);
781 WebUI* our_web_ui = GetRenderManager()->pending_web_ui() ?
782 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
783 if (our_web_ui) {
784 // Don't override the title in view source mode.
785 entry = controller_.GetVisibleEntry();
786 if (!(entry && entry->IsViewSourceMode())) {
787 // Give the Web UI the chance to override our title.
788 const base::string16& title = our_web_ui->GetOverriddenTitle();
789 if (!title.empty())
790 return title;
794 // We use the title for the last committed entry rather than a pending
795 // navigation entry. For example, when the user types in a URL, we want to
796 // keep the old page's title until the new load has committed and we get a new
797 // title.
798 entry = controller_.GetLastCommittedEntry();
800 // We make an exception for initial navigations.
801 if (controller_.IsInitialNavigation()) {
802 // We only want to use the title from the visible entry in one of two cases:
803 // 1. There's already a committed entry for an initial navigation, in which
804 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
805 // 2. The pending entry has been explicitly assigned a title to display.
807 // If there's no last committed entry and no assigned title, we should fall
808 // back to |page_title_when_no_navigation_entry_| rather than showing the
809 // URL.
810 if (entry ||
811 (controller_.GetVisibleEntry() &&
812 !controller_.GetVisibleEntry()->GetTitle().empty())) {
813 entry = controller_.GetVisibleEntry();
817 if (entry) {
818 return entry->GetTitleForDisplay(accept_languages);
821 // |page_title_when_no_navigation_entry_| is finally used
822 // if no title cannot be retrieved.
823 return page_title_when_no_navigation_entry_;
826 int32 WebContentsImpl::GetMaxPageID() {
827 return GetMaxPageIDForSiteInstance(GetSiteInstance());
830 int32 WebContentsImpl::GetMaxPageIDForSiteInstance(
831 SiteInstance* site_instance) {
832 if (max_page_ids_.find(site_instance->GetId()) == max_page_ids_.end())
833 max_page_ids_[site_instance->GetId()] = -1;
835 return max_page_ids_[site_instance->GetId()];
838 void WebContentsImpl::UpdateMaxPageID(int32 page_id) {
839 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id);
842 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
843 SiteInstance* site_instance, int32 page_id) {
844 if (GetMaxPageIDForSiteInstance(site_instance) < page_id)
845 max_page_ids_[site_instance->GetId()] = page_id;
848 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents* web_contents) {
849 WebContentsImpl* contents = static_cast<WebContentsImpl*>(web_contents);
850 max_page_ids_ = contents->max_page_ids_;
853 SiteInstanceImpl* WebContentsImpl::GetSiteInstance() const {
854 return GetRenderManager()->current_host()->GetSiteInstance();
857 SiteInstanceImpl* WebContentsImpl::GetPendingSiteInstance() const {
858 RenderViewHostImpl* dest_rvh =
859 GetRenderManager()->pending_render_view_host() ?
860 GetRenderManager()->pending_render_view_host() :
861 GetRenderManager()->current_host();
862 return dest_rvh->GetSiteInstance();
865 bool WebContentsImpl::IsLoading() const {
866 return is_loading_;
869 bool WebContentsImpl::IsLoadingToDifferentDocument() const {
870 return is_loading_ && is_load_to_different_document_;
873 bool WebContentsImpl::IsWaitingForResponse() const {
874 return waiting_for_response_ && is_load_to_different_document_;
877 const net::LoadStateWithParam& WebContentsImpl::GetLoadState() const {
878 return load_state_;
881 const base::string16& WebContentsImpl::GetLoadStateHost() const {
882 return load_state_host_;
885 uint64 WebContentsImpl::GetUploadSize() const {
886 return upload_size_;
889 uint64 WebContentsImpl::GetUploadPosition() const {
890 return upload_position_;
893 std::set<GURL> WebContentsImpl::GetSitesInTab() const {
894 std::set<GURL> sites;
895 frame_tree_.ForEach(base::Bind(&CollectSites,
896 base::Unretained(GetBrowserContext()),
897 base::Unretained(&sites)));
898 return sites;
901 const std::string& WebContentsImpl::GetEncoding() const {
902 return canonical_encoding_;
905 bool WebContentsImpl::DisplayedInsecureContent() const {
906 return displayed_insecure_content_;
909 void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size) {
910 DCHECK(!is_being_destroyed_);
911 ++capturer_count_;
912 DVLOG(1) << "There are now " << capturer_count_
913 << " capturing(s) of WebContentsImpl@" << this;
915 // Note: This provides a hint to upstream code to size the views optimally
916 // for quality (e.g., to avoid scaling).
917 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
918 preferred_size_for_capture_ = capture_size;
919 OnPreferredSizeChanged(preferred_size_);
923 void WebContentsImpl::DecrementCapturerCount() {
924 --capturer_count_;
925 DVLOG(1) << "There are now " << capturer_count_
926 << " capturing(s) of WebContentsImpl@" << this;
927 DCHECK_LE(0, capturer_count_);
929 if (is_being_destroyed_)
930 return;
932 if (capturer_count_ == 0) {
933 const gfx::Size old_size = preferred_size_for_capture_;
934 preferred_size_for_capture_ = gfx::Size();
935 OnPreferredSizeChanged(old_size);
938 if (IsHidden()) {
939 DVLOG(1) << "Executing delayed WasHidden().";
940 WasHidden();
944 int WebContentsImpl::GetCapturerCount() const {
945 return capturer_count_;
948 bool WebContentsImpl::IsAudioMuted() const {
949 return audio_muter_.get() && audio_muter_->is_muting();
952 void WebContentsImpl::SetAudioMuted(bool mute) {
953 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
954 << " for WebContentsImpl@" << this;
956 if (mute == IsAudioMuted())
957 return;
959 if (mute) {
960 if (!audio_muter_)
961 audio_muter_.reset(new WebContentsAudioMuter(this));
962 audio_muter_->StartMuting();
963 } else {
964 DCHECK(audio_muter_);
965 audio_muter_->StopMuting();
968 // Notification for UI updates in response to the changed muting state.
969 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
972 bool WebContentsImpl::IsCrashed() const {
973 return (crashed_status_ == base::TERMINATION_STATUS_PROCESS_CRASHED ||
974 crashed_status_ == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
975 crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
978 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
979 int error_code) {
980 if (status == crashed_status_)
981 return;
983 crashed_status_ = status;
984 crashed_error_code_ = error_code;
985 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
988 base::TerminationStatus WebContentsImpl::GetCrashedStatus() const {
989 return crashed_status_;
992 bool WebContentsImpl::IsBeingDestroyed() const {
993 return is_being_destroyed_;
996 void WebContentsImpl::NotifyNavigationStateChanged(
997 InvalidateTypes changed_flags) {
998 // Create and release the audio power save blocker depending on whether the
999 // tab is actively producing audio or not.
1000 if (changed_flags == INVALIDATE_TYPE_TAB &&
1001 AudioStreamMonitor::monitoring_available()) {
1002 if (WasRecentlyAudible()) {
1003 if (!audio_power_save_blocker_)
1004 CreateAudioPowerSaveBlocker();
1005 } else {
1006 audio_power_save_blocker_.reset();
1010 if (delegate_)
1011 delegate_->NavigationStateChanged(this, changed_flags);
1014 base::TimeTicks WebContentsImpl::GetLastActiveTime() const {
1015 return last_active_time_;
1018 void WebContentsImpl::WasShown() {
1019 controller_.SetActive(true);
1021 std::set<RenderWidgetHostView*> widgets = GetRenderWidgetHostViewsInTree();
1022 for (std::set<RenderWidgetHostView*>::iterator iter = widgets.begin();
1023 iter != widgets.end();
1024 iter++) {
1025 if (*iter) {
1026 (*iter)->Show();
1027 #if defined(OS_MACOSX)
1028 (*iter)->SetActive(true);
1029 #endif
1033 last_active_time_ = base::TimeTicks::Now();
1035 // The resize rect might have changed while this was inactive -- send the new
1036 // one to make sure it's up to date.
1037 RenderViewHostImpl* rvh =
1038 static_cast<RenderViewHostImpl*>(GetRenderViewHost());
1039 if (rvh) {
1040 rvh->ResizeRectChanged(GetRootWindowResizerRect());
1043 // Restore power save blocker if there are active video players running.
1044 if (!active_video_players_.empty() && !video_power_save_blocker_)
1045 CreateVideoPowerSaveBlocker();
1047 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasShown());
1049 should_normally_be_visible_ = true;
1052 void WebContentsImpl::WasHidden() {
1053 // If there are entities capturing screenshots or video (e.g., mirroring),
1054 // don't activate the "disable rendering" optimization.
1055 if (capturer_count_ == 0) {
1056 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1057 // open a tab in the background, then closes the tab before selecting it.
1058 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1059 // removes the |GetRenderViewHost()|; then when we actually destroy the
1060 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1061 // calls us).
1062 std::set<RenderWidgetHostView*> widgets = GetRenderWidgetHostViewsInTree();
1063 for (std::set<RenderWidgetHostView*>::iterator iter = widgets.begin();
1064 iter != widgets.end();
1065 iter++) {
1066 if (*iter)
1067 (*iter)->Hide();
1070 // Release any video power save blockers held as video is not visible.
1071 video_power_save_blocker_.reset();
1074 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasHidden());
1076 should_normally_be_visible_ = false;
1079 bool WebContentsImpl::NeedToFireBeforeUnload() {
1080 // TODO(creis): Should we fire even for interstitial pages?
1081 return WillNotifyDisconnection() &&
1082 !ShowingInterstitialPage() &&
1083 !static_cast<RenderViewHostImpl*>(
1084 GetRenderViewHost())->SuddenTerminationAllowed();
1087 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition) {
1088 static_cast<RenderFrameHostImpl*>(GetMainFrame())->DispatchBeforeUnload(
1089 for_cross_site_transition);
1092 void WebContentsImpl::Stop() {
1093 GetRenderManager()->Stop();
1094 FOR_EACH_OBSERVER(WebContentsObserver, observers_, NavigationStopped());
1097 WebContents* WebContentsImpl::Clone() {
1098 // We use our current SiteInstance since the cloned entry will use it anyway.
1099 // We pass our own opener so that the cloned page can access it if it was
1100 // before.
1101 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
1102 create_params.initial_size = GetContainerBounds().size();
1103 WebContentsImpl* tc = CreateWithOpener(create_params, opener_);
1104 tc->GetController().CopyStateFrom(controller_);
1105 FOR_EACH_OBSERVER(WebContentsObserver,
1106 observers_,
1107 DidCloneToNewWebContents(this, tc));
1108 return tc;
1111 void WebContentsImpl::Observe(int type,
1112 const NotificationSource& source,
1113 const NotificationDetails& details) {
1114 switch (type) {
1115 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
1116 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
1117 RenderWidgetHostView* view = host->GetView();
1118 if (view == GetFullscreenRenderWidgetHostView()) {
1119 // We cannot just call view_->RestoreFocus() here. On some platforms,
1120 // attempting to focus the currently-invisible WebContentsView will be
1121 // flat-out ignored. Therefore, this boolean is used to track whether
1122 // we will request focus after the fullscreen widget has been
1123 // destroyed.
1124 fullscreen_widget_had_focus_at_shutdown_ = (view && view->HasFocus());
1125 } else {
1126 for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
1127 i != pending_widget_views_.end(); ++i) {
1128 if (host->GetView() == i->second) {
1129 pending_widget_views_.erase(i);
1130 break;
1134 break;
1136 default:
1137 NOTREACHED();
1141 WebContents* WebContentsImpl::GetWebContents() {
1142 return this;
1145 void WebContentsImpl::Init(const WebContents::CreateParams& params) {
1146 // This is set before initializing the render manager since
1147 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
1148 // it should be hidden.
1149 should_normally_be_visible_ = !params.initially_hidden;
1151 GetRenderManager()->Init(
1152 params.browser_context, params.site_instance, params.routing_id,
1153 params.main_frame_routing_id);
1155 WebContentsViewDelegate* delegate =
1156 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1158 if (browser_plugin_guest_) {
1159 scoped_ptr<WebContentsView> platform_view(CreateWebContentsView(
1160 this, delegate, &render_view_host_delegate_view_));
1162 WebContentsViewGuest* rv = new WebContentsViewGuest(
1163 this, browser_plugin_guest_.get(), platform_view.Pass(),
1164 render_view_host_delegate_view_);
1165 render_view_host_delegate_view_ = rv;
1166 view_.reset(rv);
1167 } else {
1168 // Regular WebContentsView.
1169 view_.reset(CreateWebContentsView(
1170 this, delegate, &render_view_host_delegate_view_));
1172 CHECK(render_view_host_delegate_view_);
1173 CHECK(view_.get());
1175 gfx::Size initial_size = params.initial_size;
1176 view_->CreateView(initial_size, params.context);
1178 // Listen for whether our opener gets destroyed.
1179 if (opener_)
1180 AddDestructionObserver(opener_);
1182 #if defined(ENABLE_PLUGINS)
1183 plugin_content_origin_whitelist_.reset(
1184 new PluginContentOriginWhitelist(this));
1185 #endif
1187 registrar_.Add(this,
1188 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1189 NotificationService::AllBrowserContextsAndSources());
1191 midi_dispatcher_host_.reset(new MidiDispatcherHost(this));
1193 screen_orientation_dispatcher_host_.reset(
1194 new ScreenOrientationDispatcherHostImpl(this));
1196 manifest_manager_host_.reset(new ManifestManagerHost(this));
1198 #if defined(OS_ANDROID)
1199 date_time_chooser_.reset(new DateTimeChooserAndroid());
1200 #endif
1203 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
1204 RemoveDestructionObserver(web_contents);
1206 // Clear the opener if it has been closed.
1207 if (web_contents == opener_) {
1208 opener_ = NULL;
1209 return;
1211 // Clear a pending contents that has been closed before being shown.
1212 for (PendingContents::iterator iter = pending_contents_.begin();
1213 iter != pending_contents_.end();
1214 ++iter) {
1215 if (iter->second != web_contents)
1216 continue;
1217 pending_contents_.erase(iter);
1218 return;
1220 NOTREACHED();
1223 void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
1224 if (!ContainsKey(destruction_observers_, web_contents)) {
1225 destruction_observers_[web_contents] =
1226 new DestructionObserver(this, web_contents);
1230 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
1231 DestructionObservers::iterator iter =
1232 destruction_observers_.find(web_contents);
1233 if (iter != destruction_observers_.end()) {
1234 delete destruction_observers_[web_contents];
1235 destruction_observers_.erase(iter);
1239 void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
1240 observers_.AddObserver(observer);
1243 void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
1244 observers_.RemoveObserver(observer);
1247 std::set<RenderWidgetHostView*>
1248 WebContentsImpl::GetRenderWidgetHostViewsInTree() {
1249 std::set<RenderWidgetHostView*> set;
1250 if (ShowingInterstitialPage()) {
1251 set.insert(GetRenderWidgetHostView());
1252 } else {
1253 ForEachFrame(
1254 base::Bind(&AddRenderWidgetHostViewToSet, base::Unretained(&set)));
1256 return set;
1259 void WebContentsImpl::Activate() {
1260 if (delegate_)
1261 delegate_->ActivateContents(this);
1264 void WebContentsImpl::Deactivate() {
1265 if (delegate_)
1266 delegate_->DeactivateContents(this);
1269 void WebContentsImpl::LostCapture() {
1270 if (delegate_)
1271 delegate_->LostCapture();
1274 void WebContentsImpl::RenderWidgetDeleted(
1275 RenderWidgetHostImpl* render_widget_host) {
1276 if (is_being_destroyed_) {
1277 // |created_widgets_| might have been destroyed.
1278 return;
1281 std::set<RenderWidgetHostImpl*>::iterator iter =
1282 created_widgets_.find(render_widget_host);
1283 if (iter != created_widgets_.end())
1284 created_widgets_.erase(iter);
1286 if (render_widget_host &&
1287 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_) {
1288 if (delegate_ && delegate_->EmbedsFullscreenWidget())
1289 delegate_->ToggleFullscreenModeForTab(this, false);
1290 FOR_EACH_OBSERVER(WebContentsObserver,
1291 observers_,
1292 DidDestroyFullscreenWidget(
1293 fullscreen_widget_routing_id_));
1294 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
1295 if (fullscreen_widget_had_focus_at_shutdown_)
1296 view_->RestoreFocus();
1300 void WebContentsImpl::RenderWidgetGotFocus(
1301 RenderWidgetHostImpl* render_widget_host) {
1302 // Notify the delegate if an embedded fullscreen widget was focused.
1303 if (delegate_ && render_widget_host &&
1304 delegate_->EmbedsFullscreenWidget() &&
1305 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView())
1306 delegate_->WebContentsFocused(this);
1309 bool WebContentsImpl::PreHandleKeyboardEvent(
1310 const NativeWebKeyboardEvent& event,
1311 bool* is_keyboard_shortcut) {
1312 return delegate_ &&
1313 delegate_->PreHandleKeyboardEvent(this, event, is_keyboard_shortcut);
1316 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1317 if (browser_plugin_embedder_ &&
1318 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
1319 return;
1321 if (delegate_)
1322 delegate_->HandleKeyboardEvent(this, event);
1325 bool WebContentsImpl::HandleWheelEvent(
1326 const blink::WebMouseWheelEvent& event) {
1327 #if !defined(OS_MACOSX)
1328 // On platforms other than Mac, control+mousewheel changes zoom. On Mac, this
1329 // isn't done for two reasons:
1330 // -the OS already has a gesture to do this through pinch-zoom
1331 // -if a user starts an inertial scroll, let's go, and presses control
1332 // (i.e. control+tab) then the OS's buffered scroll events will come in
1333 // with control key set which isn't what the user wants
1334 if (delegate_ &&
1335 event.wheelTicksY &&
1336 (event.modifiers & blink::WebInputEvent::ControlKey) &&
1337 // Avoid adjusting the zoom in response to two-finger-scrolling touchpad
1338 // gestures, which are regrettably easy to trigger accidentally.
1339 !event.hasPreciseScrollingDeltas) {
1340 delegate_->ContentsZoomChange(event.wheelTicksY > 0);
1341 return true;
1343 #endif
1344 return false;
1347 bool WebContentsImpl::PreHandleGestureEvent(
1348 const blink::WebGestureEvent& event) {
1349 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
1352 bool WebContentsImpl::HandleGestureEvent(
1353 const blink::WebGestureEvent& event) {
1354 // Some platforms (eg. Mac) send GesturePinch events for trackpad pinch-zoom.
1355 // Use them to implement browser zoom, as for HandleWheelEvent above.
1356 if (event.type == blink::WebInputEvent::GesturePinchUpdate &&
1357 event.sourceDevice == blink::WebGestureDeviceTouchpad) {
1358 // The scale difference necessary to trigger a zoom action. Derived from
1359 // experimentation to find a value that feels reasonable.
1360 const float kZoomStepValue = 0.6f;
1362 // Find the (absolute) thresholds on either side of the current zoom factor,
1363 // then convert those to actual numbers to trigger a zoom in or out.
1364 // This logic deliberately makes the range around the starting zoom value
1365 // for the gesture twice as large as the other ranges (i.e., the notches are
1366 // at ..., -3*step, -2*step, -step, step, 2*step, 3*step, ... but not at 0)
1367 // so that it's easier to get back to your starting point than it is to
1368 // overshoot.
1369 float nextStep = (abs(currentPinchZoomStepDelta_) + 1) * kZoomStepValue;
1370 float backStep = abs(currentPinchZoomStepDelta_) * kZoomStepValue;
1371 float zoomInThreshold = (currentPinchZoomStepDelta_ >= 0) ? nextStep
1372 : -backStep;
1373 float zoomOutThreshold = (currentPinchZoomStepDelta_ <= 0) ? -nextStep
1374 : backStep;
1376 totalPinchGestureAmount_ += (event.data.pinchUpdate.scale - 1.0);
1377 if (totalPinchGestureAmount_ > zoomInThreshold) {
1378 currentPinchZoomStepDelta_++;
1379 if (delegate_)
1380 delegate_->ContentsZoomChange(true);
1381 } else if (totalPinchGestureAmount_ < zoomOutThreshold) {
1382 currentPinchZoomStepDelta_--;
1383 if (delegate_)
1384 delegate_->ContentsZoomChange(false);
1386 return true;
1389 return false;
1392 void WebContentsImpl::HandleMouseDown() {
1393 if (delegate_)
1394 delegate_->HandleMouseDown();
1397 void WebContentsImpl::HandleMouseUp() {
1398 if (delegate_)
1399 delegate_->HandleMouseUp();
1402 void WebContentsImpl::HandlePointerActivate() {
1403 if (delegate_)
1404 delegate_->HandlePointerActivate();
1407 void WebContentsImpl::HandleGestureBegin() {
1408 if (delegate_)
1409 delegate_->HandleGestureBegin();
1412 void WebContentsImpl::HandleGestureEnd() {
1413 if (delegate_)
1414 delegate_->HandleGestureEnd();
1417 void WebContentsImpl::ToggleFullscreenMode(bool enter_fullscreen) {
1418 // This method is being called to enter or leave renderer-initiated fullscreen
1419 // mode. Either way, make sure any existing fullscreen widget is shut down
1420 // first.
1421 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1422 if (widget_view)
1423 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1425 if (delegate_)
1426 delegate_->ToggleFullscreenModeForTab(this, enter_fullscreen);
1428 FOR_EACH_OBSERVER(WebContentsObserver,
1429 observers_,
1430 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1433 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1434 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
1437 void WebContentsImpl::RequestToLockMouse(bool user_gesture,
1438 bool last_unlocked_by_target) {
1439 if (delegate_) {
1440 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
1441 } else {
1442 GotResponseToLockMouseRequest(false);
1446 void WebContentsImpl::LostMouseLock() {
1447 if (delegate_)
1448 delegate_->LostMouseLock();
1451 void WebContentsImpl::CreateNewWindow(
1452 int render_process_id,
1453 int route_id,
1454 int main_frame_route_id,
1455 const ViewHostMsg_CreateWindow_Params& params,
1456 SessionStorageNamespace* session_storage_namespace) {
1457 // We usually create the new window in the same BrowsingInstance (group of
1458 // script-related windows), by passing in the current SiteInstance. However,
1459 // if the opener is being suppressed (in a non-guest), we create a new
1460 // SiteInstance in its own BrowsingInstance.
1461 bool is_guest = BrowserPluginGuest::IsGuest(this);
1463 // If the opener is to be suppressed, the new window can be in any process.
1464 // Since routing ids are process specific, we must not have one passed in
1465 // as argument here.
1466 DCHECK(!params.opener_suppressed || route_id == MSG_ROUTING_NONE);
1468 scoped_refptr<SiteInstance> site_instance =
1469 params.opener_suppressed && !is_guest ?
1470 SiteInstance::CreateForURL(GetBrowserContext(), params.target_url) :
1471 GetSiteInstance();
1473 // A message to create a new window can only come from the active process for
1474 // this WebContentsImpl instance. If any other process sends the request,
1475 // it is invalid and the process must be terminated.
1476 if (GetRenderProcessHost()->GetID() != render_process_id) {
1477 base::ProcessHandle process_handle =
1478 RenderProcessHost::FromID(render_process_id)->GetHandle();
1479 if (process_handle != base::kNullProcessHandle) {
1480 RecordAction(
1481 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1482 base::KillProcess(process_handle, RESULT_CODE_KILLED, false);
1484 return;
1487 // We must assign the SessionStorageNamespace before calling Init().
1489 // http://crbug.com/142685
1490 const std::string& partition_id =
1491 GetContentClient()->browser()->
1492 GetStoragePartitionIdForSite(GetBrowserContext(),
1493 site_instance->GetSiteURL());
1494 StoragePartition* partition = BrowserContext::GetStoragePartition(
1495 GetBrowserContext(), site_instance.get());
1496 DOMStorageContextWrapper* dom_storage_context =
1497 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
1498 SessionStorageNamespaceImpl* session_storage_namespace_impl =
1499 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
1500 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
1502 if (delegate_ &&
1503 !delegate_->ShouldCreateWebContents(this,
1504 route_id,
1505 params.window_container_type,
1506 params.frame_name,
1507 params.target_url,
1508 partition_id,
1509 session_storage_namespace)) {
1510 if (route_id != MSG_ROUTING_NONE &&
1511 !RenderViewHost::FromID(render_process_id, route_id)) {
1512 // If the embedder didn't create a WebContents for this route, we need to
1513 // delete the RenderView that had already been created.
1514 Send(new ViewMsg_Close(route_id));
1516 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id);
1517 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1518 main_frame_route_id);
1519 return;
1522 // Create the new web contents. This will automatically create the new
1523 // WebContentsView. In the future, we may want to create the view separately.
1524 CreateParams create_params(GetBrowserContext(), site_instance.get());
1525 create_params.routing_id = route_id;
1526 create_params.main_frame_routing_id = main_frame_route_id;
1527 create_params.opener = this;
1528 create_params.opener_suppressed = params.opener_suppressed;
1529 if (params.disposition == NEW_BACKGROUND_TAB)
1530 create_params.initially_hidden = true;
1532 WebContentsImpl* new_contents = NULL;
1533 if (!is_guest) {
1534 create_params.context = view_->GetNativeView();
1535 create_params.initial_size = GetContainerBounds().size();
1536 new_contents = static_cast<WebContentsImpl*>(
1537 WebContents::Create(create_params));
1538 } else {
1539 new_contents = GetBrowserPluginGuest()->CreateNewGuestWindow(create_params);
1541 new_contents->GetController().SetSessionStorageNamespace(
1542 partition_id,
1543 session_storage_namespace);
1544 new_contents->RenderViewCreated(new_contents->GetRenderViewHost());
1546 // Save the window for later if we're not suppressing the opener (since it
1547 // will be shown immediately).
1548 if (!params.opener_suppressed) {
1549 if (!is_guest) {
1550 WebContentsView* new_view = new_contents->view_.get();
1552 // TODO(brettw): It seems bogus that we have to call this function on the
1553 // newly created object and give it one of its own member variables.
1554 new_view->CreateViewForWidget(new_contents->GetRenderViewHost(), false);
1556 // Save the created window associated with the route so we can show it
1557 // later.
1558 DCHECK_NE(MSG_ROUTING_NONE, route_id);
1559 pending_contents_[route_id] = new_contents;
1560 AddDestructionObserver(new_contents);
1563 if (delegate_) {
1564 delegate_->WebContentsCreated(
1565 this, params.opener_render_frame_id, params.frame_name,
1566 params.target_url, new_contents);
1569 if (params.opener_suppressed) {
1570 // When the opener is suppressed, the original renderer cannot access the
1571 // new window. As a result, we need to show and navigate the window here.
1572 bool was_blocked = false;
1573 if (delegate_) {
1574 gfx::Rect initial_pos;
1575 delegate_->AddNewContents(
1576 this, new_contents, params.disposition, initial_pos,
1577 params.user_gesture, &was_blocked);
1579 if (!was_blocked) {
1580 OpenURLParams open_params(params.target_url,
1581 Referrer(),
1582 CURRENT_TAB,
1583 ui::PAGE_TRANSITION_LINK,
1584 true /* is_renderer_initiated */);
1585 open_params.user_gesture = params.user_gesture;
1586 new_contents->OpenURL(open_params);
1591 void WebContentsImpl::CreateNewWidget(int render_process_id,
1592 int route_id,
1593 blink::WebPopupType popup_type) {
1594 CreateNewWidget(render_process_id, route_id, false, popup_type);
1597 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id,
1598 int route_id) {
1599 CreateNewWidget(render_process_id, route_id, true, blink::WebPopupTypeNone);
1602 void WebContentsImpl::CreateNewWidget(int render_process_id,
1603 int route_id,
1604 bool is_fullscreen,
1605 blink::WebPopupType popup_type) {
1606 RenderProcessHost* process = GetRenderProcessHost();
1607 // A message to create a new widget can only come from the active process for
1608 // this WebContentsImpl instance. If any other process sends the request,
1609 // it is invalid and the process must be terminated.
1610 if (process->GetID() != render_process_id) {
1611 base::ProcessHandle process_handle =
1612 RenderProcessHost::FromID(render_process_id)->GetHandle();
1613 if (process_handle != base::kNullProcessHandle) {
1614 RecordAction(
1615 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1616 base::KillProcess(process_handle, RESULT_CODE_KILLED, false);
1618 return;
1621 RenderWidgetHostImpl* widget_host =
1622 new RenderWidgetHostImpl(this, process, route_id, IsHidden());
1623 created_widgets_.insert(widget_host);
1625 RenderWidgetHostViewBase* widget_view =
1626 static_cast<RenderWidgetHostViewBase*>(
1627 view_->CreateViewForPopupWidget(widget_host));
1628 if (!widget_view)
1629 return;
1630 if (!is_fullscreen) {
1631 // Popups should not get activated.
1632 widget_view->SetPopupType(popup_type);
1634 // Save the created widget associated with the route so we can show it later.
1635 pending_widget_views_[route_id] = widget_view;
1637 #if defined(OS_MACOSX)
1638 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1639 // to allow it to survive the trip without being hosted.
1640 base::mac::NSObjectRetain(widget_view->GetNativeView());
1641 #endif
1644 void WebContentsImpl::ShowCreatedWindow(int route_id,
1645 WindowOpenDisposition disposition,
1646 const gfx::Rect& initial_pos,
1647 bool user_gesture) {
1648 WebContentsImpl* contents = GetCreatedWindow(route_id);
1649 if (contents) {
1650 WebContentsDelegate* delegate = GetDelegate();
1651 if (delegate) {
1652 delegate->AddNewContents(
1653 this, contents, disposition, initial_pos, user_gesture, NULL);
1658 void WebContentsImpl::ShowCreatedWidget(int route_id,
1659 const gfx::Rect& initial_pos) {
1660 ShowCreatedWidget(route_id, false, initial_pos);
1663 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id) {
1664 ShowCreatedWidget(route_id, true, gfx::Rect());
1667 void WebContentsImpl::ShowCreatedWidget(int route_id,
1668 bool is_fullscreen,
1669 const gfx::Rect& initial_pos) {
1670 RenderWidgetHostViewBase* widget_host_view =
1671 static_cast<RenderWidgetHostViewBase*>(GetCreatedWidget(route_id));
1672 if (!widget_host_view)
1673 return;
1675 RenderWidgetHostView* view = NULL;
1676 BrowserPluginGuest* guest = GetBrowserPluginGuest();
1677 if (guest && guest->embedder_web_contents()) {
1678 view = guest->embedder_web_contents()->GetRenderWidgetHostView();
1679 } else {
1680 view = GetRenderWidgetHostView();
1683 if (is_fullscreen) {
1684 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
1685 view_->StoreFocus();
1686 fullscreen_widget_routing_id_ = route_id;
1687 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
1688 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1689 delegate_->ToggleFullscreenModeForTab(this, true);
1690 } else {
1691 widget_host_view->InitAsFullscreen(view);
1693 FOR_EACH_OBSERVER(WebContentsObserver,
1694 observers_,
1695 DidShowFullscreenWidget(route_id));
1696 if (!widget_host_view->HasFocus())
1697 widget_host_view->Focus();
1698 } else {
1699 widget_host_view->InitAsPopup(view, initial_pos);
1702 RenderWidgetHostImpl* render_widget_host_impl =
1703 RenderWidgetHostImpl::From(widget_host_view->GetRenderWidgetHost());
1704 render_widget_host_impl->Init();
1705 // Only allow privileged mouse lock for fullscreen render widget, which is
1706 // used to implement Pepper Flash fullscreen.
1707 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
1709 #if defined(OS_MACOSX)
1710 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1711 // properly embedded (or purposefully ignored) we can release the retain we
1712 // took in CreateNewWidget().
1713 base::mac::NSObjectRelease(widget_host_view->GetNativeView());
1714 #endif
1717 WebContentsImpl* WebContentsImpl::GetCreatedWindow(int route_id) {
1718 PendingContents::iterator iter = pending_contents_.find(route_id);
1720 // Certain systems can block the creation of new windows. If we didn't succeed
1721 // in creating one, just return NULL.
1722 if (iter == pending_contents_.end()) {
1723 return NULL;
1726 WebContentsImpl* new_contents = iter->second;
1727 pending_contents_.erase(route_id);
1728 RemoveDestructionObserver(new_contents);
1730 // Don't initialize the guest WebContents immediately.
1731 if (BrowserPluginGuest::IsGuest(new_contents))
1732 return new_contents;
1734 if (!new_contents->GetRenderProcessHost()->HasConnection() ||
1735 !new_contents->GetRenderViewHost()->GetView())
1736 return NULL;
1738 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
1739 // TODO(brettw): It seems bogus to reach into here and initialize the host.
1740 static_cast<RenderViewHostImpl*>(new_contents->GetRenderViewHost())->Init();
1741 static_cast<RenderFrameHostImpl*>(new_contents->GetMainFrame())->Init();
1743 return new_contents;
1746 RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int route_id) {
1747 PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
1748 if (iter == pending_widget_views_.end()) {
1749 DCHECK(false);
1750 return NULL;
1753 RenderWidgetHostView* widget_host_view = iter->second;
1754 pending_widget_views_.erase(route_id);
1756 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
1757 if (!widget_host->GetProcess()->HasConnection()) {
1758 // The view has gone away or the renderer crashed. Nothing to do.
1759 return NULL;
1762 return widget_host_view;
1765 void WebContentsImpl::RequestMediaAccessPermission(
1766 const MediaStreamRequest& request,
1767 const MediaResponseCallback& callback) {
1768 if (delegate_) {
1769 delegate_->RequestMediaAccessPermission(this, request, callback);
1770 } else {
1771 callback.Run(MediaStreamDevices(),
1772 MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN,
1773 scoped_ptr<MediaStreamUI>());
1777 bool WebContentsImpl::CheckMediaAccessPermission(const GURL& security_origin,
1778 MediaStreamType type) {
1779 DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
1780 type == MEDIA_DEVICE_VIDEO_CAPTURE);
1781 return delegate_ &&
1782 delegate_->CheckMediaAccessPermission(this, security_origin, type);
1785 SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
1786 SiteInstance* instance) {
1787 return controller_.GetSessionStorageNamespace(instance);
1790 SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
1791 return controller_.GetSessionStorageNamespaceMap();
1794 FrameTree* WebContentsImpl::GetFrameTree() {
1795 return &frame_tree_;
1798 void WebContentsImpl::SetIsVirtualKeyboardRequested(bool requested) {
1799 virtual_keyboard_requested_ = requested;
1802 bool WebContentsImpl::IsVirtualKeyboardRequested() {
1803 return virtual_keyboard_requested_;
1806 AccessibilityMode WebContentsImpl::GetAccessibilityMode() const {
1807 return accessibility_mode_;
1810 void WebContentsImpl::AccessibilityEventReceived(
1811 const std::vector<AXEventNotificationDetails>& details) {
1812 FOR_EACH_OBSERVER(
1813 WebContentsObserver, observers_, AccessibilityEventReceived(details));
1816 RenderFrameHost* WebContentsImpl::GetGuestByInstanceID(
1817 int browser_plugin_instance_id) {
1818 BrowserPluginGuestManager* guest_manager =
1819 GetBrowserContext()->GetGuestManager();
1820 WebContents* guest = guest_manager->GetGuestByInstanceID(
1821 this, browser_plugin_instance_id);
1822 if (!guest)
1823 return NULL;
1824 return guest->GetMainFrame();
1827 GeolocationServiceContext* WebContentsImpl::GetGeolocationServiceContext() {
1828 return geolocation_service_context_.get();
1831 void WebContentsImpl::OnShowValidationMessage(
1832 const gfx::Rect& anchor_in_root_view,
1833 const base::string16& main_text,
1834 const base::string16& sub_text) {
1835 if (delegate_)
1836 delegate_->ShowValidationMessage(
1837 this, anchor_in_root_view, main_text, sub_text);
1840 void WebContentsImpl::OnHideValidationMessage() {
1841 if (delegate_)
1842 delegate_->HideValidationMessage(this);
1845 void WebContentsImpl::OnMoveValidationMessage(
1846 const gfx::Rect& anchor_in_root_view) {
1847 if (delegate_)
1848 delegate_->MoveValidationMessage(this, anchor_in_root_view);
1851 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl* rwh) {
1852 if (browser_plugin_embedder_)
1853 browser_plugin_embedder_->DidSendScreenRects();
1856 BrowserAccessibilityManager*
1857 WebContentsImpl::GetRootBrowserAccessibilityManager() {
1858 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
1859 return rfh ? rfh->browser_accessibility_manager() : NULL;
1862 BrowserAccessibilityManager*
1863 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
1864 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
1865 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : NULL;
1868 void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
1869 const gfx::Size old_size = GetPreferredSize();
1870 preferred_size_ = pref_size;
1871 OnPreferredSizeChanged(old_size);
1874 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size& new_size) {
1875 if (delegate_)
1876 delegate_->ResizeDueToAutoResize(this, new_size);
1879 WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
1880 if (!delegate_)
1881 return NULL;
1883 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
1884 return new_contents;
1887 bool WebContentsImpl::Send(IPC::Message* message) {
1888 if (!GetRenderViewHost()) {
1889 delete message;
1890 return false;
1893 return GetRenderViewHost()->Send(message);
1896 bool WebContentsImpl::NavigateToPendingEntry(
1897 NavigationController::ReloadType reload_type) {
1898 FrameTreeNode* node = frame_tree_.root();
1900 // Navigate in the FrameTreeNode specified in the pending entry, if any. This
1901 // is currently only used in --site-per-process and tests.
1902 NavigationEntryImpl* pending_entry =
1903 NavigationEntryImpl::FromNavigationEntry(controller_.GetPendingEntry());
1904 if (pending_entry->frame_tree_node_id() != -1) {
1905 FrameTreeNode* subframe =
1906 frame_tree_.FindByID(pending_entry->frame_tree_node_id());
1907 DCHECK(subframe);
1908 if (subframe)
1909 node = subframe;
1912 return node->navigator()->NavigateToPendingEntry(
1913 node->current_frame_host(), reload_type);
1916 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
1917 RenderFrameHost* render_frame_host) {
1918 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1919 RenderFrameForInterstitialPageCreated(render_frame_host));
1922 void WebContentsImpl::AttachInterstitialPage(
1923 InterstitialPageImpl* interstitial_page) {
1924 DCHECK(interstitial_page);
1925 GetRenderManager()->set_interstitial_page(interstitial_page);
1927 // Cancel any visible dialogs so that they don't interfere with the
1928 // interstitial.
1929 if (dialog_manager_)
1930 dialog_manager_->CancelActiveAndPendingDialogs(this);
1932 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1933 DidAttachInterstitialPage());
1936 void WebContentsImpl::DetachInterstitialPage() {
1937 if (ShowingInterstitialPage())
1938 GetRenderManager()->remove_interstitial_page();
1939 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1940 DidDetachInterstitialPage());
1943 void WebContentsImpl::SetHistoryLengthAndPrune(
1944 const SiteInstance* site_instance,
1945 int history_length,
1946 int32 minimum_page_id) {
1947 // SetHistoryLengthAndPrune doesn't work when there are pending cross-site
1948 // navigations. Callers should ensure that this is the case.
1949 if (GetRenderManager()->pending_render_view_host()) {
1950 NOTREACHED();
1951 return;
1953 RenderViewHostImpl* rvh = GetRenderViewHostImpl();
1954 if (!rvh) {
1955 NOTREACHED();
1956 return;
1958 if (site_instance && rvh->GetSiteInstance() != site_instance) {
1959 NOTREACHED();
1960 return;
1962 Send(new ViewMsg_SetHistoryLengthAndPrune(GetRoutingID(),
1963 history_length,
1964 minimum_page_id));
1967 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache) {
1968 RenderFrameHost* focused_frame = GetFocusedFrame();
1969 if (!focused_frame)
1970 return;
1972 focused_frame->Send(new FrameMsg_Reload(
1973 focused_frame->GetRoutingID(), ignore_cache));
1976 void WebContentsImpl::Undo() {
1977 RenderFrameHost* focused_frame = GetFocusedFrame();
1978 if (!focused_frame)
1979 return;
1981 focused_frame->Send(new InputMsg_Undo(focused_frame->GetRoutingID()));
1982 RecordAction(base::UserMetricsAction("Undo"));
1985 void WebContentsImpl::Redo() {
1986 RenderFrameHost* focused_frame = GetFocusedFrame();
1987 if (!focused_frame)
1988 return;
1989 focused_frame->Send(new InputMsg_Redo(focused_frame->GetRoutingID()));
1990 RecordAction(base::UserMetricsAction("Redo"));
1993 void WebContentsImpl::Cut() {
1994 RenderFrameHost* focused_frame = GetFocusedFrame();
1995 if (!focused_frame)
1996 return;
1998 focused_frame->Send(new InputMsg_Cut(focused_frame->GetRoutingID()));
1999 RecordAction(base::UserMetricsAction("Cut"));
2002 void WebContentsImpl::Copy() {
2003 RenderFrameHost* focused_frame = GetFocusedFrame();
2004 if (!focused_frame)
2005 return;
2007 focused_frame->Send(new InputMsg_Copy(focused_frame->GetRoutingID()));
2008 RecordAction(base::UserMetricsAction("Copy"));
2011 void WebContentsImpl::CopyToFindPboard() {
2012 #if defined(OS_MACOSX)
2013 RenderFrameHost* focused_frame = GetFocusedFrame();
2014 if (!focused_frame)
2015 return;
2017 // Windows/Linux don't have the concept of a find pasteboard.
2018 focused_frame->Send(
2019 new InputMsg_CopyToFindPboard(focused_frame->GetRoutingID()));
2020 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
2021 #endif
2024 void WebContentsImpl::Paste() {
2025 RenderFrameHost* focused_frame = GetFocusedFrame();
2026 if (!focused_frame)
2027 return;
2029 focused_frame->Send(new InputMsg_Paste(focused_frame->GetRoutingID()));
2030 RecordAction(base::UserMetricsAction("Paste"));
2033 void WebContentsImpl::PasteAndMatchStyle() {
2034 RenderFrameHost* focused_frame = GetFocusedFrame();
2035 if (!focused_frame)
2036 return;
2038 focused_frame->Send(new InputMsg_PasteAndMatchStyle(
2039 focused_frame->GetRoutingID()));
2040 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
2043 void WebContentsImpl::Delete() {
2044 RenderFrameHost* focused_frame = GetFocusedFrame();
2045 if (!focused_frame)
2046 return;
2048 focused_frame->Send(new InputMsg_Delete(focused_frame->GetRoutingID()));
2049 RecordAction(base::UserMetricsAction("DeleteSelection"));
2052 void WebContentsImpl::SelectAll() {
2053 RenderFrameHost* focused_frame = GetFocusedFrame();
2054 if (!focused_frame)
2055 return;
2057 focused_frame->Send(new InputMsg_SelectAll(focused_frame->GetRoutingID()));
2058 RecordAction(base::UserMetricsAction("SelectAll"));
2061 void WebContentsImpl::Unselect() {
2062 RenderFrameHost* focused_frame = GetFocusedFrame();
2063 if (!focused_frame)
2064 return;
2066 focused_frame->Send(new InputMsg_Unselect(focused_frame->GetRoutingID()));
2067 RecordAction(base::UserMetricsAction("Unselect"));
2070 void WebContentsImpl::Replace(const base::string16& word) {
2071 RenderFrameHost* focused_frame = GetFocusedFrame();
2072 if (!focused_frame)
2073 return;
2075 focused_frame->Send(new InputMsg_Replace(
2076 focused_frame->GetRoutingID(), word));
2079 void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
2080 RenderFrameHost* focused_frame = GetFocusedFrame();
2081 if (!focused_frame)
2082 return;
2084 focused_frame->Send(new InputMsg_ReplaceMisspelling(
2085 focused_frame->GetRoutingID(), word));
2088 void WebContentsImpl::NotifyContextMenuClosed(
2089 const CustomContextMenuContext& context) {
2090 RenderFrameHost* focused_frame = GetFocusedFrame();
2091 if (!focused_frame)
2092 return;
2094 focused_frame->Send(new FrameMsg_ContextMenuClosed(
2095 focused_frame->GetRoutingID(), context));
2098 void WebContentsImpl::ExecuteCustomContextMenuCommand(
2099 int action, const CustomContextMenuContext& context) {
2100 RenderFrameHost* focused_frame = GetFocusedFrame();
2101 if (!focused_frame)
2102 return;
2104 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
2105 focused_frame->GetRoutingID(), context, action));
2108 gfx::NativeView WebContentsImpl::GetNativeView() {
2109 return view_->GetNativeView();
2112 gfx::NativeView WebContentsImpl::GetContentNativeView() {
2113 return view_->GetContentNativeView();
2116 gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
2117 return view_->GetTopLevelNativeWindow();
2120 gfx::Rect WebContentsImpl::GetViewBounds() {
2121 return view_->GetViewBounds();
2124 gfx::Rect WebContentsImpl::GetContainerBounds() {
2125 gfx::Rect rv;
2126 view_->GetContainerBounds(&rv);
2127 return rv;
2130 DropData* WebContentsImpl::GetDropData() {
2131 return view_->GetDropData();
2134 void WebContentsImpl::Focus() {
2135 view_->Focus();
2138 void WebContentsImpl::SetInitialFocus() {
2139 view_->SetInitialFocus();
2142 void WebContentsImpl::StoreFocus() {
2143 view_->StoreFocus();
2146 void WebContentsImpl::RestoreFocus() {
2147 view_->RestoreFocus();
2150 void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
2151 if (ShowingInterstitialPage()) {
2152 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse);
2153 return;
2155 RenderWidgetHostView* const fullscreen_view =
2156 GetFullscreenRenderWidgetHostView();
2157 if (fullscreen_view) {
2158 fullscreen_view->Focus();
2159 return;
2161 GetRenderViewHostImpl()->SetInitialFocus(reverse);
2164 bool WebContentsImpl::ShowingInterstitialPage() const {
2165 return GetRenderManager()->interstitial_page() != NULL;
2168 InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
2169 return GetRenderManager()->interstitial_page();
2172 bool WebContentsImpl::IsSavable() {
2173 // WebKit creates Document object when MIME type is application/xhtml+xml,
2174 // so we also support this MIME type.
2175 return contents_mime_type_ == "text/html" ||
2176 contents_mime_type_ == "text/xml" ||
2177 contents_mime_type_ == "application/xhtml+xml" ||
2178 contents_mime_type_ == "text/plain" ||
2179 contents_mime_type_ == "text/css" ||
2180 net::IsSupportedJavascriptMimeType(contents_mime_type_.c_str());
2183 void WebContentsImpl::OnSavePage() {
2184 // If we can not save the page, try to download it.
2185 if (!IsSavable()) {
2186 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML);
2187 SaveFrame(GetURL(), Referrer());
2188 return;
2191 Stop();
2193 // Create the save package and possibly prompt the user for the name to save
2194 // the page as. The user prompt is an asynchronous operation that runs on
2195 // another thread.
2196 save_package_ = new SavePackage(this);
2197 save_package_->GetSaveInfo();
2200 // Used in automated testing to bypass prompting the user for file names.
2201 // Instead, the names and paths are hard coded rather than running them through
2202 // file name sanitation and extension / mime checking.
2203 bool WebContentsImpl::SavePage(const base::FilePath& main_file,
2204 const base::FilePath& dir_path,
2205 SavePageType save_type) {
2206 // Stop the page from navigating.
2207 Stop();
2209 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
2210 return save_package_->Init(SavePackageDownloadCreatedCallback());
2213 void WebContentsImpl::SaveFrame(const GURL& url,
2214 const Referrer& referrer) {
2215 if (!GetURL().is_valid())
2216 return;
2217 bool is_main_frame = (url == GetURL());
2219 DownloadManager* dlm =
2220 BrowserContext::GetDownloadManager(GetBrowserContext());
2221 if (!dlm)
2222 return;
2223 int64 post_id = -1;
2224 if (is_main_frame) {
2225 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2226 if (entry)
2227 post_id = entry->GetPostID();
2229 scoped_ptr<DownloadUrlParameters> params(
2230 DownloadUrlParameters::FromWebContents(this, url));
2231 params->set_referrer(referrer);
2232 params->set_post_id(post_id);
2233 params->set_prefer_cache(true);
2234 if (post_id >= 0)
2235 params->set_method("POST");
2236 params->set_prompt(true);
2237 dlm->DownloadUrl(params.Pass());
2240 void WebContentsImpl::GenerateMHTML(
2241 const base::FilePath& file,
2242 const base::Callback<void(int64)>& callback) {
2243 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file, callback);
2246 const std::string& WebContentsImpl::GetContentsMimeType() const {
2247 return contents_mime_type_;
2250 bool WebContentsImpl::WillNotifyDisconnection() const {
2251 return notify_disconnection_;
2254 void WebContentsImpl::SetOverrideEncoding(const std::string& encoding) {
2255 SetEncoding(encoding);
2256 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding));
2259 void WebContentsImpl::ResetOverrideEncoding() {
2260 canonical_encoding_.clear();
2261 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2264 RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
2265 return &renderer_preferences_;
2268 void WebContentsImpl::Close() {
2269 Close(GetRenderViewHost());
2272 void WebContentsImpl::DragSourceEndedAt(int client_x, int client_y,
2273 int screen_x, int screen_y, blink::WebDragOperation operation) {
2274 if (browser_plugin_embedder_.get())
2275 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y,
2276 screen_x, screen_y, operation);
2277 if (GetRenderViewHost())
2278 GetRenderViewHostImpl()->DragSourceEndedAt(client_x, client_y,
2279 screen_x, screen_y, operation);
2282 void WebContentsImpl::DidGetResourceResponseStart(
2283 const ResourceRequestDetails& details) {
2284 controller_.ssl_manager()->DidStartResourceResponse(details);
2286 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2287 DidGetResourceResponseStart(details));
2289 // TODO(avi): Remove. http://crbug.com/170921
2290 NotificationService::current()->Notify(
2291 NOTIFICATION_RESOURCE_RESPONSE_STARTED,
2292 Source<WebContents>(this),
2293 Details<const ResourceRequestDetails>(&details));
2296 void WebContentsImpl::DidGetRedirectForResourceRequest(
2297 RenderFrameHost* render_frame_host,
2298 const ResourceRedirectDetails& details) {
2299 controller_.ssl_manager()->DidReceiveResourceRedirect(details);
2301 FOR_EACH_OBSERVER(
2302 WebContentsObserver,
2303 observers_,
2304 DidGetRedirectForResourceRequest(render_frame_host, details));
2306 // TODO(avi): Remove. http://crbug.com/170921
2307 NotificationService::current()->Notify(
2308 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
2309 Source<WebContents>(this),
2310 Details<const ResourceRedirectDetails>(&details));
2313 void WebContentsImpl::SystemDragEnded() {
2314 if (GetRenderViewHost())
2315 GetRenderViewHostImpl()->DragSourceSystemDragEnded();
2316 if (delegate_)
2317 delegate_->DragEnded();
2318 if (browser_plugin_embedder_.get())
2319 browser_plugin_embedder_->SystemDragEnded();
2322 void WebContentsImpl::UserGestureDone() {
2323 OnUserGesture();
2326 void WebContentsImpl::SetClosedByUserGesture(bool value) {
2327 closed_by_user_gesture_ = value;
2330 bool WebContentsImpl::GetClosedByUserGesture() const {
2331 return closed_by_user_gesture_;
2334 void WebContentsImpl::ViewSource() {
2335 if (!delegate_)
2336 return;
2338 NavigationEntry* entry = GetController().GetLastCommittedEntry();
2339 if (!entry)
2340 return;
2342 delegate_->ViewSourceForTab(this, entry->GetURL());
2345 void WebContentsImpl::ViewFrameSource(const GURL& url,
2346 const PageState& page_state) {
2347 if (!delegate_)
2348 return;
2350 delegate_->ViewSourceForFrame(this, url, page_state);
2353 int WebContentsImpl::GetMinimumZoomPercent() const {
2354 return minimum_zoom_percent_;
2357 int WebContentsImpl::GetMaximumZoomPercent() const {
2358 return maximum_zoom_percent_;
2361 gfx::Size WebContentsImpl::GetPreferredSize() const {
2362 return capturer_count_ == 0 ? preferred_size_ : preferred_size_for_capture_;
2365 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed) {
2366 if (GetBrowserPluginGuest())
2367 return GetBrowserPluginGuest()->LockMouse(allowed);
2369 return GetRenderViewHost() ?
2370 GetRenderViewHostImpl()->GotResponseToLockMouseRequest(allowed) : false;
2373 bool WebContentsImpl::HasOpener() const {
2374 return opener_ != NULL;
2377 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
2378 if (!color_chooser_info_.get())
2379 return;
2380 RenderFrameHost* rfh = RenderFrameHost::FromID(
2381 color_chooser_info_->render_process_id,
2382 color_chooser_info_->render_frame_id);
2383 if (!rfh)
2384 return;
2386 rfh->Send(new FrameMsg_DidChooseColorResponse(
2387 rfh->GetRoutingID(), color_chooser_info_->identifier, color));
2390 void WebContentsImpl::DidEndColorChooser() {
2391 if (!color_chooser_info_.get())
2392 return;
2393 RenderFrameHost* rfh = RenderFrameHost::FromID(
2394 color_chooser_info_->render_process_id,
2395 color_chooser_info_->render_frame_id);
2396 if (!rfh)
2397 return;
2399 rfh->Send(new FrameMsg_DidEndColorChooser(
2400 rfh->GetRoutingID(), color_chooser_info_->identifier));
2401 color_chooser_info_.reset();
2404 int WebContentsImpl::DownloadImage(const GURL& url,
2405 bool is_favicon,
2406 uint32_t max_bitmap_size,
2407 const ImageDownloadCallback& callback) {
2408 int id = StartDownload(GetMainFrame(), url, is_favicon, max_bitmap_size);
2409 image_download_map_[id] = callback;
2410 return id;
2413 bool WebContentsImpl::IsSubframe() const {
2414 return is_subframe_;
2417 void WebContentsImpl::Find(int request_id,
2418 const base::string16& search_text,
2419 const blink::WebFindOptions& options) {
2420 // See if a top level browser plugin handles the find request first.
2421 if (browser_plugin_embedder_ &&
2422 browser_plugin_embedder_->Find(request_id, search_text, options)) {
2423 return;
2425 Send(new ViewMsg_Find(GetRoutingID(), request_id, search_text, options));
2428 void WebContentsImpl::StopFinding(StopFindAction action) {
2429 Send(new ViewMsg_StopFinding(GetRoutingID(), action));
2432 void WebContentsImpl::InsertCSS(const std::string& css) {
2433 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2434 GetMainFrame()->GetRoutingID(), css));
2437 bool WebContentsImpl::WasRecentlyAudible() {
2438 return audio_stream_monitor_.WasRecentlyAudible();
2441 void WebContentsImpl::GetManifest(const GetManifestCallback& callback) {
2442 manifest_manager_host_->GetManifest(GetMainFrame(), callback);
2445 bool WebContentsImpl::FocusLocationBarByDefault() {
2446 NavigationEntry* entry = controller_.GetVisibleEntry();
2447 if (entry && entry->GetURL() == GURL(url::kAboutBlankURL))
2448 return true;
2449 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
2452 void WebContentsImpl::SetFocusToLocationBar(bool select_all) {
2453 if (delegate_)
2454 delegate_->SetFocusToLocationBar(select_all);
2457 void WebContentsImpl::DidStartProvisionalLoad(
2458 RenderFrameHostImpl* render_frame_host,
2459 const GURL& validated_url,
2460 bool is_error_page,
2461 bool is_iframe_srcdoc) {
2462 // Notify observers about the start of the provisional load.
2463 FOR_EACH_OBSERVER(
2464 WebContentsObserver,
2465 observers_,
2466 DidStartProvisionalLoadForFrame(
2467 render_frame_host, validated_url, is_error_page, is_iframe_srcdoc));
2470 void WebContentsImpl::DidStartNavigationTransition(
2471 RenderFrameHostImpl* render_frame_host) {
2472 #if defined(OS_ANDROID)
2473 int render_frame_id = render_frame_host->GetRoutingID();
2474 GetWebContentsAndroid()->DidStartNavigationTransitionForFrame(
2475 render_frame_id);
2476 #endif
2479 void WebContentsImpl::DidFailProvisionalLoadWithError(
2480 RenderFrameHostImpl* render_frame_host,
2481 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
2482 GURL validated_url(params.url);
2483 FOR_EACH_OBSERVER(WebContentsObserver,
2484 observers_,
2485 DidFailProvisionalLoad(render_frame_host,
2486 validated_url,
2487 params.error_code,
2488 params.error_description));
2491 void WebContentsImpl::DidFailLoadWithError(
2492 RenderFrameHostImpl* render_frame_host,
2493 const GURL& url,
2494 int error_code,
2495 const base::string16& error_description) {
2496 FOR_EACH_OBSERVER(
2497 WebContentsObserver,
2498 observers_,
2499 DidFailLoad(render_frame_host, url, error_code, error_description));
2502 void WebContentsImpl::NotifyChangedNavigationState(
2503 InvalidateTypes changed_flags) {
2504 NotifyNavigationStateChanged(changed_flags);
2507 void WebContentsImpl::AboutToNavigateRenderFrame(
2508 RenderFrameHostImpl* render_frame_host) {
2509 // Notify observers that we will navigate in this RenderFrame.
2510 FOR_EACH_OBSERVER(
2511 WebContentsObserver,
2512 observers_,
2513 AboutToNavigateRenderFrame(render_frame_host));
2516 void WebContentsImpl::DidStartNavigationToPendingEntry(
2517 RenderFrameHostImpl* render_frame_host,
2518 const GURL& url,
2519 NavigationController::ReloadType reload_type) {
2520 // Notify observers about navigation.
2521 FOR_EACH_OBSERVER(
2522 WebContentsObserver,
2523 observers_,
2524 DidStartNavigationToPendingEntry(url, reload_type));
2527 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
2528 const OpenURLParams& params) {
2529 WebContents* new_contents = OpenURL(params);
2531 if (new_contents) {
2532 // Notify observers.
2533 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2534 DidOpenRequestedURL(new_contents,
2535 render_frame_host,
2536 params.url,
2537 params.referrer,
2538 params.disposition,
2539 params.transition));
2543 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2544 if (!delegate_)
2545 return false;
2546 return delegate_->ShouldPreserveAbortedURLs(this);
2549 void WebContentsImpl::DidCommitProvisionalLoad(
2550 RenderFrameHostImpl* render_frame_host,
2551 const GURL& url,
2552 ui::PageTransition transition_type) {
2553 // Notify observers about the commit of the provisional load.
2554 FOR_EACH_OBSERVER(WebContentsObserver,
2555 observers_,
2556 DidCommitProvisionalLoadForFrame(
2557 render_frame_host, url, transition_type));
2560 void WebContentsImpl::DidNavigateMainFramePreCommit(
2561 bool navigation_is_within_page) {
2562 // Ensure fullscreen mode is exited before committing the navigation to a
2563 // different page. The next page will not start out assuming it is in
2564 // fullscreen mode.
2565 if (navigation_is_within_page) {
2566 // No page change? Then, the renderer and browser can remain in fullscreen.
2567 return;
2569 if (IsFullscreenForCurrentTab())
2570 GetRenderViewHost()->ExitFullscreen();
2571 DCHECK(!IsFullscreenForCurrentTab());
2574 void WebContentsImpl::DidNavigateMainFramePostCommit(
2575 const LoadCommittedDetails& details,
2576 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2577 if (details.is_navigation_to_different_page()) {
2578 // Clear the status bubble. This is a workaround for a bug where WebKit
2579 // doesn't let us know that the cursor left an element during a
2580 // transition (this is also why the mouse cursor remains as a hand after
2581 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2582 // clear the bubble when a user navigates to a named anchor in the same
2583 // page.
2584 UpdateTargetURL(GURL());
2587 if (!details.is_in_page) {
2588 // Once the main frame is navigated, we're no longer considered to have
2589 // displayed insecure content.
2590 displayed_insecure_content_ = false;
2591 SSLManager::NotifySSLInternalStateChanged(
2592 GetController().GetBrowserContext());
2595 // Notify observers about navigation.
2596 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2597 DidNavigateMainFrame(details, params));
2599 if (delegate_)
2600 delegate_->DidNavigateMainFramePostCommit(this);
2601 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
2604 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2605 RenderFrameHostImpl* render_frame_host,
2606 const LoadCommittedDetails& details,
2607 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2608 // Now that something has committed, we don't need to track whether the
2609 // initial page has been accessed.
2610 has_accessed_initial_document_ = false;
2612 // If we navigate off the page, close all JavaScript dialogs.
2613 if (dialog_manager_ && !details.is_in_page)
2614 dialog_manager_->CancelActiveAndPendingDialogs(this);
2616 // Notify observers about navigation.
2617 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2618 DidNavigateAnyFrame(render_frame_host, details, params));
2621 void WebContentsImpl::SetMainFrameMimeType(const std::string& mime_type) {
2622 contents_mime_type_ = mime_type;
2625 bool WebContentsImpl::CanOverscrollContent() const {
2626 // Disable overscroll when touch emulation is on. See crbug.com/369938.
2627 if (force_disable_overscroll_content_)
2628 return false;
2630 if (delegate_)
2631 return delegate_->CanOverscrollContent();
2633 return false;
2636 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color) {
2637 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2638 DidChangeThemeColor(theme_color));
2641 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2642 const GURL& url,
2643 const std::string& security_info,
2644 const std::string& http_method,
2645 const std::string& mime_type,
2646 ResourceType resource_type) {
2647 base::StatsCounter cache("WebKit.CacheHit");
2648 cache.Increment();
2650 // Send out a notification that we loaded a resource from our memory cache.
2651 int cert_id = 0;
2652 net::CertStatus cert_status = 0;
2653 int security_bits = -1;
2654 int connection_status = 0;
2655 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids;
2656 DeserializeSecurityInfo(security_info, &cert_id, &cert_status,
2657 &security_bits, &connection_status,
2658 &signed_certificate_timestamp_ids);
2659 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details
2660 LoadFromMemoryCacheDetails details(
2661 url, GetRenderProcessHost()->GetID(), cert_id, cert_status, http_method,
2662 mime_type, resource_type);
2664 controller_.ssl_manager()->DidLoadFromMemoryCache(details);
2666 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2667 DidLoadResourceFromMemoryCache(details));
2669 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
2670 scoped_refptr<net::URLRequestContextGetter> request_context(
2671 resource_type == RESOURCE_TYPE_MEDIA ?
2672 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2673 GetRenderProcessHost()->GetID()) :
2674 GetBrowserContext()->GetRequestContextForRenderProcess(
2675 GetRenderProcessHost()->GetID()));
2676 BrowserThread::PostTask(
2677 BrowserThread::IO,
2678 FROM_HERE,
2679 base::Bind(&NotifyCacheOnIO, request_context, url, http_method));
2683 void WebContentsImpl::OnDidDisplayInsecureContent() {
2684 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
2685 displayed_insecure_content_ = true;
2686 SSLManager::NotifySSLInternalStateChanged(
2687 GetController().GetBrowserContext());
2690 void WebContentsImpl::OnDidRunInsecureContent(
2691 const std::string& security_origin, const GURL& target_url) {
2692 LOG(WARNING) << security_origin << " ran insecure content from "
2693 << target_url.possibly_invalid_spec();
2694 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
2695 if (EndsWith(security_origin, kDotGoogleDotCom, false))
2696 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
2697 controller_.ssl_manager()->DidRunInsecureContent(security_origin);
2698 displayed_insecure_content_ = true;
2699 SSLManager::NotifySSLInternalStateChanged(
2700 GetController().GetBrowserContext());
2703 void WebContentsImpl::OnDocumentLoadedInFrame() {
2704 CHECK(render_frame_message_source_);
2705 CHECK(!render_view_message_source_);
2706 RenderFrameHostImpl* rfh =
2707 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2708 FOR_EACH_OBSERVER(
2709 WebContentsObserver, observers_, DocumentLoadedInFrame(rfh));
2712 void WebContentsImpl::OnDidFinishLoad(
2713 const GURL& url) {
2714 if (!render_frame_message_source_) {
2715 RecordAction(base::UserMetricsAction("BadMessageTerminate_RVD2"));
2716 GetRenderProcessHost()->ReceivedBadMessage();
2717 return;
2720 GURL validated_url(url);
2721 RenderProcessHost* render_process_host =
2722 render_frame_message_source_->GetProcess();
2723 render_process_host->FilterURL(false, &validated_url);
2725 RenderFrameHostImpl* rfh =
2726 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2727 FOR_EACH_OBSERVER(
2728 WebContentsObserver, observers_, DidFinishLoad(rfh, validated_url));
2731 void WebContentsImpl::OnDidStartLoading(bool to_different_document) {
2732 RenderFrameHostImpl* rfh =
2733 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2734 int64 render_frame_id = rfh->frame_tree_node()->frame_tree_node_id();
2736 // It is possible to get multiple calls to OnDidStartLoading that don't have
2737 // corresponding calls to OnDidStopLoading:
2738 // - With "swappedout://" URLs, this happens when a RenderView gets swapped
2739 // out for a cross-process navigation, and it turns into a placeholder for
2740 // one being rendered in a different process.
2741 // - Also, there might be more than one RenderFrameHost sharing the same
2742 // FrameTreeNode (and thus sharing its ID) each sending a start.
2743 // - But in the future, once clamy@ moves navigation network requests to the
2744 // browser process, there's a good chance that callbacks about starting and
2745 // stopping will all be handled by the browser. When that happens, there
2746 // should no longer be a start/stop call imbalance. TODO(avi): When this
2747 // future arrives, update this code to not allow this case.
2748 DCHECK_GE(loading_frames_in_progress_, 0);
2749 if (loading_progresses_.find(render_frame_id) == loading_progresses_.end()) {
2750 if (loading_frames_in_progress_ == 0)
2751 DidStartLoading(rfh, to_different_document);
2752 ++loading_frames_in_progress_;
2755 loading_progresses_[render_frame_id] = kMinimumLoadingProgress;
2756 SendLoadProgressChanged();
2759 void WebContentsImpl::OnDidStopLoading() {
2760 RenderFrameHostImpl* rfh =
2761 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2762 int64 render_frame_id = rfh->frame_tree_node()->frame_tree_node_id();
2764 if (loading_progresses_.find(render_frame_id) != loading_progresses_.end()) {
2765 // Load stopped while we were still tracking load. Make sure we update
2766 // progress based on this frame's completion.
2767 loading_progresses_[render_frame_id] = 1.0;
2768 SendLoadProgressChanged();
2769 // Then we clean-up our states.
2770 if (loading_total_progress_ == 1.0)
2771 ResetLoadProgressState();
2774 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
2775 // calls DidStopLoading() without a matching DidStartLoading().
2776 if (loading_frames_in_progress_ == 0)
2777 return;
2778 --loading_frames_in_progress_;
2779 if (loading_frames_in_progress_ == 0)
2780 DidStopLoading(rfh);
2783 void WebContentsImpl::OnDidChangeLoadProgress(double load_progress) {
2784 RenderFrameHostImpl* rfh =
2785 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2786 int64 render_frame_id = rfh->frame_tree_node()->frame_tree_node_id();
2788 loading_progresses_[render_frame_id] = load_progress;
2790 // We notify progress change immediately for the first and last updates.
2791 // Also, since the message loop may be pretty busy when a page is loaded, it
2792 // might not execute a posted task in a timely manner so we make sure to
2793 // immediately send progress report if enough time has passed.
2794 base::TimeDelta min_delay =
2795 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
2796 if (load_progress == 1.0 || loading_last_progress_update_.is_null() ||
2797 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay) {
2798 // If there is a pending task to send progress, it is now obsolete.
2799 loading_weak_factory_.InvalidateWeakPtrs();
2800 SendLoadProgressChanged();
2801 if (loading_total_progress_ == 1.0)
2802 ResetLoadProgressState();
2803 return;
2806 if (loading_weak_factory_.HasWeakPtrs())
2807 return;
2809 base::MessageLoop::current()->PostDelayedTask(
2810 FROM_HERE,
2811 base::Bind(&WebContentsImpl::SendLoadProgressChanged,
2812 loading_weak_factory_.GetWeakPtr()),
2813 min_delay);
2816 void WebContentsImpl::OnGoToEntryAtOffset(int offset) {
2817 if (!delegate_ || delegate_->OnGoToEntryOffset(offset))
2818 controller_.GoToOffset(offset);
2821 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent,
2822 int maximum_percent) {
2823 minimum_zoom_percent_ = minimum_percent;
2824 maximum_zoom_percent_ = maximum_percent;
2827 void WebContentsImpl::OnEnumerateDirectory(int request_id,
2828 const base::FilePath& path) {
2829 if (!delegate_)
2830 return;
2832 ChildProcessSecurityPolicyImpl* policy =
2833 ChildProcessSecurityPolicyImpl::GetInstance();
2834 if (policy->CanReadFile(GetRenderProcessHost()->GetID(), path))
2835 delegate_->EnumerateDirectory(this, request_id, path);
2838 void WebContentsImpl::OnRegisterProtocolHandler(const std::string& protocol,
2839 const GURL& url,
2840 const base::string16& title,
2841 bool user_gesture) {
2842 if (!delegate_)
2843 return;
2845 ChildProcessSecurityPolicyImpl* policy =
2846 ChildProcessSecurityPolicyImpl::GetInstance();
2847 if (policy->IsPseudoScheme(protocol))
2848 return;
2850 delegate_->RegisterProtocolHandler(this, protocol, url, user_gesture);
2853 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string& protocol,
2854 const GURL& url,
2855 bool user_gesture) {
2856 if (!delegate_)
2857 return;
2859 ChildProcessSecurityPolicyImpl* policy =
2860 ChildProcessSecurityPolicyImpl::GetInstance();
2861 if (policy->IsPseudoScheme(protocol))
2862 return;
2864 delegate_->UnregisterProtocolHandler(this, protocol, url, user_gesture);
2867 void WebContentsImpl::OnFindReply(int request_id,
2868 int number_of_matches,
2869 const gfx::Rect& selection_rect,
2870 int active_match_ordinal,
2871 bool final_update) {
2872 if (delegate_) {
2873 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
2874 active_match_ordinal, final_update);
2878 #if defined(OS_ANDROID)
2879 void WebContentsImpl::OnFindMatchRectsReply(
2880 int version,
2881 const std::vector<gfx::RectF>& rects,
2882 const gfx::RectF& active_rect) {
2883 if (delegate_)
2884 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
2887 void WebContentsImpl::OnOpenDateTimeDialog(
2888 const ViewHostMsg_DateTimeDialogValue_Params& value) {
2889 date_time_chooser_->ShowDialog(GetTopLevelNativeWindow(),
2890 GetRenderViewHost(),
2891 value.dialog_type,
2892 value.dialog_value,
2893 value.minimum,
2894 value.maximum,
2895 value.step,
2896 value.suggestions);
2898 #endif
2900 void WebContentsImpl::OnDomOperationResponse(const std::string& json_string,
2901 int automation_id) {
2902 DomOperationNotificationDetails details(json_string, automation_id);
2903 NotificationService::current()->Notify(
2904 NOTIFICATION_DOM_OPERATION_RESPONSE,
2905 Source<WebContents>(this),
2906 Details<DomOperationNotificationDetails>(&details));
2909 void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
2910 bool blocked_by_policy) {
2911 // Notify observers about navigation.
2912 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2913 AppCacheAccessed(manifest_url, blocked_by_policy));
2916 void WebContentsImpl::OnOpenColorChooser(
2917 int color_chooser_id,
2918 SkColor color,
2919 const std::vector<ColorSuggestion>& suggestions) {
2920 ColorChooser* new_color_chooser = delegate_ ?
2921 delegate_->OpenColorChooser(this, color, suggestions) :
2922 NULL;
2923 if (!new_color_chooser)
2924 return;
2925 if (color_chooser_info_.get())
2926 color_chooser_info_->chooser->End();
2928 color_chooser_info_.reset(new ColorChooserInfo(
2929 render_frame_message_source_->GetProcess()->GetID(),
2930 render_frame_message_source_->GetRoutingID(),
2931 new_color_chooser,
2932 color_chooser_id));
2935 void WebContentsImpl::OnEndColorChooser(int color_chooser_id) {
2936 if (color_chooser_info_ &&
2937 color_chooser_id == color_chooser_info_->identifier)
2938 color_chooser_info_->chooser->End();
2941 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id,
2942 SkColor color) {
2943 if (color_chooser_info_ &&
2944 color_chooser_id == color_chooser_info_->identifier)
2945 color_chooser_info_->chooser->SetSelectedColor(color);
2948 // This exists for render views that don't have a WebUI, but do have WebUI
2949 // bindings enabled.
2950 void WebContentsImpl::OnWebUISend(const GURL& source_url,
2951 const std::string& name,
2952 const base::ListValue& args) {
2953 if (delegate_)
2954 delegate_->WebUISend(this, source_url, name, args);
2957 #if defined(ENABLE_PLUGINS)
2958 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id,
2959 const base::FilePath& path,
2960 bool is_hung) {
2961 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
2963 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2964 PluginHungStatusChanged(plugin_child_id, path, is_hung));
2967 void WebContentsImpl::OnPluginCrashed(const base::FilePath& plugin_path,
2968 base::ProcessId plugin_pid) {
2969 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2970 PluginCrashed(plugin_path, plugin_pid));
2973 void WebContentsImpl::OnRequestPpapiBrokerPermission(
2974 int routing_id,
2975 const GURL& url,
2976 const base::FilePath& plugin_path) {
2977 if (!delegate_) {
2978 OnPpapiBrokerPermissionResult(routing_id, false);
2979 return;
2982 if (!delegate_->RequestPpapiBrokerPermission(
2983 this, url, plugin_path,
2984 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult,
2985 base::Unretained(this), routing_id))) {
2986 NOTIMPLEMENTED();
2987 OnPpapiBrokerPermissionResult(routing_id, false);
2991 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id,
2992 bool result) {
2993 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id, result));
2996 void WebContentsImpl::OnBrowserPluginMessage(const IPC::Message& message) {
2997 // This creates a BrowserPluginEmbedder, which handles all the BrowserPlugin
2998 // specific messages for this WebContents. This means that any message from
2999 // a BrowserPlugin prior to this will be ignored.
3000 // For more info, see comment above classes BrowserPluginEmbedder and
3001 // BrowserPluginGuest.
3002 CHECK(!browser_plugin_embedder_.get());
3003 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
3004 browser_plugin_embedder_->OnMessageReceived(message);
3006 #endif // defined(ENABLE_PLUGINS)
3008 void WebContentsImpl::OnDidDownloadImage(
3009 int id,
3010 int http_status_code,
3011 const GURL& image_url,
3012 const std::vector<SkBitmap>& bitmaps,
3013 const std::vector<gfx::Size>& original_bitmap_sizes) {
3014 if (bitmaps.size() != original_bitmap_sizes.size())
3015 return;
3017 ImageDownloadMap::iterator iter = image_download_map_.find(id);
3018 if (iter == image_download_map_.end()) {
3019 // Currently WebContents notifies us of ANY downloads so that it is
3020 // possible to get here.
3021 return;
3023 if (!iter->second.is_null()) {
3024 iter->second.Run(
3025 id, http_status_code, image_url, bitmaps, original_bitmap_sizes);
3027 image_download_map_.erase(id);
3030 void WebContentsImpl::OnUpdateFaviconURL(
3031 const std::vector<FaviconURL>& candidates) {
3032 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3033 DidUpdateFaviconURL(candidates));
3036 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3037 // ChromeOS has its own way of handling power save blocks for media.
3038 #if !defined(OS_CHROMEOS)
3039 DCHECK(!audio_power_save_blocker_);
3040 audio_power_save_blocker_ = PowerSaveBlocker::Create(
3041 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension, "Playing Audio");
3042 #endif
3045 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3046 // ChromeOS has its own way of handling power save blocks for media.
3047 #if !defined(OS_CHROMEOS)
3048 DCHECK(!video_power_save_blocker_);
3049 DCHECK(!active_video_players_.empty());
3050 video_power_save_blocker_ = PowerSaveBlocker::Create(
3051 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep, "Playing Video");
3052 #if defined(OS_ANDROID)
3053 static_cast<PowerSaveBlockerImpl*>(video_power_save_blocker_.get())
3054 ->InitDisplaySleepBlocker(GetView()->GetNativeView());
3055 #endif
3056 #endif
3059 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3060 // If there are no more audio players and we don't have audio stream
3061 // monitoring, release the audio power save blocker here instead of during
3062 // NotifyNavigationStateChanged().
3063 if (active_audio_players_.empty() &&
3064 !AudioStreamMonitor::monitoring_available()) {
3065 audio_power_save_blocker_.reset();
3068 // If there are no more video players, clear the video power save blocker.
3069 if (active_video_players_.empty())
3070 video_power_save_blocker_.reset();
3073 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie,
3074 bool has_video,
3075 bool has_audio,
3076 bool is_remote) {
3077 // Ignore the videos playing remotely and don't hold the wake lock for the
3078 // screen.
3079 if (is_remote) return;
3081 if (has_audio) {
3082 AddMediaPlayerEntry(player_cookie, &active_audio_players_);
3084 // If we don't have audio stream monitoring, allocate the audio power save
3085 // blocker here instead of during NotifyNavigationStateChanged().
3086 if (!audio_power_save_blocker_ &&
3087 !AudioStreamMonitor::monitoring_available()) {
3088 CreateAudioPowerSaveBlocker();
3092 if (has_video) {
3093 AddMediaPlayerEntry(player_cookie, &active_video_players_);
3095 // If we're not hidden and have just created a player, create a blocker.
3096 if (!video_power_save_blocker_ && !IsHidden())
3097 CreateVideoPowerSaveBlocker();
3101 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie) {
3102 RemoveMediaPlayerEntry(player_cookie, &active_audio_players_);
3103 RemoveMediaPlayerEntry(player_cookie, &active_video_players_);
3104 MaybeReleasePowerSaveBlockers();
3107 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3108 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3109 DidFirstVisuallyNonEmptyPaint());
3112 void WebContentsImpl::DidChangeVisibleSSLState() {
3113 if (delegate_)
3114 delegate_->VisibleSSLStateChanged(this);
3117 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3118 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3119 BeforeFormRepostWarningShow());
3122 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3123 Activate();
3124 if (delegate_)
3125 delegate_->ShowRepostFormWarningDialog(this);
3128 bool WebContentsImpl::HasAccessedInitialDocument() {
3129 return has_accessed_initial_document_;
3132 // Notifies the RenderWidgetHost instance about the fact that the page is
3133 // loading, or done loading.
3134 void WebContentsImpl::SetIsLoading(RenderViewHost* render_view_host,
3135 bool is_loading,
3136 bool to_different_document,
3137 LoadNotificationDetails* details) {
3138 if (is_loading == is_loading_)
3139 return;
3141 if (!is_loading) {
3142 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
3143 base::string16());
3144 load_state_host_.clear();
3145 upload_size_ = 0;
3146 upload_position_ = 0;
3149 GetRenderManager()->SetIsLoading(is_loading);
3151 is_loading_ = is_loading;
3152 waiting_for_response_ = is_loading;
3153 is_load_to_different_document_ = to_different_document;
3155 if (delegate_)
3156 delegate_->LoadingStateChanged(this, to_different_document);
3157 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
3159 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
3160 if (is_loading) {
3161 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3162 this, "URL", url);
3163 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3164 DidStartLoading(render_view_host));
3165 } else {
3166 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3167 this, "URL", url);
3168 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3169 DidStopLoading(render_view_host));
3172 // TODO(avi): Remove. http://crbug.com/170921
3173 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
3174 NotificationDetails det = NotificationService::NoDetails();
3175 if (details)
3176 det = Details<LoadNotificationDetails>(details);
3177 NotificationService::current()->Notify(
3178 type, Source<NavigationController>(&controller_), det);
3181 void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
3182 RenderFrameHost* focused_frame = GetFocusedFrame();
3183 if (!focused_frame)
3184 return;
3186 focused_frame->Send(new InputMsg_MoveRangeSelectionExtent(
3187 focused_frame->GetRoutingID(), extent));
3190 void WebContentsImpl::SelectRange(const gfx::Point& base,
3191 const gfx::Point& extent) {
3192 RenderFrameHost* focused_frame = GetFocusedFrame();
3193 if (!focused_frame)
3194 return;
3196 focused_frame->Send(
3197 new InputMsg_SelectRange(focused_frame->GetRoutingID(), base, extent));
3200 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost* rvh) {
3201 // If we are creating a RVH for a restored controller, then we need to make
3202 // sure the RenderView starts with a next_page_id_ larger than the number
3203 // of restored entries. This must be called before the RenderView starts
3204 // navigating (to avoid a race between the browser updating max_page_id and
3205 // the renderer updating next_page_id_). Because of this, we only call this
3206 // from CreateRenderView and allow that to notify the RenderView for us.
3207 int max_restored_page_id = controller_.GetMaxRestoredPageID();
3208 if (max_restored_page_id >
3209 GetMaxPageIDForSiteInstance(rvh->GetSiteInstance()))
3210 UpdateMaxPageIDForSiteInstance(rvh->GetSiteInstance(),
3211 max_restored_page_id);
3214 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl* entry,
3215 const base::string16& title) {
3216 // For file URLs without a title, use the pathname instead. In the case of a
3217 // synthesized title, we don't want the update to count toward the "one set
3218 // per page of the title to history."
3219 base::string16 final_title;
3220 bool explicit_set;
3221 if (entry && entry->GetURL().SchemeIsFile() && title.empty()) {
3222 final_title = base::UTF8ToUTF16(entry->GetURL().ExtractFileName());
3223 explicit_set = false; // Don't count synthetic titles toward the set limit.
3224 } else {
3225 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
3226 explicit_set = true;
3229 // If a page is created via window.open and never navigated,
3230 // there will be no navigation entry. In this situation,
3231 // |page_title_when_no_navigation_entry_| will be used for page title.
3232 if (entry) {
3233 if (final_title == entry->GetTitle())
3234 return false; // Nothing changed, don't bother.
3236 entry->SetTitle(final_title);
3237 } else {
3238 if (page_title_when_no_navigation_entry_ == final_title)
3239 return false; // Nothing changed, don't bother.
3241 page_title_when_no_navigation_entry_ = final_title;
3244 // Lastly, set the title for the view.
3245 view_->SetPageTitle(final_title);
3247 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3248 TitleWasSet(entry, explicit_set));
3250 // TODO(avi): Remove. http://crbug.com/170921
3251 std::pair<NavigationEntry*, bool> details =
3252 std::make_pair(entry, explicit_set);
3253 NotificationService::current()->Notify(
3254 NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,
3255 Source<WebContents>(this),
3256 Details<std::pair<NavigationEntry*, bool> >(&details));
3258 return true;
3261 void WebContentsImpl::SendLoadProgressChanged() {
3262 loading_last_progress_update_ = base::TimeTicks::Now();
3263 double progress = 0.0;
3264 int frame_count = 0;
3266 for (LoadingProgressMap::iterator it = loading_progresses_.begin();
3267 it != loading_progresses_.end();
3268 ++it) {
3269 progress += it->second;
3270 ++frame_count;
3272 if (frame_count == 0)
3273 return;
3274 progress /= frame_count;
3275 DCHECK(progress <= 1.0);
3277 if (progress <= loading_total_progress_)
3278 return;
3279 loading_total_progress_ = progress;
3281 if (delegate_)
3282 delegate_->LoadProgressChanged(this, progress);
3285 void WebContentsImpl::ResetLoadProgressState() {
3286 loading_progresses_.clear();
3287 loading_total_progress_ = 0.0;
3288 loading_weak_factory_.InvalidateWeakPtrs();
3289 loading_last_progress_update_ = base::TimeTicks();
3292 void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_host,
3293 RenderViewHost* new_host) {
3294 // After sending out a swap notification, we need to send a disconnect
3295 // notification so that clients that pick up a pointer to |this| can NULL the
3296 // pointer. See Bug 1230284.
3297 notify_disconnection_ = true;
3298 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3299 RenderViewHostChanged(old_host, new_host));
3301 // TODO(avi): Remove. http://crbug.com/170921
3302 std::pair<RenderViewHost*, RenderViewHost*> details =
3303 std::make_pair(old_host, new_host);
3304 NotificationService::current()->Notify(
3305 NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
3306 Source<WebContents>(this),
3307 Details<std::pair<RenderViewHost*, RenderViewHost*> >(&details));
3309 // Ensure that the associated embedder gets cleared after a RenderViewHost
3310 // gets swapped, so we don't reuse the same embedder next time a
3311 // RenderViewHost is attached to this WebContents.
3312 RemoveBrowserPluginEmbedder();
3315 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_host,
3316 RenderFrameHost* new_host) {
3317 FOR_EACH_OBSERVER(WebContentsObserver,
3318 observers_,
3319 RenderFrameHostChanged(old_host, new_host));
3322 // TODO(avi): Remove this entire function because this notification is already
3323 // covered by two observer functions. http://crbug.com/170921
3324 void WebContentsImpl::NotifyDisconnected() {
3325 if (!notify_disconnection_)
3326 return;
3328 notify_disconnection_ = false;
3329 NotificationService::current()->Notify(
3330 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
3331 Source<WebContents>(this),
3332 NotificationService::NoDetails());
3335 void WebContentsImpl::NotifyNavigationEntryCommitted(
3336 const LoadCommittedDetails& load_details) {
3337 FOR_EACH_OBSERVER(
3338 WebContentsObserver, observers_, NavigationEntryCommitted(load_details));
3341 bool WebContentsImpl::OnMessageReceived(RenderFrameHost* render_frame_host,
3342 const IPC::Message& message) {
3343 return OnMessageReceived(NULL, render_frame_host, message);
3346 const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3347 return GetLastCommittedURL();
3350 void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
3351 // Note this is only for subframes, the notification for the main frame
3352 // happens in RenderViewCreated.
3353 FOR_EACH_OBSERVER(WebContentsObserver,
3354 observers_,
3355 RenderFrameCreated(render_frame_host));
3356 SetAccessibilityModeOnFrame(accessibility_mode_, render_frame_host);
3359 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
3360 ClearPowerSaveBlockers(render_frame_host);
3361 FOR_EACH_OBSERVER(WebContentsObserver,
3362 observers_,
3363 RenderFrameDeleted(render_frame_host));
3366 void WebContentsImpl::WorkerCrashed(RenderFrameHost* render_frame_host) {
3367 if (delegate_)
3368 delegate_->WorkerCrashed(this);
3371 void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
3372 const ContextMenuParams& params) {
3373 ContextMenuParams context_menu_params(params);
3374 // Allow WebContentsDelegates to handle the context menu operation first.
3375 if (GetBrowserPluginGuest()) {
3376 WebContentsViewGuest* view_guest =
3377 static_cast<WebContentsViewGuest*>(GetView());
3378 context_menu_params = view_guest->ConvertContextMenuParams(params);
3380 if (delegate_ && delegate_->HandleContextMenu(context_menu_params))
3381 return;
3383 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
3384 context_menu_params);
3387 void WebContentsImpl::RunJavaScriptMessage(
3388 RenderFrameHost* render_frame_host,
3389 const base::string16& message,
3390 const base::string16& default_prompt,
3391 const GURL& frame_url,
3392 JavaScriptMessageType javascript_message_type,
3393 IPC::Message* reply_msg) {
3394 // Suppress JavaScript dialogs when requested. Also suppress messages when
3395 // showing an interstitial as it's shown over the previous page and we don't
3396 // want the hidden page's dialogs to interfere with the interstitial.
3397 bool suppress_this_message =
3398 static_cast<RenderFrameHostImpl*>(render_frame_host)->is_swapped_out() ||
3399 ShowingInterstitialPage() ||
3400 !delegate_ ||
3401 delegate_->ShouldSuppressDialogs() ||
3402 !delegate_->GetJavaScriptDialogManager();
3404 if (!suppress_this_message) {
3405 std::string accept_lang = GetContentClient()->browser()->
3406 GetAcceptLangs(GetBrowserContext());
3407 dialog_manager_ = delegate_->GetJavaScriptDialogManager();
3408 dialog_manager_->RunJavaScriptDialog(
3409 this,
3410 frame_url.GetOrigin(),
3411 accept_lang,
3412 javascript_message_type,
3413 message,
3414 default_prompt,
3415 base::Bind(&WebContentsImpl::OnDialogClosed,
3416 base::Unretained(this),
3417 render_frame_host->GetProcess()->GetID(),
3418 render_frame_host->GetRoutingID(),
3419 reply_msg,
3420 false),
3421 &suppress_this_message);
3424 if (suppress_this_message) {
3425 // If we are suppressing messages, just reply as if the user immediately
3426 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3427 OnDialogClosed(render_frame_host->GetProcess()->GetID(),
3428 render_frame_host->GetRoutingID(), reply_msg,
3429 true, false, base::string16());
3432 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3433 // http://crbug.com/288961 ). The only safe thing to do here is return.
3436 void WebContentsImpl::RunBeforeUnloadConfirm(
3437 RenderFrameHost* render_frame_host,
3438 const base::string16& message,
3439 bool is_reload,
3440 IPC::Message* reply_msg) {
3441 RenderFrameHostImpl* rfhi =
3442 static_cast<RenderFrameHostImpl*>(render_frame_host);
3443 if (delegate_)
3444 delegate_->WillRunBeforeUnloadConfirm();
3446 bool suppress_this_message =
3447 rfhi->rfh_state() != RenderFrameHostImpl::STATE_DEFAULT ||
3448 !delegate_ ||
3449 delegate_->ShouldSuppressDialogs() ||
3450 !delegate_->GetJavaScriptDialogManager();
3451 if (suppress_this_message) {
3452 rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16(), true);
3453 return;
3456 is_showing_before_unload_dialog_ = true;
3457 dialog_manager_ = delegate_->GetJavaScriptDialogManager();
3458 dialog_manager_->RunBeforeUnloadDialog(
3459 this, message, is_reload,
3460 base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
3461 render_frame_host->GetProcess()->GetID(),
3462 render_frame_host->GetRoutingID(), reply_msg,
3463 false));
3466 WebContents* WebContentsImpl::GetAsWebContents() {
3467 return this;
3470 bool WebContentsImpl::IsNeverVisible() {
3471 if (!delegate_)
3472 return false;
3473 return delegate_->IsNeverVisible(this);
3476 #if defined(OS_WIN)
3477 gfx::NativeViewAccessible WebContentsImpl::GetParentNativeViewAccessible() {
3478 return accessible_parent_;
3480 #endif
3482 RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
3483 return render_view_host_delegate_view_;
3486 RendererPreferences WebContentsImpl::GetRendererPrefs(
3487 BrowserContext* browser_context) const {
3488 return renderer_preferences_;
3491 gfx::Rect WebContentsImpl::GetRootWindowResizerRect() const {
3492 if (delegate_)
3493 return delegate_->GetRootWindowResizerRect();
3494 return gfx::Rect();
3497 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3498 if (browser_plugin_embedder_)
3499 browser_plugin_embedder_.reset();
3502 void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
3503 // Don't send notifications if we are just creating a swapped-out RVH for
3504 // the opener chain. These won't be used for view-source or WebUI, so it's
3505 // ok to return early.
3506 if (!static_cast<RenderViewHostImpl*>(render_view_host)->is_active())
3507 return;
3509 if (delegate_)
3510 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
3512 NotificationService::current()->Notify(
3513 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
3514 Source<WebContents>(this),
3515 Details<RenderViewHost>(render_view_host));
3517 // When we're creating views, we're still doing initial setup, so we always
3518 // use the pending Web UI rather than any possibly existing committed one.
3519 if (GetRenderManager()->pending_web_ui())
3520 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host);
3522 NavigationEntry* entry = controller_.GetPendingEntry();
3523 if (entry && entry->IsViewSourceMode()) {
3524 // Put the renderer in view source mode.
3525 render_view_host->Send(
3526 new ViewMsg_EnableViewSourceMode(render_view_host->GetRoutingID()));
3529 view_->RenderViewCreated(render_view_host);
3531 FOR_EACH_OBSERVER(
3532 WebContentsObserver, observers_, RenderViewCreated(render_view_host));
3534 // We tell the observers now instead of when the main RenderFrameHostImpl is
3535 // constructed because otherwise it would be too early (i.e. IPCs sent to the
3536 // frame would be dropped because it's not created yet).
3537 RenderFrameHost* main_frame = render_view_host->GetMainFrame();
3538 FOR_EACH_OBSERVER(
3539 WebContentsObserver, observers_, RenderFrameCreated(main_frame));
3540 SetAccessibilityModeOnFrame(accessibility_mode_, main_frame);
3542 DevToolsManager::GetInstance()->RenderViewCreated(this, render_view_host);
3545 void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
3546 if (rvh != GetRenderViewHost()) {
3547 // Don't notify the world, since this came from a renderer in the
3548 // background.
3549 return;
3552 notify_disconnection_ = true;
3553 // TODO(avi): Remove. http://crbug.com/170921
3554 NotificationService::current()->Notify(
3555 NOTIFICATION_WEB_CONTENTS_CONNECTED,
3556 Source<WebContents>(this),
3557 NotificationService::NoDetails());
3559 bool was_crashed = IsCrashed();
3560 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
3562 // Restore the focus to the tab (otherwise the focus will be on the top
3563 // window).
3564 if (was_crashed && !FocusLocationBarByDefault() &&
3565 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
3566 view_->Focus();
3569 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewReady());
3572 void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
3573 base::TerminationStatus status,
3574 int error_code) {
3575 if (rvh != GetRenderViewHost()) {
3576 // The pending page's RenderViewHost is gone.
3577 return;
3580 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3581 // renderer may not have made a clean exit.
3582 if (IsFullscreenForCurrentTab())
3583 ToggleFullscreenMode(false);
3585 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3586 if (dialog_manager_)
3587 dialog_manager_->CancelActiveAndPendingDialogs(this);
3589 if (delegate_)
3590 delegate_->HideValidationMessage(this);
3592 SetIsLoading(rvh, false, true, NULL);
3593 NotifyDisconnected();
3594 SetIsCrashed(status, error_code);
3596 // Reset the loading progress. TODO(avi): What does it mean to have a
3597 // "renderer crash" when there is more than one renderer process serving a
3598 // webpage? Once this function is called at a more granular frame level, we
3599 // probably will need to more granularly reset the state here.
3600 ResetLoadProgressState();
3601 loading_frames_in_progress_ = 0;
3603 FOR_EACH_OBSERVER(WebContentsObserver,
3604 observers_,
3605 RenderProcessGone(GetCrashedStatus()));
3608 void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
3609 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewDeleted(rvh));
3612 void WebContentsImpl::UpdateState(RenderViewHost* rvh,
3613 int32 page_id,
3614 const PageState& page_state) {
3615 // Ensure that this state update comes from either the active RVH or one of
3616 // the swapped out RVHs. We don't expect to hear from any other RVHs.
3617 // TODO(nasko): This should go through RenderFrameHost.
3618 // TODO(creis): We can't update state for cross-process subframes until we
3619 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
3620 if (rvh != GetRenderViewHost() &&
3621 !GetRenderManager()->IsRVHOnSwappedOutList(
3622 static_cast<RenderViewHostImpl*>(rvh)))
3623 return;
3625 // We must be prepared to handle state updates for any page, these occur
3626 // when the user is scrolling and entering form data, as well as when we're
3627 // leaving a page, in which case our state may have already been moved to
3628 // the next page. The navigation controller will look up the appropriate
3629 // NavigationEntry and update it when it is notified via the delegate.
3631 int entry_index = controller_.GetEntryIndexWithPageID(
3632 rvh->GetSiteInstance(), page_id);
3633 if (entry_index < 0)
3634 return;
3635 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
3637 if (page_state == entry->GetPageState())
3638 return; // Nothing to update.
3639 entry->SetPageState(page_state);
3640 controller_.NotifyEntryChanged(entry, entry_index);
3643 void WebContentsImpl::UpdateTargetURL(const GURL& url) {
3644 if (delegate_)
3645 delegate_->UpdateTargetURL(this, url);
3648 void WebContentsImpl::Close(RenderViewHost* rvh) {
3649 #if defined(OS_MACOSX)
3650 // The UI may be in an event-tracking loop, such as between the
3651 // mouse-down and mouse-up in text selection or a button click.
3652 // Defer the close until after tracking is complete, so that we
3653 // don't free objects out from under the UI.
3654 // TODO(shess): This could get more fine-grained. For instance,
3655 // closing a tab in another window while selecting text in the
3656 // current window's Omnibox should be just fine.
3657 if (view_->IsEventTracking()) {
3658 view_->CloseTabAfterEventTracking();
3659 return;
3661 #endif
3663 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3664 if (delegate_ && rvh == GetRenderViewHost())
3665 delegate_->CloseContents(this);
3668 void WebContentsImpl::SwappedOut(RenderFrameHost* rfh) {
3669 if (delegate_ && rfh->GetRenderViewHost() == GetRenderViewHost())
3670 delegate_->SwappedOut(this);
3673 void WebContentsImpl::DidDeferAfterResponseStarted(
3674 const TransitionLayerData& transition_data) {
3675 #if defined(OS_ANDROID)
3676 GetWebContentsAndroid()->DidDeferAfterResponseStarted(transition_data);
3677 #endif
3680 bool WebContentsImpl::WillHandleDeferAfterResponseStarted() {
3681 #if defined(OS_ANDROID)
3682 return GetWebContentsAndroid()->WillHandleDeferAfterResponseStarted();
3683 #else
3684 return false;
3685 #endif
3688 void WebContentsImpl::RequestMove(const gfx::Rect& new_bounds) {
3689 if (delegate_ && delegate_->IsPopupOrPanel(this))
3690 delegate_->MoveContents(this, new_bounds);
3693 void WebContentsImpl::DidStartLoading(RenderFrameHost* render_frame_host,
3694 bool to_different_document) {
3695 SetIsLoading(render_frame_host->GetRenderViewHost(), true,
3696 to_different_document, NULL);
3699 void WebContentsImpl::DidStopLoading(RenderFrameHost* render_frame_host) {
3700 scoped_ptr<LoadNotificationDetails> details;
3702 // Use the last committed entry rather than the active one, in case a
3703 // pending entry has been created.
3704 NavigationEntry* entry = controller_.GetLastCommittedEntry();
3705 Navigator* navigator = frame_tree_.root()->navigator();
3707 // An entry may not exist for a stop when loading an initial blank page or
3708 // if an iframe injected by script into a blank page finishes loading.
3709 if (entry) {
3710 base::TimeDelta elapsed =
3711 base::TimeTicks::Now() - navigator->GetCurrentLoadStart();
3713 details.reset(new LoadNotificationDetails(
3714 entry->GetVirtualURL(),
3715 entry->GetTransitionType(),
3716 elapsed,
3717 &controller_,
3718 controller_.GetCurrentEntryIndex()));
3721 SetIsLoading(render_frame_host->GetRenderViewHost(), false, true,
3722 details.get());
3725 void WebContentsImpl::DidCancelLoading() {
3726 controller_.DiscardNonCommittedEntries();
3728 // Update the URL display.
3729 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3732 void WebContentsImpl::DidAccessInitialDocument() {
3733 has_accessed_initial_document_ = true;
3735 // We may have left a failed browser-initiated navigation in the address bar
3736 // to let the user edit it and try again. Clear it now that content might
3737 // show up underneath it.
3738 if (!IsLoading() && controller_.GetPendingEntry())
3739 controller_.DiscardPendingEntry();
3741 // Update the URL display.
3742 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3745 void WebContentsImpl::DidDisownOpener(RenderFrameHost* render_frame_host) {
3746 // No action is necessary if the opener has already been cleared.
3747 if (!opener_)
3748 return;
3750 // Clear our opener so that future cross-process navigations don't have an
3751 // opener assigned.
3752 RemoveDestructionObserver(opener_);
3753 opener_ = NULL;
3755 // Notify all swapped out RenderViewHosts for this tab. This is important
3756 // in case we go back to them, or if another window in those processes tries
3757 // to access window.opener.
3758 GetRenderManager()->DidDisownOpener(render_frame_host);
3761 void WebContentsImpl::DocumentOnLoadCompleted(
3762 RenderFrameHost* render_frame_host) {
3763 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3764 DocumentOnLoadCompletedInMainFrame());
3766 // TODO(avi): Remove. http://crbug.com/170921
3767 NotificationService::current()->Notify(
3768 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
3769 Source<WebContents>(this),
3770 NotificationService::NoDetails());
3773 void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
3774 int32 page_id,
3775 const base::string16& title,
3776 base::i18n::TextDirection title_direction) {
3777 RenderViewHost* rvh = render_frame_host->GetRenderViewHost();
3779 // If we have a title, that's a pretty good indication that we've started
3780 // getting useful data.
3781 SetNotWaitingForResponse();
3783 // Try to find the navigation entry, which might not be the current one.
3784 // For example, it might be from a pending RVH for the pending entry.
3785 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
3786 rvh->GetSiteInstance(), page_id);
3788 // We can handle title updates when we don't have an entry in
3789 // UpdateTitleForEntry, but only if the update is from the current RVH.
3790 // TODO(avi): Change to make decisions based on the RenderFrameHost.
3791 if (!entry && rvh != GetRenderViewHost())
3792 return;
3794 // TODO(evan): make use of title_direction.
3795 // http://code.google.com/p/chromium/issues/detail?id=27094
3796 if (!UpdateTitleForEntry(entry, title))
3797 return;
3799 // Broadcast notifications when the UI should be updated.
3800 if (entry == controller_.GetEntryAtOffset(0))
3801 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
3804 void WebContentsImpl::UpdateEncoding(RenderFrameHost* render_frame_host,
3805 const std::string& encoding) {
3806 SetEncoding(encoding);
3809 void WebContentsImpl::DocumentAvailableInMainFrame(
3810 RenderViewHost* render_view_host) {
3811 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3812 DocumentAvailableInMainFrame());
3814 void WebContentsImpl::RouteCloseEvent(RenderViewHost* rvh) {
3815 // Tell the active RenderViewHost to run unload handlers and close, as long
3816 // as the request came from a RenderViewHost in the same BrowsingInstance.
3817 // In most cases, we receive this from a swapped out RenderViewHost.
3818 // It is possible to receive it from one that has just been swapped in,
3819 // in which case we might as well deliver the message anyway.
3820 if (rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3821 GetRenderViewHost()->ClosePage();
3824 void WebContentsImpl::RouteMessageEvent(
3825 RenderViewHost* rvh,
3826 const ViewMsg_PostMessage_Params& params) {
3827 // Only deliver the message to the active RenderViewHost if the request
3828 // came from a RenderViewHost in the same BrowsingInstance or if this
3829 // WebContents is dedicated to a browser plugin guest.
3830 // Note: This check means that an embedder could theoretically receive a
3831 // postMessage from anyone (not just its own guests). However, this is
3832 // probably not a risk for apps since other pages won't have references
3833 // to App windows.
3834 if (!rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()) &&
3835 !GetBrowserPluginGuest() && !GetBrowserPluginEmbedder())
3836 return;
3838 ViewMsg_PostMessage_Params new_params(params);
3840 if (!params.message_port_ids.empty()) {
3841 MessagePortMessageFilter* message_port_message_filter =
3842 static_cast<RenderProcessHostImpl*>(GetRenderProcessHost())
3843 ->message_port_message_filter();
3844 message_port_message_filter->UpdateMessagePortsWithNewRoutes(
3845 params.message_port_ids,
3846 &new_params.new_routing_ids);
3849 // If there is a source_routing_id, translate it to the routing ID for
3850 // the equivalent swapped out RVH in the target process. If we need
3851 // to create a swapped out RVH for the source tab, we create its opener
3852 // chain as well, since those will also be accessible to the target page.
3853 if (new_params.source_routing_id != MSG_ROUTING_NONE) {
3854 // Try to look up the WebContents for the source page.
3855 WebContentsImpl* source_contents = NULL;
3856 RenderViewHostImpl* source_rvh = RenderViewHostImpl::FromID(
3857 rvh->GetProcess()->GetID(), params.source_routing_id);
3858 if (source_rvh) {
3859 source_contents = static_cast<WebContentsImpl*>(
3860 source_rvh->GetDelegate()->GetAsWebContents());
3863 if (source_contents) {
3864 if (GetBrowserPluginGuest()) {
3865 // We create a swapped out RenderView for the embedder in the guest's
3866 // render process but we intentionally do not expose the embedder's
3867 // opener chain to it.
3868 new_params.source_routing_id =
3869 source_contents->CreateSwappedOutRenderView(GetSiteInstance());
3870 } else {
3871 new_params.source_routing_id =
3872 source_contents->CreateOpenerRenderViews(GetSiteInstance());
3874 } else {
3875 // We couldn't find it, so don't pass a source frame.
3876 new_params.source_routing_id = MSG_ROUTING_NONE;
3880 // In most cases, we receive this from a swapped out RenderViewHost.
3881 // It is possible to receive it from one that has just been swapped in,
3882 // in which case we might as well deliver the message anyway.
3883 Send(new ViewMsg_PostMessageEvent(GetRoutingID(), new_params));
3886 bool WebContentsImpl::AddMessageToConsole(int32 level,
3887 const base::string16& message,
3888 int32 line_no,
3889 const base::string16& source_id) {
3890 if (!delegate_)
3891 return false;
3892 return delegate_->AddMessageToConsole(this, level, message, line_no,
3893 source_id);
3896 WebPreferences WebContentsImpl::ComputeWebkitPrefs() {
3897 // We want to base the page config off of the actual URL, rather than the
3898 // virtual URL.
3899 // TODO(nasko): Investigate how to remove the GetActiveEntry usage here,
3900 // as it is deprecated and can be out of sync with GetRenderViewHost().
3901 GURL url = controller_.GetActiveEntry()
3902 ? controller_.GetActiveEntry()->GetURL() : GURL::EmptyGURL();
3904 return GetRenderManager()->current_host()->ComputeWebkitPrefs(url);
3907 int WebContentsImpl::CreateSwappedOutRenderView(
3908 SiteInstance* instance) {
3909 return GetRenderManager()->CreateRenderFrame(
3910 instance, MSG_ROUTING_NONE, CREATE_RF_SWAPPED_OUT |
3911 CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
3912 CREATE_RF_HIDDEN);
3915 void WebContentsImpl::OnUserGesture() {
3916 // Notify observers.
3917 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetUserGesture());
3919 ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
3920 if (rdh) // NULL in unittests.
3921 rdh->OnUserGesture(this);
3924 void WebContentsImpl::OnIgnoredUIEvent() {
3925 // Notify observers.
3926 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetIgnoredUIEvent());
3929 void WebContentsImpl::RendererUnresponsive(RenderViewHost* render_view_host) {
3930 // Don't show hung renderer dialog for a swapped out RVH.
3931 if (render_view_host != GetRenderViewHost())
3932 return;
3934 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(render_view_host);
3935 RenderFrameHostImpl* rfhi =
3936 static_cast<RenderFrameHostImpl*>(rvhi->GetMainFrame());
3938 // Ignore renderer unresponsive event if debugger is attached to the tab
3939 // since the event may be a result of the renderer sitting on a breakpoint.
3940 // See http://crbug.com/65458
3941 if (DevToolsAgentHost::IsDebuggerAttached(this))
3942 return;
3944 if (rfhi->is_waiting_for_beforeunload_ack() ||
3945 rfhi->IsWaitingForUnloadACK()) {
3946 // Hang occurred while firing the beforeunload/unload handler.
3947 // Pretend the handler fired so tab closing continues as if it had.
3948 rvhi->set_sudden_termination_allowed(true);
3950 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
3951 return;
3953 // If the tab hangs in the beforeunload/unload handler there's really
3954 // nothing we can do to recover. If the hang is in the beforeunload handler,
3955 // pretend the beforeunload listeners have all fired and allow the delegate
3956 // to continue closing; the user will not have the option of cancelling the
3957 // close. Otherwise, pretend the unload listeners have all fired and close
3958 // the tab.
3959 bool close = true;
3960 if (rfhi->is_waiting_for_beforeunload_ack() && delegate_) {
3961 delegate_->BeforeUnloadFired(this, true, &close);
3963 if (close)
3964 Close(rvhi);
3965 return;
3968 if (!GetRenderViewHostImpl() || !GetRenderViewHostImpl()->IsRenderViewLive())
3969 return;
3971 if (delegate_)
3972 delegate_->RendererUnresponsive(this);
3975 void WebContentsImpl::RendererResponsive(RenderViewHost* render_view_host) {
3976 if (delegate_)
3977 delegate_->RendererResponsive(this);
3980 void WebContentsImpl::LoadStateChanged(
3981 const GURL& url,
3982 const net::LoadStateWithParam& load_state,
3983 uint64 upload_position,
3984 uint64 upload_size) {
3985 load_state_ = load_state;
3986 upload_position_ = upload_position;
3987 upload_size_ = upload_size;
3988 load_state_host_ = net::IDNToUnicode(url.host(),
3989 GetContentClient()->browser()->GetAcceptLangs(
3990 GetBrowserContext()));
3991 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
3992 SetNotWaitingForResponse();
3993 if (IsLoading()) {
3994 NotifyNavigationStateChanged(static_cast<InvalidateTypes>(
3995 INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB));
3999 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
4000 bool proceed, const base::TimeTicks& proceed_time,
4001 bool* proceed_to_fire_unload) {
4002 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4003 BeforeUnloadFired(proceed_time));
4004 if (delegate_)
4005 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
4006 // Note: |this| might be deleted at this point.
4009 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4010 RenderViewHost* render_view_host) {
4011 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
4012 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
4015 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4016 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4017 gfx::Size size = GetSizeForNewRenderView();
4018 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4019 // here during container initialization and normal window size will be set
4020 // later. In case of tab duplication this resizing to 0x0 prevents setting
4021 // normal size later so just ignore it.
4022 if (!size.IsEmpty())
4023 view_->SizeContents(size);
4026 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4027 // We need to cancel modal dialogs when doing a process swap, since the load
4028 // deferrer would prevent us from swapping out.
4029 if (dialog_manager_)
4030 dialog_manager_->CancelActiveAndPendingDialogs(this);
4033 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_host,
4034 RenderFrameHost* new_host,
4035 bool is_main_frame) {
4036 if (is_main_frame) {
4037 NotifyViewSwapped(old_host ? old_host->GetRenderViewHost() : NULL,
4038 new_host->GetRenderViewHost());
4040 // Make sure the visible RVH reflects the new delegate's preferences.
4041 if (delegate_)
4042 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4044 view_->RenderViewSwappedIn(new_host->GetRenderViewHost());
4047 NotifyFrameSwapped(old_host, new_host);
4050 int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
4051 SiteInstance* instance) {
4052 if (!opener_)
4053 return MSG_ROUTING_NONE;
4055 // Recursively create RenderViews for anything else in the opener chain.
4056 return opener_->CreateOpenerRenderViews(instance);
4059 int WebContentsImpl::CreateOpenerRenderViews(SiteInstance* instance) {
4060 int opener_route_id = MSG_ROUTING_NONE;
4062 // If this tab has an opener, ensure it has a RenderView in the given
4063 // SiteInstance as well.
4064 if (opener_)
4065 opener_route_id = opener_->CreateOpenerRenderViews(instance);
4067 // If any of the renderers (current, pending, or swapped out) for this
4068 // WebContents has the same SiteInstance, use it.
4069 if (GetRenderManager()->current_host()->GetSiteInstance() == instance)
4070 return GetRenderManager()->current_host()->GetRoutingID();
4072 if (GetRenderManager()->pending_render_view_host() &&
4073 GetRenderManager()->pending_render_view_host()->GetSiteInstance() ==
4074 instance)
4075 return GetRenderManager()->pending_render_view_host()->GetRoutingID();
4077 RenderViewHostImpl* rvh = GetRenderManager()->GetSwappedOutRenderViewHost(
4078 instance);
4079 if (rvh)
4080 return rvh->GetRoutingID();
4082 // Create a swapped out RenderView in the given SiteInstance if none exists,
4083 // setting its opener to the given route_id. Return the new view's route_id.
4084 return GetRenderManager()->CreateRenderFrame(
4085 instance, opener_route_id, CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
4086 CREATE_RF_SWAPPED_OUT | CREATE_RF_HIDDEN);
4089 NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
4090 return GetController();
4093 WebUIImpl* WebContentsImpl::CreateWebUIForRenderManager(const GURL& url) {
4094 return static_cast<WebUIImpl*>(CreateWebUI(url));
4097 NavigationEntry*
4098 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4099 return controller_.GetLastCommittedEntry();
4102 bool WebContentsImpl::CreateRenderViewForRenderManager(
4103 RenderViewHost* render_view_host,
4104 int opener_route_id,
4105 int proxy_routing_id,
4106 bool for_main_frame_navigation) {
4107 TRACE_EVENT0("browser,navigation",
4108 "WebContentsImpl::CreateRenderViewForRenderManager");
4109 // Can be NULL during tests.
4110 RenderWidgetHostViewBase* rwh_view;
4111 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
4112 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
4113 // case this because RWH is still a base class of RenderViewHost, and child
4114 // frame RWHVs are unique in that they do not have their own WebContents.
4115 if (!for_main_frame_navigation) {
4116 RenderWidgetHostViewChildFrame* rwh_view_child =
4117 new RenderWidgetHostViewChildFrame(render_view_host);
4118 rwh_view = rwh_view_child;
4119 } else {
4120 rwh_view = view_->CreateViewForWidget(render_view_host, false);
4123 // Now that the RenderView has been created, we need to tell it its size.
4124 if (rwh_view)
4125 rwh_view->SetSize(GetSizeForNewRenderView());
4127 // Make sure we use the correct starting page_id in the new RenderView.
4128 UpdateMaxPageIDIfNecessary(render_view_host);
4129 int32 max_page_id =
4130 GetMaxPageIDForSiteInstance(render_view_host->GetSiteInstance());
4132 if (!static_cast<RenderViewHostImpl*>(
4133 render_view_host)->CreateRenderView(base::string16(),
4134 opener_route_id,
4135 proxy_routing_id,
4136 max_page_id,
4137 created_with_opener_)) {
4138 return false;
4141 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4142 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4143 // linux. See crbug.com/83941.
4144 if (rwh_view) {
4145 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
4146 render_widget_host->WasResized();
4148 #endif
4150 return true;
4153 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4154 RenderFrameHost* render_frame_host,
4155 int parent_routing_id,
4156 int proxy_routing_id) {
4157 TRACE_EVENT0("browser,navigation",
4158 "WebContentsImpl::CreateRenderFrameForRenderManager");
4160 RenderFrameHostImpl* rfh =
4161 static_cast<RenderFrameHostImpl*>(render_frame_host);
4162 if (!rfh->CreateRenderFrame(parent_routing_id, proxy_routing_id))
4163 return false;
4165 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4166 // RenderFrameHost will have to be associated with the appropriate
4167 // RenderWidgetHostView or a new one should be created here.
4169 return true;
4172 #if defined(OS_ANDROID)
4174 base::android::ScopedJavaLocalRef<jobject>
4175 WebContentsImpl::GetJavaWebContents() {
4176 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
4177 return GetWebContentsAndroid()->GetJavaObject();
4180 WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
4181 WebContentsAndroid* web_contents_android =
4182 static_cast<WebContentsAndroid*>(GetUserData(kWebContentsAndroidKey));
4183 if (!web_contents_android) {
4184 web_contents_android = new WebContentsAndroid(this);
4185 SetUserData(kWebContentsAndroidKey, web_contents_android);
4187 return web_contents_android;
4190 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4191 return CreateRenderViewForRenderManager(GetRenderViewHost(),
4192 MSG_ROUTING_NONE,
4193 MSG_ROUTING_NONE,
4194 true);
4197 #elif defined(OS_MACOSX)
4199 void WebContentsImpl::SetAllowOtherViews(bool allow) {
4200 view_->SetAllowOtherViews(allow);
4203 bool WebContentsImpl::GetAllowOtherViews() {
4204 return view_->GetAllowOtherViews();
4207 #endif
4209 void WebContentsImpl::OnDialogClosed(int render_process_id,
4210 int render_frame_id,
4211 IPC::Message* reply_msg,
4212 bool dialog_was_suppressed,
4213 bool success,
4214 const base::string16& user_input) {
4215 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
4216 render_frame_id);
4217 last_dialog_suppressed_ = dialog_was_suppressed;
4219 if (is_showing_before_unload_dialog_ && !success) {
4220 // If a beforeunload dialog is canceled, we need to stop the throbber from
4221 // spinning, since we forced it to start spinning in Navigate.
4222 if (rfh)
4223 DidStopLoading(rfh);
4224 controller_.DiscardNonCommittedEntries();
4226 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4227 BeforeUnloadDialogCancelled());
4230 is_showing_before_unload_dialog_ = false;
4231 if (rfh) {
4232 rfh->JavaScriptDialogClosed(reply_msg, success, user_input,
4233 dialog_was_suppressed);
4234 } else {
4235 // Don't leak the sync IPC reply if the RFH or process is gone.
4236 delete reply_msg;
4240 void WebContentsImpl::SetEncoding(const std::string& encoding) {
4241 if (encoding == last_reported_encoding_)
4242 return;
4243 last_reported_encoding_ = encoding;
4245 canonical_encoding_ = GetContentClient()->browser()->
4246 GetCanonicalEncodingNameByAliasName(encoding);
4249 bool WebContentsImpl::IsHidden() {
4250 return capturer_count_ == 0 && !should_normally_be_visible_;
4253 RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
4254 return frame_tree_.root()->render_manager();
4257 RenderViewHostImpl* WebContentsImpl::GetRenderViewHostImpl() {
4258 return static_cast<RenderViewHostImpl*>(GetRenderViewHost());
4261 BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
4262 return browser_plugin_guest_.get();
4265 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest* guest) {
4266 CHECK(!browser_plugin_guest_);
4267 browser_plugin_guest_.reset(guest);
4270 BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
4271 return browser_plugin_embedder_.get();
4274 void WebContentsImpl::ClearPowerSaveBlockers(
4275 RenderFrameHost* render_frame_host) {
4276 RemoveAllMediaPlayerEntries(render_frame_host, &active_audio_players_);
4277 RemoveAllMediaPlayerEntries(render_frame_host, &active_video_players_);
4278 MaybeReleasePowerSaveBlockers();
4281 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4282 active_audio_players_.clear();
4283 active_video_players_.clear();
4284 audio_power_save_blocker_.reset();
4285 video_power_save_blocker_.reset();
4288 gfx::Size WebContentsImpl::GetSizeForNewRenderView() {
4289 gfx::Size size;
4290 if (delegate_)
4291 size = delegate_->GetSizeForNewRenderView(this);
4292 if (size.IsEmpty())
4293 size = GetContainerBounds().size();
4294 return size;
4297 void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
4298 FOR_EACH_OBSERVER(
4299 WebContentsObserver, observers_, FrameDetached(render_frame_host));
4302 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
4303 if (!delegate_)
4304 return;
4305 const gfx::Size new_size = GetPreferredSize();
4306 if (new_size != old_size)
4307 delegate_->UpdatePreferredSize(this, new_size);
4310 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie,
4311 ActiveMediaPlayerMap* player_map) {
4312 const uintptr_t key =
4313 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4314 DCHECK(std::find((*player_map)[key].begin(),
4315 (*player_map)[key].end(),
4316 player_cookie) == (*player_map)[key].end());
4317 (*player_map)[key].push_back(player_cookie);
4320 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie,
4321 ActiveMediaPlayerMap* player_map) {
4322 const uintptr_t key =
4323 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4324 ActiveMediaPlayerMap::iterator it = player_map->find(key);
4325 if (it == player_map->end())
4326 return;
4328 // Remove the player.
4329 PlayerList::iterator player_it =
4330 std::find(it->second.begin(), it->second.end(), player_cookie);
4331 if (player_it != it->second.end())
4332 it->second.erase(player_it);
4334 // If there are no players left, remove the map entry.
4335 if (it->second.empty())
4336 player_map->erase(it);
4339 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4340 RenderFrameHost* render_frame_host,
4341 ActiveMediaPlayerMap* player_map) {
4342 ActiveMediaPlayerMap::iterator it =
4343 player_map->find(reinterpret_cast<uintptr_t>(render_frame_host));
4344 if (it == player_map->end())
4345 return;
4346 player_map->erase(it);
4349 void WebContentsImpl::ResumeResponseDeferredAtStart() {
4350 FrameTreeNode* node = frame_tree_.root();
4351 node->render_manager()->ResumeResponseDeferredAtStart();
4354 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
4355 force_disable_overscroll_content_ = force_disable;
4356 if (view_)
4357 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4360 } // namespace content