Blink roll 25b6bd3a7a131ffe68d809546ad1a20707915cdc:3a503f41ae42e5b79cfcd2ff10e65afde...
[chromium-blink-merge.git] / content / browser / web_contents / web_contents_impl.cc
blob8f6bfe119faf03f2fae0155768483b36596ada24
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 if (delegate_ && delegate_->SaveFrame(url, referrer))
2218 return;
2220 bool is_main_frame = (url == GetURL());
2222 DownloadManager* dlm =
2223 BrowserContext::GetDownloadManager(GetBrowserContext());
2224 if (!dlm)
2225 return;
2226 int64 post_id = -1;
2227 if (is_main_frame) {
2228 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2229 if (entry)
2230 post_id = entry->GetPostID();
2232 scoped_ptr<DownloadUrlParameters> params(
2233 DownloadUrlParameters::FromWebContents(this, url));
2234 params->set_referrer(referrer);
2235 params->set_post_id(post_id);
2236 params->set_prefer_cache(true);
2237 if (post_id >= 0)
2238 params->set_method("POST");
2239 params->set_prompt(true);
2240 dlm->DownloadUrl(params.Pass());
2243 void WebContentsImpl::GenerateMHTML(
2244 const base::FilePath& file,
2245 const base::Callback<void(int64)>& callback) {
2246 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file, callback);
2249 const std::string& WebContentsImpl::GetContentsMimeType() const {
2250 return contents_mime_type_;
2253 bool WebContentsImpl::WillNotifyDisconnection() const {
2254 return notify_disconnection_;
2257 void WebContentsImpl::SetOverrideEncoding(const std::string& encoding) {
2258 SetEncoding(encoding);
2259 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding));
2262 void WebContentsImpl::ResetOverrideEncoding() {
2263 canonical_encoding_.clear();
2264 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2267 RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
2268 return &renderer_preferences_;
2271 void WebContentsImpl::Close() {
2272 Close(GetRenderViewHost());
2275 void WebContentsImpl::DragSourceEndedAt(int client_x, int client_y,
2276 int screen_x, int screen_y, blink::WebDragOperation operation) {
2277 if (browser_plugin_embedder_.get())
2278 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y,
2279 screen_x, screen_y, operation);
2280 if (GetRenderViewHost())
2281 GetRenderViewHostImpl()->DragSourceEndedAt(client_x, client_y,
2282 screen_x, screen_y, operation);
2285 void WebContentsImpl::DidGetResourceResponseStart(
2286 const ResourceRequestDetails& details) {
2287 controller_.ssl_manager()->DidStartResourceResponse(details);
2289 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2290 DidGetResourceResponseStart(details));
2292 // TODO(avi): Remove. http://crbug.com/170921
2293 NotificationService::current()->Notify(
2294 NOTIFICATION_RESOURCE_RESPONSE_STARTED,
2295 Source<WebContents>(this),
2296 Details<const ResourceRequestDetails>(&details));
2299 void WebContentsImpl::DidGetRedirectForResourceRequest(
2300 RenderFrameHost* render_frame_host,
2301 const ResourceRedirectDetails& details) {
2302 controller_.ssl_manager()->DidReceiveResourceRedirect(details);
2304 FOR_EACH_OBSERVER(
2305 WebContentsObserver,
2306 observers_,
2307 DidGetRedirectForResourceRequest(render_frame_host, details));
2309 // TODO(avi): Remove. http://crbug.com/170921
2310 NotificationService::current()->Notify(
2311 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
2312 Source<WebContents>(this),
2313 Details<const ResourceRedirectDetails>(&details));
2316 void WebContentsImpl::SystemDragEnded() {
2317 if (GetRenderViewHost())
2318 GetRenderViewHostImpl()->DragSourceSystemDragEnded();
2319 if (delegate_)
2320 delegate_->DragEnded();
2321 if (browser_plugin_embedder_.get())
2322 browser_plugin_embedder_->SystemDragEnded();
2325 void WebContentsImpl::UserGestureDone() {
2326 OnUserGesture();
2329 void WebContentsImpl::SetClosedByUserGesture(bool value) {
2330 closed_by_user_gesture_ = value;
2333 bool WebContentsImpl::GetClosedByUserGesture() const {
2334 return closed_by_user_gesture_;
2337 void WebContentsImpl::ViewSource() {
2338 if (!delegate_)
2339 return;
2341 NavigationEntry* entry = GetController().GetLastCommittedEntry();
2342 if (!entry)
2343 return;
2345 delegate_->ViewSourceForTab(this, entry->GetURL());
2348 void WebContentsImpl::ViewFrameSource(const GURL& url,
2349 const PageState& page_state) {
2350 if (!delegate_)
2351 return;
2353 delegate_->ViewSourceForFrame(this, url, page_state);
2356 int WebContentsImpl::GetMinimumZoomPercent() const {
2357 return minimum_zoom_percent_;
2360 int WebContentsImpl::GetMaximumZoomPercent() const {
2361 return maximum_zoom_percent_;
2364 gfx::Size WebContentsImpl::GetPreferredSize() const {
2365 return capturer_count_ == 0 ? preferred_size_ : preferred_size_for_capture_;
2368 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed) {
2369 if (GetBrowserPluginGuest())
2370 return GetBrowserPluginGuest()->LockMouse(allowed);
2372 return GetRenderViewHost() ?
2373 GetRenderViewHostImpl()->GotResponseToLockMouseRequest(allowed) : false;
2376 bool WebContentsImpl::HasOpener() const {
2377 return opener_ != NULL;
2380 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
2381 if (!color_chooser_info_.get())
2382 return;
2383 RenderFrameHost* rfh = RenderFrameHost::FromID(
2384 color_chooser_info_->render_process_id,
2385 color_chooser_info_->render_frame_id);
2386 if (!rfh)
2387 return;
2389 rfh->Send(new FrameMsg_DidChooseColorResponse(
2390 rfh->GetRoutingID(), color_chooser_info_->identifier, color));
2393 void WebContentsImpl::DidEndColorChooser() {
2394 if (!color_chooser_info_.get())
2395 return;
2396 RenderFrameHost* rfh = RenderFrameHost::FromID(
2397 color_chooser_info_->render_process_id,
2398 color_chooser_info_->render_frame_id);
2399 if (!rfh)
2400 return;
2402 rfh->Send(new FrameMsg_DidEndColorChooser(
2403 rfh->GetRoutingID(), color_chooser_info_->identifier));
2404 color_chooser_info_.reset();
2407 int WebContentsImpl::DownloadImage(const GURL& url,
2408 bool is_favicon,
2409 uint32_t max_bitmap_size,
2410 const ImageDownloadCallback& callback) {
2411 int id = StartDownload(GetMainFrame(), url, is_favicon, max_bitmap_size);
2412 image_download_map_[id] = callback;
2413 return id;
2416 bool WebContentsImpl::IsSubframe() const {
2417 return is_subframe_;
2420 void WebContentsImpl::Find(int request_id,
2421 const base::string16& search_text,
2422 const blink::WebFindOptions& options) {
2423 // See if a top level browser plugin handles the find request first.
2424 if (browser_plugin_embedder_ &&
2425 browser_plugin_embedder_->Find(request_id, search_text, options)) {
2426 return;
2428 Send(new ViewMsg_Find(GetRoutingID(), request_id, search_text, options));
2431 void WebContentsImpl::StopFinding(StopFindAction action) {
2432 Send(new ViewMsg_StopFinding(GetRoutingID(), action));
2435 void WebContentsImpl::InsertCSS(const std::string& css) {
2436 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2437 GetMainFrame()->GetRoutingID(), css));
2440 bool WebContentsImpl::WasRecentlyAudible() {
2441 return audio_stream_monitor_.WasRecentlyAudible();
2444 void WebContentsImpl::GetManifest(const GetManifestCallback& callback) {
2445 manifest_manager_host_->GetManifest(GetMainFrame(), callback);
2448 bool WebContentsImpl::FocusLocationBarByDefault() {
2449 NavigationEntry* entry = controller_.GetVisibleEntry();
2450 if (entry && entry->GetURL() == GURL(url::kAboutBlankURL))
2451 return true;
2452 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
2455 void WebContentsImpl::SetFocusToLocationBar(bool select_all) {
2456 if (delegate_)
2457 delegate_->SetFocusToLocationBar(select_all);
2460 void WebContentsImpl::DidStartProvisionalLoad(
2461 RenderFrameHostImpl* render_frame_host,
2462 const GURL& validated_url,
2463 bool is_error_page,
2464 bool is_iframe_srcdoc) {
2465 // Notify observers about the start of the provisional load.
2466 FOR_EACH_OBSERVER(
2467 WebContentsObserver,
2468 observers_,
2469 DidStartProvisionalLoadForFrame(
2470 render_frame_host, validated_url, is_error_page, is_iframe_srcdoc));
2473 void WebContentsImpl::DidStartNavigationTransition(
2474 RenderFrameHostImpl* render_frame_host) {
2475 #if defined(OS_ANDROID)
2476 int render_frame_id = render_frame_host->GetRoutingID();
2477 GetWebContentsAndroid()->DidStartNavigationTransitionForFrame(
2478 render_frame_id);
2479 #endif
2482 void WebContentsImpl::DidFailProvisionalLoadWithError(
2483 RenderFrameHostImpl* render_frame_host,
2484 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
2485 GURL validated_url(params.url);
2486 FOR_EACH_OBSERVER(WebContentsObserver,
2487 observers_,
2488 DidFailProvisionalLoad(render_frame_host,
2489 validated_url,
2490 params.error_code,
2491 params.error_description));
2494 void WebContentsImpl::DidFailLoadWithError(
2495 RenderFrameHostImpl* render_frame_host,
2496 const GURL& url,
2497 int error_code,
2498 const base::string16& error_description) {
2499 FOR_EACH_OBSERVER(
2500 WebContentsObserver,
2501 observers_,
2502 DidFailLoad(render_frame_host, url, error_code, error_description));
2505 void WebContentsImpl::NotifyChangedNavigationState(
2506 InvalidateTypes changed_flags) {
2507 NotifyNavigationStateChanged(changed_flags);
2510 void WebContentsImpl::AboutToNavigateRenderFrame(
2511 RenderFrameHostImpl* render_frame_host) {
2512 // Notify observers that we will navigate in this RenderFrame.
2513 FOR_EACH_OBSERVER(
2514 WebContentsObserver,
2515 observers_,
2516 AboutToNavigateRenderFrame(render_frame_host));
2519 void WebContentsImpl::DidStartNavigationToPendingEntry(
2520 RenderFrameHostImpl* render_frame_host,
2521 const GURL& url,
2522 NavigationController::ReloadType reload_type) {
2523 // Notify observers about navigation.
2524 FOR_EACH_OBSERVER(
2525 WebContentsObserver,
2526 observers_,
2527 DidStartNavigationToPendingEntry(url, reload_type));
2530 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
2531 const OpenURLParams& params) {
2532 WebContents* new_contents = OpenURL(params);
2534 if (new_contents) {
2535 // Notify observers.
2536 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2537 DidOpenRequestedURL(new_contents,
2538 render_frame_host,
2539 params.url,
2540 params.referrer,
2541 params.disposition,
2542 params.transition));
2546 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2547 if (!delegate_)
2548 return false;
2549 return delegate_->ShouldPreserveAbortedURLs(this);
2552 void WebContentsImpl::DidCommitProvisionalLoad(
2553 RenderFrameHostImpl* render_frame_host,
2554 const GURL& url,
2555 ui::PageTransition transition_type) {
2556 // Notify observers about the commit of the provisional load.
2557 FOR_EACH_OBSERVER(WebContentsObserver,
2558 observers_,
2559 DidCommitProvisionalLoadForFrame(
2560 render_frame_host, url, transition_type));
2563 void WebContentsImpl::DidNavigateMainFramePreCommit(
2564 bool navigation_is_within_page) {
2565 // Ensure fullscreen mode is exited before committing the navigation to a
2566 // different page. The next page will not start out assuming it is in
2567 // fullscreen mode.
2568 if (navigation_is_within_page) {
2569 // No page change? Then, the renderer and browser can remain in fullscreen.
2570 return;
2572 if (IsFullscreenForCurrentTab())
2573 GetRenderViewHost()->ExitFullscreen();
2574 DCHECK(!IsFullscreenForCurrentTab());
2577 void WebContentsImpl::DidNavigateMainFramePostCommit(
2578 const LoadCommittedDetails& details,
2579 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2580 if (details.is_navigation_to_different_page()) {
2581 // Clear the status bubble. This is a workaround for a bug where WebKit
2582 // doesn't let us know that the cursor left an element during a
2583 // transition (this is also why the mouse cursor remains as a hand after
2584 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2585 // clear the bubble when a user navigates to a named anchor in the same
2586 // page.
2587 UpdateTargetURL(GURL());
2590 if (!details.is_in_page) {
2591 // Once the main frame is navigated, we're no longer considered to have
2592 // displayed insecure content.
2593 displayed_insecure_content_ = false;
2594 SSLManager::NotifySSLInternalStateChanged(
2595 GetController().GetBrowserContext());
2598 // Notify observers about navigation.
2599 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2600 DidNavigateMainFrame(details, params));
2602 if (delegate_)
2603 delegate_->DidNavigateMainFramePostCommit(this);
2604 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
2607 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2608 RenderFrameHostImpl* render_frame_host,
2609 const LoadCommittedDetails& details,
2610 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2611 // Now that something has committed, we don't need to track whether the
2612 // initial page has been accessed.
2613 has_accessed_initial_document_ = false;
2615 // If we navigate off the page, close all JavaScript dialogs.
2616 if (dialog_manager_ && !details.is_in_page)
2617 dialog_manager_->CancelActiveAndPendingDialogs(this);
2619 // Notify observers about navigation.
2620 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2621 DidNavigateAnyFrame(render_frame_host, details, params));
2624 void WebContentsImpl::SetMainFrameMimeType(const std::string& mime_type) {
2625 contents_mime_type_ = mime_type;
2628 bool WebContentsImpl::CanOverscrollContent() const {
2629 // Disable overscroll when touch emulation is on. See crbug.com/369938.
2630 if (force_disable_overscroll_content_)
2631 return false;
2633 if (delegate_)
2634 return delegate_->CanOverscrollContent();
2636 return false;
2639 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color) {
2640 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2641 DidChangeThemeColor(theme_color));
2644 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2645 const GURL& url,
2646 const std::string& security_info,
2647 const std::string& http_method,
2648 const std::string& mime_type,
2649 ResourceType resource_type) {
2650 base::StatsCounter cache("WebKit.CacheHit");
2651 cache.Increment();
2653 // Send out a notification that we loaded a resource from our memory cache.
2654 int cert_id = 0;
2655 net::CertStatus cert_status = 0;
2656 int security_bits = -1;
2657 int connection_status = 0;
2658 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids;
2659 DeserializeSecurityInfo(security_info, &cert_id, &cert_status,
2660 &security_bits, &connection_status,
2661 &signed_certificate_timestamp_ids);
2662 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details
2663 LoadFromMemoryCacheDetails details(
2664 url, GetRenderProcessHost()->GetID(), cert_id, cert_status, http_method,
2665 mime_type, resource_type);
2667 controller_.ssl_manager()->DidLoadFromMemoryCache(details);
2669 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2670 DidLoadResourceFromMemoryCache(details));
2672 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
2673 scoped_refptr<net::URLRequestContextGetter> request_context(
2674 resource_type == RESOURCE_TYPE_MEDIA ?
2675 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2676 GetRenderProcessHost()->GetID()) :
2677 GetBrowserContext()->GetRequestContextForRenderProcess(
2678 GetRenderProcessHost()->GetID()));
2679 BrowserThread::PostTask(
2680 BrowserThread::IO,
2681 FROM_HERE,
2682 base::Bind(&NotifyCacheOnIO, request_context, url, http_method));
2686 void WebContentsImpl::OnDidDisplayInsecureContent() {
2687 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
2688 displayed_insecure_content_ = true;
2689 SSLManager::NotifySSLInternalStateChanged(
2690 GetController().GetBrowserContext());
2693 void WebContentsImpl::OnDidRunInsecureContent(
2694 const std::string& security_origin, const GURL& target_url) {
2695 LOG(WARNING) << security_origin << " ran insecure content from "
2696 << target_url.possibly_invalid_spec();
2697 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
2698 if (EndsWith(security_origin, kDotGoogleDotCom, false))
2699 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
2700 controller_.ssl_manager()->DidRunInsecureContent(security_origin);
2701 displayed_insecure_content_ = true;
2702 SSLManager::NotifySSLInternalStateChanged(
2703 GetController().GetBrowserContext());
2706 void WebContentsImpl::OnDocumentLoadedInFrame() {
2707 CHECK(render_frame_message_source_);
2708 CHECK(!render_view_message_source_);
2709 RenderFrameHostImpl* rfh =
2710 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2711 FOR_EACH_OBSERVER(
2712 WebContentsObserver, observers_, DocumentLoadedInFrame(rfh));
2715 void WebContentsImpl::OnDidFinishLoad(
2716 const GURL& url) {
2717 if (!render_frame_message_source_) {
2718 RecordAction(base::UserMetricsAction("BadMessageTerminate_RVD2"));
2719 GetRenderProcessHost()->ReceivedBadMessage();
2720 return;
2723 GURL validated_url(url);
2724 RenderProcessHost* render_process_host =
2725 render_frame_message_source_->GetProcess();
2726 render_process_host->FilterURL(false, &validated_url);
2728 RenderFrameHostImpl* rfh =
2729 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2730 FOR_EACH_OBSERVER(
2731 WebContentsObserver, observers_, DidFinishLoad(rfh, validated_url));
2734 void WebContentsImpl::OnDidStartLoading(bool to_different_document) {
2735 RenderFrameHostImpl* rfh =
2736 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2737 int64 render_frame_id = rfh->frame_tree_node()->frame_tree_node_id();
2739 // It is possible to get multiple calls to OnDidStartLoading that don't have
2740 // corresponding calls to OnDidStopLoading:
2741 // - With "swappedout://" URLs, this happens when a RenderView gets swapped
2742 // out for a cross-process navigation, and it turns into a placeholder for
2743 // one being rendered in a different process.
2744 // - Also, there might be more than one RenderFrameHost sharing the same
2745 // FrameTreeNode (and thus sharing its ID) each sending a start.
2746 // - But in the future, once clamy@ moves navigation network requests to the
2747 // browser process, there's a good chance that callbacks about starting and
2748 // stopping will all be handled by the browser. When that happens, there
2749 // should no longer be a start/stop call imbalance. TODO(avi): When this
2750 // future arrives, update this code to not allow this case.
2751 DCHECK_GE(loading_frames_in_progress_, 0);
2752 if (loading_progresses_.find(render_frame_id) == loading_progresses_.end()) {
2753 if (loading_frames_in_progress_ == 0)
2754 DidStartLoading(rfh, to_different_document);
2755 ++loading_frames_in_progress_;
2758 loading_progresses_[render_frame_id] = kMinimumLoadingProgress;
2759 SendLoadProgressChanged();
2762 void WebContentsImpl::OnDidStopLoading() {
2763 RenderFrameHostImpl* rfh =
2764 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2765 int64 render_frame_id = rfh->frame_tree_node()->frame_tree_node_id();
2767 if (loading_progresses_.find(render_frame_id) != loading_progresses_.end()) {
2768 // Load stopped while we were still tracking load. Make sure we update
2769 // progress based on this frame's completion.
2770 loading_progresses_[render_frame_id] = 1.0;
2771 SendLoadProgressChanged();
2772 // Then we clean-up our states.
2773 if (loading_total_progress_ == 1.0)
2774 ResetLoadProgressState();
2777 // TODO(japhet): This should be a DCHECK, but the pdf plugin sometimes
2778 // calls DidStopLoading() without a matching DidStartLoading().
2779 if (loading_frames_in_progress_ == 0)
2780 return;
2781 --loading_frames_in_progress_;
2782 if (loading_frames_in_progress_ == 0)
2783 DidStopLoading(rfh);
2786 void WebContentsImpl::OnDidChangeLoadProgress(double load_progress) {
2787 RenderFrameHostImpl* rfh =
2788 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2789 int64 render_frame_id = rfh->frame_tree_node()->frame_tree_node_id();
2791 loading_progresses_[render_frame_id] = load_progress;
2793 // We notify progress change immediately for the first and last updates.
2794 // Also, since the message loop may be pretty busy when a page is loaded, it
2795 // might not execute a posted task in a timely manner so we make sure to
2796 // immediately send progress report if enough time has passed.
2797 base::TimeDelta min_delay =
2798 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
2799 if (load_progress == 1.0 || loading_last_progress_update_.is_null() ||
2800 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay) {
2801 // If there is a pending task to send progress, it is now obsolete.
2802 loading_weak_factory_.InvalidateWeakPtrs();
2803 SendLoadProgressChanged();
2804 if (loading_total_progress_ == 1.0)
2805 ResetLoadProgressState();
2806 return;
2809 if (loading_weak_factory_.HasWeakPtrs())
2810 return;
2812 base::MessageLoop::current()->PostDelayedTask(
2813 FROM_HERE,
2814 base::Bind(&WebContentsImpl::SendLoadProgressChanged,
2815 loading_weak_factory_.GetWeakPtr()),
2816 min_delay);
2819 void WebContentsImpl::OnGoToEntryAtOffset(int offset) {
2820 if (!delegate_ || delegate_->OnGoToEntryOffset(offset))
2821 controller_.GoToOffset(offset);
2824 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent,
2825 int maximum_percent) {
2826 minimum_zoom_percent_ = minimum_percent;
2827 maximum_zoom_percent_ = maximum_percent;
2830 void WebContentsImpl::OnEnumerateDirectory(int request_id,
2831 const base::FilePath& path) {
2832 if (!delegate_)
2833 return;
2835 ChildProcessSecurityPolicyImpl* policy =
2836 ChildProcessSecurityPolicyImpl::GetInstance();
2837 if (policy->CanReadFile(GetRenderProcessHost()->GetID(), path))
2838 delegate_->EnumerateDirectory(this, request_id, path);
2841 void WebContentsImpl::OnRegisterProtocolHandler(const std::string& protocol,
2842 const GURL& url,
2843 const base::string16& title,
2844 bool user_gesture) {
2845 if (!delegate_)
2846 return;
2848 ChildProcessSecurityPolicyImpl* policy =
2849 ChildProcessSecurityPolicyImpl::GetInstance();
2850 if (policy->IsPseudoScheme(protocol))
2851 return;
2853 delegate_->RegisterProtocolHandler(this, protocol, url, user_gesture);
2856 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string& protocol,
2857 const GURL& url,
2858 bool user_gesture) {
2859 if (!delegate_)
2860 return;
2862 ChildProcessSecurityPolicyImpl* policy =
2863 ChildProcessSecurityPolicyImpl::GetInstance();
2864 if (policy->IsPseudoScheme(protocol))
2865 return;
2867 delegate_->UnregisterProtocolHandler(this, protocol, url, user_gesture);
2870 void WebContentsImpl::OnFindReply(int request_id,
2871 int number_of_matches,
2872 const gfx::Rect& selection_rect,
2873 int active_match_ordinal,
2874 bool final_update) {
2875 if (delegate_) {
2876 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
2877 active_match_ordinal, final_update);
2881 #if defined(OS_ANDROID)
2882 void WebContentsImpl::OnFindMatchRectsReply(
2883 int version,
2884 const std::vector<gfx::RectF>& rects,
2885 const gfx::RectF& active_rect) {
2886 if (delegate_)
2887 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
2890 void WebContentsImpl::OnOpenDateTimeDialog(
2891 const ViewHostMsg_DateTimeDialogValue_Params& value) {
2892 date_time_chooser_->ShowDialog(GetTopLevelNativeWindow(),
2893 GetRenderViewHost(),
2894 value.dialog_type,
2895 value.dialog_value,
2896 value.minimum,
2897 value.maximum,
2898 value.step,
2899 value.suggestions);
2901 #endif
2903 void WebContentsImpl::OnDomOperationResponse(const std::string& json_string,
2904 int automation_id) {
2905 DomOperationNotificationDetails details(json_string, automation_id);
2906 NotificationService::current()->Notify(
2907 NOTIFICATION_DOM_OPERATION_RESPONSE,
2908 Source<WebContents>(this),
2909 Details<DomOperationNotificationDetails>(&details));
2912 void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
2913 bool blocked_by_policy) {
2914 // Notify observers about navigation.
2915 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2916 AppCacheAccessed(manifest_url, blocked_by_policy));
2919 void WebContentsImpl::OnOpenColorChooser(
2920 int color_chooser_id,
2921 SkColor color,
2922 const std::vector<ColorSuggestion>& suggestions) {
2923 ColorChooser* new_color_chooser = delegate_ ?
2924 delegate_->OpenColorChooser(this, color, suggestions) :
2925 NULL;
2926 if (!new_color_chooser)
2927 return;
2928 if (color_chooser_info_.get())
2929 color_chooser_info_->chooser->End();
2931 color_chooser_info_.reset(new ColorChooserInfo(
2932 render_frame_message_source_->GetProcess()->GetID(),
2933 render_frame_message_source_->GetRoutingID(),
2934 new_color_chooser,
2935 color_chooser_id));
2938 void WebContentsImpl::OnEndColorChooser(int color_chooser_id) {
2939 if (color_chooser_info_ &&
2940 color_chooser_id == color_chooser_info_->identifier)
2941 color_chooser_info_->chooser->End();
2944 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id,
2945 SkColor color) {
2946 if (color_chooser_info_ &&
2947 color_chooser_id == color_chooser_info_->identifier)
2948 color_chooser_info_->chooser->SetSelectedColor(color);
2951 // This exists for render views that don't have a WebUI, but do have WebUI
2952 // bindings enabled.
2953 void WebContentsImpl::OnWebUISend(const GURL& source_url,
2954 const std::string& name,
2955 const base::ListValue& args) {
2956 if (delegate_)
2957 delegate_->WebUISend(this, source_url, name, args);
2960 #if defined(ENABLE_PLUGINS)
2961 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id,
2962 const base::FilePath& path,
2963 bool is_hung) {
2964 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
2966 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2967 PluginHungStatusChanged(plugin_child_id, path, is_hung));
2970 void WebContentsImpl::OnPluginCrashed(const base::FilePath& plugin_path,
2971 base::ProcessId plugin_pid) {
2972 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2973 PluginCrashed(plugin_path, plugin_pid));
2976 void WebContentsImpl::OnRequestPpapiBrokerPermission(
2977 int routing_id,
2978 const GURL& url,
2979 const base::FilePath& plugin_path) {
2980 if (!delegate_) {
2981 OnPpapiBrokerPermissionResult(routing_id, false);
2982 return;
2985 if (!delegate_->RequestPpapiBrokerPermission(
2986 this, url, plugin_path,
2987 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult,
2988 base::Unretained(this), routing_id))) {
2989 NOTIMPLEMENTED();
2990 OnPpapiBrokerPermissionResult(routing_id, false);
2994 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id,
2995 bool result) {
2996 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id, result));
2999 void WebContentsImpl::OnBrowserPluginMessage(const IPC::Message& message) {
3000 // This creates a BrowserPluginEmbedder, which handles all the BrowserPlugin
3001 // specific messages for this WebContents. This means that any message from
3002 // a BrowserPlugin prior to this will be ignored.
3003 // For more info, see comment above classes BrowserPluginEmbedder and
3004 // BrowserPluginGuest.
3005 CHECK(!browser_plugin_embedder_.get());
3006 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
3007 browser_plugin_embedder_->OnMessageReceived(message);
3009 #endif // defined(ENABLE_PLUGINS)
3011 void WebContentsImpl::OnDidDownloadImage(
3012 int id,
3013 int http_status_code,
3014 const GURL& image_url,
3015 const std::vector<SkBitmap>& bitmaps,
3016 const std::vector<gfx::Size>& original_bitmap_sizes) {
3017 if (bitmaps.size() != original_bitmap_sizes.size())
3018 return;
3020 ImageDownloadMap::iterator iter = image_download_map_.find(id);
3021 if (iter == image_download_map_.end()) {
3022 // Currently WebContents notifies us of ANY downloads so that it is
3023 // possible to get here.
3024 return;
3026 if (!iter->second.is_null()) {
3027 iter->second.Run(
3028 id, http_status_code, image_url, bitmaps, original_bitmap_sizes);
3030 image_download_map_.erase(id);
3033 void WebContentsImpl::OnUpdateFaviconURL(
3034 const std::vector<FaviconURL>& candidates) {
3035 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3036 DidUpdateFaviconURL(candidates));
3039 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3040 // ChromeOS has its own way of handling power save blocks for media.
3041 #if !defined(OS_CHROMEOS)
3042 DCHECK(!audio_power_save_blocker_);
3043 audio_power_save_blocker_ = PowerSaveBlocker::Create(
3044 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension, "Playing Audio");
3045 #endif
3048 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3049 // ChromeOS has its own way of handling power save blocks for media.
3050 #if !defined(OS_CHROMEOS)
3051 DCHECK(!video_power_save_blocker_);
3052 DCHECK(!active_video_players_.empty());
3053 video_power_save_blocker_ = PowerSaveBlocker::Create(
3054 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep, "Playing Video");
3055 #if defined(OS_ANDROID)
3056 static_cast<PowerSaveBlockerImpl*>(video_power_save_blocker_.get())
3057 ->InitDisplaySleepBlocker(GetView()->GetNativeView());
3058 #endif
3059 #endif
3062 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3063 // If there are no more audio players and we don't have audio stream
3064 // monitoring, release the audio power save blocker here instead of during
3065 // NotifyNavigationStateChanged().
3066 if (active_audio_players_.empty() &&
3067 !AudioStreamMonitor::monitoring_available()) {
3068 audio_power_save_blocker_.reset();
3071 // If there are no more video players, clear the video power save blocker.
3072 if (active_video_players_.empty())
3073 video_power_save_blocker_.reset();
3076 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie,
3077 bool has_video,
3078 bool has_audio,
3079 bool is_remote) {
3080 // Ignore the videos playing remotely and don't hold the wake lock for the
3081 // screen.
3082 if (is_remote) return;
3084 if (has_audio) {
3085 AddMediaPlayerEntry(player_cookie, &active_audio_players_);
3087 // If we don't have audio stream monitoring, allocate the audio power save
3088 // blocker here instead of during NotifyNavigationStateChanged().
3089 if (!audio_power_save_blocker_ &&
3090 !AudioStreamMonitor::monitoring_available()) {
3091 CreateAudioPowerSaveBlocker();
3095 if (has_video) {
3096 AddMediaPlayerEntry(player_cookie, &active_video_players_);
3098 // If we're not hidden and have just created a player, create a blocker.
3099 if (!video_power_save_blocker_ && !IsHidden())
3100 CreateVideoPowerSaveBlocker();
3104 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie) {
3105 RemoveMediaPlayerEntry(player_cookie, &active_audio_players_);
3106 RemoveMediaPlayerEntry(player_cookie, &active_video_players_);
3107 MaybeReleasePowerSaveBlockers();
3110 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3111 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3112 DidFirstVisuallyNonEmptyPaint());
3115 void WebContentsImpl::DidChangeVisibleSSLState() {
3116 if (delegate_)
3117 delegate_->VisibleSSLStateChanged(this);
3120 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3121 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3122 BeforeFormRepostWarningShow());
3125 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3126 Activate();
3127 if (delegate_)
3128 delegate_->ShowRepostFormWarningDialog(this);
3131 bool WebContentsImpl::HasAccessedInitialDocument() {
3132 return has_accessed_initial_document_;
3135 // Notifies the RenderWidgetHost instance about the fact that the page is
3136 // loading, or done loading.
3137 void WebContentsImpl::SetIsLoading(RenderViewHost* render_view_host,
3138 bool is_loading,
3139 bool to_different_document,
3140 LoadNotificationDetails* details) {
3141 if (is_loading == is_loading_)
3142 return;
3144 if (!is_loading) {
3145 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
3146 base::string16());
3147 load_state_host_.clear();
3148 upload_size_ = 0;
3149 upload_position_ = 0;
3152 GetRenderManager()->SetIsLoading(is_loading);
3154 is_loading_ = is_loading;
3155 waiting_for_response_ = is_loading;
3156 is_load_to_different_document_ = to_different_document;
3158 if (delegate_)
3159 delegate_->LoadingStateChanged(this, to_different_document);
3160 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
3162 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
3163 if (is_loading) {
3164 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3165 this, "URL", url);
3166 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3167 DidStartLoading(render_view_host));
3168 } else {
3169 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3170 this, "URL", url);
3171 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3172 DidStopLoading(render_view_host));
3175 // TODO(avi): Remove. http://crbug.com/170921
3176 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
3177 NotificationDetails det = NotificationService::NoDetails();
3178 if (details)
3179 det = Details<LoadNotificationDetails>(details);
3180 NotificationService::current()->Notify(
3181 type, Source<NavigationController>(&controller_), det);
3184 void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
3185 RenderFrameHost* focused_frame = GetFocusedFrame();
3186 if (!focused_frame)
3187 return;
3189 focused_frame->Send(new InputMsg_MoveRangeSelectionExtent(
3190 focused_frame->GetRoutingID(), extent));
3193 void WebContentsImpl::SelectRange(const gfx::Point& base,
3194 const gfx::Point& extent) {
3195 RenderFrameHost* focused_frame = GetFocusedFrame();
3196 if (!focused_frame)
3197 return;
3199 focused_frame->Send(
3200 new InputMsg_SelectRange(focused_frame->GetRoutingID(), base, extent));
3203 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost* rvh) {
3204 // If we are creating a RVH for a restored controller, then we need to make
3205 // sure the RenderView starts with a next_page_id_ larger than the number
3206 // of restored entries. This must be called before the RenderView starts
3207 // navigating (to avoid a race between the browser updating max_page_id and
3208 // the renderer updating next_page_id_). Because of this, we only call this
3209 // from CreateRenderView and allow that to notify the RenderView for us.
3210 int max_restored_page_id = controller_.GetMaxRestoredPageID();
3211 if (max_restored_page_id >
3212 GetMaxPageIDForSiteInstance(rvh->GetSiteInstance()))
3213 UpdateMaxPageIDForSiteInstance(rvh->GetSiteInstance(),
3214 max_restored_page_id);
3217 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl* entry,
3218 const base::string16& title) {
3219 // For file URLs without a title, use the pathname instead. In the case of a
3220 // synthesized title, we don't want the update to count toward the "one set
3221 // per page of the title to history."
3222 base::string16 final_title;
3223 bool explicit_set;
3224 if (entry && entry->GetURL().SchemeIsFile() && title.empty()) {
3225 final_title = base::UTF8ToUTF16(entry->GetURL().ExtractFileName());
3226 explicit_set = false; // Don't count synthetic titles toward the set limit.
3227 } else {
3228 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
3229 explicit_set = true;
3232 // If a page is created via window.open and never navigated,
3233 // there will be no navigation entry. In this situation,
3234 // |page_title_when_no_navigation_entry_| will be used for page title.
3235 if (entry) {
3236 if (final_title == entry->GetTitle())
3237 return false; // Nothing changed, don't bother.
3239 entry->SetTitle(final_title);
3240 } else {
3241 if (page_title_when_no_navigation_entry_ == final_title)
3242 return false; // Nothing changed, don't bother.
3244 page_title_when_no_navigation_entry_ = final_title;
3247 // Lastly, set the title for the view.
3248 view_->SetPageTitle(final_title);
3250 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3251 TitleWasSet(entry, explicit_set));
3253 // TODO(avi): Remove. http://crbug.com/170921
3254 std::pair<NavigationEntry*, bool> details =
3255 std::make_pair(entry, explicit_set);
3256 NotificationService::current()->Notify(
3257 NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,
3258 Source<WebContents>(this),
3259 Details<std::pair<NavigationEntry*, bool> >(&details));
3261 return true;
3264 void WebContentsImpl::SendLoadProgressChanged() {
3265 loading_last_progress_update_ = base::TimeTicks::Now();
3266 double progress = 0.0;
3267 int frame_count = 0;
3269 for (LoadingProgressMap::iterator it = loading_progresses_.begin();
3270 it != loading_progresses_.end();
3271 ++it) {
3272 progress += it->second;
3273 ++frame_count;
3275 if (frame_count == 0)
3276 return;
3277 progress /= frame_count;
3278 DCHECK(progress <= 1.0);
3280 if (progress <= loading_total_progress_)
3281 return;
3282 loading_total_progress_ = progress;
3284 if (delegate_)
3285 delegate_->LoadProgressChanged(this, progress);
3288 void WebContentsImpl::ResetLoadProgressState() {
3289 loading_progresses_.clear();
3290 loading_total_progress_ = 0.0;
3291 loading_weak_factory_.InvalidateWeakPtrs();
3292 loading_last_progress_update_ = base::TimeTicks();
3295 void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_host,
3296 RenderViewHost* new_host) {
3297 // After sending out a swap notification, we need to send a disconnect
3298 // notification so that clients that pick up a pointer to |this| can NULL the
3299 // pointer. See Bug 1230284.
3300 notify_disconnection_ = true;
3301 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3302 RenderViewHostChanged(old_host, new_host));
3304 // TODO(avi): Remove. http://crbug.com/170921
3305 std::pair<RenderViewHost*, RenderViewHost*> details =
3306 std::make_pair(old_host, new_host);
3307 NotificationService::current()->Notify(
3308 NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
3309 Source<WebContents>(this),
3310 Details<std::pair<RenderViewHost*, RenderViewHost*> >(&details));
3312 // Ensure that the associated embedder gets cleared after a RenderViewHost
3313 // gets swapped, so we don't reuse the same embedder next time a
3314 // RenderViewHost is attached to this WebContents.
3315 RemoveBrowserPluginEmbedder();
3318 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_host,
3319 RenderFrameHost* new_host) {
3320 FOR_EACH_OBSERVER(WebContentsObserver,
3321 observers_,
3322 RenderFrameHostChanged(old_host, new_host));
3325 // TODO(avi): Remove this entire function because this notification is already
3326 // covered by two observer functions. http://crbug.com/170921
3327 void WebContentsImpl::NotifyDisconnected() {
3328 if (!notify_disconnection_)
3329 return;
3331 notify_disconnection_ = false;
3332 NotificationService::current()->Notify(
3333 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
3334 Source<WebContents>(this),
3335 NotificationService::NoDetails());
3338 void WebContentsImpl::NotifyNavigationEntryCommitted(
3339 const LoadCommittedDetails& load_details) {
3340 FOR_EACH_OBSERVER(
3341 WebContentsObserver, observers_, NavigationEntryCommitted(load_details));
3344 bool WebContentsImpl::OnMessageReceived(RenderFrameHost* render_frame_host,
3345 const IPC::Message& message) {
3346 return OnMessageReceived(NULL, render_frame_host, message);
3349 const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3350 return GetLastCommittedURL();
3353 void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
3354 // Note this is only for subframes, the notification for the main frame
3355 // happens in RenderViewCreated.
3356 FOR_EACH_OBSERVER(WebContentsObserver,
3357 observers_,
3358 RenderFrameCreated(render_frame_host));
3359 SetAccessibilityModeOnFrame(accessibility_mode_, render_frame_host);
3362 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
3363 ClearPowerSaveBlockers(render_frame_host);
3364 FOR_EACH_OBSERVER(WebContentsObserver,
3365 observers_,
3366 RenderFrameDeleted(render_frame_host));
3369 void WebContentsImpl::WorkerCrashed(RenderFrameHost* render_frame_host) {
3370 if (delegate_)
3371 delegate_->WorkerCrashed(this);
3374 void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
3375 const ContextMenuParams& params) {
3376 ContextMenuParams context_menu_params(params);
3377 // Allow WebContentsDelegates to handle the context menu operation first.
3378 if (GetBrowserPluginGuest()) {
3379 WebContentsViewGuest* view_guest =
3380 static_cast<WebContentsViewGuest*>(GetView());
3381 context_menu_params = view_guest->ConvertContextMenuParams(params);
3383 if (delegate_ && delegate_->HandleContextMenu(context_menu_params))
3384 return;
3386 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
3387 context_menu_params);
3390 void WebContentsImpl::RunJavaScriptMessage(
3391 RenderFrameHost* render_frame_host,
3392 const base::string16& message,
3393 const base::string16& default_prompt,
3394 const GURL& frame_url,
3395 JavaScriptMessageType javascript_message_type,
3396 IPC::Message* reply_msg) {
3397 // Suppress JavaScript dialogs when requested. Also suppress messages when
3398 // showing an interstitial as it's shown over the previous page and we don't
3399 // want the hidden page's dialogs to interfere with the interstitial.
3400 bool suppress_this_message =
3401 static_cast<RenderFrameHostImpl*>(render_frame_host)->is_swapped_out() ||
3402 ShowingInterstitialPage() || !delegate_ ||
3403 delegate_->ShouldSuppressDialogs(this) ||
3404 !delegate_->GetJavaScriptDialogManager(this);
3406 if (!suppress_this_message) {
3407 std::string accept_lang = GetContentClient()->browser()->
3408 GetAcceptLangs(GetBrowserContext());
3409 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3410 dialog_manager_->RunJavaScriptDialog(
3411 this,
3412 frame_url.GetOrigin(),
3413 accept_lang,
3414 javascript_message_type,
3415 message,
3416 default_prompt,
3417 base::Bind(&WebContentsImpl::OnDialogClosed,
3418 base::Unretained(this),
3419 render_frame_host->GetProcess()->GetID(),
3420 render_frame_host->GetRoutingID(),
3421 reply_msg,
3422 false),
3423 &suppress_this_message);
3426 if (suppress_this_message) {
3427 // If we are suppressing messages, just reply as if the user immediately
3428 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3429 OnDialogClosed(render_frame_host->GetProcess()->GetID(),
3430 render_frame_host->GetRoutingID(), reply_msg,
3431 true, false, base::string16());
3434 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3435 // http://crbug.com/288961 ). The only safe thing to do here is return.
3438 void WebContentsImpl::RunBeforeUnloadConfirm(
3439 RenderFrameHost* render_frame_host,
3440 const base::string16& message,
3441 bool is_reload,
3442 IPC::Message* reply_msg) {
3443 RenderFrameHostImpl* rfhi =
3444 static_cast<RenderFrameHostImpl*>(render_frame_host);
3445 if (delegate_)
3446 delegate_->WillRunBeforeUnloadConfirm();
3448 bool suppress_this_message =
3449 rfhi->rfh_state() != RenderFrameHostImpl::STATE_DEFAULT || !delegate_ ||
3450 delegate_->ShouldSuppressDialogs(this) ||
3451 !delegate_->GetJavaScriptDialogManager(this);
3452 if (suppress_this_message) {
3453 rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16(), true);
3454 return;
3457 is_showing_before_unload_dialog_ = true;
3458 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
3459 dialog_manager_->RunBeforeUnloadDialog(
3460 this, message, is_reload,
3461 base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
3462 render_frame_host->GetProcess()->GetID(),
3463 render_frame_host->GetRoutingID(), reply_msg,
3464 false));
3467 WebContents* WebContentsImpl::GetAsWebContents() {
3468 return this;
3471 bool WebContentsImpl::IsNeverVisible() {
3472 if (!delegate_)
3473 return false;
3474 return delegate_->IsNeverVisible(this);
3477 #if defined(OS_WIN)
3478 gfx::NativeViewAccessible WebContentsImpl::GetParentNativeViewAccessible() {
3479 return accessible_parent_;
3481 #endif
3483 RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
3484 return render_view_host_delegate_view_;
3487 RendererPreferences WebContentsImpl::GetRendererPrefs(
3488 BrowserContext* browser_context) const {
3489 return renderer_preferences_;
3492 gfx::Rect WebContentsImpl::GetRootWindowResizerRect() const {
3493 if (delegate_)
3494 return delegate_->GetRootWindowResizerRect();
3495 return gfx::Rect();
3498 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3499 if (browser_plugin_embedder_)
3500 browser_plugin_embedder_.reset();
3503 void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
3504 // Don't send notifications if we are just creating a swapped-out RVH for
3505 // the opener chain. These won't be used for view-source or WebUI, so it's
3506 // ok to return early.
3507 if (!static_cast<RenderViewHostImpl*>(render_view_host)->is_active())
3508 return;
3510 if (delegate_)
3511 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
3513 NotificationService::current()->Notify(
3514 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
3515 Source<WebContents>(this),
3516 Details<RenderViewHost>(render_view_host));
3518 // When we're creating views, we're still doing initial setup, so we always
3519 // use the pending Web UI rather than any possibly existing committed one.
3520 if (GetRenderManager()->pending_web_ui())
3521 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host);
3523 NavigationEntry* entry = controller_.GetPendingEntry();
3524 if (entry && entry->IsViewSourceMode()) {
3525 // Put the renderer in view source mode.
3526 render_view_host->Send(
3527 new ViewMsg_EnableViewSourceMode(render_view_host->GetRoutingID()));
3530 view_->RenderViewCreated(render_view_host);
3532 FOR_EACH_OBSERVER(
3533 WebContentsObserver, observers_, RenderViewCreated(render_view_host));
3535 // We tell the observers now instead of when the main RenderFrameHostImpl is
3536 // constructed because otherwise it would be too early (i.e. IPCs sent to the
3537 // frame would be dropped because it's not created yet).
3538 RenderFrameHost* main_frame = render_view_host->GetMainFrame();
3539 FOR_EACH_OBSERVER(
3540 WebContentsObserver, observers_, RenderFrameCreated(main_frame));
3541 SetAccessibilityModeOnFrame(accessibility_mode_, main_frame);
3543 DevToolsManager::GetInstance()->RenderViewCreated(this, render_view_host);
3546 void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
3547 if (rvh != GetRenderViewHost()) {
3548 // Don't notify the world, since this came from a renderer in the
3549 // background.
3550 return;
3553 notify_disconnection_ = true;
3554 // TODO(avi): Remove. http://crbug.com/170921
3555 NotificationService::current()->Notify(
3556 NOTIFICATION_WEB_CONTENTS_CONNECTED,
3557 Source<WebContents>(this),
3558 NotificationService::NoDetails());
3560 bool was_crashed = IsCrashed();
3561 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
3563 // Restore the focus to the tab (otherwise the focus will be on the top
3564 // window).
3565 if (was_crashed && !FocusLocationBarByDefault() &&
3566 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
3567 view_->Focus();
3570 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewReady());
3573 void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
3574 base::TerminationStatus status,
3575 int error_code) {
3576 if (rvh != GetRenderViewHost()) {
3577 // The pending page's RenderViewHost is gone.
3578 return;
3581 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3582 // renderer may not have made a clean exit.
3583 if (IsFullscreenForCurrentTab())
3584 ToggleFullscreenMode(false);
3586 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3587 if (dialog_manager_)
3588 dialog_manager_->CancelActiveAndPendingDialogs(this);
3590 if (delegate_)
3591 delegate_->HideValidationMessage(this);
3593 SetIsLoading(rvh, false, true, NULL);
3594 NotifyDisconnected();
3595 SetIsCrashed(status, error_code);
3597 // Reset the loading progress. TODO(avi): What does it mean to have a
3598 // "renderer crash" when there is more than one renderer process serving a
3599 // webpage? Once this function is called at a more granular frame level, we
3600 // probably will need to more granularly reset the state here.
3601 ResetLoadProgressState();
3602 loading_frames_in_progress_ = 0;
3604 FOR_EACH_OBSERVER(WebContentsObserver,
3605 observers_,
3606 RenderProcessGone(GetCrashedStatus()));
3609 void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
3610 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewDeleted(rvh));
3613 void WebContentsImpl::UpdateState(RenderViewHost* rvh,
3614 int32 page_id,
3615 const PageState& page_state) {
3616 // Ensure that this state update comes from either the active RVH or one of
3617 // the swapped out RVHs. We don't expect to hear from any other RVHs.
3618 // TODO(nasko): This should go through RenderFrameHost.
3619 // TODO(creis): We can't update state for cross-process subframes until we
3620 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
3621 if (rvh != GetRenderViewHost() &&
3622 !GetRenderManager()->IsRVHOnSwappedOutList(
3623 static_cast<RenderViewHostImpl*>(rvh)))
3624 return;
3626 // We must be prepared to handle state updates for any page, these occur
3627 // when the user is scrolling and entering form data, as well as when we're
3628 // leaving a page, in which case our state may have already been moved to
3629 // the next page. The navigation controller will look up the appropriate
3630 // NavigationEntry and update it when it is notified via the delegate.
3632 int entry_index = controller_.GetEntryIndexWithPageID(
3633 rvh->GetSiteInstance(), page_id);
3634 if (entry_index < 0)
3635 return;
3636 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
3638 if (page_state == entry->GetPageState())
3639 return; // Nothing to update.
3640 entry->SetPageState(page_state);
3641 controller_.NotifyEntryChanged(entry, entry_index);
3644 void WebContentsImpl::UpdateTargetURL(const GURL& url) {
3645 if (delegate_)
3646 delegate_->UpdateTargetURL(this, url);
3649 void WebContentsImpl::Close(RenderViewHost* rvh) {
3650 #if defined(OS_MACOSX)
3651 // The UI may be in an event-tracking loop, such as between the
3652 // mouse-down and mouse-up in text selection or a button click.
3653 // Defer the close until after tracking is complete, so that we
3654 // don't free objects out from under the UI.
3655 // TODO(shess): This could get more fine-grained. For instance,
3656 // closing a tab in another window while selecting text in the
3657 // current window's Omnibox should be just fine.
3658 if (view_->IsEventTracking()) {
3659 view_->CloseTabAfterEventTracking();
3660 return;
3662 #endif
3664 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3665 if (delegate_ && rvh == GetRenderViewHost())
3666 delegate_->CloseContents(this);
3669 void WebContentsImpl::SwappedOut(RenderFrameHost* rfh) {
3670 if (delegate_ && rfh->GetRenderViewHost() == GetRenderViewHost())
3671 delegate_->SwappedOut(this);
3674 void WebContentsImpl::DidDeferAfterResponseStarted(
3675 const TransitionLayerData& transition_data) {
3676 #if defined(OS_ANDROID)
3677 GetWebContentsAndroid()->DidDeferAfterResponseStarted(transition_data);
3678 #endif
3681 bool WebContentsImpl::WillHandleDeferAfterResponseStarted() {
3682 #if defined(OS_ANDROID)
3683 return GetWebContentsAndroid()->WillHandleDeferAfterResponseStarted();
3684 #else
3685 return false;
3686 #endif
3689 void WebContentsImpl::RequestMove(const gfx::Rect& new_bounds) {
3690 if (delegate_ && delegate_->IsPopupOrPanel(this))
3691 delegate_->MoveContents(this, new_bounds);
3694 void WebContentsImpl::DidStartLoading(RenderFrameHost* render_frame_host,
3695 bool to_different_document) {
3696 SetIsLoading(render_frame_host->GetRenderViewHost(), true,
3697 to_different_document, NULL);
3700 void WebContentsImpl::DidStopLoading(RenderFrameHost* render_frame_host) {
3701 scoped_ptr<LoadNotificationDetails> details;
3703 // Use the last committed entry rather than the active one, in case a
3704 // pending entry has been created.
3705 NavigationEntry* entry = controller_.GetLastCommittedEntry();
3706 Navigator* navigator = frame_tree_.root()->navigator();
3708 // An entry may not exist for a stop when loading an initial blank page or
3709 // if an iframe injected by script into a blank page finishes loading.
3710 if (entry) {
3711 base::TimeDelta elapsed =
3712 base::TimeTicks::Now() - navigator->GetCurrentLoadStart();
3714 details.reset(new LoadNotificationDetails(
3715 entry->GetVirtualURL(),
3716 entry->GetTransitionType(),
3717 elapsed,
3718 &controller_,
3719 controller_.GetCurrentEntryIndex()));
3722 SetIsLoading(render_frame_host->GetRenderViewHost(), false, true,
3723 details.get());
3726 void WebContentsImpl::DidCancelLoading() {
3727 controller_.DiscardNonCommittedEntries();
3729 // Update the URL display.
3730 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3733 void WebContentsImpl::DidAccessInitialDocument() {
3734 has_accessed_initial_document_ = true;
3736 // We may have left a failed browser-initiated navigation in the address bar
3737 // to let the user edit it and try again. Clear it now that content might
3738 // show up underneath it.
3739 if (!IsLoading() && controller_.GetPendingEntry())
3740 controller_.DiscardPendingEntry();
3742 // Update the URL display.
3743 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3746 void WebContentsImpl::DidDisownOpener(RenderFrameHost* render_frame_host) {
3747 // No action is necessary if the opener has already been cleared.
3748 if (!opener_)
3749 return;
3751 // Clear our opener so that future cross-process navigations don't have an
3752 // opener assigned.
3753 RemoveDestructionObserver(opener_);
3754 opener_ = NULL;
3756 // Notify all swapped out RenderViewHosts for this tab. This is important
3757 // in case we go back to them, or if another window in those processes tries
3758 // to access window.opener.
3759 GetRenderManager()->DidDisownOpener(render_frame_host);
3762 void WebContentsImpl::DocumentOnLoadCompleted(
3763 RenderFrameHost* render_frame_host) {
3764 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3765 DocumentOnLoadCompletedInMainFrame());
3767 // TODO(avi): Remove. http://crbug.com/170921
3768 NotificationService::current()->Notify(
3769 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
3770 Source<WebContents>(this),
3771 NotificationService::NoDetails());
3774 void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
3775 int32 page_id,
3776 const base::string16& title,
3777 base::i18n::TextDirection title_direction) {
3778 RenderViewHost* rvh = render_frame_host->GetRenderViewHost();
3780 // If we have a title, that's a pretty good indication that we've started
3781 // getting useful data.
3782 SetNotWaitingForResponse();
3784 // Try to find the navigation entry, which might not be the current one.
3785 // For example, it might be from a pending RVH for the pending entry.
3786 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
3787 rvh->GetSiteInstance(), page_id);
3789 // We can handle title updates when we don't have an entry in
3790 // UpdateTitleForEntry, but only if the update is from the current RVH.
3791 // TODO(avi): Change to make decisions based on the RenderFrameHost.
3792 if (!entry && rvh != GetRenderViewHost())
3793 return;
3795 // TODO(evan): make use of title_direction.
3796 // http://code.google.com/p/chromium/issues/detail?id=27094
3797 if (!UpdateTitleForEntry(entry, title))
3798 return;
3800 // Broadcast notifications when the UI should be updated.
3801 if (entry == controller_.GetEntryAtOffset(0))
3802 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
3805 void WebContentsImpl::UpdateEncoding(RenderFrameHost* render_frame_host,
3806 const std::string& encoding) {
3807 SetEncoding(encoding);
3810 void WebContentsImpl::DocumentAvailableInMainFrame(
3811 RenderViewHost* render_view_host) {
3812 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3813 DocumentAvailableInMainFrame());
3815 void WebContentsImpl::RouteCloseEvent(RenderViewHost* rvh) {
3816 // Tell the active RenderViewHost to run unload handlers and close, as long
3817 // as the request came from a RenderViewHost in the same BrowsingInstance.
3818 // In most cases, we receive this from a swapped out RenderViewHost.
3819 // It is possible to receive it from one that has just been swapped in,
3820 // in which case we might as well deliver the message anyway.
3821 if (rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3822 GetRenderViewHost()->ClosePage();
3825 void WebContentsImpl::RouteMessageEvent(
3826 RenderViewHost* rvh,
3827 const ViewMsg_PostMessage_Params& params) {
3828 // Only deliver the message to the active RenderViewHost if the request
3829 // came from a RenderViewHost in the same BrowsingInstance or if this
3830 // WebContents is dedicated to a browser plugin guest.
3831 // Note: This check means that an embedder could theoretically receive a
3832 // postMessage from anyone (not just its own guests). However, this is
3833 // probably not a risk for apps since other pages won't have references
3834 // to App windows.
3835 if (!rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()) &&
3836 !GetBrowserPluginGuest() && !GetBrowserPluginEmbedder())
3837 return;
3839 ViewMsg_PostMessage_Params new_params(params);
3841 if (!params.message_port_ids.empty()) {
3842 MessagePortMessageFilter* message_port_message_filter =
3843 static_cast<RenderProcessHostImpl*>(GetRenderProcessHost())
3844 ->message_port_message_filter();
3845 message_port_message_filter->UpdateMessagePortsWithNewRoutes(
3846 params.message_port_ids,
3847 &new_params.new_routing_ids);
3850 // If there is a source_routing_id, translate it to the routing ID for
3851 // the equivalent swapped out RVH in the target process. If we need
3852 // to create a swapped out RVH for the source tab, we create its opener
3853 // chain as well, since those will also be accessible to the target page.
3854 if (new_params.source_routing_id != MSG_ROUTING_NONE) {
3855 // Try to look up the WebContents for the source page.
3856 WebContentsImpl* source_contents = NULL;
3857 RenderViewHostImpl* source_rvh = RenderViewHostImpl::FromID(
3858 rvh->GetProcess()->GetID(), params.source_routing_id);
3859 if (source_rvh) {
3860 source_contents = static_cast<WebContentsImpl*>(
3861 source_rvh->GetDelegate()->GetAsWebContents());
3864 if (source_contents) {
3865 if (GetBrowserPluginGuest()) {
3866 // We create a swapped out RenderView for the embedder in the guest's
3867 // render process but we intentionally do not expose the embedder's
3868 // opener chain to it.
3869 new_params.source_routing_id =
3870 source_contents->CreateSwappedOutRenderView(GetSiteInstance());
3871 } else {
3872 new_params.source_routing_id =
3873 source_contents->CreateOpenerRenderViews(GetSiteInstance());
3875 } else {
3876 // We couldn't find it, so don't pass a source frame.
3877 new_params.source_routing_id = MSG_ROUTING_NONE;
3881 // In most cases, we receive this from a swapped out RenderViewHost.
3882 // It is possible to receive it from one that has just been swapped in,
3883 // in which case we might as well deliver the message anyway.
3884 Send(new ViewMsg_PostMessageEvent(GetRoutingID(), new_params));
3887 bool WebContentsImpl::AddMessageToConsole(int32 level,
3888 const base::string16& message,
3889 int32 line_no,
3890 const base::string16& source_id) {
3891 if (!delegate_)
3892 return false;
3893 return delegate_->AddMessageToConsole(this, level, message, line_no,
3894 source_id);
3897 WebPreferences WebContentsImpl::ComputeWebkitPrefs() {
3898 // We want to base the page config off of the actual URL, rather than the
3899 // virtual URL.
3900 // TODO(nasko): Investigate how to remove the GetActiveEntry usage here,
3901 // as it is deprecated and can be out of sync with GetRenderViewHost().
3902 GURL url = controller_.GetActiveEntry()
3903 ? controller_.GetActiveEntry()->GetURL() : GURL::EmptyGURL();
3905 return GetRenderManager()->current_host()->ComputeWebkitPrefs(url);
3908 int WebContentsImpl::CreateSwappedOutRenderView(
3909 SiteInstance* instance) {
3910 return GetRenderManager()->CreateRenderFrame(
3911 instance, MSG_ROUTING_NONE, CREATE_RF_SWAPPED_OUT |
3912 CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
3913 CREATE_RF_HIDDEN);
3916 void WebContentsImpl::OnUserGesture() {
3917 // Notify observers.
3918 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetUserGesture());
3920 ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
3921 if (rdh) // NULL in unittests.
3922 rdh->OnUserGesture(this);
3925 void WebContentsImpl::OnIgnoredUIEvent() {
3926 // Notify observers.
3927 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetIgnoredUIEvent());
3930 void WebContentsImpl::RendererUnresponsive(RenderViewHost* render_view_host) {
3931 // Don't show hung renderer dialog for a swapped out RVH.
3932 if (render_view_host != GetRenderViewHost())
3933 return;
3935 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(render_view_host);
3936 RenderFrameHostImpl* rfhi =
3937 static_cast<RenderFrameHostImpl*>(rvhi->GetMainFrame());
3939 // Ignore renderer unresponsive event if debugger is attached to the tab
3940 // since the event may be a result of the renderer sitting on a breakpoint.
3941 // See http://crbug.com/65458
3942 if (DevToolsAgentHost::IsDebuggerAttached(this))
3943 return;
3945 if (rfhi->is_waiting_for_beforeunload_ack() ||
3946 rfhi->IsWaitingForUnloadACK()) {
3947 // Hang occurred while firing the beforeunload/unload handler.
3948 // Pretend the handler fired so tab closing continues as if it had.
3949 rvhi->set_sudden_termination_allowed(true);
3951 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
3952 return;
3954 // If the tab hangs in the beforeunload/unload handler there's really
3955 // nothing we can do to recover. If the hang is in the beforeunload handler,
3956 // pretend the beforeunload listeners have all fired and allow the delegate
3957 // to continue closing; the user will not have the option of cancelling the
3958 // close. Otherwise, pretend the unload listeners have all fired and close
3959 // the tab.
3960 bool close = true;
3961 if (rfhi->is_waiting_for_beforeunload_ack() && delegate_) {
3962 delegate_->BeforeUnloadFired(this, true, &close);
3964 if (close)
3965 Close(rvhi);
3966 return;
3969 if (!GetRenderViewHostImpl() || !GetRenderViewHostImpl()->IsRenderViewLive())
3970 return;
3972 if (delegate_)
3973 delegate_->RendererUnresponsive(this);
3976 void WebContentsImpl::RendererResponsive(RenderViewHost* render_view_host) {
3977 if (delegate_)
3978 delegate_->RendererResponsive(this);
3981 void WebContentsImpl::LoadStateChanged(
3982 const GURL& url,
3983 const net::LoadStateWithParam& load_state,
3984 uint64 upload_position,
3985 uint64 upload_size) {
3986 load_state_ = load_state;
3987 upload_position_ = upload_position;
3988 upload_size_ = upload_size;
3989 load_state_host_ = net::IDNToUnicode(url.host(),
3990 GetContentClient()->browser()->GetAcceptLangs(
3991 GetBrowserContext()));
3992 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
3993 SetNotWaitingForResponse();
3994 if (IsLoading()) {
3995 NotifyNavigationStateChanged(static_cast<InvalidateTypes>(
3996 INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB));
4000 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
4001 bool proceed, const base::TimeTicks& proceed_time,
4002 bool* proceed_to_fire_unload) {
4003 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4004 BeforeUnloadFired(proceed_time));
4005 if (delegate_)
4006 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
4007 // Note: |this| might be deleted at this point.
4010 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4011 RenderViewHost* render_view_host) {
4012 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
4013 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
4016 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4017 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4018 gfx::Size size = GetSizeForNewRenderView();
4019 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4020 // here during container initialization and normal window size will be set
4021 // later. In case of tab duplication this resizing to 0x0 prevents setting
4022 // normal size later so just ignore it.
4023 if (!size.IsEmpty())
4024 view_->SizeContents(size);
4027 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4028 // We need to cancel modal dialogs when doing a process swap, since the load
4029 // deferrer would prevent us from swapping out.
4030 if (dialog_manager_)
4031 dialog_manager_->CancelActiveAndPendingDialogs(this);
4034 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_host,
4035 RenderFrameHost* new_host,
4036 bool is_main_frame) {
4037 if (is_main_frame) {
4038 NotifyViewSwapped(old_host ? old_host->GetRenderViewHost() : NULL,
4039 new_host->GetRenderViewHost());
4041 // Make sure the visible RVH reflects the new delegate's preferences.
4042 if (delegate_)
4043 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4045 view_->RenderViewSwappedIn(new_host->GetRenderViewHost());
4048 NotifyFrameSwapped(old_host, new_host);
4051 int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
4052 SiteInstance* instance) {
4053 if (!opener_)
4054 return MSG_ROUTING_NONE;
4056 // Recursively create RenderViews for anything else in the opener chain.
4057 return opener_->CreateOpenerRenderViews(instance);
4060 int WebContentsImpl::CreateOpenerRenderViews(SiteInstance* instance) {
4061 int opener_route_id = MSG_ROUTING_NONE;
4063 // If this tab has an opener, ensure it has a RenderView in the given
4064 // SiteInstance as well.
4065 if (opener_)
4066 opener_route_id = opener_->CreateOpenerRenderViews(instance);
4068 // If any of the renderers (current, pending, or swapped out) for this
4069 // WebContents has the same SiteInstance, use it.
4070 if (GetRenderManager()->current_host()->GetSiteInstance() == instance)
4071 return GetRenderManager()->current_host()->GetRoutingID();
4073 if (GetRenderManager()->pending_render_view_host() &&
4074 GetRenderManager()->pending_render_view_host()->GetSiteInstance() ==
4075 instance)
4076 return GetRenderManager()->pending_render_view_host()->GetRoutingID();
4078 RenderViewHostImpl* rvh = GetRenderManager()->GetSwappedOutRenderViewHost(
4079 instance);
4080 if (rvh)
4081 return rvh->GetRoutingID();
4083 // Create a swapped out RenderView in the given SiteInstance if none exists,
4084 // setting its opener to the given route_id. Return the new view's route_id.
4085 return GetRenderManager()->CreateRenderFrame(
4086 instance, opener_route_id, CREATE_RF_FOR_MAIN_FRAME_NAVIGATION |
4087 CREATE_RF_SWAPPED_OUT | CREATE_RF_HIDDEN);
4090 NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
4091 return GetController();
4094 WebUIImpl* WebContentsImpl::CreateWebUIForRenderManager(const GURL& url) {
4095 return static_cast<WebUIImpl*>(CreateWebUI(url));
4098 NavigationEntry*
4099 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4100 return controller_.GetLastCommittedEntry();
4103 bool WebContentsImpl::CreateRenderViewForRenderManager(
4104 RenderViewHost* render_view_host,
4105 int opener_route_id,
4106 int proxy_routing_id,
4107 bool for_main_frame_navigation) {
4108 TRACE_EVENT0("browser,navigation",
4109 "WebContentsImpl::CreateRenderViewForRenderManager");
4110 // Can be NULL during tests.
4111 RenderWidgetHostViewBase* rwh_view;
4112 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
4113 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
4114 // case this because RWH is still a base class of RenderViewHost, and child
4115 // frame RWHVs are unique in that they do not have their own WebContents.
4116 if (!for_main_frame_navigation) {
4117 RenderWidgetHostViewChildFrame* rwh_view_child =
4118 new RenderWidgetHostViewChildFrame(render_view_host);
4119 rwh_view = rwh_view_child;
4120 } else {
4121 rwh_view = view_->CreateViewForWidget(render_view_host, false);
4124 // Now that the RenderView has been created, we need to tell it its size.
4125 if (rwh_view)
4126 rwh_view->SetSize(GetSizeForNewRenderView());
4128 // Make sure we use the correct starting page_id in the new RenderView.
4129 UpdateMaxPageIDIfNecessary(render_view_host);
4130 int32 max_page_id =
4131 GetMaxPageIDForSiteInstance(render_view_host->GetSiteInstance());
4133 if (!static_cast<RenderViewHostImpl*>(
4134 render_view_host)->CreateRenderView(base::string16(),
4135 opener_route_id,
4136 proxy_routing_id,
4137 max_page_id,
4138 created_with_opener_)) {
4139 return false;
4142 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4143 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4144 // linux. See crbug.com/83941.
4145 if (rwh_view) {
4146 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
4147 render_widget_host->WasResized();
4149 #endif
4151 return true;
4154 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4155 RenderFrameHost* render_frame_host,
4156 int parent_routing_id,
4157 int proxy_routing_id) {
4158 TRACE_EVENT0("browser,navigation",
4159 "WebContentsImpl::CreateRenderFrameForRenderManager");
4161 RenderFrameHostImpl* rfh =
4162 static_cast<RenderFrameHostImpl*>(render_frame_host);
4163 if (!rfh->CreateRenderFrame(parent_routing_id, proxy_routing_id))
4164 return false;
4166 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4167 // RenderFrameHost will have to be associated with the appropriate
4168 // RenderWidgetHostView or a new one should be created here.
4170 return true;
4173 #if defined(OS_ANDROID)
4175 base::android::ScopedJavaLocalRef<jobject>
4176 WebContentsImpl::GetJavaWebContents() {
4177 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
4178 return GetWebContentsAndroid()->GetJavaObject();
4181 WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
4182 WebContentsAndroid* web_contents_android =
4183 static_cast<WebContentsAndroid*>(GetUserData(kWebContentsAndroidKey));
4184 if (!web_contents_android) {
4185 web_contents_android = new WebContentsAndroid(this);
4186 SetUserData(kWebContentsAndroidKey, web_contents_android);
4188 return web_contents_android;
4191 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4192 return CreateRenderViewForRenderManager(GetRenderViewHost(),
4193 MSG_ROUTING_NONE,
4194 MSG_ROUTING_NONE,
4195 true);
4198 #elif defined(OS_MACOSX)
4200 void WebContentsImpl::SetAllowOtherViews(bool allow) {
4201 view_->SetAllowOtherViews(allow);
4204 bool WebContentsImpl::GetAllowOtherViews() {
4205 return view_->GetAllowOtherViews();
4208 #endif
4210 void WebContentsImpl::OnDialogClosed(int render_process_id,
4211 int render_frame_id,
4212 IPC::Message* reply_msg,
4213 bool dialog_was_suppressed,
4214 bool success,
4215 const base::string16& user_input) {
4216 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
4217 render_frame_id);
4218 last_dialog_suppressed_ = dialog_was_suppressed;
4220 if (is_showing_before_unload_dialog_ && !success) {
4221 // If a beforeunload dialog is canceled, we need to stop the throbber from
4222 // spinning, since we forced it to start spinning in Navigate.
4223 if (rfh)
4224 DidStopLoading(rfh);
4225 controller_.DiscardNonCommittedEntries();
4227 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
4228 BeforeUnloadDialogCancelled());
4231 is_showing_before_unload_dialog_ = false;
4232 if (rfh) {
4233 rfh->JavaScriptDialogClosed(reply_msg, success, user_input,
4234 dialog_was_suppressed);
4235 } else {
4236 // Don't leak the sync IPC reply if the RFH or process is gone.
4237 delete reply_msg;
4241 void WebContentsImpl::SetEncoding(const std::string& encoding) {
4242 if (encoding == last_reported_encoding_)
4243 return;
4244 last_reported_encoding_ = encoding;
4246 canonical_encoding_ = GetContentClient()->browser()->
4247 GetCanonicalEncodingNameByAliasName(encoding);
4250 bool WebContentsImpl::IsHidden() {
4251 return capturer_count_ == 0 && !should_normally_be_visible_;
4254 RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
4255 return frame_tree_.root()->render_manager();
4258 RenderViewHostImpl* WebContentsImpl::GetRenderViewHostImpl() {
4259 return static_cast<RenderViewHostImpl*>(GetRenderViewHost());
4262 BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
4263 return browser_plugin_guest_.get();
4266 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest* guest) {
4267 CHECK(!browser_plugin_guest_);
4268 browser_plugin_guest_.reset(guest);
4271 BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
4272 return browser_plugin_embedder_.get();
4275 void WebContentsImpl::ClearPowerSaveBlockers(
4276 RenderFrameHost* render_frame_host) {
4277 RemoveAllMediaPlayerEntries(render_frame_host, &active_audio_players_);
4278 RemoveAllMediaPlayerEntries(render_frame_host, &active_video_players_);
4279 MaybeReleasePowerSaveBlockers();
4282 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4283 active_audio_players_.clear();
4284 active_video_players_.clear();
4285 audio_power_save_blocker_.reset();
4286 video_power_save_blocker_.reset();
4289 gfx::Size WebContentsImpl::GetSizeForNewRenderView() {
4290 gfx::Size size;
4291 if (delegate_)
4292 size = delegate_->GetSizeForNewRenderView(this);
4293 if (size.IsEmpty())
4294 size = GetContainerBounds().size();
4295 return size;
4298 void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
4299 FOR_EACH_OBSERVER(
4300 WebContentsObserver, observers_, FrameDetached(render_frame_host));
4303 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
4304 if (!delegate_)
4305 return;
4306 const gfx::Size new_size = GetPreferredSize();
4307 if (new_size != old_size)
4308 delegate_->UpdatePreferredSize(this, new_size);
4311 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie,
4312 ActiveMediaPlayerMap* player_map) {
4313 const uintptr_t key =
4314 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4315 DCHECK(std::find((*player_map)[key].begin(),
4316 (*player_map)[key].end(),
4317 player_cookie) == (*player_map)[key].end());
4318 (*player_map)[key].push_back(player_cookie);
4321 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie,
4322 ActiveMediaPlayerMap* player_map) {
4323 const uintptr_t key =
4324 reinterpret_cast<uintptr_t>(render_frame_message_source_);
4325 ActiveMediaPlayerMap::iterator it = player_map->find(key);
4326 if (it == player_map->end())
4327 return;
4329 // Remove the player.
4330 PlayerList::iterator player_it =
4331 std::find(it->second.begin(), it->second.end(), player_cookie);
4332 if (player_it != it->second.end())
4333 it->second.erase(player_it);
4335 // If there are no players left, remove the map entry.
4336 if (it->second.empty())
4337 player_map->erase(it);
4340 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4341 RenderFrameHost* render_frame_host,
4342 ActiveMediaPlayerMap* player_map) {
4343 ActiveMediaPlayerMap::iterator it =
4344 player_map->find(reinterpret_cast<uintptr_t>(render_frame_host));
4345 if (it == player_map->end())
4346 return;
4347 player_map->erase(it);
4350 void WebContentsImpl::ResumeResponseDeferredAtStart() {
4351 FrameTreeNode* node = frame_tree_.root();
4352 node->render_manager()->ResumeResponseDeferredAtStart();
4355 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
4356 force_disable_overscroll_content_ = force_disable;
4357 if (view_)
4358 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
4361 } // namespace content