Saving content will prefer to retrieve the data out of the HTTP cache for GETs.
[chromium-blink-merge.git] / content / browser / tab_contents / tab_contents.cc
blobaccc5649113ad57a45959c16e0ea6277de56a4ff
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/tab_contents/tab_contents.h"
7 #include <cmath>
9 #include "base/command_line.h"
10 #include "base/metrics/histogram.h"
11 #include "base/metrics/stats_counters.h"
12 #include "base/string16.h"
13 #include "base/string_util.h"
14 #include "base/time.h"
15 #include "base/utf_string_conversions.h"
16 #include "content/browser/child_process_security_policy.h"
17 #include "content/browser/debugger/devtools_manager_impl.h"
18 #include "content/browser/download/download_stats.h"
19 #include "content/browser/download/save_package.h"
20 #include "content/browser/host_zoom_map.h"
21 #include "content/browser/in_process_webkit/session_storage_namespace.h"
22 #include "content/browser/intents/web_intents_dispatcher_impl.h"
23 #include "content/browser/load_from_memory_cache_details.h"
24 #include "content/browser/load_notification_details.h"
25 #include "content/browser/renderer_host/render_process_host_impl.h"
26 #include "content/browser/renderer_host/render_view_host.h"
27 #include "content/browser/renderer_host/render_widget_host_view.h"
28 #include "content/browser/renderer_host/resource_dispatcher_host.h"
29 #include "content/browser/renderer_host/resource_request_details.h"
30 #include "content/browser/site_instance_impl.h"
31 #include "content/browser/tab_contents/interstitial_page.h"
32 #include "content/browser/tab_contents/navigation_entry_impl.h"
33 #include "content/browser/tab_contents/provisional_load_details.h"
34 #include "content/browser/tab_contents/title_updated_details.h"
35 #include "content/browser/webui/web_ui_impl.h"
36 #include "content/common/intents_messages.h"
37 #include "content/common/view_messages.h"
38 #include "content/public/browser/browser_context.h"
39 #include "content/public/browser/content_browser_client.h"
40 #include "content/public/browser/devtools_agent_host_registry.h"
41 #include "content/public/browser/download_manager.h"
42 #include "content/public/browser/invalidate_type.h"
43 #include "content/public/browser/navigation_details.h"
44 #include "content/public/browser/notification_service.h"
45 #include "content/public/browser/user_metrics.h"
46 #include "content/public/browser/web_contents_delegate.h"
47 #include "content/public/browser/web_contents_observer.h"
48 #include "content/public/browser/web_contents_view.h"
49 #include "content/public/browser/web_ui_controller_factory.h"
50 #include "content/public/common/bindings_policy.h"
51 #include "content/public/common/content_constants.h"
52 #include "content/public/common/content_restriction.h"
53 #include "content/public/common/url_constants.h"
54 #include "net/base/mime_util.h"
55 #include "net/base/net_util.h"
56 #include "net/url_request/url_request_context_getter.h"
57 #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
58 #include "ui/gfx/codec/png_codec.h"
59 #include "webkit/glue/web_intent_data.h"
60 #include "webkit/glue/webpreferences.h"
62 #if defined(OS_MACOSX)
63 #include "ui/gfx/surface/io_surface_support_mac.h"
64 #endif // defined(OS_MACOSX)
66 // Cross-Site Navigations
68 // If a TabContents is told to navigate to a different web site (as determined
69 // by SiteInstance), it will replace its current RenderViewHost with a new
70 // RenderViewHost dedicated to the new SiteInstance. This works as follows:
72 // - Navigate determines whether the destination is cross-site, and if so,
73 // it creates a pending_render_view_host_.
74 // - The pending RVH is "suspended," so that no navigation messages are sent to
75 // its renderer until the onbeforeunload JavaScript handler has a chance to
76 // run in the current RVH.
77 // - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
78 // that it has a pending cross-site request. ResourceDispatcherHost will
79 // check for this when the response arrives.
80 // - The current RVH runs its onbeforeunload handler. If it returns false, we
81 // cancel all the pending logic. Otherwise we allow the pending RVH to send
82 // the navigation request to its renderer.
83 // - ResourceDispatcherHost receives a ResourceRequest on the IO thread for the
84 // main resource load on the pending RVH. It checks CrossSiteRequestManager
85 // to see that it is a cross-site request, and installs a
86 // CrossSiteResourceHandler.
87 // - When RDH receives a response, the BufferedResourceHandler determines
88 // whether it is a download. If so, it sends a message to the new renderer
89 // causing it to cancel the request, and the download proceeds. For now, the
90 // pending RVH remains until the next DidNavigate event for this TabContents.
91 // This isn't ideal, but it doesn't affect any functionality.
92 // - After RDH receives a response and determines that it is safe and not a
93 // download, it pauses the response to first run the old page's onunload
94 // handler. It does this by asynchronously calling the OnCrossSiteResponse
95 // method of TabContents on the UI thread, which sends a SwapOut message
96 // to the current RVH.
97 // - Once the onunload handler is finished, a SwapOut_ACK message is sent to
98 // the ResourceDispatcherHost, who unpauses the response. Data is then sent
99 // to the pending RVH.
100 // - The pending renderer sends a FrameNavigate message that invokes the
101 // DidNavigate method. This replaces the current RVH with the
102 // pending RVH.
103 // - The previous renderer is kept swapped out in RenderViewHostManager in case
104 // the user goes back. The process only stays live if another tab is using
105 // it, but if so, the existing frame relationships will be maintained.
107 using content::DevToolsAgentHost;
108 using content::DevToolsAgentHostRegistry;
109 using content::DevToolsManagerImpl;
110 using content::DownloadItem;
111 using content::DownloadManager;
112 using content::GlobalRequestID;
113 using content::NavigationController;
114 using content::NavigationEntry;
115 using content::NavigationEntryImpl;
116 using content::OpenURLParams;
117 using content::RenderViewHostDelegate;
118 using content::SiteInstance;
119 using content::SSLStatus;
120 using content::UserMetricsAction;
121 using content::WebContents;
122 using content::WebContentsObserver;
123 using content::WebUI;
124 using content::WebUIController;
125 using content::WebUIControllerFactory;
127 namespace {
129 // Amount of time we wait between when a key event is received and the renderer
130 // is queried for its state and pushed to the NavigationEntry.
131 const int kQueryStateDelay = 5000;
133 const int kSyncWaitDelay = 40;
135 static const char kDotGoogleDotCom[] = ".google.com";
137 #if defined(OS_WIN)
139 BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
140 // Note: erase is required to properly paint some widgets borders. This can
141 // be seen with textfields.
142 InvalidateRect(hwnd, NULL, TRUE);
143 return TRUE;
145 #endif
147 ViewMsg_Navigate_Type::Value GetNavigationType(
148 content::BrowserContext* browser_context, const NavigationEntryImpl& entry,
149 NavigationController::ReloadType reload_type) {
150 switch (reload_type) {
151 case NavigationControllerImpl::RELOAD:
152 return ViewMsg_Navigate_Type::RELOAD;
153 case NavigationControllerImpl::RELOAD_IGNORING_CACHE:
154 return ViewMsg_Navigate_Type::RELOAD_IGNORING_CACHE;
155 case NavigationControllerImpl::NO_RELOAD:
156 break; // Fall through to rest of function.
159 if (entry.restore_type() == NavigationEntryImpl::RESTORE_LAST_SESSION &&
160 browser_context->DidLastSessionExitCleanly())
161 return ViewMsg_Navigate_Type::RESTORE;
163 return ViewMsg_Navigate_Type::NORMAL;
166 void MakeNavigateParams(const NavigationEntryImpl& entry,
167 const NavigationControllerImpl& controller,
168 content::WebContentsDelegate* delegate,
169 NavigationController::ReloadType reload_type,
170 ViewMsg_Navigate_Params* params) {
171 params->page_id = entry.GetPageID();
172 params->pending_history_list_offset = controller.GetIndexOfEntry(&entry);
173 params->current_history_list_offset = controller.GetLastCommittedEntryIndex();
174 params->current_history_list_length = controller.GetEntryCount();
175 params->url = entry.GetURL();
176 params->referrer = entry.GetReferrer();
177 params->transition = entry.GetTransitionType();
178 params->state = entry.GetContentState();
179 params->navigation_type =
180 GetNavigationType(controller.GetBrowserContext(), entry, reload_type);
181 params->request_time = base::Time::Now();
182 params->extra_headers = entry.extra_headers();
183 params->transferred_request_child_id =
184 entry.transferred_global_request_id().child_id;
185 params->transferred_request_request_id =
186 entry.transferred_global_request_id().request_id;
188 if (delegate)
189 delegate->AddNavigationHeaders(params->url, &params->extra_headers);
192 } // namespace
194 namespace content {
196 WebContents* WebContents::Create(
197 BrowserContext* browser_context,
198 SiteInstance* site_instance,
199 int routing_id,
200 const WebContents* base_tab_contents,
201 SessionStorageNamespace* session_storage_namespace) {
202 return new TabContents(browser_context,
203 site_instance,
204 routing_id,
205 static_cast<const TabContents*>(base_tab_contents),
206 session_storage_namespace);
210 // TabContents ----------------------------------------------------------------
212 TabContents::TabContents(content::BrowserContext* browser_context,
213 SiteInstance* site_instance,
214 int routing_id,
215 const TabContents* base_tab_contents,
216 SessionStorageNamespace* session_storage_namespace)
217 : delegate_(NULL),
218 ALLOW_THIS_IN_INITIALIZER_LIST(controller_(
219 this, browser_context, session_storage_namespace)),
220 ALLOW_THIS_IN_INITIALIZER_LIST(view_(
221 content::GetContentClient()->browser()->CreateWebContentsView(this))),
222 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(this, this)),
223 is_loading_(false),
224 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
225 crashed_error_code_(0),
226 waiting_for_response_(false),
227 load_state_(net::LOAD_STATE_IDLE, string16()),
228 upload_size_(0),
229 upload_position_(0),
230 displayed_insecure_content_(false),
231 capturing_contents_(false),
232 is_being_destroyed_(false),
233 notify_disconnection_(false),
234 dialog_creator_(NULL),
235 #if defined(OS_WIN)
236 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
237 #endif
238 is_showing_before_unload_dialog_(false),
239 opener_web_ui_type_(WebUI::kNoWebUI),
240 closed_by_user_gesture_(false),
241 minimum_zoom_percent_(
242 static_cast<int>(content::kMinimumZoomFactor * 100)),
243 maximum_zoom_percent_(
244 static_cast<int>(content::kMaximumZoomFactor * 100)),
245 temporary_zoom_settings_(false),
246 content_restrictions_(0),
247 view_type_(content::VIEW_TYPE_TAB_CONTENTS) {
248 render_manager_.Init(browser_context, site_instance, routing_id);
250 // We have the initial size of the view be based on the size of the passed in
251 // tab contents (normally a tab from the same window).
252 view_->CreateView(base_tab_contents ?
253 base_tab_contents->GetView()->GetContainerSize() : gfx::Size());
255 #if defined(ENABLE_JAVA_BRIDGE)
256 java_bridge_dispatcher_host_manager_.reset(
257 new JavaBridgeDispatcherHostManager(this));
258 #endif
261 TabContents::~TabContents() {
262 is_being_destroyed_ = true;
264 // Clear out any JavaScript state.
265 if (dialog_creator_)
266 dialog_creator_->ResetJavaScriptState(this);
268 NotifyDisconnected();
270 // Notify any observer that have a reference on this tab contents.
271 content::NotificationService::current()->Notify(
272 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
273 content::Source<WebContents>(this),
274 content::NotificationService::NoDetails());
276 // TODO(brettw) this should be moved to the view.
277 #if defined(OS_WIN) && !defined(USE_AURA)
278 // If we still have a window handle, destroy it. GetNativeView can return
279 // NULL if this contents was part of a window that closed.
280 if (GetNativeView()) {
281 RenderViewHost* host = GetRenderViewHost();
282 if (host && host->view())
283 host->view()->WillWmDestroy();
285 #endif
287 // OnCloseStarted isn't called in unit tests.
288 if (!tab_close_start_time_.is_null()) {
289 UMA_HISTOGRAM_TIMES("Tab.Close",
290 base::TimeTicks::Now() - tab_close_start_time_);
293 FOR_EACH_OBSERVER(WebContentsObserver, observers_, TabContentsDestroyed());
295 SetDelegate(NULL);
298 NavigationControllerImpl& TabContents::GetControllerImpl() {
299 return controller_;
302 RenderViewHostManager* TabContents::GetRenderManagerForTesting() {
303 return &render_manager_;
306 bool TabContents::OnMessageReceived(const IPC::Message& message) {
307 if (GetWebUI() &&
308 static_cast<WebUIImpl*>(GetWebUI())->OnMessageReceived(message)) {
309 return true;
312 ObserverListBase<WebContentsObserver>::Iterator it(observers_);
313 WebContentsObserver* observer;
314 while ((observer = it.GetNext()) != NULL)
315 if (observer->OnMessageReceived(message))
316 return true;
318 bool handled = true;
319 bool message_is_ok = true;
320 IPC_BEGIN_MESSAGE_MAP_EX(TabContents, message, message_is_ok)
321 IPC_MESSAGE_HANDLER(IntentsHostMsg_RegisterIntentService,
322 OnRegisterIntentService)
323 IPC_MESSAGE_HANDLER(IntentsHostMsg_WebIntentDispatch,
324 OnWebIntentDispatch)
325 IPC_MESSAGE_HANDLER(ViewHostMsg_DidStartProvisionalLoadForFrame,
326 OnDidStartProvisionalLoadForFrame)
327 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRedirectProvisionalLoad,
328 OnDidRedirectProvisionalLoad)
329 IPC_MESSAGE_HANDLER(ViewHostMsg_DidFailProvisionalLoadWithError,
330 OnDidFailProvisionalLoadWithError)
331 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache,
332 OnDidLoadResourceFromMemoryCache)
333 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent,
334 OnDidDisplayInsecureContent)
335 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent,
336 OnDidRunInsecureContent)
337 IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentLoadedInFrame,
338 OnDocumentLoadedInFrame)
339 IPC_MESSAGE_HANDLER(ViewHostMsg_DidFinishLoad, OnDidFinishLoad)
340 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateContentRestrictions,
341 OnUpdateContentRestrictions)
342 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset)
343 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits, OnUpdateZoomLimits)
344 IPC_MESSAGE_HANDLER(ViewHostMsg_SaveURLAs, OnSaveURL)
345 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory, OnEnumerateDirectory)
346 IPC_MESSAGE_HANDLER(ViewHostMsg_JSOutOfMemory, OnJSOutOfMemory)
347 IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler,
348 OnRegisterProtocolHandler)
349 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply, OnFindReply)
350 IPC_MESSAGE_HANDLER(ViewHostMsg_CrashedPlugin, OnCrashedPlugin)
351 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed, OnAppCacheAccessed)
352 IPC_MESSAGE_UNHANDLED(handled = false)
353 IPC_END_MESSAGE_MAP_EX()
355 if (!message_is_ok) {
356 content::RecordAction(UserMetricsAction("BadMessageTerminate_RVD"));
357 GetRenderProcessHost()->ReceivedBadMessage();
360 return handled;
363 void TabContents::RunFileChooser(
364 RenderViewHost* render_view_host,
365 const content::FileChooserParams& params) {
366 delegate_->RunFileChooser(this, params);
369 NavigationController& TabContents::GetController() {
370 return controller_;
373 const NavigationController& TabContents::GetController() const {
374 return controller_;
377 content::BrowserContext* TabContents::GetBrowserContext() const {
378 return controller_.GetBrowserContext();
381 void TabContents::SetViewType(content::ViewType type) {
382 view_type_ = type;
385 content::ViewType TabContents::GetViewType() const {
386 return view_type_;
389 const GURL& TabContents::GetURL() const {
390 // We may not have a navigation entry yet
391 NavigationEntry* entry = controller_.GetActiveEntry();
392 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
396 const base::PropertyBag* TabContents::GetPropertyBag() const {
397 return &property_bag_;
400 base::PropertyBag* TabContents::GetPropertyBag() {
401 return &property_bag_;
404 content::WebContentsDelegate* TabContents::GetDelegate() {
405 return delegate_;
408 void TabContents::SetDelegate(content::WebContentsDelegate* delegate) {
409 // TODO(cbentzel): remove this debugging code?
410 if (delegate == delegate_)
411 return;
412 if (delegate_)
413 delegate_->Detach(this);
414 delegate_ = delegate;
415 if (delegate_)
416 delegate_->Attach(this);
419 content::RenderProcessHost* TabContents::GetRenderProcessHost() const {
420 if (render_manager_.current_host())
421 return render_manager_.current_host()->process();
422 else
423 return NULL;
426 RenderViewHost* TabContents::GetRenderViewHost() const {
427 return render_manager_.current_host();
430 RenderWidgetHostView* TabContents::GetRenderWidgetHostView() const {
431 return render_manager_.GetRenderWidgetHostView();
434 content::WebContentsView* TabContents::GetView() const {
435 return view_.get();
438 content::WebUI* TabContents::CreateWebUI(const GURL& url) {
439 WebUIControllerFactory* factory =
440 content::GetContentClient()->browser()->GetWebUIControllerFactory();
441 if (!factory)
442 return NULL;
443 WebUIImpl* web_ui = new WebUIImpl(this);
444 WebUIController* controller =
445 factory->CreateWebUIControllerForURL(web_ui, url);
446 if (controller) {
447 web_ui->SetController(controller);
448 return web_ui;
451 delete web_ui;
452 return NULL;
455 content::WebUI* TabContents::GetWebUI() const {
456 return render_manager_.web_ui() ? render_manager_.web_ui()
457 : render_manager_.pending_web_ui();
460 content::WebUI* TabContents::GetCommittedWebUI() const {
461 return render_manager_.web_ui();
464 const string16& TabContents::GetTitle() const {
465 // Transient entries take precedence. They are used for interstitial pages
466 // that are shown on top of existing pages.
467 NavigationEntry* entry = controller_.GetTransientEntry();
468 std::string accept_languages =
469 content::GetContentClient()->browser()->GetAcceptLangs(
470 GetBrowserContext());
471 if (entry) {
472 return entry->GetTitleForDisplay(accept_languages);
474 WebUI* our_web_ui = render_manager_.pending_web_ui() ?
475 render_manager_.pending_web_ui() : render_manager_.web_ui();
476 if (our_web_ui) {
477 // Don't override the title in view source mode.
478 entry = controller_.GetActiveEntry();
479 if (!(entry && entry->IsViewSourceMode())) {
480 // Give the Web UI the chance to override our title.
481 const string16& title = our_web_ui->GetOverriddenTitle();
482 if (!title.empty())
483 return title;
487 // We use the title for the last committed entry rather than a pending
488 // navigation entry. For example, when the user types in a URL, we want to
489 // keep the old page's title until the new load has committed and we get a new
490 // title.
491 entry = controller_.GetLastCommittedEntry();
492 if (entry) {
493 return entry->GetTitleForDisplay(accept_languages);
496 // |page_title_when_no_navigation_entry_| is finally used
497 // if no title cannot be retrieved.
498 return page_title_when_no_navigation_entry_;
501 int32 TabContents::GetMaxPageID() {
502 return GetMaxPageIDForSiteInstance(GetSiteInstance());
505 int32 TabContents::GetMaxPageIDForSiteInstance(SiteInstance* site_instance) {
506 if (max_page_ids_.find(site_instance->GetId()) == max_page_ids_.end())
507 max_page_ids_[site_instance->GetId()] = -1;
509 return max_page_ids_[site_instance->GetId()];
512 void TabContents::UpdateMaxPageID(int32 page_id) {
513 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id);
516 void TabContents::UpdateMaxPageIDForSiteInstance(
517 SiteInstance* site_instance, int32 page_id) {
518 if (GetMaxPageIDForSiteInstance(site_instance) < page_id)
519 max_page_ids_[site_instance->GetId()] = page_id;
522 void TabContents::CopyMaxPageIDsFrom(TabContents* tab_contents) {
523 max_page_ids_ = tab_contents->max_page_ids_;
526 SiteInstance* TabContents::GetSiteInstance() const {
527 return render_manager_.current_host()->site_instance();
530 SiteInstance* TabContents::GetPendingSiteInstance() const {
531 RenderViewHost* dest_rvh = render_manager_.pending_render_view_host() ?
532 render_manager_.pending_render_view_host() :
533 render_manager_.current_host();
534 return dest_rvh->site_instance();
537 bool TabContents::IsLoading() const {
538 return is_loading_;
541 bool TabContents::IsWaitingForResponse() const {
542 return waiting_for_response_;
545 const net::LoadStateWithParam& TabContents::GetLoadState() const {
546 return load_state_;
549 const string16& TabContents::GetLoadStateHost() const {
550 return load_state_host_;
553 uint64 TabContents::GetUploadSize() const {
554 return upload_size_;
557 uint64 TabContents::GetUploadPosition() const {
558 return upload_position_;
561 const std::string& TabContents::GetEncoding() const {
562 return encoding_;
565 bool TabContents::DisplayedInsecureContent() const {
566 return displayed_insecure_content_;
569 void TabContents::SetCapturingContents(bool cap) {
570 capturing_contents_ = cap;
573 bool TabContents::IsCrashed() const {
574 return (crashed_status_ == base::TERMINATION_STATUS_PROCESS_CRASHED ||
575 crashed_status_ == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
576 crashed_status_ == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
579 void TabContents::SetIsCrashed(base::TerminationStatus status, int error_code) {
580 if (status == crashed_status_)
581 return;
583 crashed_status_ = status;
584 crashed_error_code_ = error_code;
585 NotifyNavigationStateChanged(content::INVALIDATE_TYPE_TAB);
588 base::TerminationStatus TabContents::GetCrashedStatus() const {
589 return crashed_status_;
592 bool TabContents::IsBeingDestroyed() const {
593 return is_being_destroyed_;
596 void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
597 if (delegate_)
598 delegate_->NavigationStateChanged(this, changed_flags);
601 void TabContents::DidBecomeSelected() {
602 controller_.SetActive(true);
603 RenderWidgetHostView* rwhv = GetRenderWidgetHostView();
604 if (rwhv) {
605 rwhv->DidBecomeSelected();
606 #if defined(OS_MACOSX)
607 rwhv->SetActive(true);
608 #endif
611 last_selected_time_ = base::TimeTicks::Now();
613 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidBecomeSelected());
617 base::TimeTicks TabContents::GetLastSelectedTime() const {
618 return last_selected_time_;
621 void TabContents::WasHidden() {
622 if (!capturing_contents_) {
623 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
624 // open a tab in then background, then closes the tab before selecting it.
625 // This is because closing the tab calls TabContents::Destroy(), which
626 // removes the |GetRenderViewHost()|; then when we actually destroy the
627 // window, OnWindowPosChanged() notices and calls HideContents() (which
628 // calls us).
629 RenderWidgetHostView* rwhv = GetRenderWidgetHostView();
630 if (rwhv)
631 rwhv->WasHidden();
634 content::NotificationService::current()->Notify(
635 content::NOTIFICATION_WEB_CONTENTS_HIDDEN,
636 content::Source<WebContents>(this),
637 content::NotificationService::NoDetails());
640 void TabContents::ShowContents() {
641 RenderWidgetHostView* rwhv = GetRenderWidgetHostView();
642 if (rwhv)
643 rwhv->DidBecomeSelected();
646 void TabContents::HideContents() {
647 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
648 // our superclass HideContents(), because some callers want to be very picky
649 // about the order in which these get called. In addition to making the code
650 // here practically impossible to understand, this also means we end up
651 // calling TabContents::WasHidden() twice if callers call both versions of
652 // HideContents() on a TabContents.
653 WasHidden();
656 bool TabContents::NeedToFireBeforeUnload() {
657 // TODO(creis): Should we fire even for interstitial pages?
658 return WillNotifyDisconnection() &&
659 !ShowingInterstitialPage() &&
660 !GetRenderViewHost()->SuddenTerminationAllowed();
663 void TabContents::Stop() {
664 render_manager_.Stop();
665 FOR_EACH_OBSERVER(WebContentsObserver, observers_, StopNavigation());
668 WebContents* TabContents::Clone() {
669 // We create a new SiteInstance so that the new tab won't share processes
670 // with the old one. This can be changed in the future if we need it to share
671 // processes for some reason.
672 TabContents* tc = new TabContents(
673 GetBrowserContext(),
674 SiteInstance::Create(GetBrowserContext()),
675 MSG_ROUTING_NONE, this, NULL);
676 tc->GetControllerImpl().CopyStateFrom(controller_);
677 return tc;
680 void TabContents::ShowPageInfo(const GURL& url,
681 const SSLStatus& ssl,
682 bool show_history) {
683 if (!delegate_)
684 return;
686 delegate_->ShowPageInfo(GetBrowserContext(), url, ssl, show_history);
689 void TabContents::AddNewContents(WebContents* new_contents,
690 WindowOpenDisposition disposition,
691 const gfx::Rect& initial_pos,
692 bool user_gesture) {
693 if (!delegate_)
694 return;
696 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
697 user_gesture);
700 gfx::NativeView TabContents::GetContentNativeView() const {
701 return view_->GetContentNativeView();
704 gfx::NativeView TabContents::GetNativeView() const {
705 return view_->GetNativeView();
708 void TabContents::GetContainerBounds(gfx::Rect* out) const {
709 view_->GetContainerBounds(out);
712 void TabContents::Focus() {
713 view_->Focus();
716 void TabContents::AddObserver(WebContentsObserver* observer) {
717 observers_.AddObserver(observer);
720 void TabContents::RemoveObserver(WebContentsObserver* observer) {
721 observers_.RemoveObserver(observer);
724 void TabContents::Activate() {
725 if (delegate_)
726 delegate_->ActivateContents(this);
729 void TabContents::Deactivate() {
730 if (delegate_)
731 delegate_->DeactivateContents(this);
734 void TabContents::LostCapture() {
735 if (delegate_)
736 delegate_->LostCapture();
739 bool TabContents::PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event,
740 bool* is_keyboard_shortcut) {
741 return delegate_ &&
742 delegate_->PreHandleKeyboardEvent(event, is_keyboard_shortcut);
745 void TabContents::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
746 if (delegate_)
747 delegate_->HandleKeyboardEvent(event);
750 void TabContents::HandleMouseDown() {
751 if (delegate_)
752 delegate_->HandleMouseDown();
755 void TabContents::HandleMouseUp() {
756 if (delegate_)
757 delegate_->HandleMouseUp();
760 void TabContents::HandleMouseActivate() {
761 if (delegate_)
762 delegate_->HandleMouseActivate();
765 void TabContents::ToggleFullscreenMode(bool enter_fullscreen) {
766 if (delegate_)
767 delegate_->ToggleFullscreenModeForTab(this, enter_fullscreen);
770 bool TabContents::IsFullscreenForCurrentTab() const {
771 return delegate_ ? delegate_->IsFullscreenForTab(this) : false;
774 void TabContents::RequestToLockMouse() {
775 if (delegate_) {
776 delegate_->RequestToLockMouse(this);
777 } else {
778 GotResponseToLockMouseRequest(false);
782 void TabContents::LostMouseLock() {
783 if (delegate_)
784 delegate_->LostMouseLock();
787 void TabContents::UpdatePreferredSize(const gfx::Size& pref_size) {
788 preferred_size_ = pref_size;
789 if (delegate_)
790 delegate_->UpdatePreferredSize(this, pref_size);
793 void TabContents::WebUISend(RenderViewHost* render_view_host,
794 const GURL& source_url,
795 const std::string& name,
796 const base::ListValue& args) {
797 if (delegate_)
798 delegate_->WebUISend(this, source_url, name, args);
801 WebContents* TabContents::OpenURL(const OpenURLParams& params) {
802 if (!delegate_)
803 return NULL;
805 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
806 // Notify observers.
807 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
808 DidOpenURL(params.url, params.referrer,
809 params.disposition, params.transition));
810 return new_contents;
813 bool TabContents::NavigateToPendingEntry(
814 NavigationController::ReloadType reload_type) {
815 return NavigateToEntry(
816 *NavigationEntryImpl::FromNavigationEntry(controller_.GetPendingEntry()),
817 reload_type);
820 bool TabContents::NavigateToEntry(
821 const NavigationEntryImpl& entry,
822 NavigationController::ReloadType reload_type) {
823 // The renderer will reject IPC messages with URLs longer than
824 // this limit, so don't attempt to navigate with a longer URL.
825 if (entry.GetURL().spec().size() > content::kMaxURLChars)
826 return false;
828 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
829 if (!dest_render_view_host)
830 return false; // Unable to create the desired render view host.
832 // For security, we should never send non-Web-UI URLs to a Web UI renderer.
833 // Double check that here.
834 int enabled_bindings = dest_render_view_host->enabled_bindings();
835 WebUIControllerFactory* factory =
836 content::GetContentClient()->browser()->GetWebUIControllerFactory();
837 bool is_allowed_in_web_ui_renderer =
838 factory &&
839 factory->IsURLAcceptableForWebUI(GetBrowserContext(), entry.GetURL());
840 #if defined(OS_CHROMEOS)
841 is_allowed_in_web_ui_renderer |= entry.GetURL().SchemeIs(chrome::kDataScheme);
842 #endif
843 CHECK(!(enabled_bindings & content::BINDINGS_POLICY_WEB_UI) ||
844 is_allowed_in_web_ui_renderer);
846 // Tell DevTools agent that it is attached prior to the navigation.
847 DevToolsManagerImpl::GetInstance()->OnNavigatingToPendingEntry(
848 GetRenderViewHost(),
849 dest_render_view_host,
850 entry.GetURL());
852 // Used for page load time metrics.
853 current_load_start_ = base::TimeTicks::Now();
855 // Navigate in the desired RenderViewHost.
856 ViewMsg_Navigate_Params navigate_params;
857 MakeNavigateParams(entry, controller_, delegate_, reload_type,
858 &navigate_params);
859 dest_render_view_host->Navigate(navigate_params);
861 if (entry.GetPageID() == -1) {
862 // HACK!! This code suppresses javascript: URLs from being added to
863 // session history, which is what we want to do for javascript: URLs that
864 // do not generate content. What we really need is a message from the
865 // renderer telling us that a new page was not created. The same message
866 // could be used for mailto: URLs and the like.
867 if (entry.GetURL().SchemeIs(chrome::kJavaScriptScheme))
868 return false;
871 // Notify observers about navigation.
872 FOR_EACH_OBSERVER(WebContentsObserver,
873 observers_,
874 NavigateToPendingEntry(entry.GetURL(), reload_type));
876 if (delegate_)
877 delegate_->DidNavigateToPendingEntry(this);
879 return true;
882 void TabContents::SetHistoryLengthAndPrune(
883 const SiteInstance* site_instance,
884 int history_length,
885 int32 minimum_page_id) {
886 // SetHistoryLengthAndPrune doesn't work when there are pending cross-site
887 // navigations. Callers should ensure that this is the case.
888 if (render_manager_.pending_render_view_host()) {
889 NOTREACHED();
890 return;
892 RenderViewHost* rvh = GetRenderViewHost();
893 if (!rvh) {
894 NOTREACHED();
895 return;
897 if (site_instance && rvh->site_instance() != site_instance) {
898 NOTREACHED();
899 return;
901 rvh->Send(new ViewMsg_SetHistoryLengthAndPrune(rvh->routing_id(),
902 history_length,
903 minimum_page_id));
906 void TabContents::FocusThroughTabTraversal(bool reverse) {
907 if (ShowingInterstitialPage()) {
908 render_manager_.interstitial_page()->FocusThroughTabTraversal(reverse);
909 return;
911 GetRenderViewHost()->SetInitialFocus(reverse);
914 bool TabContents::ShowingInterstitialPage() const {
915 return render_manager_.interstitial_page() != NULL;
918 InterstitialPage* TabContents::GetInterstitialPage() const {
919 return render_manager_.interstitial_page();
922 bool TabContents::IsSavable() {
923 // WebKit creates Document object when MIME type is application/xhtml+xml,
924 // so we also support this MIME type.
925 return contents_mime_type_ == "text/html" ||
926 contents_mime_type_ == "text/xml" ||
927 contents_mime_type_ == "application/xhtml+xml" ||
928 contents_mime_type_ == "text/plain" ||
929 contents_mime_type_ == "text/css" ||
930 net::IsSupportedJavascriptMimeType(contents_mime_type_.c_str());
933 void TabContents::OnSavePage() {
934 // If we can not save the page, try to download it.
935 if (!IsSavable()) {
936 DownloadManager* dlm = GetBrowserContext()->GetDownloadManager();
937 const GURL& current_page_url = GetURL();
938 if (dlm && current_page_url.is_valid()) {
939 DownloadSaveInfo save_info;
940 save_info.prompt_for_save_location = true;
941 dlm->DownloadUrl(current_page_url,
942 GURL(),
944 true, // prefer_cache
945 save_info,
946 this);
947 download_stats::RecordDownloadCount(
948 download_stats::INITIATED_BY_SAVE_PACKAGE_FAILURE_COUNT);
949 return;
953 Stop();
955 // Create the save package and possibly prompt the user for the name to save
956 // the page as. The user prompt is an asynchronous operation that runs on
957 // another thread.
958 save_package_ = new SavePackage(this);
959 save_package_->GetSaveInfo();
962 // Used in automated testing to bypass prompting the user for file names.
963 // Instead, the names and paths are hard coded rather than running them through
964 // file name sanitation and extension / mime checking.
965 bool TabContents::SavePage(const FilePath& main_file, const FilePath& dir_path,
966 content::SavePageType save_type) {
967 // Stop the page from navigating.
968 Stop();
970 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
971 return save_package_->Init();
974 bool TabContents::IsActiveEntry(int32 page_id) {
975 NavigationEntryImpl* active_entry =
976 NavigationEntryImpl::FromNavigationEntry(controller_.GetActiveEntry());
977 return (active_entry != NULL &&
978 active_entry->site_instance() == GetSiteInstance() &&
979 active_entry->GetPageID() == page_id);
982 const std::string& TabContents::GetContentsMimeType() const {
983 return contents_mime_type_;
986 bool TabContents::WillNotifyDisconnection() const {
987 return notify_disconnection_;
990 void TabContents::SetOverrideEncoding(const std::string& encoding) {
991 SetEncoding(encoding);
992 GetRenderViewHost()->Send(new ViewMsg_SetPageEncoding(
993 GetRenderViewHost()->routing_id(), encoding));
996 void TabContents::ResetOverrideEncoding() {
997 encoding_.clear();
998 GetRenderViewHost()->Send(new ViewMsg_ResetPageEncodingToDefault(
999 GetRenderViewHost()->routing_id()));
1002 content::RendererPreferences* TabContents::GetMutableRendererPrefs() {
1003 return &renderer_preferences_;
1006 void TabContents::SetNewTabStartTime(const base::TimeTicks& time) {
1007 new_tab_start_time_ = time;
1010 base::TimeTicks TabContents::GetNewTabStartTime() const {
1011 return new_tab_start_time_;
1014 void TabContents::OnCloseStarted() {
1015 if (tab_close_start_time_.is_null())
1016 tab_close_start_time_ = base::TimeTicks::Now();
1019 bool TabContents::ShouldAcceptDragAndDrop() const {
1020 #if defined(OS_CHROMEOS)
1021 // ChromeOS panels (pop-ups) do not take drag-n-drop.
1022 // See http://crosbug.com/2413
1023 if (delegate_ && delegate_->IsPopupOrPanel(this))
1024 return false;
1025 return true;
1026 #else
1027 return true;
1028 #endif
1031 void TabContents::SystemDragEnded() {
1032 if (GetRenderViewHost())
1033 GetRenderViewHost()->DragSourceSystemDragEnded();
1034 if (delegate_)
1035 delegate_->DragEnded();
1038 void TabContents::SetClosedByUserGesture(bool value) {
1039 closed_by_user_gesture_ = value;
1042 bool TabContents::GetClosedByUserGesture() const {
1043 return closed_by_user_gesture_;
1046 double TabContents::GetZoomLevel() const {
1047 HostZoomMap* zoom_map = GetBrowserContext()->GetHostZoomMap();
1048 if (!zoom_map)
1049 return 0;
1051 double zoom_level;
1052 if (temporary_zoom_settings_) {
1053 zoom_level = zoom_map->GetTemporaryZoomLevel(
1054 GetRenderProcessHost()->GetID(), GetRenderViewHost()->routing_id());
1055 } else {
1056 GURL url;
1057 NavigationEntry* active_entry = GetController().GetActiveEntry();
1058 // Since zoom map is updated using rewritten URL, use rewritten URL
1059 // to get the zoom level.
1060 url = active_entry ? active_entry->GetURL() : GURL::EmptyGURL();
1061 zoom_level = zoom_map->GetZoomLevel(net::GetHostOrSpecFromURL(url));
1063 return zoom_level;
1066 int TabContents::GetZoomPercent(bool* enable_increment,
1067 bool* enable_decrement) {
1068 *enable_decrement = *enable_increment = false;
1069 // Calculate the zoom percent from the factor. Round up to the nearest whole
1070 // number.
1071 int percent = static_cast<int>(
1072 WebKit::WebView::zoomLevelToZoomFactor(GetZoomLevel()) * 100 + 0.5);
1073 *enable_decrement = percent > minimum_zoom_percent_;
1074 *enable_increment = percent < maximum_zoom_percent_;
1075 return percent;
1078 void TabContents::ViewSource() {
1079 if (!delegate_)
1080 return;
1082 NavigationEntry* active_entry = GetController().GetActiveEntry();
1083 if (!active_entry)
1084 return;
1086 delegate_->ViewSourceForTab(this, active_entry->GetURL());
1089 void TabContents::ViewFrameSource(const GURL& url,
1090 const std::string& content_state) {
1091 if (!delegate_)
1092 return;
1094 delegate_->ViewSourceForFrame(this, url, content_state);
1097 int TabContents::GetMinimumZoomPercent() const {
1098 return minimum_zoom_percent_;
1101 int TabContents::GetMaximumZoomPercent() const {
1102 return maximum_zoom_percent_;
1105 gfx::Size TabContents::GetPreferredSize() const {
1106 return preferred_size_;
1109 int TabContents::GetContentRestrictions() const {
1110 return content_restrictions_;
1113 WebUI::TypeID TabContents::GetWebUITypeForCurrentState() {
1114 WebUIControllerFactory* factory =
1115 content::GetContentClient()->browser()->GetWebUIControllerFactory();
1116 if (!factory)
1117 return WebUI::kNoWebUI;
1118 return factory->GetWebUIType(GetBrowserContext(), GetURL());
1121 content::WebUI* TabContents::GetWebUIForCurrentState() {
1122 // When there is a pending navigation entry, we want to use the pending WebUI
1123 // that goes along with it to control the basic flags. For example, we want to
1124 // show the pending URL in the URL bar, so we want the display_url flag to
1125 // be from the pending entry.
1127 // The confusion comes because there are multiple possibilities for the
1128 // initial load in a tab as a side effect of the way the RenderViewHostManager
1129 // works.
1131 // - For the very first tab the load looks "normal". The new tab Web UI is
1132 // the pending one, and we want it to apply here.
1134 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1135 // get switched to the one previously associated with the new tab pages.
1136 // This switching will cause the manager to commit the RVH/WebUI. So we'll
1137 // have a committed Web UI in this case.
1139 // This condition handles all of these cases:
1141 // - First load in first tab: no committed nav entry + pending nav entry +
1142 // pending dom ui:
1143 // -> Use pending Web UI if any.
1145 // - First load in second tab: no committed nav entry + pending nav entry +
1146 // no pending Web UI:
1147 // -> Use the committed Web UI if any.
1149 // - Second navigation in any tab: committed nav entry + pending nav entry:
1150 // -> Use pending Web UI if any.
1152 // - Normal state with no load: committed nav entry + no pending nav entry:
1153 // -> Use committed Web UI.
1154 if (controller_.GetPendingEntry() &&
1155 (controller_.GetLastCommittedEntry() ||
1156 render_manager_.pending_web_ui()))
1157 return render_manager_.pending_web_ui();
1158 return render_manager_.web_ui();
1161 bool TabContents::GotResponseToLockMouseRequest(bool allowed) {
1162 return GetRenderViewHost() ?
1163 GetRenderViewHost()->GotResponseToLockMouseRequest(allowed) : false;
1166 bool TabContents::FocusLocationBarByDefault() {
1167 content::WebUI* web_ui = GetWebUIForCurrentState();
1168 if (web_ui)
1169 return web_ui->ShouldFocusLocationBarByDefault();
1170 NavigationEntry* entry = controller_.GetActiveEntry();
1171 if (entry && entry->GetURL() == GURL(chrome::kAboutBlankURL))
1172 return true;
1173 return false;
1176 void TabContents::SetFocusToLocationBar(bool select_all) {
1177 if (delegate_)
1178 delegate_->SetFocusToLocationBar(select_all);
1181 void TabContents::OnRegisterIntentService(const string16& action,
1182 const string16& type,
1183 const string16& href,
1184 const string16& title,
1185 const string16& disposition) {
1186 delegate_->RegisterIntentHandler(
1187 this, action, type, href, title, disposition);
1190 void TabContents::OnWebIntentDispatch(const webkit_glue::WebIntentData& intent,
1191 int intent_id) {
1192 WebIntentsDispatcherImpl* intents_dispatcher =
1193 new WebIntentsDispatcherImpl(this, intent, intent_id);
1194 delegate_->WebIntentDispatch(this, intents_dispatcher);
1197 void TabContents::OnDidStartProvisionalLoadForFrame(int64 frame_id,
1198 bool is_main_frame,
1199 const GURL& opener_url,
1200 const GURL& url) {
1201 bool is_error_page = (url.spec() == chrome::kUnreachableWebDataURL);
1202 GURL validated_url(url);
1203 GetRenderViewHost()->FilterURL(ChildProcessSecurityPolicy::GetInstance(),
1204 GetRenderProcessHost()->GetID(), &validated_url);
1206 RenderViewHost* rvh =
1207 render_manager_.pending_render_view_host() ?
1208 render_manager_.pending_render_view_host() : GetRenderViewHost();
1209 // Notify observers about the start of the provisional load.
1210 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1211 DidStartProvisionalLoadForFrame(frame_id, is_main_frame,
1212 validated_url, is_error_page, rvh));
1214 if (is_main_frame) {
1215 // Notify observers about the provisional change in the main frame URL.
1216 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1217 ProvisionalChangeToMainFrameUrl(url, opener_url));
1221 void TabContents::OnDidRedirectProvisionalLoad(int32 page_id,
1222 const GURL& opener_url,
1223 const GURL& source_url,
1224 const GURL& target_url) {
1225 // TODO(creis): Remove this method and have the pre-rendering code listen to
1226 // the ResourceDispatcherHost's RESOURCE_RECEIVED_REDIRECT notification
1227 // instead. See http://crbug.com/78512.
1228 NavigationEntry* entry;
1229 if (page_id == -1)
1230 entry = controller_.GetPendingEntry();
1231 else
1232 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1233 if (!entry || entry->GetURL() != source_url)
1234 return;
1236 // Notify observers about the provisional change in the main frame URL.
1237 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1238 ProvisionalChangeToMainFrameUrl(target_url,
1239 opener_url));
1242 void TabContents::OnDidFailProvisionalLoadWithError(
1243 const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) {
1244 VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
1245 << ", error_code: " << params.error_code
1246 << ", error_description: " << params.error_description
1247 << ", is_main_frame: " << params.is_main_frame
1248 << ", showing_repost_interstitial: " <<
1249 params.showing_repost_interstitial
1250 << ", frame_id: " << params.frame_id;
1251 GURL validated_url(params.url);
1252 GetRenderViewHost()->FilterURL(ChildProcessSecurityPolicy::GetInstance(),
1253 GetRenderProcessHost()->GetID(), &validated_url);
1255 if (net::ERR_ABORTED == params.error_code) {
1256 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1257 // This means that the interstitial won't be torn down properly, which is
1258 // bad. But if we have an interstitial, go back to another tab type, and
1259 // then load the same interstitial again, we could end up getting the first
1260 // interstitial's "failed" message (as a result of the cancel) when we're on
1261 // the second one.
1263 // We can't tell this apart, so we think we're tearing down the current page
1264 // which will cause a crash later one. There is also some code in
1265 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1266 // out because of this problem.
1268 // http://code.google.com/p/chromium/issues/detail?id=2855
1269 // Because this will not tear down the interstitial properly, if "back" is
1270 // back to another tab type, the interstitial will still be somewhat alive
1271 // in the previous tab type. If you navigate somewhere that activates the
1272 // tab with the interstitial again, you'll see a flash before the new load
1273 // commits of the interstitial page.
1274 if (ShowingInterstitialPage()) {
1275 LOG(WARNING) << "Discarding message during interstitial.";
1276 return;
1279 // Discard our pending entry if the load canceled (e.g. if we decided to
1280 // download the file instead of load it). We do not verify that the URL
1281 // being canceled matches the pending entry's URL because they will not
1282 // match if a redirect occurred (in which case we do not want to leave a
1283 // stale redirect URL showing). This means that we also cancel the pending
1284 // entry if the user started a new navigation. As a result, the navigation
1285 // controller may not remember that a load is in progress, but the
1286 // navigation will still commit even if there is no pending entry.
1287 if (controller_.GetPendingEntry())
1288 DidCancelLoading();
1290 render_manager_.RendererAbortedProvisionalLoad(GetRenderViewHost());
1293 // Send out a notification that we failed a provisional load with an error.
1294 ProvisionalLoadDetails details(
1295 params.is_main_frame,
1296 controller_.IsURLInPageNavigation(validated_url),
1297 validated_url,
1298 std::string(),
1299 false,
1300 params.frame_id);
1301 details.set_error_code(params.error_code);
1303 content::NotificationService::current()->Notify(
1304 content::NOTIFICATION_FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1305 content::Source<NavigationController>(&controller_),
1306 content::Details<ProvisionalLoadDetails>(&details));
1308 FOR_EACH_OBSERVER(WebContentsObserver,
1309 observers_,
1310 DidFailProvisionalLoad(params.frame_id,
1311 params.is_main_frame,
1312 validated_url,
1313 params.error_code,
1314 params.error_description));
1317 void TabContents::OnDidLoadResourceFromMemoryCache(
1318 const GURL& url,
1319 const std::string& security_info,
1320 const std::string& http_method,
1321 ResourceType::Type resource_type) {
1322 base::StatsCounter cache("WebKit.CacheHit");
1323 cache.Increment();
1325 // Send out a notification that we loaded a resource from our memory cache.
1326 int cert_id = 0;
1327 net::CertStatus cert_status = 0;
1328 int security_bits = -1;
1329 int connection_status = 0;
1330 SSLManager::DeserializeSecurityInfo(security_info,
1331 &cert_id, &cert_status,
1332 &security_bits,
1333 &connection_status);
1334 LoadFromMemoryCacheDetails details(url, GetRenderProcessHost()->GetID(),
1335 cert_id, cert_status);
1337 content::NotificationService::current()->Notify(
1338 content::NOTIFICATION_LOAD_FROM_MEMORY_CACHE,
1339 content::Source<NavigationController>(&controller_),
1340 content::Details<LoadFromMemoryCacheDetails>(&details));
1343 void TabContents::OnDidDisplayInsecureContent() {
1344 content::RecordAction(UserMetricsAction("SSL.DisplayedInsecureContent"));
1345 displayed_insecure_content_ = true;
1346 SSLManager::NotifySSLInternalStateChanged(&GetControllerImpl());
1349 void TabContents::OnDidRunInsecureContent(
1350 const std::string& security_origin, const GURL& target_url) {
1351 LOG(INFO) << security_origin << " ran insecure content from "
1352 << target_url.possibly_invalid_spec();
1353 content::RecordAction(UserMetricsAction("SSL.RanInsecureContent"));
1354 if (EndsWith(security_origin, kDotGoogleDotCom, false)) {
1355 content::RecordAction(
1356 UserMetricsAction("SSL.RanInsecureContentGoogle"));
1358 controller_.GetSSLManager()->DidRunInsecureContent(security_origin);
1359 displayed_insecure_content_ = true;
1360 SSLManager::NotifySSLInternalStateChanged(&GetControllerImpl());
1363 void TabContents::OnDocumentLoadedInFrame(int64 frame_id) {
1364 controller_.DocumentLoadedInFrame();
1365 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1366 DocumentLoadedInFrame(frame_id));
1369 void TabContents::OnDidFinishLoad(
1370 int64 frame_id,
1371 const GURL& validated_url,
1372 bool is_main_frame) {
1373 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1374 DidFinishLoad(frame_id, validated_url, is_main_frame));
1377 void TabContents::OnDidFailLoadWithError(int64 frame_id,
1378 const GURL& validated_url,
1379 bool is_main_frame,
1380 int error_code,
1381 const string16& error_description) {
1382 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1383 DidFailLoad(frame_id, validated_url, is_main_frame,
1384 error_code, error_description));
1387 void TabContents::OnUpdateContentRestrictions(int restrictions) {
1388 content_restrictions_ = restrictions;
1389 delegate_->ContentRestrictionsChanged(this);
1392 void TabContents::OnGoToEntryAtOffset(int offset) {
1393 if (!delegate_ || delegate_->OnGoToEntryOffset(offset)) {
1394 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
1395 controller_.GetEntryAtOffset(offset));
1396 if (!entry)
1397 return;
1398 // Note that we don't call NavigationController::GotToOffset() as we don't
1399 // want to create a pending navigation entry (it might end up lingering
1400 // http://crbug.com/51680).
1401 entry->SetTransitionType(
1402 content::PageTransitionFromInt(
1403 entry->GetTransitionType() |
1404 content::PAGE_TRANSITION_FORWARD_BACK));
1405 NavigateToEntry(*entry, NavigationControllerImpl::NO_RELOAD);
1407 // If the entry is being restored and doesn't have a SiteInstance yet, fill
1408 // it in now that we know. This allows us to find the entry when it commits.
1409 if (!entry->site_instance() &&
1410 entry->restore_type() != NavigationEntryImpl::RESTORE_NONE) {
1411 entry->set_site_instance(
1412 static_cast<SiteInstanceImpl*>(GetPendingSiteInstance()));
1417 void TabContents::OnUpdateZoomLimits(int minimum_percent,
1418 int maximum_percent,
1419 bool remember) {
1420 minimum_zoom_percent_ = minimum_percent;
1421 maximum_zoom_percent_ = maximum_percent;
1422 temporary_zoom_settings_ = !remember;
1425 void TabContents::OnSaveURL(const GURL& url) {
1426 DownloadManager* dlm = GetBrowserContext()->GetDownloadManager();
1427 DownloadSaveInfo save_info;
1428 save_info.prompt_for_save_location = true;
1429 dlm->DownloadUrl(url, GetURL(), "", true, save_info, this);
1432 void TabContents::OnEnumerateDirectory(int request_id,
1433 const FilePath& path) {
1434 delegate_->EnumerateDirectory(this, request_id, path);
1437 void TabContents::OnJSOutOfMemory() {
1438 delegate_->JSOutOfMemory(this);
1441 void TabContents::OnRegisterProtocolHandler(const std::string& protocol,
1442 const GURL& url,
1443 const string16& title) {
1444 delegate_->RegisterProtocolHandler(this, protocol, url, title);
1447 void TabContents::OnFindReply(int request_id,
1448 int number_of_matches,
1449 const gfx::Rect& selection_rect,
1450 int active_match_ordinal,
1451 bool final_update) {
1452 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
1453 active_match_ordinal, final_update);
1454 // Send a notification to the renderer that we are ready to receive more
1455 // results from the scoping effort of the Find operation. The FindInPage
1456 // scoping is asynchronous and periodically sends results back up to the
1457 // browser using IPC. In an effort to not spam the browser we have the
1458 // browser send an ACK for each FindReply message and have the renderer
1459 // queue up the latest status message while waiting for this ACK.
1460 GetRenderViewHost()->Send(
1461 new ViewMsg_FindReplyACK(GetRenderViewHost()->routing_id()));
1464 void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
1465 delegate_->CrashedPlugin(this, plugin_path);
1468 void TabContents::OnAppCacheAccessed(const GURL& manifest_url,
1469 bool blocked_by_policy) {
1470 // Notify observers about navigation.
1471 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1472 AppCacheAccessed(manifest_url, blocked_by_policy));
1475 // Notifies the RenderWidgetHost instance about the fact that the page is
1476 // loading, or done loading and calls the base implementation.
1477 void TabContents::SetIsLoading(bool is_loading,
1478 LoadNotificationDetails* details) {
1479 if (is_loading == is_loading_)
1480 return;
1482 if (!is_loading) {
1483 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE, string16());
1484 load_state_host_.clear();
1485 upload_size_ = 0;
1486 upload_position_ = 0;
1489 render_manager_.SetIsLoading(is_loading);
1491 is_loading_ = is_loading;
1492 waiting_for_response_ = is_loading;
1494 if (delegate_)
1495 delegate_->LoadingStateChanged(this);
1496 NotifyNavigationStateChanged(content::INVALIDATE_TYPE_LOAD);
1498 int type = is_loading ? content::NOTIFICATION_LOAD_START :
1499 content::NOTIFICATION_LOAD_STOP;
1500 content::NotificationDetails det = content::NotificationService::NoDetails();
1501 if (details)
1502 det = content::Details<LoadNotificationDetails>(details);
1503 content::NotificationService::current()->Notify(type,
1504 content::Source<NavigationController>(&controller_),
1505 det);
1508 void TabContents::DidNavigateMainFramePostCommit(
1509 const content::LoadCommittedDetails& details,
1510 const ViewHostMsg_FrameNavigate_Params& params) {
1511 if (opener_web_ui_type_ != WebUI::kNoWebUI) {
1512 // If this is a window.open navigation, use the same WebUI as the renderer
1513 // that opened the window, as long as both renderers have the same
1514 // privileges.
1515 if (delegate_ && opener_web_ui_type_ == GetWebUITypeForCurrentState()) {
1516 WebUIImpl* web_ui = static_cast<WebUIImpl*>(CreateWebUI(GetURL()));
1517 // web_ui might be NULL if the URL refers to a non-existent extension.
1518 if (web_ui) {
1519 render_manager_.SetWebUIPostCommit(web_ui);
1520 web_ui->RenderViewCreated(GetRenderViewHost());
1523 opener_web_ui_type_ = WebUI::kNoWebUI;
1526 if (details.is_navigation_to_different_page()) {
1527 // Clear the status bubble. This is a workaround for a bug where WebKit
1528 // doesn't let us know that the cursor left an element during a
1529 // transition (this is also why the mouse cursor remains as a hand after
1530 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1531 // clear the bubble when a user navigates to a named anchor in the same
1532 // page.
1533 UpdateTargetURL(details.entry->GetPageID(), GURL());
1536 if (!details.is_in_page) {
1537 // Once the main frame is navigated, we're no longer considered to have
1538 // displayed insecure content.
1539 displayed_insecure_content_ = false;
1542 // Notify observers about navigation.
1543 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1544 DidNavigateMainFrame(details, params));
1547 void TabContents::DidNavigateAnyFramePostCommit(
1548 RenderViewHost* render_view_host,
1549 const content::LoadCommittedDetails& details,
1550 const ViewHostMsg_FrameNavigate_Params& params) {
1551 // If we navigate off the page, reset JavaScript state. This does nothing
1552 // to prevent a malicious script from spamming messages, since the script
1553 // could just reload the page to stop blocking.
1554 if (dialog_creator_ && !details.is_in_page) {
1555 dialog_creator_->ResetJavaScriptState(this);
1556 dialog_creator_ = NULL;
1559 // Notify observers about navigation.
1560 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1561 DidNavigateAnyFrame(details, params));
1564 void TabContents::UpdateMaxPageIDIfNecessary(RenderViewHost* rvh) {
1565 // If we are creating a RVH for a restored controller, then we need to make
1566 // sure the RenderView starts with a next_page_id_ larger than the number
1567 // of restored entries. This must be called before the RenderView starts
1568 // navigating (to avoid a race between the browser updating max_page_id and
1569 // the renderer updating next_page_id_). Because of this, we only call this
1570 // from CreateRenderView and allow that to notify the RenderView for us.
1571 int max_restored_page_id = controller_.GetMaxRestoredPageID();
1572 if (max_restored_page_id > GetMaxPageIDForSiteInstance(rvh->site_instance()))
1573 UpdateMaxPageIDForSiteInstance(rvh->site_instance(), max_restored_page_id);
1576 bool TabContents::UpdateTitleForEntry(NavigationEntryImpl* entry,
1577 const string16& title) {
1578 // For file URLs without a title, use the pathname instead. In the case of a
1579 // synthesized title, we don't want the update to count toward the "one set
1580 // per page of the title to history."
1581 string16 final_title;
1582 bool explicit_set;
1583 if (entry && entry->GetURL().SchemeIsFile() && title.empty()) {
1584 final_title = UTF8ToUTF16(entry->GetURL().ExtractFileName());
1585 explicit_set = false; // Don't count synthetic titles toward the set limit.
1586 } else {
1587 TrimWhitespace(title, TRIM_ALL, &final_title);
1588 explicit_set = true;
1591 // If a page is created via window.open and never navigated,
1592 // there will be no navigation entry. In this situation,
1593 // |page_title_when_no_navigaiton_entry_| will be used for page title.
1594 if (entry) {
1595 if (final_title == entry->GetTitle())
1596 return false; // Nothing changed, don't bother.
1598 entry->SetTitle(final_title);
1599 } else {
1600 if (page_title_when_no_navigation_entry_ == final_title)
1601 return false; // Nothing changed, don't bother.
1603 page_title_when_no_navigation_entry_ = final_title;
1606 // Lastly, set the title for the view.
1607 view_->SetPageTitle(final_title);
1609 TitleUpdatedDetails details(entry, explicit_set);
1611 content::NotificationService::current()->Notify(
1612 content::NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,
1613 content::Source<WebContents>(this),
1614 content::Details<TitleUpdatedDetails>(&details));
1616 return true;
1619 void TabContents::NotifySwapped() {
1620 // After sending out a swap notification, we need to send a disconnect
1621 // notification so that clients that pick up a pointer to |this| can NULL the
1622 // pointer. See Bug 1230284.
1623 notify_disconnection_ = true;
1624 content::NotificationService::current()->Notify(
1625 content::NOTIFICATION_WEB_CONTENTS_SWAPPED,
1626 content::Source<WebContents>(this),
1627 content::NotificationService::NoDetails());
1630 void TabContents::NotifyConnected() {
1631 notify_disconnection_ = true;
1632 content::NotificationService::current()->Notify(
1633 content::NOTIFICATION_WEB_CONTENTS_CONNECTED,
1634 content::Source<WebContents>(this),
1635 content::NotificationService::NoDetails());
1638 void TabContents::NotifyDisconnected() {
1639 if (!notify_disconnection_)
1640 return;
1642 notify_disconnection_ = false;
1643 content::NotificationService::current()->Notify(
1644 content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
1645 content::Source<WebContents>(this),
1646 content::NotificationService::NoDetails());
1649 RenderViewHostDelegate::View* TabContents::GetViewDelegate() {
1650 return view_.get();
1653 RenderViewHostDelegate::RendererManagement*
1654 TabContents::GetRendererManagementDelegate() {
1655 return &render_manager_;
1658 content::RendererPreferences TabContents::GetRendererPrefs(
1659 content::BrowserContext* browser_context) const {
1660 return renderer_preferences_;
1663 WebContents* TabContents::GetAsWebContents() {
1664 return this;
1667 content::ViewType TabContents::GetRenderViewType() const {
1668 return view_type_;
1671 gfx::Rect TabContents::GetRootWindowResizerRect() const {
1672 if (delegate_)
1673 return delegate_->GetRootWindowResizerRect();
1674 return gfx::Rect();
1677 void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1678 content::NotificationService::current()->Notify(
1679 content::NOTIFICATION_RENDER_VIEW_HOST_CREATED_FOR_TAB,
1680 content::Source<WebContents>(this),
1681 content::Details<RenderViewHost>(render_view_host));
1682 NavigationEntry* entry = controller_.GetActiveEntry();
1683 if (!entry)
1684 return;
1686 // When we're creating views, we're still doing initial setup, so we always
1687 // use the pending Web UI rather than any possibly existing committed one.
1688 if (render_manager_.pending_web_ui())
1689 render_manager_.pending_web_ui()->RenderViewCreated(render_view_host);
1691 if (entry->IsViewSourceMode()) {
1692 // Put the renderer in view source mode.
1693 render_view_host->Send(
1694 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1697 GetView()->RenderViewCreated(render_view_host);
1699 FOR_EACH_OBSERVER(
1700 WebContentsObserver, observers_, RenderViewCreated(render_view_host));
1703 void TabContents::RenderViewReady(RenderViewHost* rvh) {
1704 if (rvh != GetRenderViewHost()) {
1705 // Don't notify the world, since this came from a renderer in the
1706 // background.
1707 return;
1710 NotifyConnected();
1711 bool was_crashed = IsCrashed();
1712 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
1714 // Restore the focus to the tab (otherwise the focus will be on the top
1715 // window).
1716 if (was_crashed && !FocusLocationBarByDefault() &&
1717 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
1718 Focus();
1721 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewReady());
1724 void TabContents::RenderViewGone(RenderViewHost* rvh,
1725 base::TerminationStatus status,
1726 int error_code) {
1727 if (rvh != GetRenderViewHost()) {
1728 // The pending page's RenderViewHost is gone.
1729 return;
1732 SetIsLoading(false, NULL);
1733 NotifyDisconnected();
1734 SetIsCrashed(status, error_code);
1735 GetView()->OnTabCrashed(GetCrashedStatus(), crashed_error_code_);
1737 FOR_EACH_OBSERVER(WebContentsObserver,
1738 observers_,
1739 RenderViewGone(GetCrashedStatus()));
1742 void TabContents::RenderViewDeleted(RenderViewHost* rvh) {
1743 render_manager_.RenderViewDeleted(rvh);
1744 FOR_EACH_OBSERVER(WebContentsObserver, observers_, RenderViewDeleted(rvh));
1747 void TabContents::DidNavigate(RenderViewHost* rvh,
1748 const ViewHostMsg_FrameNavigate_Params& params) {
1749 if (content::PageTransitionIsMainFrame(params.transition))
1750 render_manager_.DidNavigateMainFrame(rvh);
1752 // Update the site of the SiteInstance if it doesn't have one yet.
1753 if (!static_cast<SiteInstanceImpl*>(GetSiteInstance())->HasSite())
1754 static_cast<SiteInstanceImpl*>(GetSiteInstance())->SetSite(params.url);
1756 // Need to update MIME type here because it's referred to in
1757 // UpdateNavigationCommands() called by RendererDidNavigate() to
1758 // determine whether or not to enable the encoding menu.
1759 // It's updated only for the main frame. For a subframe,
1760 // RenderView::UpdateURL does not set params.contents_mime_type.
1761 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1762 // TODO(jungshik): Add a test for the encoding menu to avoid
1763 // regressing it again.
1764 if (content::PageTransitionIsMainFrame(params.transition))
1765 contents_mime_type_ = params.contents_mime_type;
1767 content::LoadCommittedDetails details;
1768 bool did_navigate = controller_.RendererDidNavigate(params, &details);
1770 // Send notification about committed provisional loads. This notification is
1771 // different from the NAV_ENTRY_COMMITTED notification which doesn't include
1772 // the actual URL navigated to and isn't sent for AUTO_SUBFRAME navigations.
1773 if (details.type != content::NAVIGATION_TYPE_NAV_IGNORE) {
1774 // For AUTO_SUBFRAME navigations, an event for the main frame is generated
1775 // that is not recorded in the navigation history. For the purpose of
1776 // tracking navigation events, we treat this event as a sub frame navigation
1777 // event.
1778 bool is_main_frame = did_navigate ? details.is_main_frame : false;
1779 content::PageTransition transition_type = params.transition;
1780 // Whether or not a page transition was triggered by going backward or
1781 // forward in the history is only stored in the navigation controller's
1782 // entry list.
1783 if (did_navigate &&
1784 (controller_.GetActiveEntry()->GetTransitionType() &
1785 content::PAGE_TRANSITION_FORWARD_BACK)) {
1786 transition_type = content::PageTransitionFromInt(
1787 params.transition | content::PAGE_TRANSITION_FORWARD_BACK);
1789 // Notify observers about the commit of the provisional load.
1790 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1791 DidCommitProvisionalLoadForFrame(params.frame_id,
1792 is_main_frame, params.url, transition_type));
1795 if (!did_navigate)
1796 return; // No navigation happened.
1798 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1799 // for the appropriate notification (best) or you can add it to
1800 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1801 // necessary, please).
1803 // Run post-commit tasks.
1804 if (details.is_main_frame) {
1805 DidNavigateMainFramePostCommit(details, params);
1806 if (delegate_)
1807 delegate_->DidNavigateMainFramePostCommit(this);
1809 DidNavigateAnyFramePostCommit(rvh, details, params);
1812 void TabContents::UpdateState(RenderViewHost* rvh,
1813 int32 page_id,
1814 const std::string& state) {
1815 // Ensure that this state update comes from either the active RVH or one of
1816 // the swapped out RVHs. We don't expect to hear from any other RVHs.
1817 DCHECK(rvh == GetRenderViewHost() || render_manager_.IsSwappedOut(rvh));
1819 // We must be prepared to handle state updates for any page, these occur
1820 // when the user is scrolling and entering form data, as well as when we're
1821 // leaving a page, in which case our state may have already been moved to
1822 // the next page. The navigation controller will look up the appropriate
1823 // NavigationEntry and update it when it is notified via the delegate.
1825 int entry_index = controller_.GetEntryIndexWithPageID(
1826 rvh->site_instance(), page_id);
1827 if (entry_index < 0)
1828 return;
1829 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1831 if (state == entry->GetContentState())
1832 return; // Nothing to update.
1833 entry->SetContentState(state);
1834 controller_.NotifyEntryChanged(entry, entry_index);
1837 void TabContents::UpdateTitle(RenderViewHost* rvh,
1838 int32 page_id,
1839 const string16& title,
1840 base::i18n::TextDirection title_direction) {
1841 // If we have a title, that's a pretty good indication that we've started
1842 // getting useful data.
1843 SetNotWaitingForResponse();
1845 DCHECK(rvh == GetRenderViewHost());
1846 NavigationEntryImpl* entry = controller_.GetEntryWithPageID(
1847 rvh->site_instance(), page_id);
1849 // TODO(evan): make use of title_direction.
1850 // http://code.google.com/p/chromium/issues/detail?id=27094
1851 if (!UpdateTitleForEntry(entry, title))
1852 return;
1854 // Broadcast notifications when the UI should be updated.
1855 if (entry == controller_.GetEntryAtOffset(0))
1856 NotifyNavigationStateChanged(content::INVALIDATE_TYPE_TITLE);
1859 void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1860 const std::string& encoding) {
1861 SetEncoding(encoding);
1864 void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1865 if (delegate_)
1866 delegate_->UpdateTargetURL(this, page_id, url);
1869 void TabContents::Close(RenderViewHost* rvh) {
1870 // The UI may be in an event-tracking loop, such as between the
1871 // mouse-down and mouse-up in text selection or a button click.
1872 // Defer the close until after tracking is complete, so that we
1873 // don't free objects out from under the UI.
1874 // TODO(shess): This could probably be integrated with the
1875 // IsDoingDrag() test below. Punting for now because I need more
1876 // research to understand how this impacts platforms other than Mac.
1877 // TODO(shess): This could get more fine-grained. For instance,
1878 // closing a tab in another window while selecting text in the
1879 // current window's Omnibox should be just fine.
1880 if (GetView()->IsEventTracking()) {
1881 GetView()->CloseTabAfterEventTracking();
1882 return;
1885 // If we close the tab while we're in the middle of a drag, we'll crash.
1886 // Instead, cancel the drag and close it as soon as the drag ends.
1887 if (GetView()->IsDoingDrag()) {
1888 GetView()->CancelDragAndCloseTab();
1889 return;
1892 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1893 if (delegate_ && rvh == GetRenderViewHost())
1894 delegate_->CloseContents(this);
1897 void TabContents::SwappedOut(RenderViewHost* rvh) {
1898 if (delegate_ && rvh == GetRenderViewHost())
1899 delegate_->SwappedOut(this);
1902 void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1903 if (delegate_ && delegate_->IsPopupOrPanel(this))
1904 delegate_->MoveContents(this, new_bounds);
1907 void TabContents::DidStartLoading() {
1908 SetIsLoading(true, NULL);
1910 if (delegate_ && content_restrictions_) {
1911 content_restrictions_ = 0;
1912 delegate_->ContentRestrictionsChanged(this);
1915 // Notify observers about navigation.
1916 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidStartLoading());
1919 void TabContents::DidStopLoading() {
1920 scoped_ptr<LoadNotificationDetails> details;
1922 NavigationEntry* entry = controller_.GetActiveEntry();
1923 // An entry may not exist for a stop when loading an initial blank page or
1924 // if an iframe injected by script into a blank page finishes loading.
1925 if (entry) {
1926 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1928 details.reset(new LoadNotificationDetails(
1929 entry->GetVirtualURL(),
1930 entry->GetTransitionType(),
1931 elapsed,
1932 &controller_,
1933 controller_.GetCurrentEntryIndex()));
1936 SetIsLoading(false, details.get());
1938 // Notify observers about navigation.
1939 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidStopLoading());
1942 void TabContents::DidCancelLoading() {
1943 controller_.DiscardNonCommittedEntries();
1945 // Update the URL display.
1946 NotifyNavigationStateChanged(content::INVALIDATE_TYPE_URL);
1949 void TabContents::DidChangeLoadProgress(double progress) {
1950 if (delegate_)
1951 delegate_->LoadProgressChanged(progress);
1954 void TabContents::DocumentAvailableInMainFrame(
1955 RenderViewHost* render_view_host) {
1956 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
1957 DocumentAvailableInMainFrame());
1960 void TabContents::DocumentOnLoadCompletedInMainFrame(
1961 RenderViewHost* render_view_host,
1962 int32 page_id) {
1963 content::NotificationService::current()->Notify(
1964 content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
1965 content::Source<WebContents>(this),
1966 content::Details<int>(&page_id));
1969 void TabContents::RequestOpenURL(const GURL& url,
1970 const content::Referrer& referrer,
1971 WindowOpenDisposition disposition,
1972 int64 source_frame_id) {
1973 // Delegate to RequestTransferURL because this is just the generic
1974 // case where |old_request_id| is empty.
1975 RequestTransferURL(url, referrer, disposition, source_frame_id,
1976 GlobalRequestID());
1979 void TabContents::RequestTransferURL(const GURL& url,
1980 const content::Referrer& referrer,
1981 WindowOpenDisposition disposition,
1982 int64 source_frame_id,
1983 const GlobalRequestID& old_request_id) {
1984 WebContents* new_contents = NULL;
1985 content::PageTransition transition_type = content::PAGE_TRANSITION_LINK;
1986 if (render_manager_.web_ui()) {
1987 // When we're a Web UI, it will provide a page transition type for us (this
1988 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1989 // generated suggestions).
1991 // Note also that we hide the referrer for Web UI pages. We don't really
1992 // want web sites to see a referrer of "chrome://blah" (and some
1993 // chrome: URLs might have search terms or other stuff we don't want to
1994 // send to the site), so we send no referrer.
1995 OpenURLParams params(url, content::Referrer(), disposition,
1996 render_manager_.web_ui()->GetLinkTransitionType(),
1997 false /* is_renderer_initiated */);
1998 params.transferred_global_request_id = old_request_id;
1999 new_contents = OpenURL(params);
2000 transition_type = render_manager_.web_ui()->GetLinkTransitionType();
2001 } else {
2002 OpenURLParams params(url, referrer, disposition,
2003 content::PAGE_TRANSITION_LINK, true /* is_renderer_initiated */);
2004 params.transferred_global_request_id = old_request_id;
2005 new_contents = OpenURL(params);
2007 if (new_contents) {
2008 // Notify observers.
2009 FOR_EACH_OBSERVER(WebContentsObserver, observers_,
2010 DidOpenRequestedURL(new_contents,
2011 url,
2012 referrer,
2013 disposition,
2014 transition_type,
2015 source_frame_id));
2019 void TabContents::RunJavaScriptMessage(
2020 const RenderViewHost* rvh,
2021 const string16& message,
2022 const string16& default_prompt,
2023 const GURL& frame_url,
2024 ui::JavascriptMessageType javascript_message_type,
2025 IPC::Message* reply_msg,
2026 bool* did_suppress_message) {
2027 // Suppress JavaScript dialogs when requested. Also suppress messages when
2028 // showing an interstitial as it's shown over the previous page and we don't
2029 // want the hidden page's dialogs to interfere with the interstitial.
2030 bool suppress_this_message =
2031 rvh->is_swapped_out() ||
2032 ShowingInterstitialPage() ||
2033 !delegate_ ||
2034 delegate_->ShouldSuppressDialogs();
2036 if (!suppress_this_message) {
2037 content::JavaScriptDialogCreator::TitleType title_type;
2038 string16 title;
2040 if (!frame_url.has_host()) {
2041 title_type = content::JavaScriptDialogCreator::DIALOG_TITLE_NONE;
2042 } else {
2043 title_type = content::JavaScriptDialogCreator::DIALOG_TITLE_FORMATTED_URL;
2044 title = net::FormatUrl(
2045 frame_url.GetOrigin(),
2046 content::GetContentClient()->browser()->GetAcceptLangs(
2047 GetBrowserContext()));
2050 dialog_creator_ = delegate_->GetJavaScriptDialogCreator();
2051 dialog_creator_->RunJavaScriptDialog(this,
2052 title_type,
2053 title,
2054 javascript_message_type,
2055 message,
2056 default_prompt,
2057 reply_msg,
2058 &suppress_this_message);
2061 if (suppress_this_message) {
2062 // If we are suppressing messages, just reply as if the user immediately
2063 // pressed "Cancel".
2064 OnDialogClosed(reply_msg, false, string16());
2067 *did_suppress_message = suppress_this_message;
2070 void TabContents::RunBeforeUnloadConfirm(const RenderViewHost* rvh,
2071 const string16& message,
2072 IPC::Message* reply_msg) {
2073 if (delegate_)
2074 delegate_->WillRunBeforeUnloadConfirm();
2076 bool suppress_this_message =
2077 rvh->is_swapped_out() ||
2078 !delegate_ ||
2079 delegate_->ShouldSuppressDialogs();
2080 if (suppress_this_message) {
2081 GetRenderViewHost()->JavaScriptDialogClosed(reply_msg, true, string16());
2082 return;
2085 is_showing_before_unload_dialog_ = true;
2086 dialog_creator_ = delegate_->GetJavaScriptDialogCreator();
2087 dialog_creator_->RunBeforeUnloadDialog(this,
2088 message,
2089 reply_msg);
2092 WebPreferences TabContents::GetWebkitPrefs() {
2093 WebPreferences web_prefs =
2094 content::GetContentClient()->browser()->GetWebkitPrefs(
2095 GetRenderViewHost());
2097 // Force accelerated compositing and 2d canvas off for chrome:, about: and
2098 // chrome-devtools: pages (unless it's specifically allowed).
2099 if ((GetURL().SchemeIs(chrome::kChromeDevToolsScheme) ||
2100 // Allow accelerated compositing for keyboard and log in screen.
2101 GetURL().SchemeIs(chrome::kChromeUIScheme) ||
2102 (GetURL().SchemeIs(chrome::kAboutScheme) &&
2103 GetURL().spec() != chrome::kAboutBlankURL)) &&
2104 !web_prefs.allow_webui_compositing) {
2105 web_prefs.accelerated_compositing_enabled = false;
2106 web_prefs.accelerated_2d_canvas_enabled = false;
2109 return web_prefs;
2112 void TabContents::OnUserGesture() {
2113 // Notify observers.
2114 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetUserGesture());
2116 ResourceDispatcherHost* rdh = ResourceDispatcherHost::Get();
2117 if (rdh) // NULL in unittests.
2118 rdh->OnUserGesture(this);
2121 void TabContents::OnIgnoredUIEvent() {
2122 // Notify observers.
2123 FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidGetIgnoredUIEvent());
2126 void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2127 bool is_during_unload) {
2128 // Don't show hung renderer dialog for a swapped out RVH.
2129 if (rvh != GetRenderViewHost())
2130 return;
2132 // Ignore renderer unresponsive event if debugger is attached to the tab
2133 // since the event may be a result of the renderer sitting on a breakpoint.
2134 // See http://crbug.com/65458
2135 DevToolsAgentHost* agent =
2136 content::DevToolsAgentHostRegistry::GetDevToolsAgentHost(rvh);
2137 if (agent &&
2138 DevToolsManagerImpl::GetInstance()->GetDevToolsClientHostFor(agent))
2139 return;
2141 if (is_during_unload) {
2142 // Hang occurred while firing the beforeunload/unload handler.
2143 // Pretend the handler fired so tab closing continues as if it had.
2144 rvh->set_sudden_termination_allowed(true);
2146 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2147 return;
2149 // If the tab hangs in the beforeunload/unload handler there's really
2150 // nothing we can do to recover. Pretend the unload listeners have
2151 // all fired and close the tab. If the hang is in the beforeunload handler
2152 // then the user will not have the option of cancelling the close.
2153 Close(rvh);
2154 return;
2157 if (!GetRenderViewHost() || !GetRenderViewHost()->IsRenderViewLive())
2158 return;
2160 if (delegate_)
2161 delegate_->RendererUnresponsive(this);
2164 void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
2165 if (delegate_)
2166 delegate_->RendererResponsive(this);
2169 void TabContents::LoadStateChanged(const GURL& url,
2170 const net::LoadStateWithParam& load_state,
2171 uint64 upload_position,
2172 uint64 upload_size) {
2173 load_state_ = load_state;
2174 upload_position_ = upload_position;
2175 upload_size_ = upload_size;
2176 load_state_host_ = net::IDNToUnicode(url.host(),
2177 content::GetContentClient()->browser()->GetAcceptLangs(
2178 GetBrowserContext()));
2179 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
2180 SetNotWaitingForResponse();
2181 if (IsLoading()) {
2182 NotifyNavigationStateChanged(
2183 content::INVALIDATE_TYPE_LOAD | content::INVALIDATE_TYPE_TAB);
2187 void TabContents::WorkerCrashed() {
2188 if (delegate_)
2189 delegate_->WorkerCrashed(this);
2192 void TabContents::BeforeUnloadFiredFromRenderManager(
2193 bool proceed,
2194 bool* proceed_to_fire_unload) {
2195 if (delegate_)
2196 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2199 void TabContents::DidStartLoadingFromRenderManager(
2200 RenderViewHost* render_view_host) {
2201 DidStartLoading();
2204 void TabContents::RenderViewGoneFromRenderManager(
2205 RenderViewHost* render_view_host) {
2206 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
2207 RenderViewGone(render_view_host, crashed_status_, crashed_error_code_);
2210 void TabContents::UpdateRenderViewSizeForRenderManager() {
2211 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
2212 gfx::Size size = view_->GetContainerSize();
2213 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
2214 // here during container initialization and normal window size will be set
2215 // later. In case of tab duplication this resizing to 0x0 prevents setting
2216 // normal size later so just ignore it.
2217 if (!size.IsEmpty())
2218 view_->SizeContents(size);
2221 void TabContents::NotifySwappedFromRenderManager() {
2222 NotifySwapped();
2225 NavigationControllerImpl& TabContents::GetControllerForRenderManager() {
2226 return GetControllerImpl();
2229 WebUIImpl* TabContents::CreateWebUIForRenderManager(const GURL& url) {
2230 return static_cast<WebUIImpl*>(CreateWebUI(url));
2233 NavigationEntry*
2234 TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2235 return controller_.GetLastCommittedEntry();
2238 bool TabContents::CreateRenderViewForRenderManager(
2239 RenderViewHost* render_view_host) {
2240 // Can be NULL during tests.
2241 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2243 // Now that the RenderView has been created, we need to tell it its size.
2244 if (rwh_view)
2245 rwh_view->SetSize(view_->GetContainerSize());
2247 // Make sure we use the correct starting page_id in the new RenderView.
2248 UpdateMaxPageIDIfNecessary(render_view_host);
2249 int32 max_page_id =
2250 GetMaxPageIDForSiteInstance(render_view_host->site_instance());
2252 if (!render_view_host->CreateRenderView(string16(), max_page_id))
2253 return false;
2255 #if defined(OS_LINUX) || defined(OS_OPENBSD)
2256 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
2257 // linux. See crbug.com/83941.
2258 if (rwh_view) {
2259 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
2260 render_widget_host->WasResized();
2262 #endif
2264 return true;
2267 void TabContents::OnDialogClosed(IPC::Message* reply_msg,
2268 bool success,
2269 const string16& user_input) {
2270 if (is_showing_before_unload_dialog_ && !success) {
2271 // If a beforeunload dialog is canceled, we need to stop the throbber from
2272 // spinning, since we forced it to start spinning in Navigate.
2273 DidStopLoading();
2275 tab_close_start_time_ = base::TimeTicks();
2277 is_showing_before_unload_dialog_ = false;
2278 GetRenderViewHost()->JavaScriptDialogClosed(reply_msg, success, user_input);
2281 gfx::NativeWindow TabContents::GetDialogRootWindow() const {
2282 return view_->GetTopLevelNativeWindow();
2285 void TabContents::OnDialogShown() {
2286 Activate();
2289 void TabContents::SetEncoding(const std::string& encoding) {
2290 encoding_ = content::GetContentClient()->browser()->
2291 GetCanonicalEncodingNameByAliasName(encoding);
2294 void TabContents::CreateViewAndSetSizeForRVH(RenderViewHost* rvh) {
2295 RenderWidgetHostView* rwh_view = GetView()->CreateViewForWidget(rvh);
2296 // Can be NULL during tests.
2297 if (rwh_view)
2298 rwh_view->SetSize(GetView()->GetContainerSize());