Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / content / browser / web_contents / web_contents_impl.cc
blobea872a6957b5757bd88c23c708fecf8612e542aa
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/browser_plugin/browser_plugin_embedder.h"
22 #include "content/browser/browser_plugin/browser_plugin_guest.h"
23 #include "content/browser/browser_plugin/browser_plugin_guest_manager.h"
24 #include "content/browser/child_process_security_policy_impl.h"
25 #include "content/browser/devtools/render_view_devtools_agent_host.h"
26 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
27 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
28 #include "content/browser/download/download_stats.h"
29 #include "content/browser/download/mhtml_generation_manager.h"
30 #include "content/browser/download/save_package.h"
31 #include "content/browser/frame_host/cross_process_frame_connector.h"
32 #include "content/browser/frame_host/interstitial_page_impl.h"
33 #include "content/browser/frame_host/navigation_entry_impl.h"
34 #include "content/browser/frame_host/navigator_impl.h"
35 #include "content/browser/frame_host/render_frame_host_impl.h"
36 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
37 #include "content/browser/host_zoom_map_impl.h"
38 #include "content/browser/loader/resource_dispatcher_host_impl.h"
39 #include "content/browser/message_port_message_filter.h"
40 #include "content/browser/message_port_service.h"
41 #include "content/browser/power_save_blocker_impl.h"
42 #include "content/browser/renderer_host/render_process_host_impl.h"
43 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
44 #include "content/browser/renderer_host/render_view_host_impl.h"
45 #include "content/browser/renderer_host/render_widget_host_impl.h"
46 #include "content/browser/renderer_host/render_widget_host_view_base.h"
47 #include "content/browser/site_instance_impl.h"
48 #include "content/browser/web_contents/web_contents_view_guest.h"
49 #include "content/browser/webui/generic_handler.h"
50 #include "content/browser/webui/web_ui_controller_factory_registry.h"
51 #include "content/browser/webui/web_ui_impl.h"
52 #include "content/common/browser_plugin/browser_plugin_constants.h"
53 #include "content/common/browser_plugin/browser_plugin_messages.h"
54 #include "content/common/frame_messages.h"
55 #include "content/common/image_messages.h"
56 #include "content/common/input_messages.h"
57 #include "content/common/ssl_status_serialization.h"
58 #include "content/common/view_messages.h"
59 #include "content/public/browser/ax_event_notification_details.h"
60 #include "content/public/browser/browser_context.h"
61 #include "content/public/browser/content_browser_client.h"
62 #include "content/public/browser/devtools_agent_host.h"
63 #include "content/public/browser/download_manager.h"
64 #include "content/public/browser/download_url_parameters.h"
65 #include "content/public/browser/invalidate_type.h"
66 #include "content/public/browser/javascript_dialog_manager.h"
67 #include "content/public/browser/load_from_memory_cache_details.h"
68 #include "content/public/browser/load_notification_details.h"
69 #include "content/public/browser/navigation_details.h"
70 #include "content/public/browser/notification_details.h"
71 #include "content/public/browser/notification_service.h"
72 #include "content/public/browser/resource_request_details.h"
73 #include "content/public/browser/storage_partition.h"
74 #include "content/public/browser/user_metrics.h"
75 #include "content/public/browser/web_contents_delegate.h"
76 #include "content/public/browser/web_contents_observer.h"
77 #include "content/public/common/bindings_policy.h"
78 #include "content/public/common/content_constants.h"
79 #include "content/public/common/content_switches.h"
80 #include "content/public/common/page_zoom.h"
81 #include "content/public/common/result_codes.h"
82 #include "content/public/common/url_constants.h"
83 #include "content/public/common/url_utils.h"
84 #include "net/base/mime_util.h"
85 #include "net/base/net_util.h"
86 #include "net/http/http_cache.h"
87 #include "net/http/http_transaction_factory.h"
88 #include "net/url_request/url_request_context.h"
89 #include "net/url_request/url_request_context_getter.h"
90 #include "ui/base/layout.h"
91 #include "ui/gfx/display.h"
92 #include "ui/gfx/screen.h"
93 #include "ui/gl/gl_switches.h"
94 #include "webkit/common/webpreferences.h"
96 #if defined(OS_ANDROID)
97 #include "content/browser/android/date_time_chooser_android.h"
98 #include "content/browser/media/android/browser_media_player_manager.h"
99 #include "content/browser/renderer_host/java/java_bridge_dispatcher_host_manager.h"
100 #include "content/browser/web_contents/web_contents_android.h"
101 #include "content/common/java_bridge_messages.h"
102 #include "content/public/browser/android/content_view_core.h"
103 #endif
105 #if defined(OS_MACOSX)
106 #include "base/mac/foundation_util.h"
107 #include "ui/gl/io_surface_support_mac.h"
108 #endif
110 // Cross-Site Navigations
112 // If a WebContentsImpl is told to navigate to a different web site (as
113 // determined by SiteInstance), it will replace its current RenderViewHost with
114 // a new RenderViewHost dedicated to the new SiteInstance. This works as
115 // follows:
117 // - RVHM::Navigate determines whether the destination is cross-site, and if so,
118 // it creates a pending_render_view_host_.
119 // - The pending RVH is "suspended," so that no navigation messages are sent to
120 // its renderer until the beforeunload JavaScript handler has a chance to
121 // run in the current RVH.
122 // - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
123 // that it has a pending cross-site request. We will check this on the IO
124 // thread when deciding how to handle the response.
125 // - The current RVH runs its beforeunload handler. If it returns false, we
126 // cancel all the pending logic. Otherwise we allow the pending RVH to send
127 // the navigation request to its renderer.
128 // - ResourceDispatcherHost receives a ResourceRequest on the IO thread for the
129 // main resource load on the pending RVH. It creates a
130 // CrossSiteResourceHandler to check whether a process swap is needed when
131 // the request is ready to commit.
132 // - When RDH receives a response, the BufferedResourceHandler determines
133 // whether it is a download. If so, it sends a message to the new renderer
134 // causing it to cancel the request, and the download proceeds. For now, the
135 // pending RVH remains until the next DidNavigate event for this
136 // WebContentsImpl. This isn't ideal, but it doesn't affect any functionality.
137 // - After RDH receives a response and determines that it is safe and not a
138 // download, the CrossSiteResourceHandler checks whether a process swap is
139 // needed (either because CrossSiteRequestManager has state for it or because
140 // a transfer was needed for a redirect).
141 // - If so, CrossSiteResourceHandler pauses the response to first run the old
142 // page's unload handler. It does this by asynchronously calling the
143 // OnCrossSiteResponse method of RenderFrameHostManager on the UI thread,
144 // which sends a SwapOut message to the current RVH.
145 // - Once the unload handler is finished, RVHM::SwappedOut checks if a transfer
146 // to a new process is needed, based on the stored pending_nav_params_. (This
147 // is independent of whether we started out with a cross-process navigation.)
148 // - If not, it just tells the ResourceDispatcherHost to resume the response
149 // to its current RenderViewHost.
150 // - If so, it cancels the current pending RenderViewHost and sets up a new
151 // navigation using RequestTransferURL. When the transferred request
152 // arrives in the ResourceDispatcherHost, we transfer the response and
153 // resume it.
154 // - The pending renderer sends a FrameNavigate message that invokes the
155 // DidNavigate method. This replaces the current RVH with the
156 // pending RVH.
157 // - The previous renderer is kept swapped out in RenderFrameHostManager in case
158 // the user goes back. The process only stays live if another tab is using
159 // it, but if so, the existing frame relationships will be maintained.
161 namespace content {
162 namespace {
164 const char kDotGoogleDotCom[] = ".google.com";
166 #if defined(OS_ANDROID)
167 const char kWebContentsAndroidKey[] = "web_contents_android";
168 #endif // OS_ANDROID
170 base::LazyInstance<std::vector<WebContentsImpl::CreatedCallback> >
171 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
173 static int StartDownload(content::RenderFrameHost* rfh,
174 const GURL& url,
175 bool is_favicon,
176 uint32_t max_bitmap_size) {
177 static int g_next_image_download_id = 0;
178 rfh->Send(new ImageMsg_DownloadImage(rfh->GetRoutingID(),
179 ++g_next_image_download_id,
180 url,
181 is_favicon,
182 max_bitmap_size));
183 return g_next_image_download_id;
186 void NotifyCacheOnIO(
187 scoped_refptr<net::URLRequestContextGetter> request_context,
188 const GURL& url,
189 const std::string& http_method) {
190 request_context->GetURLRequestContext()->http_transaction_factory()->
191 GetCache()->OnExternalCacheHit(url, http_method);
194 // Helper function for retrieving all the sites in a frame tree.
195 bool CollectSites(BrowserContext* context,
196 std::set<GURL>* sites,
197 FrameTreeNode* node) {
198 sites->insert(SiteInstance::GetSiteForURL(context, node->current_url()));
199 return true;
202 bool ForEachFrameInternal(
203 const base::Callback<void(RenderFrameHost*)>& on_frame,
204 FrameTreeNode* node) {
205 on_frame.Run(node->current_frame_host());
206 return true;
209 bool ForEachPendingFrameInternal(
210 const base::Callback<void(RenderFrameHost*)>& on_frame,
211 FrameTreeNode* node) {
212 RenderFrameHost* pending_frame_host =
213 node->render_manager()->pending_frame_host();
214 if (pending_frame_host)
215 on_frame.Run(pending_frame_host);
216 return true;
219 void SendToAllFramesInternal(IPC::Message* message, RenderFrameHost* rfh) {
220 IPC::Message* message_copy = new IPC::Message(*message);
221 message_copy->set_routing_id(rfh->GetRoutingID());
222 rfh->Send(message_copy);
225 void RunRenderFrameDeleted(
226 ObserverList<WebContentsObserver>* observer_list,
227 RenderFrameHost* render_frame_host) {
228 FOR_EACH_OBSERVER(WebContentsObserver,
229 *observer_list,
230 RenderFrameDeleted(render_frame_host));
233 } // namespace
235 WebContents* WebContents::Create(const WebContents::CreateParams& params) {
236 return WebContentsImpl::CreateWithOpener(
237 params, static_cast<WebContentsImpl*>(params.opener));
240 WebContents* WebContents::CreateWithSessionStorage(
241 const WebContents::CreateParams& params,
242 const SessionStorageNamespaceMap& session_storage_namespace_map) {
243 WebContentsImpl* new_contents = new WebContentsImpl(
244 params.browser_context, NULL);
246 for (SessionStorageNamespaceMap::const_iterator it =
247 session_storage_namespace_map.begin();
248 it != session_storage_namespace_map.end();
249 ++it) {
250 new_contents->GetController()
251 .SetSessionStorageNamespace(it->first, it->second.get());
254 new_contents->Init(params);
255 return new_contents;
258 void WebContentsImpl::AddCreatedCallback(const CreatedCallback& callback) {
259 g_created_callbacks.Get().push_back(callback);
262 void WebContentsImpl::RemoveCreatedCallback(const CreatedCallback& callback) {
263 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
264 if (g_created_callbacks.Get().at(i).Equals(callback)) {
265 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
266 return;
271 WebContents* WebContents::FromRenderViewHost(const RenderViewHost* rvh) {
272 return rvh->GetDelegate()->GetAsWebContents();
275 WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
276 RenderFrameHostImpl* rfh_impl = static_cast<RenderFrameHostImpl*>(rfh);
277 if (!rfh_impl)
278 return NULL;
279 return rfh_impl->delegate()->GetAsWebContents();
282 // WebContentsImpl::DestructionObserver ----------------------------------------
284 class WebContentsImpl::DestructionObserver : public WebContentsObserver {
285 public:
286 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
287 : WebContentsObserver(watched_contents),
288 owner_(owner) {
291 // WebContentsObserver:
292 virtual void WebContentsDestroyed(WebContents* web_contents) OVERRIDE {
293 owner_->OnWebContentsDestroyed(static_cast<WebContentsImpl*>(web_contents));
296 private:
297 WebContentsImpl* owner_;
299 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
302 WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id,
303 int render_frame_id,
304 ColorChooser* chooser,
305 int identifier)
306 : render_process_id(render_process_id),
307 render_frame_id(render_frame_id),
308 chooser(chooser),
309 identifier(identifier) {
312 WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
315 // WebContentsImpl -------------------------------------------------------------
317 WebContentsImpl::WebContentsImpl(
318 BrowserContext* browser_context,
319 WebContentsImpl* opener)
320 : delegate_(NULL),
321 controller_(this, browser_context),
322 render_view_host_delegate_view_(NULL),
323 opener_(opener),
324 created_with_opener_(!!opener),
325 #if defined(OS_WIN)
326 accessible_parent_(NULL),
327 #endif
328 frame_tree_(new NavigatorImpl(&controller_, this),
329 this, this, this, this),
330 is_loading_(false),
331 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
332 crashed_error_code_(0),
333 waiting_for_response_(false),
334 load_state_(net::LOAD_STATE_IDLE, base::string16()),
335 upload_size_(0),
336 upload_position_(0),
337 displayed_insecure_content_(false),
338 has_accessed_initial_document_(false),
339 capturer_count_(0),
340 should_normally_be_visible_(true),
341 is_being_destroyed_(false),
342 notify_disconnection_(false),
343 dialog_manager_(NULL),
344 is_showing_before_unload_dialog_(false),
345 last_active_time_(base::TimeTicks::Now()),
346 closed_by_user_gesture_(false),
347 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)),
348 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)),
349 temporary_zoom_settings_(false),
350 totalPinchGestureAmount_(0),
351 currentPinchZoomStepDelta_(0),
352 render_view_message_source_(NULL),
353 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
354 is_subframe_(false),
355 last_dialog_suppressed_(false) {
356 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
357 g_created_callbacks.Get().at(i).Run(this);
358 frame_tree_.SetFrameRemoveListener(
359 base::Bind(&WebContentsImpl::OnFrameRemoved,
360 base::Unretained(this)));
363 WebContentsImpl::~WebContentsImpl() {
364 is_being_destroyed_ = true;
366 // If there is an interstitial page being shown, tell it to close down early
367 // so that this contents will be alive enough to handle all the UI triggered
368 // by that. <http://crbug.com/363564>
369 InterstitialPageImpl* interstitial_page =
370 static_cast<InterstitialPageImpl*>(GetInterstitialPage());
371 if (interstitial_page)
372 interstitial_page->WebContentsWillBeDestroyed();
374 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
375 // shutdown and be deleted as well.
376 frame_tree_.ForEach(
377 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown));
379 ClearAllPowerSaveBlockers();
381 for (std::set<RenderWidgetHostImpl*>::iterator iter =
382 created_widgets_.begin(); iter != created_widgets_.end(); ++iter) {
383 (*iter)->DetachDelegate();
385 created_widgets_.clear();
387 // Clear out any JavaScript state.
388 if (dialog_manager_)
389 dialog_manager_->WebContentsDestroyed(this);
391 if (color_chooser_info_.get())
392 color_chooser_info_->chooser->End();
394 NotifyDisconnected();
396 // Notify any observer that have a reference on this WebContents.
397 NotificationService::current()->Notify(
398 NOTIFICATION_WEB_CONTENTS_DESTROYED,
399 Source<WebContents>(this),
400 NotificationService::NoDetails());
402 base::Callback<void(RenderFrameHost*)> run_render_frame_deleted_callback =
403 base::Bind(&RunRenderFrameDeleted, base::Unretained(&observers_));
404 frame_tree_.ForEach(base::Bind(&ForEachPendingFrameInternal,
405 run_render_frame_deleted_callback));
407 RenderViewHost* pending_rvh = GetRenderManager()->pending_render_view_host();
408 if (pending_rvh) {
409 FOR_EACH_OBSERVER(WebContentsObserver,
410 observers_,
411 RenderViewDeleted(pending_rvh));
414 ForEachFrame(run_render_frame_deleted_callback);
416 FOR_EACH_OBSERVER(WebContentsObserver,
417 observers_,
418 RenderViewDeleted(GetRenderManager()->current_host()));
420 FOR_EACH_OBSERVER(WebContentsObserver,
421 observers_,
422 WebContentsImplDestroyed());
424 SetDelegate(NULL);
426 STLDeleteContainerPairSecondPointers(destruction_observers_.begin(),
427 destruction_observers_.end());
430 WebContentsImpl* WebContentsImpl::CreateWithOpener(
431 const WebContents::CreateParams& params,
432 WebContentsImpl* opener) {
433 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
434 WebContentsImpl* new_contents = new WebContentsImpl(
435 params.browser_context, opener);
437 new_contents->Init(params);
438 return new_contents;
441 // static
442 BrowserPluginGuest* WebContentsImpl::CreateGuest(
443 BrowserContext* browser_context,
444 SiteInstance* site_instance,
445 int guest_instance_id,
446 scoped_ptr<base::DictionaryValue> extra_params) {
447 WebContentsImpl* new_contents = new WebContentsImpl(browser_context, NULL);
449 // This makes |new_contents| act as a guest.
450 // For more info, see comment above class BrowserPluginGuest.
451 BrowserPluginGuest::Create(
452 guest_instance_id, site_instance, new_contents, extra_params.Pass());
454 WebContents::CreateParams create_params(browser_context, site_instance);
455 new_contents->Init(create_params);
457 // We are instantiating a WebContents for browser plugin. Set its subframe bit
458 // to true.
459 new_contents->is_subframe_ = true;
461 return new_contents->browser_plugin_guest_.get();
464 RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
465 return GetRenderManager();
468 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
469 const IPC::Message& message) {
470 return OnMessageReceived(render_view_host, NULL, message);
473 bool WebContentsImpl::OnMessageReceived(RenderViewHost* render_view_host,
474 RenderFrameHost* render_frame_host,
475 const IPC::Message& message) {
476 DCHECK(render_view_host || render_frame_host);
477 if (GetWebUI() &&
478 static_cast<WebUIImpl*>(GetWebUI())->OnMessageReceived(message)) {
479 return true;
482 ObserverListBase<WebContentsObserver>::Iterator it(observers_);
483 WebContentsObserver* observer;
484 while ((observer = it.GetNext()) != NULL)
485 if (observer->OnMessageReceived(message))
486 return true;
488 // Message handlers should be aware of which
489 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
490 // stored in render_(view|frame)_message_source_.
491 if (render_frame_host) {
492 if (RenderViewDevToolsAgentHost::DispatchIPCMessage(
493 render_frame_host->GetRenderViewHost(), message))
494 return true;
495 render_frame_message_source_ = render_frame_host;
496 } else {
497 if (RenderViewDevToolsAgentHost::DispatchIPCMessage(
498 render_view_host, message))
499 return true;
500 render_view_message_source_ = render_view_host;
503 bool handled = true;
504 bool message_is_ok = true;
505 IPC_BEGIN_MESSAGE_MAP_EX(WebContentsImpl, message, message_is_ok)
506 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
507 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
508 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse,
509 OnDomOperationResponse)
510 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad,
511 OnDocumentLoadedInFrame)
512 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad, OnDidFinishLoad)
513 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser, OnOpenColorChooser)
514 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser, OnEndColorChooser)
515 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser,
516 OnSetSelectedColorInColorChooser)
517 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification,
518 OnMediaPlayingNotification)
519 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification,
520 OnMediaPausedNotification)
521 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache,
522 OnDidLoadResourceFromMemoryCache)
523 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent,
524 OnDidDisplayInsecureContent)
525 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent,
526 OnDidRunInsecureContent)
527 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset)
528 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits, OnUpdateZoomLimits)
529 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory, OnEnumerateDirectory)
530 IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler,
531 OnRegisterProtocolHandler)
532 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply, OnFindReply)
533 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed, OnAppCacheAccessed)
534 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend, OnWebUISend)
535 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
536 OnRequestPpapiBrokerPermission)
537 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_AllocateInstanceID,
538 OnBrowserPluginMessage(message))
539 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach,
540 OnBrowserPluginMessage(message))
541 IPC_MESSAGE_HANDLER(ImageHostMsg_DidDownloadImage, OnDidDownloadImage)
542 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL, OnUpdateFaviconURL)
543 IPC_MESSAGE_HANDLER(ViewHostMsg_DidFirstVisuallyNonEmptyPaint,
544 OnFirstVisuallyNonEmptyPaint)
545 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage,
546 OnShowValidationMessage)
547 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage,
548 OnHideValidationMessage)
549 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage,
550 OnMoveValidationMessage)
551 #if defined(OS_ANDROID)
552 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply,
553 OnFindMatchRectsReply)
554 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog,
555 OnOpenDateTimeDialog)
556 IPC_MESSAGE_HANDLER_DELAY_REPLY(JavaBridgeHostMsg_GetChannelHandle,
557 OnJavaBridgeGetChannelHandle)
558 #endif
559 IPC_MESSAGE_UNHANDLED(handled = false)
560 IPC_END_MESSAGE_MAP_EX()
561 render_view_message_source_ = NULL;
562 render_frame_message_source_ = NULL;
564 if (!message_is_ok) {
565 RecordAction(base::UserMetricsAction("BadMessageTerminate_RVD"));
566 GetRenderProcessHost()->ReceivedBadMessage();
569 return handled;
572 void WebContentsImpl::RunFileChooser(
573 RenderViewHost* render_view_host,
574 const FileChooserParams& params) {
575 if (delegate_)
576 delegate_->RunFileChooser(this, params);
579 NavigationControllerImpl& WebContentsImpl::GetController() {
580 return controller_;
583 const NavigationControllerImpl& WebContentsImpl::GetController() const {
584 return controller_;
587 BrowserContext* WebContentsImpl::GetBrowserContext() const {
588 return controller_.GetBrowserContext();
591 const GURL& WebContentsImpl::GetURL() const {
592 // We may not have a navigation entry yet.
593 NavigationEntry* entry = controller_.GetVisibleEntry();
594 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
597 const GURL& WebContentsImpl::GetVisibleURL() const {
598 // We may not have a navigation entry yet.
599 NavigationEntry* entry = controller_.GetVisibleEntry();
600 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
603 const GURL& WebContentsImpl::GetLastCommittedURL() const {
604 // We may not have a navigation entry yet.
605 NavigationEntry* entry = controller_.GetLastCommittedEntry();
606 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
609 WebContentsDelegate* WebContentsImpl::GetDelegate() {
610 return delegate_;
613 void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
614 // TODO(cbentzel): remove this debugging code?
615 if (delegate == delegate_)
616 return;
617 if (delegate_)
618 delegate_->Detach(this);
619 delegate_ = delegate;
620 if (delegate_) {
621 delegate_->Attach(this);
622 // Ensure the visible RVH reflects the new delegate's preferences.
623 if (view_)
624 view_->SetOverscrollControllerEnabled(delegate->CanOverscrollContent());
628 RenderProcessHost* WebContentsImpl::GetRenderProcessHost() const {
629 RenderViewHostImpl* host = GetRenderManager()->current_host();
630 return host ? host->GetProcess() : NULL;
633 RenderFrameHost* WebContentsImpl::GetMainFrame() {
634 return frame_tree_.root()->current_frame_host();
637 RenderFrameHost* WebContentsImpl::GetFocusedFrame() {
638 if (!frame_tree_.GetFocusedFrame())
639 return NULL;
640 return frame_tree_.GetFocusedFrame()->current_frame_host();
643 void WebContentsImpl::ForEachFrame(
644 const base::Callback<void(RenderFrameHost*)>& on_frame) {
645 frame_tree_.ForEach(base::Bind(&ForEachFrameInternal, on_frame));
648 void WebContentsImpl::SendToAllFrames(IPC::Message* message) {
649 ForEachFrame(base::Bind(&SendToAllFramesInternal, message));
650 delete message;
653 RenderViewHost* WebContentsImpl::GetRenderViewHost() const {
654 return GetRenderManager()->current_host();
657 WebContents* WebContentsImpl::GetEmbedderWebContents() const {
658 BrowserPluginGuest* guest = GetBrowserPluginGuest();
659 if (guest)
660 return guest->embedder_web_contents();
661 return NULL;
664 int WebContentsImpl::GetEmbeddedInstanceID() const {
665 BrowserPluginGuest* guest = GetBrowserPluginGuest();
666 if (guest)
667 return guest->instance_id();
668 return 0;
671 int WebContentsImpl::GetRoutingID() const {
672 if (!GetRenderViewHost())
673 return MSG_ROUTING_NONE;
675 return GetRenderViewHost()->GetRoutingID();
678 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
679 return fullscreen_widget_routing_id_;
682 RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() const {
683 return GetRenderManager()->GetRenderWidgetHostView();
686 RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView()
687 const {
688 RenderWidgetHost* const widget_host =
689 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
690 GetFullscreenWidgetRoutingID());
691 return widget_host ? widget_host->GetView() : NULL;
694 WebContentsView* WebContentsImpl::GetView() const {
695 return view_.get();
698 WebUI* WebContentsImpl::CreateWebUI(const GURL& url) {
699 WebUIImpl* web_ui = new WebUIImpl(this);
700 WebUIController* controller = WebUIControllerFactoryRegistry::GetInstance()->
701 CreateWebUIControllerForURL(web_ui, url);
702 if (controller) {
703 web_ui->AddMessageHandler(new GenericHandler());
704 web_ui->SetController(controller);
705 return web_ui;
708 delete web_ui;
709 return NULL;
712 WebUI* WebContentsImpl::GetWebUI() const {
713 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
714 : GetRenderManager()->pending_web_ui();
717 WebUI* WebContentsImpl::GetCommittedWebUI() const {
718 return GetRenderManager()->web_ui();
721 void WebContentsImpl::SetUserAgentOverride(const std::string& override) {
722 if (GetUserAgentOverride() == override)
723 return;
725 renderer_preferences_.user_agent_override = override;
727 // Send the new override string to the renderer.
728 RenderViewHost* host = GetRenderViewHost();
729 if (host)
730 host->SyncRendererPrefs();
732 // Reload the page if a load is currently in progress to avoid having
733 // different parts of the page loaded using different user agents.
734 NavigationEntry* entry = controller_.GetVisibleEntry();
735 if (is_loading_ && entry != NULL && entry->GetIsOverridingUserAgent())
736 controller_.ReloadIgnoringCache(true);
738 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
739 UserAgentOverrideSet(override));
742 const std::string& WebContentsImpl::GetUserAgentOverride() const {
743 return renderer_preferences_.user_agent_override;
746 #if defined(OS_WIN)
747 void WebContentsImpl::SetParentNativeViewAccessible(
748 gfx::NativeViewAccessible accessible_parent) {
749 accessible_parent_ = accessible_parent;
750 if (GetRenderViewHost())
751 GetRenderViewHostImpl()->SetParentNativeViewAccessible(accessible_parent);
753 #endif
755 const base::string16& WebContentsImpl::GetTitle() const {
756 // Transient entries take precedence. They are used for interstitial pages
757 // that are shown on top of existing pages.
758 NavigationEntry* entry = controller_.GetTransientEntry();
759 std::string accept_languages =
760 GetContentClient()->browser()->GetAcceptLangs(
761 GetBrowserContext());
762 if (entry) {
763 return entry->GetTitleForDisplay(accept_languages);
765 WebUI* our_web_ui = GetRenderManager()->pending_web_ui() ?
766 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
767 if (our_web_ui) {
768 // Don't override the title in view source mode.
769 entry = controller_.GetVisibleEntry();
770 if (!(entry && entry->IsViewSourceMode())) {
771 // Give the Web UI the chance to override our title.
772 const base::string16& title = our_web_ui->GetOverriddenTitle();
773 if (!title.empty())
774 return title;
778 // We use the title for the last committed entry rather than a pending
779 // navigation entry. For example, when the user types in a URL, we want to
780 // keep the old page's title until the new load has committed and we get a new
781 // title.
782 entry = controller_.GetLastCommittedEntry();
784 // We make an exception for initial navigations.
785 if (controller_.IsInitialNavigation()) {
786 // We only want to use the title from the visible entry in one of two cases:
787 // 1. There's already a committed entry for an initial navigation, in which
788 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
789 // 2. The pending entry has been explicitly assigned a title to display.
791 // If there's no last committed entry and no assigned title, we should fall
792 // back to |page_title_when_no_navigation_entry_| rather than showing the
793 // URL.
794 if (entry ||
795 (controller_.GetVisibleEntry() &&
796 !controller_.GetVisibleEntry()->GetTitle().empty())) {
797 entry = controller_.GetVisibleEntry();
801 if (entry) {
802 return entry->GetTitleForDisplay(accept_languages);
805 // |page_title_when_no_navigation_entry_| is finally used
806 // if no title cannot be retrieved.
807 return page_title_when_no_navigation_entry_;
810 int32 WebContentsImpl::GetMaxPageID() {
811 return GetMaxPageIDForSiteInstance(GetSiteInstance());
814 int32 WebContentsImpl::GetMaxPageIDForSiteInstance(
815 SiteInstance* site_instance) {
816 if (max_page_ids_.find(site_instance->GetId()) == max_page_ids_.end())
817 max_page_ids_[site_instance->GetId()] = -1;
819 return max_page_ids_[site_instance->GetId()];
822 void WebContentsImpl::UpdateMaxPageID(int32 page_id) {
823 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id);
826 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
827 SiteInstance* site_instance, int32 page_id) {
828 if (GetMaxPageIDForSiteInstance(site_instance) < page_id)
829 max_page_ids_[site_instance->GetId()] = page_id;
832 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents* web_contents) {
833 WebContentsImpl* contents = static_cast<WebContentsImpl*>(web_contents);
834 max_page_ids_ = contents->max_page_ids_;
837 SiteInstance* WebContentsImpl::GetSiteInstance() const {
838 return GetRenderManager()->current_host()->GetSiteInstance();
841 SiteInstance* WebContentsImpl::GetPendingSiteInstance() const {
842 RenderViewHost* dest_rvh = GetRenderManager()->pending_render_view_host() ?
843 GetRenderManager()->pending_render_view_host() :
844 GetRenderManager()->current_host();
845 return dest_rvh->GetSiteInstance();
848 bool WebContentsImpl::IsLoading() const {
849 return is_loading_;
852 bool WebContentsImpl::IsWaitingForResponse() const {
853 return waiting_for_response_;
856 const net::LoadStateWithParam& WebContentsImpl::GetLoadState() const {
857 return load_state_;
860 const base::string16& WebContentsImpl::GetLoadStateHost() const {
861 return load_state_host_;
864 uint64 WebContentsImpl::GetUploadSize() const {
865 return upload_size_;
868 uint64 WebContentsImpl::GetUploadPosition() const {
869 return upload_position_;
872 std::set<GURL> WebContentsImpl::GetSitesInTab() const {
873 std::set<GURL> sites;
874 frame_tree_.ForEach(base::Bind(&CollectSites,
875 base::Unretained(GetBrowserContext()),
876 base::Unretained(&sites)));
877 return sites;
880 const std::string& WebContentsImpl::GetEncoding() const {
881 return encoding_;
884 bool WebContentsImpl::DisplayedInsecureContent() const {
885 return displayed_insecure_content_;
888 void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size) {
889 DCHECK(!is_being_destroyed_);
890 ++capturer_count_;
891 DVLOG(1) << "There are now " << capturer_count_
892 << " capturing(s) of WebContentsImpl@" << this;
894 // Note: This provides a hint to upstream code to size the views optimally
895 // for quality (e.g., to avoid scaling).
896 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
897 preferred_size_for_capture_ = capture_size;
898 OnPreferredSizeChanged(preferred_size_);
902 void WebContentsImpl::DecrementCapturerCount() {
903 --capturer_count_;
904 DVLOG(1) << "There are now " << capturer_count_
905 << " capturing(s) of WebContentsImpl@" << this;
906 DCHECK_LE(0, capturer_count_);
908 if (is_being_destroyed_)
909 return;
911 if (capturer_count_ == 0) {
912 const gfx::Size old_size = preferred_size_for_capture_;
913 preferred_size_for_capture_ = gfx::Size();
914 OnPreferredSizeChanged(old_size);
917 if (IsHidden()) {
918 DVLOG(1) << "Executing delayed WasHidden().";
919 WasHidden();
923 int WebContentsImpl::GetCapturerCount() const {
924 return capturer_count_;
927 bool WebContentsImpl::IsCrashed() const {
928 return (crashed_status_ == base::TERMINATION_STATUS_PROCESS_CRASHED ||
929 crashed_status_ == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
930 crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
933 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
934 int error_code) {
935 if (status == crashed_status_)
936 return;
938 crashed_status_ = status;
939 crashed_error_code_ = error_code;
940 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
943 base::TerminationStatus WebContentsImpl::GetCrashedStatus() const {
944 return crashed_status_;
947 bool WebContentsImpl::IsBeingDestroyed() const {
948 return is_being_destroyed_;
951 void WebContentsImpl::NotifyNavigationStateChanged(unsigned changed_flags) {
952 if (delegate_)
953 delegate_->NavigationStateChanged(this, changed_flags);
956 base::TimeTicks WebContentsImpl::GetLastActiveTime() const {
957 return last_active_time_;
960 void WebContentsImpl::WasShown() {
961 controller_.SetActive(true);
962 RenderWidgetHostView* rwhv = GetRenderWidgetHostView();
963 if (rwhv) {
964 rwhv->Show();
965 #if defined(OS_MACOSX)
966 rwhv->SetActive(true);
967 #endif
970 last_active_time_ = base::TimeTicks::Now();
972 // The resize rect might have changed while this was inactive -- send the new
973 // one to make sure it's up to date.
974 RenderViewHostImpl* rvh =
975 static_cast<RenderViewHostImpl*>(GetRenderViewHost());
976 if (rvh) {
977 rvh->ResizeRectChanged(GetRootWindowResizerRect());
980 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasShown());
982 should_normally_be_visible_ = true;
985 void WebContentsImpl::WasHidden() {
986 // If there are entities capturing screenshots or video (e.g., mirroring),
987 // don't activate the "disable rendering" optimization.
988 if (capturer_count_ == 0) {
989 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
990 // open a tab in the background, then closes the tab before selecting it.
991 // This is because closing the tab calls WebContentsImpl::Destroy(), which
992 // removes the |GetRenderViewHost()|; then when we actually destroy the
993 // window, OnWindowPosChanged() notices and calls WasHidden() (which
994 // calls us).
995 RenderWidgetHostView* rwhv = GetRenderWidgetHostView();
996 if (rwhv)
997 rwhv->Hide();
1000 FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasHidden());
1002 should_normally_be_visible_ = false;
1005 bool WebContentsImpl::NeedToFireBeforeUnload() {
1006 // TODO(creis): Should we fire even for interstitial pages?
1007 return WillNotifyDisconnection() &&
1008 !ShowingInterstitialPage() &&
1009 !static_cast<RenderViewHostImpl*>(
1010 GetRenderViewHost())->SuddenTerminationAllowed();
1013 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition) {
1014 static_cast<RenderFrameHostImpl*>(GetMainFrame())->DispatchBeforeUnload(
1015 for_cross_site_transition);
1018 void WebContentsImpl::Stop() {
1019 GetRenderManager()->Stop();
1020 FOR_EACH_OBSERVER(WebContentsObserver, observers_, NavigationStopped());
1023 WebContents* WebContentsImpl::Clone() {
1024 // We use our current SiteInstance since the cloned entry will use it anyway.
1025 // We pass our own opener so that the cloned page can access it if it was
1026 // before.
1027 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
1028 create_params.initial_size = GetContainerBounds().size();
1029 WebContentsImpl* tc = CreateWithOpener(create_params, opener_);
1030 tc->GetController().CopyStateFrom(controller_);
1031 FOR_EACH_OBSERVER(WebContentsObserver,
1032 observers_,
1033 DidCloneToNewWebContents(this, tc));
1034 return tc;
1037 void WebContentsImpl::Observe(int type,
1038 const NotificationSource& source,
1039 const NotificationDetails& details) {
1040 switch (type) {
1041 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
1042 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
1043 for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
1044 i != pending_widget_views_.end(); ++i) {
1045 if (host->GetView() == i->second) {
1046 pending_widget_views_.erase(i);
1047 break;
1050 break;
1052 default:
1053 NOTREACHED();
1057 WebContents* WebContentsImpl::GetWebContents() {
1058 return this;
1061 void WebContentsImpl::Init(const WebContents::CreateParams& params) {
1062 // This is set before initializing the render manager since
1063 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
1064 // it should be hidden.
1065 should_normally_be_visible_ = !params.initially_hidden;
1067 GetRenderManager()->Init(
1068 params.browser_context, params.site_instance, params.routing_id,
1069 params.main_frame_routing_id);
1071 WebContentsViewDelegate* delegate =
1072 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1074 if (browser_plugin_guest_) {
1075 scoped_ptr<WebContentsView> platform_view(CreateWebContentsView(
1076 this, delegate, &render_view_host_delegate_view_));
1078 WebContentsViewGuest* rv = new WebContentsViewGuest(
1079 this, browser_plugin_guest_.get(), platform_view.Pass(),
1080 render_view_host_delegate_view_);
1081 render_view_host_delegate_view_ = rv;
1082 view_.reset(rv);
1083 } else {
1084 // Regular WebContentsView.
1085 view_.reset(CreateWebContentsView(
1086 this, delegate, &render_view_host_delegate_view_));
1088 CHECK(render_view_host_delegate_view_);
1089 CHECK(view_.get());
1091 gfx::Size initial_size = params.initial_size;
1092 view_->CreateView(initial_size, params.context);
1094 // Listen for whether our opener gets destroyed.
1095 if (opener_)
1096 AddDestructionObserver(opener_);
1098 registrar_.Add(this,
1099 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
1100 NotificationService::AllBrowserContextsAndSources());
1101 #if defined(OS_ANDROID)
1102 java_bridge_dispatcher_host_manager_.reset(
1103 new JavaBridgeDispatcherHostManager(this));
1104 date_time_chooser_.reset(new DateTimeChooserAndroid());
1105 #endif
1108 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
1109 RemoveDestructionObserver(web_contents);
1111 // Clear the opener if it has been closed.
1112 if (web_contents == opener_) {
1113 opener_ = NULL;
1114 return;
1116 // Clear a pending contents that has been closed before being shown.
1117 for (PendingContents::iterator iter = pending_contents_.begin();
1118 iter != pending_contents_.end();
1119 ++iter) {
1120 if (iter->second != web_contents)
1121 continue;
1122 pending_contents_.erase(iter);
1123 return;
1125 NOTREACHED();
1128 void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
1129 if (!ContainsKey(destruction_observers_, web_contents)) {
1130 destruction_observers_[web_contents] =
1131 new DestructionObserver(this, web_contents);
1135 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
1136 DestructionObservers::iterator iter =
1137 destruction_observers_.find(web_contents);
1138 if (iter != destruction_observers_.end()) {
1139 delete destruction_observers_[web_contents];
1140 destruction_observers_.erase(iter);
1144 void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
1145 observers_.AddObserver(observer);
1148 void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
1149 observers_.RemoveObserver(observer);
1152 void WebContentsImpl::Activate() {
1153 if (delegate_)
1154 delegate_->ActivateContents(this);
1157 void WebContentsImpl::Deactivate() {
1158 if (delegate_)
1159 delegate_->DeactivateContents(this);
1162 void WebContentsImpl::LostCapture() {
1163 if (delegate_)
1164 delegate_->LostCapture();
1167 void WebContentsImpl::RenderWidgetDeleted(
1168 RenderWidgetHostImpl* render_widget_host) {
1169 if (is_being_destroyed_) {
1170 // |created_widgets_| might have been destroyed.
1171 return;
1174 std::set<RenderWidgetHostImpl*>::iterator iter =
1175 created_widgets_.find(render_widget_host);
1176 if (iter != created_widgets_.end())
1177 created_widgets_.erase(iter);
1179 if (render_widget_host &&
1180 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_) {
1181 if (delegate_ && delegate_->EmbedsFullscreenWidget())
1182 delegate_->ToggleFullscreenModeForTab(this, false);
1183 FOR_EACH_OBSERVER(WebContentsObserver,
1184 observers_,
1185 DidDestroyFullscreenWidget(
1186 fullscreen_widget_routing_id_));
1187 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
1191 bool WebContentsImpl::PreHandleKeyboardEvent(
1192 const NativeWebKeyboardEvent& event,
1193 bool* is_keyboard_shortcut) {
1194 return delegate_ &&
1195 delegate_->PreHandleKeyboardEvent(this, event, is_keyboard_shortcut);
1198 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1199 if (browser_plugin_embedder_ &&
1200 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
1201 return;
1204 if (delegate_)
1205 delegate_->HandleKeyboardEvent(this, event);
1208 bool WebContentsImpl::HandleWheelEvent(
1209 const blink::WebMouseWheelEvent& event) {
1210 #if !defined(OS_MACOSX)
1211 // On platforms other than Mac, control+mousewheel changes zoom. On Mac, this
1212 // isn't done for two reasons:
1213 // -the OS already has a gesture to do this through pinch-zoom
1214 // -if a user starts an inertial scroll, let's go, and presses control
1215 // (i.e. control+tab) then the OS's buffered scroll events will come in
1216 // with control key set which isn't what the user wants
1217 if (delegate_ &&
1218 event.wheelTicksY &&
1219 (event.modifiers & blink::WebInputEvent::ControlKey) &&
1220 // Avoid adjusting the zoom in response to two-finger-scrolling touchpad
1221 // gestures, which are regrettably easy to trigger accidentally.
1222 !event.hasPreciseScrollingDeltas) {
1223 delegate_->ContentsZoomChange(event.wheelTicksY > 0);
1224 return true;
1226 #endif
1227 return false;
1230 bool WebContentsImpl::PreHandleGestureEvent(
1231 const blink::WebGestureEvent& event) {
1232 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
1235 bool WebContentsImpl::HandleGestureEvent(
1236 const blink::WebGestureEvent& event) {
1237 // Some platforms (eg. Mac) send GesturePinch events for trackpad pinch-zoom.
1238 // Use them to implement browser zoom, as for HandleWheelEvent above.
1239 if (event.type == blink::WebInputEvent::GesturePinchUpdate &&
1240 event.sourceDevice == blink::WebGestureEvent::Touchpad) {
1241 // The scale difference necessary to trigger a zoom action. Derived from
1242 // experimentation to find a value that feels reasonable.
1243 const float kZoomStepValue = 0.6f;
1245 // Find the (absolute) thresholds on either side of the current zoom factor,
1246 // then convert those to actual numbers to trigger a zoom in or out.
1247 // This logic deliberately makes the range around the starting zoom value
1248 // for the gesture twice as large as the other ranges (i.e., the notches are
1249 // at ..., -3*step, -2*step, -step, step, 2*step, 3*step, ... but not at 0)
1250 // so that it's easier to get back to your starting point than it is to
1251 // overshoot.
1252 float nextStep = (abs(currentPinchZoomStepDelta_) + 1) * kZoomStepValue;
1253 float backStep = abs(currentPinchZoomStepDelta_) * kZoomStepValue;
1254 float zoomInThreshold = (currentPinchZoomStepDelta_ >= 0) ? nextStep
1255 : -backStep;
1256 float zoomOutThreshold = (currentPinchZoomStepDelta_ <= 0) ? -nextStep
1257 : backStep;
1259 totalPinchGestureAmount_ += (event.data.pinchUpdate.scale - 1.0);
1260 if (totalPinchGestureAmount_ > zoomInThreshold) {
1261 currentPinchZoomStepDelta_++;
1262 if (delegate_)
1263 delegate_->ContentsZoomChange(true);
1264 } else if (totalPinchGestureAmount_ < zoomOutThreshold) {
1265 currentPinchZoomStepDelta_--;
1266 if (delegate_)
1267 delegate_->ContentsZoomChange(false);
1269 return true;
1272 return false;
1275 #if defined(OS_WIN)
1276 gfx::NativeViewAccessible WebContentsImpl::GetParentNativeViewAccessible() {
1277 return accessible_parent_;
1279 #endif
1281 void WebContentsImpl::HandleMouseDown() {
1282 if (delegate_)
1283 delegate_->HandleMouseDown();
1286 void WebContentsImpl::HandleMouseUp() {
1287 if (delegate_)
1288 delegate_->HandleMouseUp();
1291 void WebContentsImpl::HandlePointerActivate() {
1292 if (delegate_)
1293 delegate_->HandlePointerActivate();
1296 void WebContentsImpl::HandleGestureBegin() {
1297 if (delegate_)
1298 delegate_->HandleGestureBegin();
1301 void WebContentsImpl::HandleGestureEnd() {
1302 if (delegate_)
1303 delegate_->HandleGestureEnd();
1306 void WebContentsImpl::ToggleFullscreenMode(bool enter_fullscreen) {
1307 // This method is being called to enter or leave renderer-initiated fullscreen
1308 // mode. Either way, make sure any existing fullscreen widget is shut down
1309 // first.
1310 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
1311 if (widget_view)
1312 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())->Shutdown();
1314 if (delegate_)
1315 delegate_->ToggleFullscreenModeForTab(this, enter_fullscreen);
1317 FOR_EACH_OBSERVER(WebContentsObserver,
1318 observers_,
1319 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1322 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1323 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
1326 void WebContentsImpl::RequestToLockMouse(bool user_gesture,
1327 bool last_unlocked_by_target) {
1328 if (delegate_) {
1329 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
1330 } else {
1331 GotResponseToLockMouseRequest(false);
1335 void WebContentsImpl::LostMouseLock() {
1336 if (delegate_)
1337 delegate_->LostMouseLock();
1340 void WebContentsImpl::CreateNewWindow(
1341 int render_process_id,
1342 int route_id,
1343 int main_frame_route_id,
1344 const ViewHostMsg_CreateWindow_Params& params,
1345 SessionStorageNamespace* session_storage_namespace) {
1346 // We usually create the new window in the same BrowsingInstance (group of
1347 // script-related windows), by passing in the current SiteInstance. However,
1348 // if the opener is being suppressed (in a non-guest), we create a new
1349 // SiteInstance in its own BrowsingInstance.
1350 bool is_guest = GetRenderProcessHost()->IsGuest();
1352 // If the opener is to be suppressed, the new window can be in any process.
1353 // Since routing ids are process specific, we must not have one passed in
1354 // as argument here.
1355 DCHECK(!params.opener_suppressed || route_id == MSG_ROUTING_NONE);
1357 scoped_refptr<SiteInstance> site_instance =
1358 params.opener_suppressed && !is_guest ?
1359 SiteInstance::CreateForURL(GetBrowserContext(), params.target_url) :
1360 GetSiteInstance();
1362 // A message to create a new window can only come from the active process for
1363 // this WebContentsImpl instance. If any other process sends the request,
1364 // it is invalid and the process must be terminated.
1365 if (GetRenderProcessHost()->GetID() != render_process_id) {
1366 base::ProcessHandle process_handle =
1367 RenderProcessHost::FromID(render_process_id)->GetHandle();
1368 if (process_handle != base::kNullProcessHandle) {
1369 RecordAction(
1370 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1371 base::KillProcess(process_handle, content::RESULT_CODE_KILLED, false);
1373 return;
1376 // We must assign the SessionStorageNamespace before calling Init().
1378 // http://crbug.com/142685
1379 const std::string& partition_id =
1380 GetContentClient()->browser()->
1381 GetStoragePartitionIdForSite(GetBrowserContext(),
1382 site_instance->GetSiteURL());
1383 StoragePartition* partition = BrowserContext::GetStoragePartition(
1384 GetBrowserContext(), site_instance.get());
1385 DOMStorageContextWrapper* dom_storage_context =
1386 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
1387 SessionStorageNamespaceImpl* session_storage_namespace_impl =
1388 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
1389 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
1391 if (delegate_ &&
1392 !delegate_->ShouldCreateWebContents(this,
1393 route_id,
1394 params.window_container_type,
1395 params.frame_name,
1396 params.target_url,
1397 partition_id,
1398 session_storage_namespace)) {
1399 if (route_id != MSG_ROUTING_NONE &&
1400 !RenderViewHost::FromID(render_process_id, route_id)) {
1401 // If the embedder didn't create a WebContents for this route, we need to
1402 // delete the RenderView that had already been created.
1403 Send(new ViewMsg_Close(route_id));
1405 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id);
1406 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1407 main_frame_route_id);
1408 return;
1411 // Create the new web contents. This will automatically create the new
1412 // WebContentsView. In the future, we may want to create the view separately.
1413 WebContentsImpl* new_contents =
1414 new WebContentsImpl(GetBrowserContext(),
1415 params.opener_suppressed ? NULL : this);
1417 new_contents->GetController().SetSessionStorageNamespace(
1418 partition_id,
1419 session_storage_namespace);
1420 CreateParams create_params(GetBrowserContext(), site_instance.get());
1421 create_params.routing_id = route_id;
1422 create_params.main_frame_routing_id = main_frame_route_id;
1423 if (!is_guest) {
1424 create_params.context = view_->GetNativeView();
1425 create_params.initial_size = GetContainerBounds().size();
1426 } else {
1427 // This makes |new_contents| act as a guest.
1428 // For more info, see comment above class BrowserPluginGuest.
1429 int instance_id =
1430 BrowserPluginGuestManager::FromBrowserContext(GetBrowserContext())->
1431 GetNextInstanceID();
1432 WebContentsImpl* new_contents_impl =
1433 static_cast<WebContentsImpl*>(new_contents);
1434 BrowserPluginGuest::CreateWithOpener(instance_id,
1435 new_contents_impl->opener() != NULL,
1436 new_contents_impl,
1437 GetBrowserPluginGuest());
1439 if (params.disposition == NEW_BACKGROUND_TAB)
1440 create_params.initially_hidden = true;
1441 new_contents->Init(create_params);
1443 // Save the window for later if we're not suppressing the opener (since it
1444 // will be shown immediately).
1445 if (!params.opener_suppressed) {
1446 if (!is_guest) {
1447 WebContentsView* new_view = new_contents->view_.get();
1449 // TODO(brettw): It seems bogus that we have to call this function on the
1450 // newly created object and give it one of its own member variables.
1451 new_view->CreateViewForWidget(new_contents->GetRenderViewHost());
1453 // Save the created window associated with the route so we can show it
1454 // later.
1455 DCHECK_NE(MSG_ROUTING_NONE, route_id);
1456 pending_contents_[route_id] = new_contents;
1457 AddDestructionObserver(new_contents);
1460 if (delegate_) {
1461 delegate_->WebContentsCreated(
1462 this, params.opener_render_frame_id, params.frame_name,
1463 params.target_url, new_contents);
1466 if (params.opener_suppressed) {
1467 // When the opener is suppressed, the original renderer cannot access the
1468 // new window. As a result, we need to show and navigate the window here.
1469 bool was_blocked = false;
1470 if (delegate_) {
1471 gfx::Rect initial_pos;
1472 delegate_->AddNewContents(
1473 this, new_contents, params.disposition, initial_pos,
1474 params.user_gesture, &was_blocked);
1476 if (!was_blocked) {
1477 OpenURLParams open_params(params.target_url,
1478 Referrer(),
1479 CURRENT_TAB,
1480 PAGE_TRANSITION_LINK,
1481 true /* is_renderer_initiated */);
1482 open_params.user_gesture = params.user_gesture;
1483 new_contents->OpenURL(open_params);
1488 void WebContentsImpl::CreateNewWidget(int render_process_id,
1489 int route_id,
1490 blink::WebPopupType popup_type) {
1491 CreateNewWidget(render_process_id, route_id, false, popup_type);
1494 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id,
1495 int route_id) {
1496 CreateNewWidget(render_process_id, route_id, true, blink::WebPopupTypeNone);
1499 void WebContentsImpl::CreateNewWidget(int render_process_id,
1500 int route_id,
1501 bool is_fullscreen,
1502 blink::WebPopupType popup_type) {
1503 RenderProcessHost* process = GetRenderProcessHost();
1504 // A message to create a new widget can only come from the active process for
1505 // this WebContentsImpl instance. If any other process sends the request,
1506 // it is invalid and the process must be terminated.
1507 if (process->GetID() != render_process_id) {
1508 base::ProcessHandle process_handle =
1509 RenderProcessHost::FromID(render_process_id)->GetHandle();
1510 if (process_handle != base::kNullProcessHandle) {
1511 RecordAction(
1512 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1513 base::KillProcess(process_handle, content::RESULT_CODE_KILLED, false);
1515 return;
1518 RenderWidgetHostImpl* widget_host =
1519 new RenderWidgetHostImpl(this, process, route_id, IsHidden());
1520 created_widgets_.insert(widget_host);
1522 RenderWidgetHostViewBase* widget_view =
1523 static_cast<RenderWidgetHostViewBase*>(
1524 view_->CreateViewForPopupWidget(widget_host));
1525 if (!widget_view)
1526 return;
1527 if (!is_fullscreen) {
1528 // Popups should not get activated.
1529 widget_view->SetPopupType(popup_type);
1531 // Save the created widget associated with the route so we can show it later.
1532 pending_widget_views_[route_id] = widget_view;
1534 #if defined(OS_MACOSX)
1535 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1536 // to allow it to survive the trip without being hosted.
1537 base::mac::NSObjectRetain(widget_view->GetNativeView());
1538 #endif
1541 void WebContentsImpl::ShowCreatedWindow(int route_id,
1542 WindowOpenDisposition disposition,
1543 const gfx::Rect& initial_pos,
1544 bool user_gesture) {
1545 WebContentsImpl* contents = GetCreatedWindow(route_id);
1546 if (contents) {
1547 WebContentsDelegate* delegate = GetDelegate();
1548 if (delegate) {
1549 delegate->AddNewContents(
1550 this, contents, disposition, initial_pos, user_gesture, NULL);
1555 void WebContentsImpl::ShowCreatedWidget(int route_id,
1556 const gfx::Rect& initial_pos) {
1557 ShowCreatedWidget(route_id, false, initial_pos);
1560 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id) {
1561 ShowCreatedWidget(route_id, true, gfx::Rect());
1564 void WebContentsImpl::ShowCreatedWidget(int route_id,
1565 bool is_fullscreen,
1566 const gfx::Rect& initial_pos) {
1567 RenderWidgetHostViewBase* widget_host_view =
1568 static_cast<RenderWidgetHostViewBase*>(GetCreatedWidget(route_id));
1569 if (!widget_host_view)
1570 return;
1572 RenderWidgetHostView* view = NULL;
1573 BrowserPluginGuest* guest = GetBrowserPluginGuest();
1574 if (guest && guest->embedder_web_contents()) {
1575 view = guest->embedder_web_contents()->GetRenderWidgetHostView();
1576 } else {
1577 view = GetRenderWidgetHostView();
1580 if (is_fullscreen) {
1581 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
1582 fullscreen_widget_routing_id_ = route_id;
1583 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
1584 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1585 delegate_->ToggleFullscreenModeForTab(this, true);
1586 } else {
1587 widget_host_view->InitAsFullscreen(view);
1589 FOR_EACH_OBSERVER(WebContentsObserver,
1590 observers_,
1591 DidShowFullscreenWidget(route_id));
1592 if (!widget_host_view->HasFocus())
1593 widget_host_view->Focus();
1594 } else {
1595 widget_host_view->InitAsPopup(view, initial_pos);
1598 RenderWidgetHostImpl* render_widget_host_impl =
1599 RenderWidgetHostImpl::From(widget_host_view->GetRenderWidgetHost());
1600 render_widget_host_impl->Init();
1601 // Only allow privileged mouse lock for fullscreen render widget, which is
1602 // used to implement Pepper Flash fullscreen.
1603 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
1605 #if defined(OS_MACOSX)
1606 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1607 // properly embedded (or purposefully ignored) we can release the retain we
1608 // took in CreateNewWidget().
1609 base::mac::NSObjectRelease(widget_host_view->GetNativeView());
1610 #endif
1613 WebContentsImpl* WebContentsImpl::GetCreatedWindow(int route_id) {
1614 PendingContents::iterator iter = pending_contents_.find(route_id);
1616 // Certain systems can block the creation of new windows. If we didn't succeed
1617 // in creating one, just return NULL.
1618 if (iter == pending_contents_.end()) {
1619 return NULL;
1622 WebContentsImpl* new_contents = iter->second;
1623 pending_contents_.erase(route_id);
1624 RemoveDestructionObserver(new_contents);
1626 // Don't initialize the guest WebContents immediately.
1627 if (new_contents->GetRenderProcessHost()->IsGuest())
1628 return new_contents;
1630 if (!new_contents->GetRenderProcessHost()->HasConnection() ||
1631 !new_contents->GetRenderViewHost()->GetView())
1632 return NULL;
1634 // TODO(brettw): It seems bogus to reach into here and initialize the host.
1635 static_cast<RenderViewHostImpl*>(new_contents->GetRenderViewHost())->Init();
1636 return new_contents;
1639 RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int route_id) {
1640 PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
1641 if (iter == pending_widget_views_.end()) {
1642 DCHECK(false);
1643 return NULL;
1646 RenderWidgetHostView* widget_host_view = iter->second;
1647 pending_widget_views_.erase(route_id);
1649 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
1650 if (!widget_host->GetProcess()->HasConnection()) {
1651 // The view has gone away or the renderer crashed. Nothing to do.
1652 return NULL;
1655 return widget_host_view;
1658 void WebContentsImpl::RequestMediaAccessPermission(
1659 const MediaStreamRequest& request,
1660 const MediaResponseCallback& callback) {
1661 if (delegate_) {
1662 delegate_->RequestMediaAccessPermission(this, request, callback);
1663 } else {
1664 callback.Run(MediaStreamDevices(),
1665 MEDIA_DEVICE_INVALID_STATE,
1666 scoped_ptr<MediaStreamUI>());
1670 SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
1671 SiteInstance* instance) {
1672 return controller_.GetSessionStorageNamespace(instance);
1675 FrameTree* WebContentsImpl::GetFrameTree() {
1676 return &frame_tree_;
1679 void WebContentsImpl::AccessibilityEventReceived(
1680 const std::vector<AXEventNotificationDetails>& details) {
1681 FOR_EACH_OBSERVER(
1682 WebContentsObserver, observers_, AccessibilityEventReceived(details));
1685 void WebContentsImpl::OnShowValidationMessage(
1686 const gfx::Rect& anchor_in_root_view,
1687 const base::string16& main_text,
1688 const base::string16& sub_text) {
1689 if (delegate_)
1690 delegate_->ShowValidationMessage(
1691 this, anchor_in_root_view, main_text, sub_text);
1694 void WebContentsImpl::OnHideValidationMessage() {
1695 if (delegate_)
1696 delegate_->HideValidationMessage(this);
1699 void WebContentsImpl::OnMoveValidationMessage(
1700 const gfx::Rect& anchor_in_root_view) {
1701 if (delegate_)
1702 delegate_->MoveValidationMessage(this, anchor_in_root_view);
1705 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl* rwh) {
1706 if (browser_plugin_embedder_)
1707 browser_plugin_embedder_->DidSendScreenRects();
1710 void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
1711 const gfx::Size old_size = GetPreferredSize();
1712 preferred_size_ = pref_size;
1713 OnPreferredSizeChanged(old_size);
1716 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size& new_size) {
1717 if (delegate_)
1718 delegate_->ResizeDueToAutoResize(this, new_size);
1721 WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
1722 if (!delegate_)
1723 return NULL;
1725 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
1726 return new_contents;
1729 bool WebContentsImpl::Send(IPC::Message* message) {
1730 if (!GetRenderViewHost()) {
1731 delete message;
1732 return false;
1735 return GetRenderViewHost()->Send(message);
1738 bool WebContentsImpl::NavigateToPendingEntry(
1739 NavigationController::ReloadType reload_type) {
1740 FrameTreeNode* node = frame_tree_.root();
1742 // If we are using --site-per-process, we should navigate in the FrameTreeNode
1743 // specified in the pending entry.
1744 NavigationEntryImpl* pending_entry =
1745 NavigationEntryImpl::FromNavigationEntry(controller_.GetPendingEntry());
1746 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess) &&
1747 pending_entry->frame_tree_node_id() != -1) {
1748 node = frame_tree_.FindByID(pending_entry->frame_tree_node_id());
1751 return node->navigator()->NavigateToPendingEntry(
1752 node->current_frame_host(), reload_type);
1755 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
1756 RenderFrameHost* render_frame_host) {
1757 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1758 RenderFrameForInterstitialPageCreated(render_frame_host));
1761 void WebContentsImpl::AttachInterstitialPage(
1762 InterstitialPageImpl* interstitial_page) {
1763 DCHECK(interstitial_page);
1764 GetRenderManager()->set_interstitial_page(interstitial_page);
1766 // Cancel any visible dialogs so that they don't interfere with the
1767 // interstitial.
1768 if (dialog_manager_)
1769 dialog_manager_->CancelActiveAndPendingDialogs(this);
1771 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1772 DidAttachInterstitialPage());
1775 void WebContentsImpl::DetachInterstitialPage() {
1776 if (ShowingInterstitialPage())
1777 GetRenderManager()->remove_interstitial_page();
1778 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1779 DidDetachInterstitialPage());
1782 void WebContentsImpl::SetHistoryLengthAndPrune(
1783 const SiteInstance* site_instance,
1784 int history_length,
1785 int32 minimum_page_id) {
1786 // SetHistoryLengthAndPrune doesn't work when there are pending cross-site
1787 // navigations. Callers should ensure that this is the case.
1788 if (GetRenderManager()->pending_render_view_host()) {
1789 NOTREACHED();
1790 return;
1792 RenderViewHostImpl* rvh = GetRenderViewHostImpl();
1793 if (!rvh) {
1794 NOTREACHED();
1795 return;
1797 if (site_instance && rvh->GetSiteInstance() != site_instance) {
1798 NOTREACHED();
1799 return;
1801 Send(new ViewMsg_SetHistoryLengthAndPrune(GetRoutingID(),
1802 history_length,
1803 minimum_page_id));
1806 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache) {
1807 RenderFrameHost* focused_frame = GetFocusedFrame();
1808 if (!focused_frame)
1809 return;
1811 focused_frame->Send(new FrameMsg_Reload(
1812 focused_frame->GetRoutingID(), ignore_cache));
1815 void WebContentsImpl::Undo() {
1816 RenderFrameHost* focused_frame = GetFocusedFrame();
1817 if (!focused_frame)
1818 return;
1820 focused_frame->Send(new InputMsg_Undo(focused_frame->GetRoutingID()));
1821 RecordAction(base::UserMetricsAction("Undo"));
1824 void WebContentsImpl::Redo() {
1825 RenderFrameHost* focused_frame = GetFocusedFrame();
1826 if (!focused_frame)
1827 return;
1828 focused_frame->Send(new InputMsg_Redo(focused_frame->GetRoutingID()));
1829 RecordAction(base::UserMetricsAction("Redo"));
1832 void WebContentsImpl::Cut() {
1833 RenderFrameHost* focused_frame = GetFocusedFrame();
1834 if (!focused_frame)
1835 return;
1837 focused_frame->Send(new InputMsg_Cut(focused_frame->GetRoutingID()));
1838 RecordAction(base::UserMetricsAction("Cut"));
1841 void WebContentsImpl::Copy() {
1842 RenderFrameHost* focused_frame = GetFocusedFrame();
1843 if (!focused_frame)
1844 return;
1846 focused_frame->Send(new InputMsg_Copy(focused_frame->GetRoutingID()));
1847 RecordAction(base::UserMetricsAction("Copy"));
1850 void WebContentsImpl::CopyToFindPboard() {
1851 #if defined(OS_MACOSX)
1852 RenderFrameHost* focused_frame = GetFocusedFrame();
1853 if (!focused_frame)
1854 return;
1856 // Windows/Linux don't have the concept of a find pasteboard.
1857 focused_frame->Send(
1858 new InputMsg_CopyToFindPboard(focused_frame->GetRoutingID()));
1859 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
1860 #endif
1863 void WebContentsImpl::Paste() {
1864 RenderFrameHost* focused_frame = GetFocusedFrame();
1865 if (!focused_frame)
1866 return;
1868 focused_frame->Send(new InputMsg_Paste(focused_frame->GetRoutingID()));
1869 RecordAction(base::UserMetricsAction("Paste"));
1872 void WebContentsImpl::PasteAndMatchStyle() {
1873 RenderFrameHost* focused_frame = GetFocusedFrame();
1874 if (!focused_frame)
1875 return;
1877 focused_frame->Send(new InputMsg_PasteAndMatchStyle(
1878 focused_frame->GetRoutingID()));
1879 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
1882 void WebContentsImpl::Delete() {
1883 RenderFrameHost* focused_frame = GetFocusedFrame();
1884 if (!focused_frame)
1885 return;
1887 focused_frame->Send(new InputMsg_Delete(focused_frame->GetRoutingID()));
1888 RecordAction(base::UserMetricsAction("DeleteSelection"));
1891 void WebContentsImpl::SelectAll() {
1892 RenderFrameHost* focused_frame = GetFocusedFrame();
1893 if (!focused_frame)
1894 return;
1896 focused_frame->Send(new InputMsg_SelectAll(focused_frame->GetRoutingID()));
1897 RecordAction(base::UserMetricsAction("SelectAll"));
1900 void WebContentsImpl::Unselect() {
1901 RenderFrameHost* focused_frame = GetFocusedFrame();
1902 if (!focused_frame)
1903 return;
1905 focused_frame->Send(new InputMsg_Unselect(focused_frame->GetRoutingID()));
1906 RecordAction(base::UserMetricsAction("Unselect"));
1909 void WebContentsImpl::Replace(const base::string16& word) {
1910 RenderFrameHost* focused_frame = GetFocusedFrame();
1911 if (!focused_frame)
1912 return;
1914 focused_frame->Send(new InputMsg_Replace(
1915 focused_frame->GetRoutingID(), word));
1918 void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
1919 RenderFrameHost* focused_frame = GetFocusedFrame();
1920 if (!focused_frame)
1921 return;
1923 focused_frame->Send(new InputMsg_ReplaceMisspelling(
1924 focused_frame->GetRoutingID(), word));
1927 void WebContentsImpl::NotifyContextMenuClosed(
1928 const CustomContextMenuContext& context) {
1929 RenderFrameHost* focused_frame = GetFocusedFrame();
1930 if (!focused_frame)
1931 return;
1933 focused_frame->Send(new FrameMsg_ContextMenuClosed(
1934 focused_frame->GetRoutingID(), context));
1937 void WebContentsImpl::ExecuteCustomContextMenuCommand(
1938 int action, const CustomContextMenuContext& context) {
1939 RenderFrameHost* focused_frame = GetFocusedFrame();
1940 if (!focused_frame)
1941 return;
1943 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
1944 focused_frame->GetRoutingID(), context, action));
1947 gfx::NativeView WebContentsImpl::GetNativeView() {
1948 return view_->GetNativeView();
1951 gfx::NativeView WebContentsImpl::GetContentNativeView() {
1952 return view_->GetContentNativeView();
1955 gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
1956 return view_->GetTopLevelNativeWindow();
1959 gfx::Rect WebContentsImpl::GetViewBounds() {
1960 return view_->GetViewBounds();
1963 gfx::Rect WebContentsImpl::GetContainerBounds() {
1964 gfx::Rect rv;
1965 view_->GetContainerBounds(&rv);
1966 return rv;
1969 DropData* WebContentsImpl::GetDropData() {
1970 return view_->GetDropData();
1973 void WebContentsImpl::Focus() {
1974 view_->Focus();
1977 void WebContentsImpl::SetInitialFocus() {
1978 view_->SetInitialFocus();
1981 void WebContentsImpl::StoreFocus() {
1982 view_->StoreFocus();
1985 void WebContentsImpl::RestoreFocus() {
1986 view_->RestoreFocus();
1989 void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
1990 if (ShowingInterstitialPage()) {
1991 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse);
1992 return;
1994 GetRenderViewHostImpl()->SetInitialFocus(reverse);
1997 bool WebContentsImpl::ShowingInterstitialPage() const {
1998 return GetRenderManager()->interstitial_page() != NULL;
2001 InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
2002 return GetRenderManager()->interstitial_page();
2005 bool WebContentsImpl::IsSavable() {
2006 // WebKit creates Document object when MIME type is application/xhtml+xml,
2007 // so we also support this MIME type.
2008 return contents_mime_type_ == "text/html" ||
2009 contents_mime_type_ == "text/xml" ||
2010 contents_mime_type_ == "application/xhtml+xml" ||
2011 contents_mime_type_ == "text/plain" ||
2012 contents_mime_type_ == "text/css" ||
2013 net::IsSupportedJavascriptMimeType(contents_mime_type_.c_str());
2016 void WebContentsImpl::OnSavePage() {
2017 // If we can not save the page, try to download it.
2018 if (!IsSavable()) {
2019 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML);
2020 SaveFrame(GetURL(), Referrer());
2021 return;
2024 Stop();
2026 // Create the save package and possibly prompt the user for the name to save
2027 // the page as. The user prompt is an asynchronous operation that runs on
2028 // another thread.
2029 save_package_ = new SavePackage(this);
2030 save_package_->GetSaveInfo();
2033 // Used in automated testing to bypass prompting the user for file names.
2034 // Instead, the names and paths are hard coded rather than running them through
2035 // file name sanitation and extension / mime checking.
2036 bool WebContentsImpl::SavePage(const base::FilePath& main_file,
2037 const base::FilePath& dir_path,
2038 SavePageType save_type) {
2039 // Stop the page from navigating.
2040 Stop();
2042 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
2043 return save_package_->Init(SavePackageDownloadCreatedCallback());
2046 void WebContentsImpl::SaveFrame(const GURL& url,
2047 const Referrer& referrer) {
2048 if (!GetURL().is_valid())
2049 return;
2050 bool is_main_frame = (url == GetURL());
2052 DownloadManager* dlm =
2053 BrowserContext::GetDownloadManager(GetBrowserContext());
2054 if (!dlm)
2055 return;
2056 int64 post_id = -1;
2057 if (is_main_frame) {
2058 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2059 if (entry)
2060 post_id = entry->GetPostID();
2062 scoped_ptr<DownloadUrlParameters> params(
2063 DownloadUrlParameters::FromWebContents(this, url));
2064 params->set_referrer(referrer);
2065 params->set_post_id(post_id);
2066 params->set_prefer_cache(true);
2067 if (post_id >= 0)
2068 params->set_method("POST");
2069 params->set_prompt(true);
2070 dlm->DownloadUrl(params.Pass());
2073 void WebContentsImpl::GenerateMHTML(
2074 const base::FilePath& file,
2075 const base::Callback<void(int64)>& callback) {
2076 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file, callback);
2079 // TODO(nasko): Rename this method to IsVisibleEntry.
2080 bool WebContentsImpl::IsActiveEntry(int32 page_id) {
2081 NavigationEntryImpl* visible_entry =
2082 NavigationEntryImpl::FromNavigationEntry(controller_.GetVisibleEntry());
2083 return (visible_entry != NULL &&
2084 visible_entry->site_instance() == GetSiteInstance() &&
2085 visible_entry->GetPageID() == page_id);
2088 const std::string& WebContentsImpl::GetContentsMimeType() const {
2089 return contents_mime_type_;
2092 bool WebContentsImpl::WillNotifyDisconnection() const {
2093 return notify_disconnection_;
2096 void WebContentsImpl::SetOverrideEncoding(const std::string& encoding) {
2097 SetEncoding(encoding);
2098 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding));
2101 void WebContentsImpl::ResetOverrideEncoding() {
2102 encoding_.clear();
2103 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2106 RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
2107 return &renderer_preferences_;
2110 void WebContentsImpl::Close() {
2111 Close(GetRenderViewHost());
2114 void WebContentsImpl::DragSourceEndedAt(int client_x, int client_y,
2115 int screen_x, int screen_y, blink::WebDragOperation operation) {
2116 if (browser_plugin_embedder_.get())
2117 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y,
2118 screen_x, screen_y, operation);
2119 if (GetRenderViewHost())
2120 GetRenderViewHostImpl()->DragSourceEndedAt(client_x, client_y,
2121 screen_x, screen_y, operation);
2124 void WebContentsImpl::DidGetResourceResponseStart(
2125 const ResourceRequestDetails& details) {
2126 controller_.ssl_manager()->DidStartResourceResponse(details);
2128 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2129 DidGetResourceResponseStart(details));
2131 // TODO(avi): Remove. http://crbug.com/170921
2132 NotificationService::current()->Notify(
2133 NOTIFICATION_RESOURCE_RESPONSE_STARTED,
2134 Source<WebContents>(this),
2135 Details<const ResourceRequestDetails>(&details));
2138 void WebContentsImpl::DidGetRedirectForResourceRequest(
2139 RenderViewHost* render_view_host,
2140 const ResourceRedirectDetails& details) {
2141 controller_.ssl_manager()->DidReceiveResourceRedirect(details);
2143 FOR_EACH_OBSERVER(
2144 WebContentsObserver,
2145 observers_,
2146 DidGetRedirectForResourceRequest(render_view_host, details));
2148 // TODO(avi): Remove. http://crbug.com/170921
2149 NotificationService::current()->Notify(
2150 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
2151 Source<WebContents>(this),
2152 Details<const ResourceRedirectDetails>(&details));
2155 void WebContentsImpl::SystemDragEnded() {
2156 if (GetRenderViewHost())
2157 GetRenderViewHostImpl()->DragSourceSystemDragEnded();
2158 if (delegate_)
2159 delegate_->DragEnded();
2160 if (browser_plugin_embedder_.get())
2161 browser_plugin_embedder_->SystemDragEnded();
2164 void WebContentsImpl::UserGestureDone() {
2165 OnUserGesture();
2168 void WebContentsImpl::SetClosedByUserGesture(bool value) {
2169 closed_by_user_gesture_ = value;
2172 bool WebContentsImpl::GetClosedByUserGesture() const {
2173 return closed_by_user_gesture_;
2176 double WebContentsImpl::GetZoomLevel() const {
2177 HostZoomMapImpl* zoom_map = static_cast<HostZoomMapImpl*>(
2178 HostZoomMap::GetForBrowserContext(GetBrowserContext()));
2179 if (!zoom_map)
2180 return 0;
2182 double zoom_level;
2183 if (temporary_zoom_settings_) {
2184 zoom_level = zoom_map->GetTemporaryZoomLevel(
2185 GetRenderProcessHost()->GetID(), GetRenderViewHost()->GetRoutingID());
2186 } else {
2187 GURL url;
2188 NavigationEntry* entry = GetController().GetLastCommittedEntry();
2189 // Since zoom map is updated using rewritten URL, use rewritten URL
2190 // to get the zoom level.
2191 url = entry ? entry->GetURL() : GURL::EmptyGURL();
2192 zoom_level = zoom_map->GetZoomLevelForHostAndScheme(url.scheme(),
2193 net::GetHostOrSpecFromURL(url));
2195 return zoom_level;
2198 int WebContentsImpl::GetZoomPercent(bool* enable_increment,
2199 bool* enable_decrement) const {
2200 *enable_decrement = *enable_increment = false;
2201 // Calculate the zoom percent from the factor. Round up to the nearest whole
2202 // number.
2203 int percent = static_cast<int>(
2204 ZoomLevelToZoomFactor(GetZoomLevel()) * 100 + 0.5);
2205 *enable_decrement = percent > minimum_zoom_percent_;
2206 *enable_increment = percent < maximum_zoom_percent_;
2207 return percent;
2210 void WebContentsImpl::ViewSource() {
2211 if (!delegate_)
2212 return;
2214 NavigationEntry* entry = GetController().GetLastCommittedEntry();
2215 if (!entry)
2216 return;
2218 delegate_->ViewSourceForTab(this, entry->GetURL());
2221 void WebContentsImpl::ViewFrameSource(const GURL& url,
2222 const PageState& page_state) {
2223 if (!delegate_)
2224 return;
2226 delegate_->ViewSourceForFrame(this, url, page_state);
2229 int WebContentsImpl::GetMinimumZoomPercent() const {
2230 return minimum_zoom_percent_;
2233 int WebContentsImpl::GetMaximumZoomPercent() const {
2234 return maximum_zoom_percent_;
2237 gfx::Size WebContentsImpl::GetPreferredSize() const {
2238 return capturer_count_ == 0 ? preferred_size_ : preferred_size_for_capture_;
2241 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed) {
2242 return GetRenderViewHost() ?
2243 GetRenderViewHostImpl()->GotResponseToLockMouseRequest(allowed) : false;
2246 bool WebContentsImpl::HasOpener() const {
2247 return opener_ != NULL;
2250 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
2251 if (!color_chooser_info_.get())
2252 return;
2253 RenderFrameHost* rfh = RenderFrameHost::FromID(
2254 color_chooser_info_->render_process_id,
2255 color_chooser_info_->render_frame_id);
2256 if (!rfh)
2257 return;
2259 rfh->Send(new FrameMsg_DidChooseColorResponse(
2260 rfh->GetRoutingID(), color_chooser_info_->identifier, color));
2263 void WebContentsImpl::DidEndColorChooser() {
2264 if (!color_chooser_info_.get())
2265 return;
2266 RenderFrameHost* rfh = RenderFrameHost::FromID(
2267 color_chooser_info_->render_process_id,
2268 color_chooser_info_->render_frame_id);
2269 if (!rfh)
2270 return;
2272 rfh->Send(new FrameMsg_DidEndColorChooser(
2273 rfh->GetRoutingID(), color_chooser_info_->identifier));
2274 color_chooser_info_.reset();
2277 int WebContentsImpl::DownloadImage(const GURL& url,
2278 bool is_favicon,
2279 uint32_t max_bitmap_size,
2280 const ImageDownloadCallback& callback) {
2281 int id = StartDownload(GetMainFrame(), url, is_favicon, max_bitmap_size);
2282 image_download_map_[id] = callback;
2283 return id;
2286 bool WebContentsImpl::IsSubframe() const {
2287 return is_subframe_;
2290 void WebContentsImpl::SetZoomLevel(double level) {
2291 Send(new ViewMsg_SetZoomLevel(GetRoutingID(), level));
2292 BrowserPluginEmbedder* embedder = GetBrowserPluginEmbedder();
2293 if (embedder)
2294 embedder->SetZoomLevel(level);
2297 void WebContentsImpl::Find(int request_id,
2298 const base::string16& search_text,
2299 const blink::WebFindOptions& options) {
2300 Send(new ViewMsg_Find(GetRoutingID(), request_id, search_text, options));
2303 void WebContentsImpl::StopFinding(StopFindAction action) {
2304 Send(new ViewMsg_StopFinding(GetRoutingID(), action));
2307 void WebContentsImpl::InsertCSS(const std::string& css) {
2308 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2309 GetMainFrame()->GetRoutingID(), css));
2312 bool WebContentsImpl::FocusLocationBarByDefault() {
2313 NavigationEntry* entry = controller_.GetVisibleEntry();
2314 if (entry && entry->GetURL() == GURL(kAboutBlankURL))
2315 return true;
2316 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
2319 void WebContentsImpl::SetFocusToLocationBar(bool select_all) {
2320 if (delegate_)
2321 delegate_->SetFocusToLocationBar(select_all);
2324 void WebContentsImpl::DidStartProvisionalLoad(
2325 RenderFrameHostImpl* render_frame_host,
2326 int parent_routing_id,
2327 const GURL& validated_url,
2328 bool is_error_page,
2329 bool is_iframe_srcdoc) {
2330 bool is_main_frame = render_frame_host->frame_tree_node()->IsMainFrame();
2331 if (is_main_frame)
2332 DidChangeLoadProgress(0);
2334 // Notify observers about the start of the provisional load.
2335 int render_frame_id = render_frame_host->GetRoutingID();
2336 RenderViewHost* render_view_host = render_frame_host->render_view_host();
2337 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2338 DidStartProvisionalLoadForFrame(
2339 render_frame_id, parent_routing_id, is_main_frame,
2340 validated_url, is_error_page, is_iframe_srcdoc,
2341 render_view_host));
2343 if (is_main_frame) {
2344 FOR_EACH_OBSERVER(
2345 WebContentsObserver,
2346 observers_,
2347 ProvisionalChangeToMainFrameUrl(validated_url,
2348 render_frame_host));
2352 void WebContentsImpl::DidFailProvisionalLoadWithError(
2353 RenderFrameHostImpl* render_frame_host,
2354 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
2355 GURL validated_url(params.url);
2356 int render_frame_id = render_frame_host->GetRoutingID();
2357 bool is_main_frame = render_frame_host->frame_tree_node()->IsMainFrame();
2358 RenderViewHost* render_view_host = render_frame_host->render_view_host();
2359 FOR_EACH_OBSERVER(
2360 WebContentsObserver,
2361 observers_,
2362 DidFailProvisionalLoad(render_frame_id,
2363 params.frame_unique_name,
2364 is_main_frame,
2365 validated_url,
2366 params.error_code,
2367 params.error_description,
2368 render_view_host));
2371 void WebContentsImpl::DidFailLoadWithError(
2372 RenderFrameHostImpl* render_frame_host,
2373 const GURL& url,
2374 int error_code,
2375 const base::string16& error_description) {
2376 int render_frame_id = render_frame_host->GetRoutingID();
2377 bool is_main_frame = render_frame_host->frame_tree_node()->IsMainFrame();
2378 RenderViewHost* render_view_host = render_frame_host->render_view_host();
2379 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2380 DidFailLoad(render_frame_id, url, is_main_frame, error_code,
2381 error_description, render_view_host));
2384 void WebContentsImpl::NotifyChangedNavigationState(
2385 InvalidateTypes changed_flags) {
2386 NotifyNavigationStateChanged(changed_flags);
2389 void WebContentsImpl::AboutToNavigateRenderFrame(
2390 RenderFrameHostImpl* render_frame_host) {
2391 // Notify observers that we will navigate in this RenderView.
2392 RenderViewHost* render_view_host = render_frame_host->render_view_host();
2393 FOR_EACH_OBSERVER(
2394 WebContentsObserver,
2395 observers_,
2396 AboutToNavigateRenderView(render_view_host));
2399 void WebContentsImpl::DidStartNavigationToPendingEntry(
2400 RenderFrameHostImpl* render_frame_host,
2401 const GURL& url,
2402 NavigationController::ReloadType reload_type) {
2403 // Notify observers about navigation.
2404 FOR_EACH_OBSERVER(
2405 WebContentsObserver,
2406 observers_,
2407 DidStartNavigationToPendingEntry(url, reload_type));
2410 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
2411 const OpenURLParams& params) {
2412 int source_render_frame_id = render_frame_host->GetRoutingID();
2413 WebContents* new_contents = OpenURL(params);
2415 if (new_contents) {
2416 // Notify observers.
2417 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2418 DidOpenRequestedURL(new_contents,
2419 params.url,
2420 params.referrer,
2421 params.disposition,
2422 params.transition,
2423 source_render_frame_id));
2427 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2428 if (!delegate_)
2429 return false;
2430 return delegate_->ShouldPreserveAbortedURLs(this);
2433 void WebContentsImpl::DidRedirectProvisionalLoad(
2434 RenderFrameHostImpl* render_frame_host,
2435 const GURL& validated_target_url) {
2436 // Notify observers about the provisional change in the main frame URL.
2437 FOR_EACH_OBSERVER(
2438 WebContentsObserver,
2439 observers_,
2440 ProvisionalChangeToMainFrameUrl(validated_target_url,
2441 render_frame_host));
2444 void WebContentsImpl::DidCommitProvisionalLoad(
2445 RenderFrameHostImpl* render_frame_host,
2446 const base::string16& frame_unique_name,
2447 bool is_main_frame,
2448 const GURL& url,
2449 PageTransition transition_type) {
2450 int render_frame_id = render_frame_host->GetRoutingID();
2451 RenderViewHost* render_view_host = render_frame_host->render_view_host();
2452 // Notify observers about the commit of the provisional load.
2453 FOR_EACH_OBSERVER(
2454 WebContentsObserver,
2455 observers_,
2456 DidCommitProvisionalLoadForFrame(render_frame_id,
2457 frame_unique_name,
2458 is_main_frame,
2459 url,
2460 transition_type,
2461 render_view_host));
2464 void WebContentsImpl::DidNavigateMainFramePreCommit(
2465 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2466 // Ensure fullscreen mode is exited before committing the navigation to a
2467 // different page. The next page will not start out assuming it is in
2468 // fullscreen mode.
2469 if (controller_.IsURLInPageNavigation(params.url,
2470 params.was_within_same_page,
2471 NAVIGATION_TYPE_UNKNOWN)) {
2472 // No page change? Then, the renderer and browser can remain in fullscreen.
2473 return;
2475 if (IsFullscreenForCurrentTab())
2476 GetRenderViewHost()->ExitFullscreen();
2477 DCHECK(!IsFullscreenForCurrentTab());
2480 void WebContentsImpl::DidNavigateMainFramePostCommit(
2481 const LoadCommittedDetails& details,
2482 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2483 if (details.is_navigation_to_different_page()) {
2484 // Clear the status bubble. This is a workaround for a bug where WebKit
2485 // doesn't let us know that the cursor left an element during a
2486 // transition (this is also why the mouse cursor remains as a hand after
2487 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2488 // clear the bubble when a user navigates to a named anchor in the same
2489 // page.
2490 UpdateTargetURL(details.entry->GetPageID(), GURL());
2493 if (!details.is_in_page) {
2494 // Once the main frame is navigated, we're no longer considered to have
2495 // displayed insecure content.
2496 displayed_insecure_content_ = false;
2497 SSLManager::NotifySSLInternalStateChanged(
2498 GetController().GetBrowserContext());
2501 // Notify observers about navigation.
2502 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2503 DidNavigateMainFrame(details, params));
2505 if (delegate_) {
2506 delegate_->DidNavigateMainFramePostCommit(this);
2507 view_->SetOverscrollControllerEnabled(delegate_->CanOverscrollContent());
2511 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2512 RenderFrameHostImpl* render_frame_host,
2513 const LoadCommittedDetails& details,
2514 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
2515 // Now that something has committed, we don't need to track whether the
2516 // initial page has been accessed.
2517 has_accessed_initial_document_ = false;
2519 // If we navigate off the page, close all JavaScript dialogs.
2520 if (dialog_manager_ && !details.is_in_page)
2521 dialog_manager_->CancelActiveAndPendingDialogs(this);
2523 // Notify observers about navigation.
2524 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2525 DidNavigateAnyFrame(details, params));
2528 void WebContentsImpl::SetMainFrameMimeType(const std::string& mime_type) {
2529 contents_mime_type_ = mime_type;
2532 bool WebContentsImpl::CanOverscrollContent() {
2533 if (delegate_)
2534 return delegate_->CanOverscrollContent();
2536 return false;
2539 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2540 const GURL& url,
2541 const std::string& security_info,
2542 const std::string& http_method,
2543 const std::string& mime_type,
2544 ResourceType::Type resource_type) {
2545 base::StatsCounter cache("WebKit.CacheHit");
2546 cache.Increment();
2548 // Send out a notification that we loaded a resource from our memory cache.
2549 int cert_id = 0;
2550 net::CertStatus cert_status = 0;
2551 int security_bits = -1;
2552 int connection_status = 0;
2553 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids;
2554 DeserializeSecurityInfo(security_info, &cert_id, &cert_status,
2555 &security_bits, &connection_status,
2556 &signed_certificate_timestamp_ids);
2557 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details
2558 LoadFromMemoryCacheDetails details(
2559 url, GetRenderProcessHost()->GetID(), cert_id, cert_status, http_method,
2560 mime_type, resource_type);
2562 controller_.ssl_manager()->DidLoadFromMemoryCache(details);
2564 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2565 DidLoadResourceFromMemoryCache(details));
2567 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
2568 scoped_refptr<net::URLRequestContextGetter> request_context(
2569 resource_type == ResourceType::MEDIA ?
2570 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2571 GetRenderProcessHost()->GetID()) :
2572 GetBrowserContext()->GetRequestContextForRenderProcess(
2573 GetRenderProcessHost()->GetID()));
2574 BrowserThread::PostTask(
2575 BrowserThread::IO,
2576 FROM_HERE,
2577 base::Bind(&NotifyCacheOnIO, request_context, url, http_method));
2581 void WebContentsImpl::OnDidDisplayInsecureContent() {
2582 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
2583 displayed_insecure_content_ = true;
2584 SSLManager::NotifySSLInternalStateChanged(
2585 GetController().GetBrowserContext());
2588 void WebContentsImpl::OnDidRunInsecureContent(
2589 const std::string& security_origin, const GURL& target_url) {
2590 LOG(WARNING) << security_origin << " ran insecure content from "
2591 << target_url.possibly_invalid_spec();
2592 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
2593 if (EndsWith(security_origin, kDotGoogleDotCom, false))
2594 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
2595 controller_.ssl_manager()->DidRunInsecureContent(security_origin);
2596 displayed_insecure_content_ = true;
2597 SSLManager::NotifySSLInternalStateChanged(
2598 GetController().GetBrowserContext());
2601 void WebContentsImpl::OnDocumentLoadedInFrame() {
2602 CHECK(render_frame_message_source_);
2603 CHECK(!render_view_message_source_);
2604 RenderFrameHostImpl* rfh =
2605 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2607 int render_frame_id = rfh->GetRoutingID();
2608 RenderViewHost* render_view_host = rfh->render_view_host();
2609 FOR_EACH_OBSERVER(WebContentsObserver,
2610 observers_,
2611 DocumentLoadedInFrame(render_frame_id, render_view_host));
2614 void WebContentsImpl::OnDidFinishLoad(
2615 const GURL& url) {
2616 if (!render_frame_message_source_) {
2617 RecordAction(base::UserMetricsAction("BadMessageTerminate_RVD2"));
2618 GetRenderProcessHost()->ReceivedBadMessage();
2619 return;
2622 GURL validated_url(url);
2623 RenderProcessHost* render_process_host =
2624 render_frame_message_source_->GetProcess();
2625 render_process_host->FilterURL(false, &validated_url);
2627 RenderFrameHostImpl* rfh =
2628 static_cast<RenderFrameHostImpl*>(render_frame_message_source_);
2629 int render_frame_id = rfh->GetRoutingID();
2630 RenderViewHost* render_view_host = rfh->render_view_host();
2631 bool is_main_frame = rfh->frame_tree_node()->IsMainFrame();
2632 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2633 DidFinishLoad(render_frame_id, validated_url,
2634 is_main_frame, render_view_host));
2637 void WebContentsImpl::OnGoToEntryAtOffset(int offset) {
2638 if (!delegate_ || delegate_->OnGoToEntryOffset(offset))
2639 controller_.GoToOffset(offset);
2642 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent,
2643 int maximum_percent,
2644 bool remember) {
2645 minimum_zoom_percent_ = minimum_percent;
2646 maximum_zoom_percent_ = maximum_percent;
2647 temporary_zoom_settings_ = !remember;
2650 void WebContentsImpl::OnEnumerateDirectory(int request_id,
2651 const base::FilePath& path) {
2652 if (!delegate_)
2653 return;
2655 ChildProcessSecurityPolicyImpl* policy =
2656 ChildProcessSecurityPolicyImpl::GetInstance();
2657 if (policy->CanReadFile(GetRenderProcessHost()->GetID(), path))
2658 delegate_->EnumerateDirectory(this, request_id, path);
2661 void WebContentsImpl::OnRegisterProtocolHandler(const std::string& protocol,
2662 const GURL& url,
2663 const base::string16& title,
2664 bool user_gesture) {
2665 if (!delegate_)
2666 return;
2668 ChildProcessSecurityPolicyImpl* policy =
2669 ChildProcessSecurityPolicyImpl::GetInstance();
2670 if (policy->IsPseudoScheme(protocol))
2671 return;
2673 delegate_->RegisterProtocolHandler(this, protocol, url, title, user_gesture);
2676 void WebContentsImpl::OnFindReply(int request_id,
2677 int number_of_matches,
2678 const gfx::Rect& selection_rect,
2679 int active_match_ordinal,
2680 bool final_update) {
2681 if (delegate_) {
2682 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
2683 active_match_ordinal, final_update);
2687 #if defined(OS_ANDROID)
2688 void WebContentsImpl::OnFindMatchRectsReply(
2689 int version,
2690 const std::vector<gfx::RectF>& rects,
2691 const gfx::RectF& active_rect) {
2692 if (delegate_)
2693 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
2696 void WebContentsImpl::OnOpenDateTimeDialog(
2697 const ViewHostMsg_DateTimeDialogValue_Params& value) {
2698 date_time_chooser_->ShowDialog(ContentViewCore::FromWebContents(this),
2699 GetRenderViewHost(),
2700 value.dialog_type,
2701 value.dialog_value,
2702 value.minimum,
2703 value.maximum,
2704 value.step,
2705 value.suggestions);
2708 void WebContentsImpl::OnJavaBridgeGetChannelHandle(IPC::Message* reply_msg) {
2709 java_bridge_dispatcher_host_manager_->OnGetChannelHandle(
2710 render_frame_message_source_, reply_msg);
2713 #endif
2715 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id,
2716 const base::FilePath& path,
2717 bool is_hung) {
2718 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
2720 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2721 PluginHungStatusChanged(plugin_child_id, path, is_hung));
2724 void WebContentsImpl::OnPluginCrashed(const base::FilePath& plugin_path,
2725 base::ProcessId plugin_pid) {
2726 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2727 PluginCrashed(plugin_path, plugin_pid));
2730 void WebContentsImpl::OnDomOperationResponse(const std::string& json_string,
2731 int automation_id) {
2732 DomOperationNotificationDetails details(json_string, automation_id);
2733 NotificationService::current()->Notify(
2734 NOTIFICATION_DOM_OPERATION_RESPONSE,
2735 Source<WebContents>(this),
2736 Details<DomOperationNotificationDetails>(&details));
2739 void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
2740 bool blocked_by_policy) {
2741 // Notify observers about navigation.
2742 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2743 AppCacheAccessed(manifest_url, blocked_by_policy));
2746 void WebContentsImpl::OnOpenColorChooser(
2747 int color_chooser_id,
2748 SkColor color,
2749 const std::vector<ColorSuggestion>& suggestions) {
2750 ColorChooser* new_color_chooser = delegate_ ?
2751 delegate_->OpenColorChooser(this, color, suggestions) :
2752 NULL;
2753 if (!new_color_chooser)
2754 return;
2755 if (color_chooser_info_.get())
2756 color_chooser_info_->chooser->End();
2758 color_chooser_info_.reset(new ColorChooserInfo(
2759 render_frame_message_source_->GetProcess()->GetID(),
2760 render_frame_message_source_->GetRoutingID(),
2761 new_color_chooser,
2762 color_chooser_id));
2765 void WebContentsImpl::OnEndColorChooser(int color_chooser_id) {
2766 if (color_chooser_info_ &&
2767 color_chooser_id == color_chooser_info_->identifier)
2768 color_chooser_info_->chooser->End();
2771 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id,
2772 SkColor color) {
2773 if (color_chooser_info_ &&
2774 color_chooser_id == color_chooser_info_->identifier)
2775 color_chooser_info_->chooser->SetSelectedColor(color);
2778 // This exists for render views that don't have a WebUI, but do have WebUI
2779 // bindings enabled.
2780 void WebContentsImpl::OnWebUISend(const GURL& source_url,
2781 const std::string& name,
2782 const base::ListValue& args) {
2783 if (delegate_)
2784 delegate_->WebUISend(this, source_url, name, args);
2787 void WebContentsImpl::OnRequestPpapiBrokerPermission(
2788 int routing_id,
2789 const GURL& url,
2790 const base::FilePath& plugin_path) {
2791 if (!delegate_) {
2792 OnPpapiBrokerPermissionResult(routing_id, false);
2793 return;
2796 if (!delegate_->RequestPpapiBrokerPermission(
2797 this, url, plugin_path,
2798 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult,
2799 base::Unretained(this), routing_id))) {
2800 NOTIMPLEMENTED();
2801 OnPpapiBrokerPermissionResult(routing_id, false);
2805 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id,
2806 bool result) {
2807 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id, result));
2810 void WebContentsImpl::OnBrowserPluginMessage(const IPC::Message& message) {
2811 // This creates a BrowserPluginEmbedder, which handles all the BrowserPlugin
2812 // specific messages for this WebContents. This means that any message from
2813 // a BrowserPlugin prior to this will be ignored.
2814 // For more info, see comment above classes BrowserPluginEmbedder and
2815 // BrowserPluginGuest.
2816 CHECK(!browser_plugin_embedder_.get());
2817 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
2818 browser_plugin_embedder_->OnMessageReceived(message);
2821 void WebContentsImpl::OnDidDownloadImage(
2822 int id,
2823 int http_status_code,
2824 const GURL& image_url,
2825 const std::vector<SkBitmap>& bitmaps,
2826 const std::vector<gfx::Size>& original_bitmap_sizes) {
2827 if (bitmaps.size() != original_bitmap_sizes.size())
2828 return;
2830 ImageDownloadMap::iterator iter = image_download_map_.find(id);
2831 if (iter == image_download_map_.end()) {
2832 // Currently WebContents notifies us of ANY downloads so that it is
2833 // possible to get here.
2834 return;
2836 if (!iter->second.is_null()) {
2837 iter->second.Run(
2838 id, http_status_code, image_url, bitmaps, original_bitmap_sizes);
2840 image_download_map_.erase(id);
2843 void WebContentsImpl::OnUpdateFaviconURL(
2844 const std::vector<FaviconURL>& candidates) {
2845 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2846 DidUpdateFaviconURL(candidates));
2849 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie,
2850 bool has_video,
2851 bool has_audio) {
2852 // Chrome OS does its own detection of audio and video.
2853 #if !defined(OS_CHROMEOS)
2854 scoped_ptr<PowerSaveBlocker> blocker;
2855 if (has_video) {
2856 blocker = PowerSaveBlocker::Create(
2857 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep, "Playing video");
2858 #if defined(OS_ANDROID)
2859 static_cast<PowerSaveBlockerImpl*>(blocker.get())
2860 ->InitDisplaySleepBlocker(GetView()->GetNativeView());
2861 #endif
2862 } else if (has_audio) {
2863 blocker = PowerSaveBlocker::Create(
2864 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension, "Playing audio");
2867 if (blocker) {
2868 power_save_blockers_[render_frame_message_source_][player_cookie] =
2869 blocker.release();
2871 #endif // !defined(OS_CHROMEOS)
2874 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie) {
2875 // Chrome OS does its own detection of audio and video.
2876 #if !defined(OS_CHROMEOS)
2877 delete power_save_blockers_[render_frame_message_source_][player_cookie];
2878 power_save_blockers_[render_frame_message_source_].erase(player_cookie);
2879 #endif // !defined(OS_CHROMEOS)
2882 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
2883 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2884 DidFirstVisuallyNonEmptyPaint());
2887 void WebContentsImpl::DidChangeVisibleSSLState() {
2888 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2889 DidChangeVisibleSSLState());
2892 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
2893 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2894 BeforeFormRepostWarningShow());
2898 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
2899 Activate();
2900 if (delegate_)
2901 delegate_->ShowRepostFormWarningDialog(this);
2904 bool WebContentsImpl::HasAccessedInitialDocument() {
2905 return has_accessed_initial_document_;
2908 // Notifies the RenderWidgetHost instance about the fact that the page is
2909 // loading, or done loading.
2910 void WebContentsImpl::SetIsLoading(RenderViewHost* render_view_host,
2911 bool is_loading,
2912 bool to_different_document,
2913 LoadNotificationDetails* details) {
2914 if (is_loading == is_loading_)
2915 return;
2917 if (!is_loading) {
2918 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
2919 base::string16());
2920 load_state_host_.clear();
2921 upload_size_ = 0;
2922 upload_position_ = 0;
2925 GetRenderManager()->SetIsLoading(is_loading);
2927 is_loading_ = is_loading;
2928 waiting_for_response_ = is_loading;
2930 if (delegate_)
2931 delegate_->LoadingStateChanged(this, to_different_document);
2932 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
2934 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
2935 if (is_loading) {
2936 TRACE_EVENT_ASYNC_BEGIN1("browser", "WebContentsImpl Loading", this,
2937 "URL", url);
2938 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2939 DidStartLoading(render_view_host));
2940 } else {
2941 TRACE_EVENT_ASYNC_END1("browser", "WebContentsImpl Loading", this,
2942 "URL", url);
2943 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2944 DidStopLoading(render_view_host));
2947 // TODO(avi): Remove. http://crbug.com/170921
2948 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
2949 NotificationDetails det = NotificationService::NoDetails();
2950 if (details)
2951 det = Details<LoadNotificationDetails>(details);
2952 NotificationService::current()->Notify(
2953 type, Source<NavigationController>(&controller_), det);
2956 void WebContentsImpl::SelectRange(const gfx::Point& start,
2957 const gfx::Point& end) {
2958 RenderFrameHost* focused_frame = GetFocusedFrame();
2959 if (!focused_frame)
2960 return;
2962 focused_frame->Send(
2963 new InputMsg_SelectRange(focused_frame->GetRoutingID(), start, end));
2966 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost* rvh) {
2967 // If we are creating a RVH for a restored controller, then we need to make
2968 // sure the RenderView starts with a next_page_id_ larger than the number
2969 // of restored entries. This must be called before the RenderView starts
2970 // navigating (to avoid a race between the browser updating max_page_id and
2971 // the renderer updating next_page_id_). Because of this, we only call this
2972 // from CreateRenderView and allow that to notify the RenderView for us.
2973 int max_restored_page_id = controller_.GetMaxRestoredPageID();
2974 if (max_restored_page_id >
2975 GetMaxPageIDForSiteInstance(rvh->GetSiteInstance()))
2976 UpdateMaxPageIDForSiteInstance(rvh->GetSiteInstance(),
2977 max_restored_page_id);
2980 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl* entry,
2981 const base::string16& title) {
2982 // For file URLs without a title, use the pathname instead. In the case of a
2983 // synthesized title, we don't want the update to count toward the "one set
2984 // per page of the title to history."
2985 base::string16 final_title;
2986 bool explicit_set;
2987 if (entry && entry->GetURL().SchemeIsFile() && title.empty()) {
2988 final_title = base::UTF8ToUTF16(entry->GetURL().ExtractFileName());
2989 explicit_set = false; // Don't count synthetic titles toward the set limit.
2990 } else {
2991 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
2992 explicit_set = true;
2995 // If a page is created via window.open and never navigated,
2996 // there will be no navigation entry. In this situation,
2997 // |page_title_when_no_navigation_entry_| will be used for page title.
2998 if (entry) {
2999 if (final_title == entry->GetTitle())
3000 return false; // Nothing changed, don't bother.
3002 entry->SetTitle(final_title);
3003 } else {
3004 if (page_title_when_no_navigation_entry_ == final_title)
3005 return false; // Nothing changed, don't bother.
3007 page_title_when_no_navigation_entry_ = final_title;
3010 // Lastly, set the title for the view.
3011 view_->SetPageTitle(final_title);
3013 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3014 TitleWasSet(entry, explicit_set));
3016 // TODO(avi): Remove. http://crbug.com/170921
3017 std::pair<NavigationEntry*, bool> details =
3018 std::make_pair(entry, explicit_set);
3019 NotificationService::current()->Notify(
3020 NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,
3021 Source<WebContents>(this),
3022 Details<std::pair<NavigationEntry*, bool> >(&details));
3024 return true;
3027 void WebContentsImpl::NotifySwapped(RenderViewHost* old_host,
3028 RenderViewHost* new_host) {
3029 // After sending out a swap notification, we need to send a disconnect
3030 // notification so that clients that pick up a pointer to |this| can NULL the
3031 // pointer. See Bug 1230284.
3032 notify_disconnection_ = true;
3033 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3034 RenderViewHostChanged(old_host, new_host));
3036 // TODO(avi): Remove. http://crbug.com/170921
3037 std::pair<RenderViewHost*, RenderViewHost*> details =
3038 std::make_pair(old_host, new_host);
3039 NotificationService::current()->Notify(
3040 NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
3041 Source<WebContents>(this),
3042 Details<std::pair<RenderViewHost*, RenderViewHost*> >(&details));
3044 // Ensure that the associated embedder gets cleared after a RenderViewHost
3045 // gets swapped, so we don't reuse the same embedder next time a
3046 // RenderViewHost is attached to this WebContents.
3047 RemoveBrowserPluginEmbedder();
3050 // TODO(avi): Remove this entire function because this notification is already
3051 // covered by two observer functions. http://crbug.com/170921
3052 void WebContentsImpl::NotifyDisconnected() {
3053 if (!notify_disconnection_)
3054 return;
3056 notify_disconnection_ = false;
3057 NotificationService::current()->Notify(
3058 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
3059 Source<WebContents>(this),
3060 NotificationService::NoDetails());
3063 void WebContentsImpl::NotifyNavigationEntryCommitted(
3064 const LoadCommittedDetails& load_details) {
3065 FOR_EACH_OBSERVER(
3066 WebContentsObserver, observers_, NavigationEntryCommitted(load_details));
3069 bool WebContentsImpl::OnMessageReceived(RenderFrameHost* render_frame_host,
3070 const IPC::Message& message) {
3071 return OnMessageReceived(NULL, render_frame_host, message);
3074 const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3075 return GetLastCommittedURL();
3078 void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
3079 // Note this is only for subframes, the notification for the main frame
3080 // happens in RenderViewCreated.
3081 FOR_EACH_OBSERVER(WebContentsObserver,
3082 observers_,
3083 RenderFrameCreated(render_frame_host));
3086 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
3087 ClearPowerSaveBlockers(render_frame_host);
3088 FOR_EACH_OBSERVER(WebContentsObserver,
3089 observers_,
3090 RenderFrameDeleted(render_frame_host));
3093 void WebContentsImpl::WorkerCrashed(RenderFrameHost* render_frame_host) {
3094 if (delegate_)
3095 delegate_->WorkerCrashed(this);
3098 void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
3099 const ContextMenuParams& params) {
3100 // Allow WebContentsDelegates to handle the context menu operation first.
3101 if (delegate_ && delegate_->HandleContextMenu(params))
3102 return;
3104 render_view_host_delegate_view_->ShowContextMenu(render_frame_host, params);
3107 void WebContentsImpl::RunJavaScriptMessage(
3108 RenderFrameHost* render_frame_host,
3109 const base::string16& message,
3110 const base::string16& default_prompt,
3111 const GURL& frame_url,
3112 JavaScriptMessageType javascript_message_type,
3113 IPC::Message* reply_msg) {
3114 // Suppress JavaScript dialogs when requested. Also suppress messages when
3115 // showing an interstitial as it's shown over the previous page and we don't
3116 // want the hidden page's dialogs to interfere with the interstitial.
3117 bool suppress_this_message =
3118 static_cast<RenderViewHostImpl*>(render_frame_host->GetRenderViewHost())->
3119 IsSwappedOut() ||
3120 ShowingInterstitialPage() ||
3121 !delegate_ ||
3122 delegate_->ShouldSuppressDialogs() ||
3123 !delegate_->GetJavaScriptDialogManager();
3125 if (!suppress_this_message) {
3126 std::string accept_lang = GetContentClient()->browser()->
3127 GetAcceptLangs(GetBrowserContext());
3128 dialog_manager_ = delegate_->GetJavaScriptDialogManager();
3129 dialog_manager_->RunJavaScriptDialog(
3130 this,
3131 frame_url.GetOrigin(),
3132 accept_lang,
3133 javascript_message_type,
3134 message,
3135 default_prompt,
3136 base::Bind(&WebContentsImpl::OnDialogClosed,
3137 base::Unretained(this),
3138 render_frame_host->GetProcess()->GetID(),
3139 render_frame_host->GetRoutingID(),
3140 reply_msg,
3141 false),
3142 &suppress_this_message);
3145 if (suppress_this_message) {
3146 // If we are suppressing messages, just reply as if the user immediately
3147 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3148 OnDialogClosed(render_frame_host->GetProcess()->GetID(),
3149 render_frame_host->GetRoutingID(), reply_msg,
3150 true, false, base::string16());
3153 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3154 // http://crbug.com/288961 ). The only safe thing to do here is return.
3157 void WebContentsImpl::RunBeforeUnloadConfirm(
3158 RenderFrameHost* render_frame_host,
3159 const base::string16& message,
3160 bool is_reload,
3161 IPC::Message* reply_msg) {
3162 RenderFrameHostImpl* rfhi =
3163 static_cast<RenderFrameHostImpl*>(render_frame_host);
3164 RenderViewHostImpl* rvhi =
3165 static_cast<RenderViewHostImpl*>(render_frame_host->GetRenderViewHost());
3166 if (delegate_)
3167 delegate_->WillRunBeforeUnloadConfirm();
3169 bool suppress_this_message =
3170 rvhi->rvh_state() != RenderViewHostImpl::STATE_DEFAULT ||
3171 !delegate_ ||
3172 delegate_->ShouldSuppressDialogs() ||
3173 !delegate_->GetJavaScriptDialogManager();
3174 if (suppress_this_message) {
3175 rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16(), true);
3176 return;
3179 is_showing_before_unload_dialog_ = true;
3180 dialog_manager_ = delegate_->GetJavaScriptDialogManager();
3181 dialog_manager_->RunBeforeUnloadDialog(
3182 this, message, is_reload,
3183 base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
3184 render_frame_host->GetProcess()->GetID(),
3185 render_frame_host->GetRoutingID(), reply_msg,
3186 false));
3189 WebContents* WebContentsImpl::GetAsWebContents() {
3190 return this;
3193 bool WebContentsImpl::IsNeverVisible() {
3194 if (!delegate_)
3195 return false;
3196 return delegate_->IsNeverVisible(this);
3199 RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
3200 return render_view_host_delegate_view_;
3203 RendererPreferences WebContentsImpl::GetRendererPrefs(
3204 BrowserContext* browser_context) const {
3205 return renderer_preferences_;
3208 gfx::Rect WebContentsImpl::GetRootWindowResizerRect() const {
3209 if (delegate_)
3210 return delegate_->GetRootWindowResizerRect();
3211 return gfx::Rect();
3214 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3215 if (browser_plugin_embedder_)
3216 browser_plugin_embedder_.reset();
3219 void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
3220 // Don't send notifications if we are just creating a swapped-out RVH for
3221 // the opener chain. These won't be used for view-source or WebUI, so it's
3222 // ok to return early.
3223 if (static_cast<RenderViewHostImpl*>(render_view_host)->IsSwappedOut())
3224 return;
3226 if (delegate_)
3227 view_->SetOverscrollControllerEnabled(delegate_->CanOverscrollContent());
3229 NotificationService::current()->Notify(
3230 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
3231 Source<WebContents>(this),
3232 Details<RenderViewHost>(render_view_host));
3234 // When we're creating views, we're still doing initial setup, so we always
3235 // use the pending Web UI rather than any possibly existing committed one.
3236 if (GetRenderManager()->pending_web_ui())
3237 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host);
3239 NavigationEntry* entry = controller_.GetPendingEntry();
3240 if (entry && entry->IsViewSourceMode()) {
3241 // Put the renderer in view source mode.
3242 render_view_host->Send(
3243 new ViewMsg_EnableViewSourceMode(render_view_host->GetRoutingID()));
3246 view_->RenderViewCreated(render_view_host);
3248 FOR_EACH_OBSERVER(
3249 WebContentsObserver, observers_, RenderViewCreated(render_view_host));
3251 // We tell the observers now instead of when the main RenderFrameHostImpl is
3252 // constructed because otherwise it would be too early (i.e. IPCs sent to the
3253 // frame would be dropped because it's not created yet).
3254 RenderFrameHost* main_frame = render_view_host->GetMainFrame();
3255 FOR_EACH_OBSERVER(
3256 WebContentsObserver, observers_, RenderFrameCreated(main_frame));
3259 void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
3260 if (rvh != GetRenderViewHost()) {
3261 // Don't notify the world, since this came from a renderer in the
3262 // background.
3263 return;
3266 notify_disconnection_ = true;
3267 // TODO(avi): Remove. http://crbug.com/170921
3268 NotificationService::current()->Notify(
3269 NOTIFICATION_WEB_CONTENTS_CONNECTED,
3270 Source<WebContents>(this),
3271 NotificationService::NoDetails());
3273 bool was_crashed = IsCrashed();
3274 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
3276 // Restore the focus to the tab (otherwise the focus will be on the top
3277 // window).
3278 if (was_crashed && !FocusLocationBarByDefault() &&
3279 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
3280 view_->Focus();
3283 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewReady());
3286 void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
3287 base::TerminationStatus status,
3288 int error_code) {
3289 if (rvh != GetRenderViewHost()) {
3290 // The pending page's RenderViewHost is gone.
3291 return;
3294 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3295 // renderer may not have made a clean exit.
3296 if (IsFullscreenForCurrentTab())
3297 ToggleFullscreenMode(false);
3299 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3300 if (dialog_manager_)
3301 dialog_manager_->CancelActiveAndPendingDialogs(this);
3303 SetIsLoading(rvh, false, true, NULL);
3304 NotifyDisconnected();
3305 SetIsCrashed(status, error_code);
3307 #if defined(OS_ANDROID)
3308 if (GetRenderViewHostImpl()->media_player_manager())
3309 GetRenderViewHostImpl()->media_player_manager()->DestroyAllMediaPlayers();
3310 #endif
3312 FOR_EACH_OBSERVER(WebContentsObserver,
3313 observers_,
3314 RenderProcessGone(GetCrashedStatus()));
3317 void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
3318 GetRenderManager()->RenderViewDeleted(rvh);
3319 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewDeleted(rvh));
3322 void WebContentsImpl::UpdateState(RenderViewHost* rvh,
3323 int32 page_id,
3324 const PageState& page_state) {
3325 // Ensure that this state update comes from either the active RVH or one of
3326 // the swapped out RVHs. We don't expect to hear from any other RVHs.
3327 // TODO(nasko): This should go through RenderFrameHost.
3328 // TODO(creis): We can't update state for cross-process subframes until we
3329 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
3330 if (rvh != GetRenderViewHost() &&
3331 !GetRenderManager()->IsRVHOnSwappedOutList(
3332 static_cast<RenderViewHostImpl*>(rvh)))
3333 return;
3335 // We must be prepared to handle state updates for any page, these occur
3336 // when the user is scrolling and entering form data, as well as when we're
3337 // leaving a page, in which case our state may have already been moved to
3338 // the next page. The navigation controller will look up the appropriate
3339 // NavigationEntry and update it when it is notified via the delegate.
3341 int entry_index = controller_.GetEntryIndexWithPageID(
3342 rvh->GetSiteInstance(), page_id);
3343 if (entry_index < 0)
3344 return;
3345 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
3347 if (page_state == entry->GetPageState())
3348 return; // Nothing to update.
3349 entry->SetPageState(page_state);
3350 controller_.NotifyEntryChanged(entry, entry_index);
3353 void WebContentsImpl::UpdateTitle(RenderViewHost* rvh,
3354 int32 page_id,
3355 const base::string16& title,
3356 base::i18n::TextDirection title_direction) {
3357 // If we have a title, that's a pretty good indication that we've started
3358 // getting useful data.
3359 SetNotWaitingForResponse();
3361 // Try to find the navigation entry, which might not be the current one.
3362 // For example, it might be from a pending RVH for the pending entry.
3363 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
3364 rvh->GetSiteInstance(), page_id);
3366 // We can handle title updates when we don't have an entry in
3367 // UpdateTitleForEntry, but only if the update is from the current RVH.
3368 if (!entry && rvh != GetRenderViewHost())
3369 return;
3371 // TODO(evan): make use of title_direction.
3372 // http://code.google.com/p/chromium/issues/detail?id=27094
3373 if (!UpdateTitleForEntry(entry, title))
3374 return;
3376 // Broadcast notifications when the UI should be updated.
3377 if (entry == controller_.GetEntryAtOffset(0))
3378 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
3381 void WebContentsImpl::UpdateEncoding(RenderViewHost* render_view_host,
3382 const std::string& encoding) {
3383 SetEncoding(encoding);
3386 void WebContentsImpl::UpdateTargetURL(int32 page_id, const GURL& url) {
3387 if (delegate_)
3388 delegate_->UpdateTargetURL(this, page_id, url);
3391 void WebContentsImpl::Close(RenderViewHost* rvh) {
3392 #if defined(OS_MACOSX)
3393 // The UI may be in an event-tracking loop, such as between the
3394 // mouse-down and mouse-up in text selection or a button click.
3395 // Defer the close until after tracking is complete, so that we
3396 // don't free objects out from under the UI.
3397 // TODO(shess): This could get more fine-grained. For instance,
3398 // closing a tab in another window while selecting text in the
3399 // current window's Omnibox should be just fine.
3400 if (view_->IsEventTracking()) {
3401 view_->CloseTabAfterEventTracking();
3402 return;
3404 #endif
3406 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3407 if (delegate_ && rvh == GetRenderViewHost())
3408 delegate_->CloseContents(this);
3411 void WebContentsImpl::SwappedOut(RenderFrameHost* rfh) {
3412 if (delegate_ && rfh->GetRenderViewHost() == GetRenderViewHost())
3413 delegate_->SwappedOut(this);
3416 void WebContentsImpl::RequestMove(const gfx::Rect& new_bounds) {
3417 if (delegate_ && delegate_->IsPopupOrPanel(this))
3418 delegate_->MoveContents(this, new_bounds);
3421 void WebContentsImpl::DidStartLoading(RenderFrameHost* render_frame_host,
3422 bool to_different_document) {
3423 SetIsLoading(render_frame_host->GetRenderViewHost(), true,
3424 to_different_document, NULL);
3427 void WebContentsImpl::DidStopLoading(RenderFrameHost* render_frame_host) {
3428 scoped_ptr<LoadNotificationDetails> details;
3430 // Use the last committed entry rather than the active one, in case a
3431 // pending entry has been created.
3432 NavigationEntry* entry = controller_.GetLastCommittedEntry();
3433 Navigator* navigator = frame_tree_.root()->navigator();
3435 // An entry may not exist for a stop when loading an initial blank page or
3436 // if an iframe injected by script into a blank page finishes loading.
3437 if (entry) {
3438 base::TimeDelta elapsed =
3439 base::TimeTicks::Now() - navigator->GetCurrentLoadStart();
3441 details.reset(new LoadNotificationDetails(
3442 entry->GetVirtualURL(),
3443 entry->GetTransitionType(),
3444 elapsed,
3445 &controller_,
3446 controller_.GetCurrentEntryIndex()));
3449 SetIsLoading(render_frame_host->GetRenderViewHost(), false, true,
3450 details.get());
3453 void WebContentsImpl::DidCancelLoading() {
3454 controller_.DiscardNonCommittedEntries();
3456 // Update the URL display.
3457 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
3460 void WebContentsImpl::DidChangeLoadProgress(double progress) {
3461 if (delegate_)
3462 delegate_->LoadProgressChanged(this, progress);
3465 void WebContentsImpl::DidAccessInitialDocument() {
3466 has_accessed_initial_document_ = true;
3468 // We may have left a failed browser-initiated navigation in the address bar
3469 // to let the user edit it and try again. Clear it now that content might
3470 // show up underneath it.
3471 if (!IsLoading() && controller_.GetPendingEntry())
3472 controller_.DiscardPendingEntry();
3474 // Update the URL display.
3475 NotifyNavigationStateChanged(content::INVALIDATE_TYPE_URL);
3478 void WebContentsImpl::DidDisownOpener(RenderFrameHost* render_frame_host) {
3479 if (opener_) {
3480 // Clear our opener so that future cross-process navigations don't have an
3481 // opener assigned.
3482 RemoveDestructionObserver(opener_);
3483 opener_ = NULL;
3486 // Notify all swapped out RenderViewHosts for this tab. This is important
3487 // in case we go back to them, or if another window in those processes tries
3488 // to access window.opener.
3489 GetRenderManager()->DidDisownOpener(render_frame_host->GetRenderViewHost());
3492 void WebContentsImpl::DocumentOnLoadCompleted(
3493 RenderFrameHost* render_frame_host) {
3494 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3495 DocumentOnLoadCompletedInMainFrame());
3497 // TODO(avi): Remove. http://crbug.com/170921
3498 NotificationService::current()->Notify(
3499 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
3500 Source<WebContents>(this),
3501 NotificationService::NoDetails());
3504 void WebContentsImpl::DocumentAvailableInMainFrame(
3505 RenderViewHost* render_view_host) {
3506 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3507 DocumentAvailableInMainFrame());
3509 void WebContentsImpl::RouteCloseEvent(RenderViewHost* rvh) {
3510 // Tell the active RenderViewHost to run unload handlers and close, as long
3511 // as the request came from a RenderViewHost in the same BrowsingInstance.
3512 // In most cases, we receive this from a swapped out RenderViewHost.
3513 // It is possible to receive it from one that has just been swapped in,
3514 // in which case we might as well deliver the message anyway.
3515 if (rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3516 GetRenderViewHost()->ClosePage();
3519 void WebContentsImpl::RouteMessageEvent(
3520 RenderViewHost* rvh,
3521 const ViewMsg_PostMessage_Params& params) {
3522 // Only deliver the message to the active RenderViewHost if the request
3523 // came from a RenderViewHost in the same BrowsingInstance or if this
3524 // WebContents is dedicated to a browser plugin guest.
3525 // Note: This check means that an embedder could theoretically receive a
3526 // postMessage from anyone (not just its own guests). However, this is
3527 // probably not a risk for apps since other pages won't have references
3528 // to App windows.
3529 if (!rvh->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()) &&
3530 !GetBrowserPluginGuest() && !GetBrowserPluginEmbedder())
3531 return;
3533 ViewMsg_PostMessage_Params new_params(params);
3535 if (!params.message_port_ids.empty()) {
3536 MessagePortMessageFilter* message_port_message_filter =
3537 static_cast<RenderProcessHostImpl*>(GetRenderProcessHost())
3538 ->message_port_message_filter();
3539 std::vector<int> new_routing_ids(params.message_port_ids.size());
3540 for (size_t i = 0; i < params.message_port_ids.size(); ++i) {
3541 new_routing_ids[i] = message_port_message_filter->GetNextRoutingID();
3542 MessagePortService::GetInstance()->UpdateMessagePort(
3543 params.message_port_ids[i],
3544 message_port_message_filter,
3545 new_routing_ids[i]);
3547 new_params.new_routing_ids = new_routing_ids;
3550 // If there is a source_routing_id, translate it to the routing ID for
3551 // the equivalent swapped out RVH in the target process. If we need
3552 // to create a swapped out RVH for the source tab, we create its opener
3553 // chain as well, since those will also be accessible to the target page.
3554 if (new_params.source_routing_id != MSG_ROUTING_NONE) {
3555 // Try to look up the WebContents for the source page.
3556 WebContentsImpl* source_contents = NULL;
3557 RenderViewHostImpl* source_rvh = RenderViewHostImpl::FromID(
3558 rvh->GetProcess()->GetID(), params.source_routing_id);
3559 if (source_rvh) {
3560 source_contents = static_cast<WebContentsImpl*>(
3561 source_rvh->GetDelegate()->GetAsWebContents());
3564 if (source_contents) {
3565 if (GetBrowserPluginGuest()) {
3566 // We create a swapped out RenderView for the embedder in the guest's
3567 // render process but we intentionally do not expose the embedder's
3568 // opener chain to it.
3569 new_params.source_routing_id =
3570 source_contents->CreateSwappedOutRenderView(GetSiteInstance());
3571 } else {
3572 new_params.source_routing_id =
3573 source_contents->CreateOpenerRenderViews(GetSiteInstance());
3575 } else {
3576 // We couldn't find it, so don't pass a source frame.
3577 new_params.source_routing_id = MSG_ROUTING_NONE;
3581 // In most cases, we receive this from a swapped out RenderViewHost.
3582 // It is possible to receive it from one that has just been swapped in,
3583 // in which case we might as well deliver the message anyway.
3584 Send(new ViewMsg_PostMessageEvent(GetRoutingID(), new_params));
3587 bool WebContentsImpl::AddMessageToConsole(int32 level,
3588 const base::string16& message,
3589 int32 line_no,
3590 const base::string16& source_id) {
3591 if (!delegate_)
3592 return false;
3593 return delegate_->AddMessageToConsole(this, level, message, line_no,
3594 source_id);
3597 WebPreferences WebContentsImpl::GetWebkitPrefs() {
3598 // We want to base the page config off of the actual URL, rather than the
3599 // virtual URL.
3600 // TODO(nasko): Investigate how to remove the GetActiveEntry usage here,
3601 // as it is deprecated and can be out of sync with GetRenderViewHost().
3602 GURL url = controller_.GetActiveEntry()
3603 ? controller_.GetActiveEntry()->GetURL() : GURL::EmptyGURL();
3605 return GetRenderManager()->current_host()->GetWebkitPrefs(url);
3608 int WebContentsImpl::CreateSwappedOutRenderView(
3609 SiteInstance* instance) {
3610 return GetRenderManager()->CreateRenderFrame(instance, MSG_ROUTING_NONE,
3611 true, true);
3614 void WebContentsImpl::OnUserGesture() {
3615 // Notify observers.
3616 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetUserGesture());
3618 ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
3619 if (rdh) // NULL in unittests.
3620 rdh->OnUserGesture(this);
3623 void WebContentsImpl::OnIgnoredUIEvent() {
3624 // Notify observers.
3625 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetIgnoredUIEvent());
3628 void WebContentsImpl::RendererUnresponsive(RenderViewHost* rvh,
3629 bool is_during_beforeunload,
3630 bool is_during_unload) {
3631 // Don't show hung renderer dialog for a swapped out RVH.
3632 if (rvh != GetRenderViewHost())
3633 return;
3635 RenderViewHostImpl* rvhi = static_cast<RenderViewHostImpl*>(rvh);
3637 // Ignore renderer unresponsive event if debugger is attached to the tab
3638 // since the event may be a result of the renderer sitting on a breakpoint.
3639 // See http://crbug.com/65458
3640 if (DevToolsAgentHost::IsDebuggerAttached(this))
3641 return;
3643 if (is_during_beforeunload || is_during_unload) {
3644 // Hang occurred while firing the beforeunload/unload handler.
3645 // Pretend the handler fired so tab closing continues as if it had.
3646 rvhi->set_sudden_termination_allowed(true);
3648 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
3649 return;
3651 // If the tab hangs in the beforeunload/unload handler there's really
3652 // nothing we can do to recover. If the hang is in the beforeunload handler,
3653 // pretend the beforeunload listeners have all fired and allow the delegate
3654 // to continue closing; the user will not have the option of cancelling the
3655 // close. Otherwise, pretend the unload listeners have all fired and close
3656 // the tab.
3657 bool close = true;
3658 if (is_during_beforeunload && delegate_) {
3659 delegate_->BeforeUnloadFired(this, true, &close);
3661 if (close)
3662 Close(rvh);
3663 return;
3666 if (!GetRenderViewHostImpl() || !GetRenderViewHostImpl()->IsRenderViewLive())
3667 return;
3669 if (delegate_)
3670 delegate_->RendererUnresponsive(this);
3673 void WebContentsImpl::RendererResponsive(RenderViewHost* render_view_host) {
3674 if (delegate_)
3675 delegate_->RendererResponsive(this);
3678 void WebContentsImpl::LoadStateChanged(
3679 const GURL& url,
3680 const net::LoadStateWithParam& load_state,
3681 uint64 upload_position,
3682 uint64 upload_size) {
3683 load_state_ = load_state;
3684 upload_position_ = upload_position;
3685 upload_size_ = upload_size;
3686 load_state_host_ = net::IDNToUnicode(url.host(),
3687 GetContentClient()->browser()->GetAcceptLangs(
3688 GetBrowserContext()));
3689 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
3690 SetNotWaitingForResponse();
3691 if (IsLoading()) {
3692 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB);
3696 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
3697 bool proceed, const base::TimeTicks& proceed_time,
3698 bool* proceed_to_fire_unload) {
3699 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3700 BeforeUnloadFired(proceed_time));
3701 if (delegate_)
3702 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
3703 // Note: |this| might be deleted at this point.
3706 void WebContentsImpl::RenderProcessGoneFromRenderManager(
3707 RenderViewHost* render_view_host) {
3708 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
3709 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
3712 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
3713 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
3714 gfx::Size size = GetSizeForNewRenderView();
3715 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
3716 // here during container initialization and normal window size will be set
3717 // later. In case of tab duplication this resizing to 0x0 prevents setting
3718 // normal size later so just ignore it.
3719 if (!size.IsEmpty())
3720 view_->SizeContents(size);
3723 void WebContentsImpl::CancelModalDialogsForRenderManager() {
3724 // We need to cancel modal dialogs when doing a process swap, since the load
3725 // deferrer would prevent us from swapping out.
3726 if (dialog_manager_)
3727 dialog_manager_->CancelActiveAndPendingDialogs(this);
3730 void WebContentsImpl::NotifySwappedFromRenderManager(RenderViewHost* old_host,
3731 RenderViewHost* new_host) {
3732 NotifySwapped(old_host, new_host);
3734 // Make sure the visible RVH reflects the new delegate's preferences.
3735 if (delegate_)
3736 view_->SetOverscrollControllerEnabled(delegate_->CanOverscrollContent());
3738 view_->RenderViewSwappedIn(new_host);
3741 int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
3742 SiteInstance* instance) {
3743 if (!opener_)
3744 return MSG_ROUTING_NONE;
3746 // Recursively create RenderViews for anything else in the opener chain.
3747 return opener_->CreateOpenerRenderViews(instance);
3750 int WebContentsImpl::CreateOpenerRenderViews(SiteInstance* instance) {
3751 int opener_route_id = MSG_ROUTING_NONE;
3753 // If this tab has an opener, ensure it has a RenderView in the given
3754 // SiteInstance as well.
3755 if (opener_)
3756 opener_route_id = opener_->CreateOpenerRenderViews(instance);
3758 // If any of the renderers (current, pending, or swapped out) for this
3759 // WebContents has the same SiteInstance, use it.
3760 if (GetRenderManager()->current_host()->GetSiteInstance() == instance)
3761 return GetRenderManager()->current_host()->GetRoutingID();
3763 if (GetRenderManager()->pending_render_view_host() &&
3764 GetRenderManager()->pending_render_view_host()->GetSiteInstance() ==
3765 instance)
3766 return GetRenderManager()->pending_render_view_host()->GetRoutingID();
3768 RenderViewHostImpl* rvh = GetRenderManager()->GetSwappedOutRenderViewHost(
3769 instance);
3770 if (rvh)
3771 return rvh->GetRoutingID();
3773 // Create a swapped out RenderView in the given SiteInstance if none exists,
3774 // setting its opener to the given route_id. Return the new view's route_id.
3775 return GetRenderManager()->CreateRenderFrame(instance, opener_route_id,
3776 true, true);
3779 NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
3780 return GetController();
3783 WebUIImpl* WebContentsImpl::CreateWebUIForRenderManager(const GURL& url) {
3784 return static_cast<WebUIImpl*>(CreateWebUI(url));
3787 NavigationEntry*
3788 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
3789 return controller_.GetLastCommittedEntry();
3792 bool WebContentsImpl::CreateRenderViewForRenderManager(
3793 RenderViewHost* render_view_host,
3794 int opener_route_id,
3795 CrossProcessFrameConnector* frame_connector) {
3796 TRACE_EVENT0("browser", "WebContentsImpl::CreateRenderViewForRenderManager");
3797 // Can be NULL during tests.
3798 RenderWidgetHostViewBase* rwh_view;
3799 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
3800 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
3801 // case this because RWH is still a base class of RenderViewHost, and child
3802 // frame RWHVs are unique in that they do not have their own WebContents.
3803 if (frame_connector) {
3804 RenderWidgetHostViewChildFrame* rwh_view_child =
3805 new RenderWidgetHostViewChildFrame(render_view_host);
3806 frame_connector->set_view(rwh_view_child);
3807 rwh_view = rwh_view_child;
3808 } else {
3809 rwh_view = view_->CreateViewForWidget(render_view_host);
3812 // Now that the RenderView has been created, we need to tell it its size.
3813 if (rwh_view)
3814 rwh_view->SetSize(GetSizeForNewRenderView());
3816 // Make sure we use the correct starting page_id in the new RenderView.
3817 UpdateMaxPageIDIfNecessary(render_view_host);
3818 int32 max_page_id =
3819 GetMaxPageIDForSiteInstance(render_view_host->GetSiteInstance());
3821 if (!static_cast<RenderViewHostImpl*>(
3822 render_view_host)->CreateRenderView(base::string16(),
3823 opener_route_id,
3824 max_page_id,
3825 created_with_opener_)) {
3826 return false;
3829 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
3830 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
3831 // linux. See crbug.com/83941.
3832 if (rwh_view) {
3833 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
3834 render_widget_host->WasResized();
3836 #endif
3838 return true;
3841 #if defined(OS_ANDROID)
3843 base::android::ScopedJavaLocalRef<jobject>
3844 WebContentsImpl::GetJavaWebContents() {
3845 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
3847 WebContentsAndroid* web_contents_android =
3848 static_cast<WebContentsAndroid*>(GetUserData(kWebContentsAndroidKey));
3849 if (!web_contents_android) {
3850 web_contents_android = new WebContentsAndroid(this);
3851 SetUserData(kWebContentsAndroidKey, web_contents_android);
3853 return web_contents_android->GetJavaObject();
3856 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
3857 return CreateRenderViewForRenderManager(GetRenderViewHost(),
3858 MSG_ROUTING_NONE,
3859 NULL);
3862 #elif defined(OS_MACOSX)
3864 void WebContentsImpl::SetAllowOverlappingViews(bool overlapping) {
3865 view_->SetAllowOverlappingViews(overlapping);
3868 bool WebContentsImpl::GetAllowOverlappingViews() {
3869 return view_->GetAllowOverlappingViews();
3872 void WebContentsImpl::SetOverlayView(WebContents* overlay,
3873 const gfx::Point& offset) {
3874 view_->SetOverlayView(static_cast<WebContentsImpl*>(overlay)->GetView(),
3875 offset);
3878 void WebContentsImpl::RemoveOverlayView() {
3879 view_->RemoveOverlayView();
3882 #endif
3884 void WebContentsImpl::OnDialogClosed(int render_process_id,
3885 int render_frame_id,
3886 IPC::Message* reply_msg,
3887 bool dialog_was_suppressed,
3888 bool success,
3889 const base::string16& user_input) {
3890 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
3891 render_frame_id);
3892 last_dialog_suppressed_ = dialog_was_suppressed;
3894 if (is_showing_before_unload_dialog_ && !success) {
3895 // If a beforeunload dialog is canceled, we need to stop the throbber from
3896 // spinning, since we forced it to start spinning in Navigate.
3897 if (rfh)
3898 DidStopLoading(rfh);
3899 controller_.DiscardNonCommittedEntries();
3901 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3902 BeforeUnloadDialogCancelled());
3905 is_showing_before_unload_dialog_ = false;
3906 if (rfh) {
3907 rfh->JavaScriptDialogClosed(reply_msg, success, user_input,
3908 dialog_was_suppressed);
3909 } else {
3910 // Don't leak the sync IPC reply if the RFH or process is gone.
3911 delete reply_msg;
3915 void WebContentsImpl::SetEncoding(const std::string& encoding) {
3916 encoding_ = GetContentClient()->browser()->
3917 GetCanonicalEncodingNameByAliasName(encoding);
3920 void WebContentsImpl::CreateViewAndSetSizeForRVH(RenderViewHost* rvh) {
3921 RenderWidgetHostViewBase* rwh_view = view_->CreateViewForWidget(rvh);
3922 // Can be NULL during tests.
3923 if (rwh_view)
3924 rwh_view->SetSize(GetContainerBounds().size());
3927 bool WebContentsImpl::IsHidden() {
3928 return capturer_count_ == 0 && !should_normally_be_visible_;
3931 RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
3932 return frame_tree_.root()->render_manager();
3935 RenderViewHostImpl* WebContentsImpl::GetRenderViewHostImpl() {
3936 return static_cast<RenderViewHostImpl*>(GetRenderViewHost());
3939 BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
3940 return browser_plugin_guest_.get();
3943 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest* guest) {
3944 CHECK(!browser_plugin_guest_);
3945 browser_plugin_guest_.reset(guest);
3948 BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
3949 return browser_plugin_embedder_.get();
3952 void WebContentsImpl::ClearPowerSaveBlockers(
3953 RenderFrameHost* render_frame_host) {
3954 STLDeleteValues(&power_save_blockers_[render_frame_host]);
3955 power_save_blockers_.erase(render_frame_host);
3958 void WebContentsImpl::ClearAllPowerSaveBlockers() {
3959 for (PowerSaveBlockerMap::iterator i(power_save_blockers_.begin());
3960 i != power_save_blockers_.end(); ++i)
3961 STLDeleteValues(&power_save_blockers_[i->first]);
3962 power_save_blockers_.clear();
3965 gfx::Size WebContentsImpl::GetSizeForNewRenderView() {
3966 gfx::Size size;
3967 if (delegate_)
3968 size = delegate_->GetSizeForNewRenderView(this);
3969 if (size.IsEmpty())
3970 size = GetContainerBounds().size();
3971 return size;
3974 void WebContentsImpl::OnFrameRemoved(
3975 RenderViewHostImpl* render_view_host,
3976 int frame_routing_id) {
3977 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
3978 FrameDetached(render_view_host, frame_routing_id));
3981 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
3982 if (!delegate_)
3983 return;
3984 const gfx::Size new_size = GetPreferredSize();
3985 if (new_size != old_size)
3986 delegate_->UpdatePreferredSize(this, new_size);
3989 } // namespace content