blob: 02af3a5aca49f2a895a01f0bdf297f832a384f0c [file] [log] [blame]
[email protected]ce5c4502009-05-06 16:46:111// Copyright (c) 2009 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]f3ec7742009-01-15 00:59:165#include "chrome/browser/tab_contents/tab_contents.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]a92b8642009-05-05 23:38:567#include "app/l10n_util.h"
[email protected]9929da92009-05-05 02:05:118#include "app/resource_bundle.h"
[email protected]420ae012009-04-24 05:16:329#include "base/file_version_info.h"
10#include "base/process_util.h"
[email protected]96d185d2009-04-24 03:28:5411#include "base/string16.h"
[email protected]996fd702009-09-04 19:12:3712#include "base/string_util.h"
[email protected]96d185d2009-04-24 03:28:5413#include "base/time.h"
[email protected]66ba4932009-06-04 19:22:1314#include "chrome/browser/blocked_popup_container.h"
[email protected]420ae012009-04-24 05:16:3215#include "chrome/browser/bookmarks/bookmark_model.h"
[email protected]96d185d2009-04-24 03:28:5416#include "chrome/browser/browser_process.h"
initial.commit09911bf2008-07-26 23:55:2917#include "chrome/browser/cert_store.h"
[email protected]aacd7cc2009-09-02 14:51:1018#include "chrome/browser/character_encoding.h"
[email protected]96d185d2009-04-24 03:28:5419#include "chrome/browser/debugger/devtools_manager.h"
[email protected]420ae012009-04-24 05:16:3220#include "chrome/browser/dom_operation_notification_details.h"
[email protected]96d185d2009-04-24 03:28:5421#include "chrome/browser/dom_ui/dom_ui.h"
22#include "chrome/browser/dom_ui/dom_ui_factory.h"
[email protected]bcef0dc02009-02-28 00:35:0223#include "chrome/browser/download/download_item_model.h"
[email protected]420ae012009-04-24 05:16:3224#include "chrome/browser/download/download_manager.h"
25#include "chrome/browser/download/download_request_manager.h"
[email protected]e7eaedde2009-09-25 20:09:4926#include "chrome/browser/external_protocol_handler.h"
[email protected]92c6f9b92009-10-24 04:35:0827#include "chrome/browser/extensions/extensions_service.h"
[email protected]0189bc722009-08-28 21:56:4828#include "chrome/browser/favicon_service.h"
[email protected]19289d02009-10-21 21:47:0029#include "chrome/browser/form_field_history_manager.h"
[email protected]420ae012009-04-24 05:16:3230#include "chrome/browser/gears_integration.h"
31#include "chrome/browser/google_util.h"
[email protected]8897c382009-05-06 17:53:2632#include "chrome/browser/hung_renderer_dialog.h"
[email protected]420ae012009-04-24 05:16:3233#include "chrome/browser/jsmessage_box_handler.h"
34#include "chrome/browser/load_from_memory_cache_details.h"
35#include "chrome/browser/load_notification_details.h"
[email protected]84abba62009-10-07 17:01:4436#include "chrome/browser/metrics/metric_event_duration_details.h"
[email protected]ea0e80892009-08-22 00:36:0537#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]c8865482009-07-23 20:40:1038#include "chrome/browser/omnibox_search_hint.h"
[email protected]fdd61c62009-04-22 19:22:5739#include "chrome/browser/password_manager/password_manager.h"
40#include "chrome/browser/plugin_installer.h"
[email protected]ce560f82009-06-03 09:39:4441#include "chrome/browser/profile.h"
[email protected]1db6ff152009-10-12 15:32:0742#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]96d185d2009-04-24 03:28:5443#include "chrome/browser/renderer_host/render_widget_host_view.h"
[email protected]fd694982009-07-03 17:32:3744#include "chrome/browser/renderer_host/resource_request_details.h"
[email protected]1db6ff152009-10-12 15:32:0745#include "chrome/browser/renderer_host/site_instance.h"
[email protected]96d185d2009-04-24 03:28:5446#include "chrome/browser/renderer_host/web_cache_manager.h"
[email protected]bd1ad682009-05-15 22:19:1747#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]7e383692009-06-12 19:14:5448#include "chrome/browser/tab_contents/interstitial_page.h"
[email protected]f3ec7742009-01-15 00:59:1649#include "chrome/browser/tab_contents/navigation_entry.h"
[email protected]de34a962009-06-26 23:22:4350#include "chrome/browser/tab_contents/provisional_load_details.h"
[email protected]f3ec7742009-01-15 00:59:1651#include "chrome/browser/tab_contents/tab_contents_delegate.h"
[email protected]fdd61c62009-04-22 19:22:5752#include "chrome/browser/tab_contents/tab_contents_view.h"
[email protected]58dca552009-06-17 00:35:0253#include "chrome/browser/tab_contents/thumbnail_generator.h"
[email protected]449478302009-06-09 20:04:2854#include "chrome/browser/thumbnail_store.h"
[email protected]420ae012009-04-24 05:16:3255#include "chrome/browser/search_engines/template_url_fetcher.h"
56#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2757#include "chrome/common/chrome_switches.h"
[email protected]5d246db22009-10-27 06:17:5758#include "chrome/common/extensions/extension_action.h"
[email protected]bfd04a62009-02-01 18:16:5659#include "chrome/common/notification_service.h"
initial.commit09911bf2008-07-26 23:55:2960#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0361#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3262#include "chrome/common/render_messages.h"
[email protected]1ee614862009-07-06 20:29:1863#include "chrome/common/renderer_preferences.h"
[email protected]96d185d2009-04-24 03:28:5464#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2665#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3266#include "grit/locale_settings.h"
67#include "net/base/mime_util.h"
68#include "net/base/net_errors.h"
[email protected]d686e812009-06-03 19:10:2969#include "net/base/net_util.h"
[email protected]420ae012009-04-24 05:16:3270#include "net/base/registry_controlled_domain.h"
[email protected]1ee614862009-07-06 20:29:1871#include "webkit/glue/password_form.h"
72#include "webkit/glue/webpreferences.h"
[email protected]3e45ba92009-02-20 21:09:0073
[email protected]304f8792009-08-19 21:28:0974#if defined(OS_CHROMEOS)
75// For GdkScreen
76#include <gdk/gdk.h>
[email protected]0ba5c5e2009-08-20 16:47:1377#endif // defined(OS_CHROMEOS)
78
79#if defined(OS_LINUX)
80#include "chrome/browser/gtk/create_application_shortcuts_dialog_gtk.h"
[email protected]d3ba77272009-09-03 00:06:0981#include "chrome/browser/gtk/gtk_theme_provider.h"
[email protected]0ba5c5e2009-08-20 16:47:1382#endif // defined(OS_LINUX)
83
[email protected]420ae012009-04-24 05:16:3284// Cross-Site Navigations
85//
86// If a TabContents is told to navigate to a different web site (as determined
87// by SiteInstance), it will replace its current RenderViewHost with a new
88// RenderViewHost dedicated to the new SiteInstance. This works as follows:
89//
90// - Navigate determines whether the destination is cross-site, and if so,
91// it creates a pending_render_view_host_ and moves into the PENDING
92// RendererState.
93// - The pending RVH is "suspended," so that no navigation messages are sent to
94// its renderer until the onbeforeunload JavaScript handler has a chance to
95// run in the current RVH.
96// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
97// that it has a pending cross-site request. ResourceDispatcherHost will
98// check for this when the response arrives.
99// - The current RVH runs its onbeforeunload handler. If it returns false, we
100// cancel all the pending logic and go back to NORMAL. Otherwise we allow
101// the pending RVH to send the navigation request to its renderer.
102// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
103// checks CrossSiteRequestManager to see that the RVH responsible has a
104// pending cross-site request, and then installs a CrossSiteEventHandler.
105// - When RDH receives a response, the BufferedEventHandler determines whether
106// it is a download. If so, it sends a message to the new renderer causing
107// it to cancel the request, and the download proceeds in the download
108// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:34109// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:32110// doesn't affect any functionality.
111// - After RDH receives a response and determines that it is safe and not a
112// download, it pauses the response to first run the old page's onunload
113// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:34114// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:32115// to the current RVH.
116// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
117// the ResourceDispatcherHost, who unpauses the response. Data is then sent
118// to the pending RVH.
119// - The pending renderer sends a FrameNavigate message that invokes the
120// DidNavigate method. This replaces the current RVH with the
121// pending RVH and goes back to the NORMAL RendererState.
122
123namespace {
124
125// Amount of time we wait between when a key event is received and the renderer
126// is queried for its state and pushed to the NavigationEntry.
127const int kQueryStateDelay = 5000;
128
129const int kSyncWaitDelay = 40;
130
[email protected]304f8792009-08-19 21:28:09131#if defined(OS_CHROMEOS)
132// If a popup window is bigger than this fraction of the screen on chrome os,
133// turn it into a tab
134const float kMaxWidthFactor = 0.5;
135const float kMaxHeightFactor = 0.6;
136#endif
137
[email protected]420ae012009-04-24 05:16:32138// If another javascript message box is displayed within
139// kJavascriptMessageExpectedDelay of a previous javascript message box being
140// dismissed, display an option to suppress future message boxes from this
141// contents.
142const int kJavascriptMessageExpectedDelay = 1000;
143
[email protected]420ae012009-04-24 05:16:32144// The list of prefs we want to observe.
145const wchar_t* kPrefsToObserve[] = {
146 prefs::kAlternateErrorPagesEnabled,
147 prefs::kWebKitJavaEnabled,
148 prefs::kWebKitJavascriptEnabled,
149 prefs::kWebKitLoadsImagesAutomatically,
150 prefs::kWebKitPluginsEnabled,
151 prefs::kWebKitUsesUniversalDetector,
152 prefs::kWebKitSerifFontFamily,
153 prefs::kWebKitSansSerifFontFamily,
154 prefs::kWebKitFixedFontFamily,
155 prefs::kWebKitDefaultFontSize,
156 prefs::kWebKitDefaultFixedFontSize,
157 prefs::kDefaultCharset
158 // kWebKitStandardFontIsSerif needs to be added
159 // if we let users pick which font to use, serif or sans-serif when
160 // no font is specified or a CSS generic family (serif or sans-serif)
161 // is not specified.
162};
163
164const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
165
[email protected]420ae012009-04-24 05:16:32166// Returns true if the entry's transition type is FORM_SUBMIT.
167bool IsFormSubmit(const NavigationEntry* entry) {
168 return (PageTransition::StripQualifier(entry->transition_type()) ==
169 PageTransition::FORM_SUBMIT);
170}
171
172#if defined(OS_WIN)
173
174BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
175 // Note: erase is required to properly paint some widgets borders. This can
176 // be seen with textfields.
177 InvalidateRect(hwnd, NULL, TRUE);
178 return TRUE;
179}
180#endif
181
[email protected]056de2d2009-06-26 16:41:34182void MakeNavigateParams(const NavigationEntry& entry, bool reload,
183 ViewMsg_Navigate_Params* params) {
184 params->page_id = entry.page_id();
185 params->url = entry.url();
186 params->referrer = entry.referrer();
187 params->transition = entry.transition_type();
188 params->state = entry.content_state();
189 params->reload = reload;
190 params->request_time = base::Time::Now();
191}
192
[email protected]420ae012009-04-24 05:16:32193} // namespace
194
195// -----------------------------------------------------------------------------
196
[email protected]fdd61c62009-04-22 19:22:57197// static
198int TabContents::find_request_id_counter_ = -1;
199
[email protected]420ae012009-04-24 05:16:32200class TabContents::GearsCreateShortcutCallbackFunctor {
201 public:
202 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
203 : contents_(contents) {}
204
205 void Run(const GearsShortcutData2& shortcut_data, bool success) {
206 if (contents_)
207 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
208 delete this;
209 }
210 void Cancel() {
211 contents_ = NULL;
212 }
213
214 private:
215 TabContents* contents_;
216};
217
[email protected]420ae012009-04-24 05:16:32218TabContents::TabContents(Profile* profile,
219 SiteInstance* site_instance,
220 int routing_id,
[email protected]34ac70502009-09-25 17:07:23221 const TabContents* base_tab_contents)
[email protected]b680ad22009-04-15 23:19:42222 : delegate_(NULL),
[email protected]66ba4932009-06-04 19:22:13223 ALLOW_THIS_IN_INITIALIZER_LIST(controller_(this, profile)),
224 ALLOW_THIS_IN_INITIALIZER_LIST(view_(
[email protected]d82ed61e2009-06-16 02:46:22225 TabContentsView::Create(this))),
226 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(this, this)),
[email protected]fdd61c62009-04-22 19:22:57227 property_bag_(),
228 registrar_(),
[email protected]d82ed61e2009-06-16 02:46:22229 ALLOW_THIS_IN_INITIALIZER_LIST(printing_(*this)),
[email protected]fdd61c62009-04-22 19:22:57230 save_package_(),
231 cancelable_consumer_(),
[email protected]19289d02009-10-21 21:47:00232 form_field_history_manager_(),
[email protected]fdd61c62009-04-22 19:22:57233 password_manager_(),
234 plugin_installer_(),
[email protected]d82ed61e2009-06-16 02:46:22235 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(this)),
[email protected]fdd61c62009-04-22 19:22:57236 select_file_dialog_(),
237 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34238 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29239 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34240 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34241 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57242 current_load_start_(),
243 load_state_(net::LOAD_STATE_IDLE),
244 load_state_host_(),
[email protected]094e5b22009-09-25 04:23:56245 upload_size_(0),
246 upload_position_(0),
[email protected]fdd61c62009-04-22 19:22:57247 received_page_title_(false),
248 is_starred_(false),
249 contents_mime_type_(),
250 encoding_(),
[email protected]332af7732009-03-11 13:21:35251 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57252 infobar_delegates_(),
[email protected]fdd61c62009-04-22 19:22:57253 find_ui_active_(false),
254 find_op_aborted_(false),
255 current_find_request_id_(find_request_id_counter_++),
256 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12257 last_search_case_sensitive_(false),
258 last_search_prepopulate_text_(NULL),
259 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57260 capturing_contents_(false),
261 is_being_destroyed_(false),
262 notify_disconnection_(false),
263 history_requests_(),
264#if defined(OS_WIN)
265 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
266#endif
267 last_javascript_message_dismissal_(),
[email protected]c2e74fe82009-09-03 17:57:44268 suppress_javascript_messages_(false),
[email protected]7ab1e7d62009-10-14 23:32:01269 is_showing_before_unload_dialog_(false),
[email protected]c2e74fe82009-09-03 17:57:44270 opener_dom_ui_type_(DOMUIFactory::kNoDOMUI) {
[email protected]420ae012009-04-24 05:16:32271 pending_install_.page_id = 0;
272 pending_install_.callback_functor = NULL;
273
[email protected]16779842009-07-08 23:45:29274#if defined(OS_CHROMEOS)
[email protected]58dca552009-06-17 00:35:02275 // Make sure the thumbnailer is started before starting the render manager.
276 // The thumbnailer will want to listen for RVH creations, one of which will
277 // happen in RVHManager::Init.
278 ThumbnailGenerator* generator = g_browser_process->GetThumbnailGenerator();
279 if (generator)
280 generator->StartThumbnailing();
281#endif
282
[email protected]12636df2009-09-28 22:32:21283 render_manager_.Init(profile, site_instance, routing_id);
[email protected]420ae012009-04-24 05:16:32284
[email protected]34ac70502009-09-25 17:07:23285 // We have the initial size of the view be based on the size of the passed in
286 // tab contents (normally a tab from the same window).
287 view_->CreateView(base_tab_contents ?
288 base_tab_contents->view()->GetContainerSize() : gfx::Size());
[email protected]420ae012009-04-24 05:16:32289
290 // Register for notifications about all interested prefs change.
291 PrefService* prefs = profile->GetPrefs();
292 if (prefs) {
293 for (int i = 0; i < kPrefsToObserveLength; ++i)
294 prefs->AddPrefObserver(kPrefsToObserve[i], this);
295 }
296
297 // Register for notifications about URL starredness changing on any profile.
298 registrar_.Add(this, NotificationType::URLS_STARRED,
299 NotificationService::AllSources());
300 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
301 NotificationService::AllSources());
302 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
303 NotificationService::AllSources());
[email protected]d3ba77272009-09-03 00:06:09304#if defined(OS_LINUX)
305 registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
306 NotificationService::AllSources());
307#endif
[email protected]420ae012009-04-24 05:16:32308
309 // Keep a global copy of the previous search string (if any).
310 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12311 last_search_prepopulate_text_ = &global_last_search;
[email protected]840b1512009-07-21 16:53:46312
[email protected]c8865482009-07-23 20:40:10313 // Set-up the showing of the omnibox search infobar if applicable.
314 if (OmniboxSearchHint::IsEnabled(profile))
315 omnibox_search_hint_.reset(new OmniboxSearchHint(this));
316
[email protected]840b1512009-07-21 16:53:46317 view_->InitRendererPrefs(&renderer_preferences_);
[email protected]332af7732009-03-11 13:21:35318}
initial.commit09911bf2008-07-26 23:55:29319
320TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32321 is_being_destroyed_ = true;
322
[email protected]bfe4c1582009-10-02 18:11:09323 // We don't want any notifications while we're running our destructor.
[email protected]420ae012009-04-24 05:16:32324 registrar_.RemoveAll();
325
326 // Unregister the notifications of all observed prefs change.
327 PrefService* prefs = profile()->GetPrefs();
328 if (prefs) {
329 for (int i = 0; i < kPrefsToObserveLength; ++i)
330 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
331 }
332
[email protected]420ae012009-04-24 05:16:32333 NotifyDisconnected();
[email protected]d82ed61e2009-06-16 02:46:22334 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:32335
336 if (pending_install_.callback_functor)
337 pending_install_.callback_functor->Cancel();
338
339 // First cleanly close all child windows.
340 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
341 // some of these to close. CloseWindows is async, so it might get called
342 // twice before it runs.
343 int size = static_cast<int>(child_windows_.size());
344 for (int i = size - 1; i >= 0; --i) {
345 ConstrainedWindow* window = child_windows_[i];
346 if (window)
347 window->CloseConstrainedWindow();
348 }
349
[email protected]66ba4932009-06-04 19:22:13350 if (blocked_popups_)
351 blocked_popups_->Destroy();
352
[email protected]420ae012009-04-24 05:16:32353 // Notify any observer that have a reference on this tab contents.
354 NotificationService::current()->Notify(
355 NotificationType::TAB_CONTENTS_DESTROYED,
356 Source<TabContents>(this),
357 NotificationService::NoDetails());
358
[email protected]1e5e74f2009-05-27 20:55:12359 // Notify any lasting InfobarDelegates that have not yet been removed that
360 // whatever infobar they were handling in this TabContents has closed,
361 // because the TabContents is going away entirely.
362 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
363 // notification may trigger infobars calls that access their delegate. (and
364 // some implementations of InfoBarDelegate do delete themselves on
365 // InfoBarClosed()).
366 for (int i = 0; i < infobar_delegate_count(); ++i) {
367 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
368 delegate->InfoBarClosed();
369 }
370 infobar_delegates_.clear();
371
[email protected]420ae012009-04-24 05:16:32372 // TODO(brettw) this should be moved to the view.
373#if defined(OS_WIN)
374 // If we still have a window handle, destroy it. GetNativeView can return
375 // NULL if this contents was part of a window that closed.
376 if (GetNativeView())
377 ::DestroyWindow(GetNativeView());
378#endif
[email protected]7ab1e7d62009-10-14 23:32:01379
380 // OnCloseStarted isn't called in unit tests.
381 if (!tab_close_start_time_.is_null()) {
382 UMA_HISTOGRAM_TIMES("Tab.Close",
383 base::TimeTicks::Now() - tab_close_start_time_);
384 }
initial.commit09911bf2008-07-26 23:55:29385}
386
[email protected]d5f942ba2008-09-26 19:30:34387// static
388void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32389 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
390
391 WebPreferences pref_defaults;
392 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
393 pref_defaults.javascript_enabled);
394 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
395 pref_defaults.web_security_enabled);
396 prefs->RegisterBooleanPref(
397 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
398 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
399 pref_defaults.loads_images_automatically);
400 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
401 pref_defaults.plugins_enabled);
402 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
403 pref_defaults.dom_paste_enabled);
404 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
405 pref_defaults.shrinks_standalone_images_to_fit);
[email protected]0df30122009-06-03 12:13:08406 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
[email protected]8922e1f2009-10-03 05:01:26407 UTF8ToWide(pref_defaults.inspector_settings));
[email protected]420ae012009-04-24 05:16:32408 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
409 pref_defaults.text_areas_are_resizable);
410 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
411 pref_defaults.java_enabled);
412
413 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
414 IDS_ACCEPT_LANGUAGES);
415 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
416 IDS_DEFAULT_ENCODING);
417 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
418 IDS_STANDARD_FONT_IS_SERIF);
419 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
420 IDS_FIXED_FONT_FAMILY);
421 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
422 IDS_SERIF_FONT_FAMILY);
423 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
424 IDS_SANS_SERIF_FONT_FAMILY);
425 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
426 IDS_CURSIVE_FONT_FAMILY);
427 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
428 IDS_FANTASY_FONT_FAMILY);
429 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
430 IDS_DEFAULT_FONT_SIZE);
431 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
432 IDS_DEFAULT_FIXED_FONT_SIZE);
433 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
434 IDS_MINIMUM_FONT_SIZE);
435 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
436 IDS_MINIMUM_LOGICAL_FONT_SIZE);
437 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
438 IDS_USES_UNIVERSAL_DETECTOR);
439 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
440 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29441}
442
[email protected]13367f72009-07-08 16:39:02443// Returns true if contains content rendered by an extension.
444bool TabContents::HostsExtension() const {
445 return GetURL().SchemeIs(chrome::kExtensionScheme);
[email protected]d5f942ba2008-09-26 19:30:34446}
447
[email protected]6e95706d2009-04-23 22:55:01448PasswordManager* TabContents::GetPasswordManager() {
449 if (password_manager_.get() == NULL)
450 password_manager_.reset(new PasswordManager(this));
451 return password_manager_.get();
452}
453
454PluginInstaller* TabContents::GetPluginInstaller() {
455 if (plugin_installer_.get() == NULL)
456 plugin_installer_.reset(new PluginInstaller(this));
457 return plugin_installer_.get();
458}
459
[email protected]d5f942ba2008-09-26 19:30:34460const GURL& TabContents::GetURL() const {
461 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57462 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]ebe89e062009-08-13 23:16:54463 return entry ? entry->virtual_url() : GURL::EmptyGURL();
[email protected]d5f942ba2008-09-26 19:30:34464}
465
[email protected]96d185d2009-04-24 03:28:54466const string16& TabContents::GetTitle() const {
[email protected]4c6092c5b2009-06-06 00:23:55467 // Transient entries take precedence. They are used for interstitial pages
468 // that are shown on top of existing pages.
469 NavigationEntry* entry = controller_.GetTransientEntry();
470 if (entry)
471 return entry->GetTitleForDisplay(&controller_);
472
[email protected]96d185d2009-04-24 03:28:54473 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
474 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
475 if (our_dom_ui) {
476 // Don't override the title in view source mode.
[email protected]4c6092c5b2009-06-06 00:23:55477 entry = controller_.GetActiveEntry();
[email protected]96d185d2009-04-24 03:28:54478 if (!(entry && entry->IsViewSourceMode())) {
479 // Give the DOM UI the chance to override our title.
480 const string16& title = our_dom_ui->overridden_title();
481 if (!title.empty())
482 return title;
483 }
484 }
485
486 // We use the title for the last committed entry rather than a pending
487 // navigation entry. For example, when the user types in a URL, we want to
488 // keep the old page's title until the new load has committed and we get a new
489 // title.
[email protected]96d185d2009-04-24 03:28:54490 entry = controller_.GetLastCommittedEntry();
491 if (entry)
492 return entry->GetTitleForDisplay(&controller_);
[email protected]96d185d2009-04-24 03:28:54493 return EmptyString16();
494}
495
[email protected]d5f942ba2008-09-26 19:30:34496int32 TabContents::GetMaxPageID() {
497 if (GetSiteInstance())
498 return GetSiteInstance()->max_page_id();
499 else
500 return max_page_id_;
501}
502
503void TabContents::UpdateMaxPageID(int32 page_id) {
504 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34505 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34506 // testing.
507 if (GetSiteInstance())
508 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34509 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34510}
511
[email protected]96d185d2009-04-24 03:28:54512SiteInstance* TabContents::GetSiteInstance() const {
513 return render_manager_.current_host()->site_instance();
514}
515
[email protected]d5f942ba2008-09-26 19:30:34516const std::wstring TabContents::GetDefaultTitle() const {
517 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
518}
519
[email protected]96d185d2009-04-24 03:28:54520bool TabContents::ShouldDisplayURL() {
521 // Don't hide the url in view source mode.
522 NavigationEntry* entry = controller_.GetActiveEntry();
523 if (entry && entry->IsViewSourceMode())
524 return true;
[email protected]83e3895b2009-06-11 00:07:16525
[email protected]96d185d2009-04-24 03:28:54526 DOMUI* dom_ui = GetDOMUIForCurrentState();
527 if (dom_ui)
528 return !dom_ui->should_hide_url();
529 return true;
530}
531
[email protected]d5f942ba2008-09-26 19:30:34532SkBitmap TabContents::GetFavIcon() const {
533 // Like GetTitle(), we also want to use the favicon for the last committed
534 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57535 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47536 if (entry)
537 return entry->favicon().bitmap();
538
[email protected]ce3fa3c2009-04-20 19:55:57539 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34540 if (entry)
541 return entry->favicon().bitmap();
[email protected]d5f942ba2008-09-26 19:30:34542 return SkBitmap();
543}
544
[email protected]0b303cc2009-09-28 22:35:15545bool TabContents::FavIconIsValid() const {
546 NavigationEntry* entry = controller_.GetTransientEntry();
547 if (entry)
548 return entry->favicon().is_valid();
549
550 entry = controller_.GetLastCommittedEntry();
551 if (entry)
552 return entry->favicon().is_valid();
553
554 return false;
555}
556
[email protected]96d185d2009-04-24 03:28:54557bool TabContents::ShouldDisplayFavIcon() {
558 // Always display a throbber during pending loads.
559 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
560 return true;
561
562 DOMUI* dom_ui = GetDOMUIForCurrentState();
563 if (dom_ui)
564 return !dom_ui->hide_favicon();
565 return true;
566}
567
[email protected]96d185d2009-04-24 03:28:54568std::wstring TabContents::GetStatusText() const {
569 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
570 return std::wstring();
571
572 switch (load_state_) {
573 case net::LOAD_STATE_WAITING_FOR_CACHE:
574 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
575 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
576 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
577 case net::LOAD_STATE_RESOLVING_HOST:
578 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
579 case net::LOAD_STATE_CONNECTING:
580 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
581 case net::LOAD_STATE_SENDING_REQUEST:
[email protected]094e5b22009-09-25 04:23:56582 if (upload_size_)
583 return l10n_util::GetStringF(
584 IDS_LOAD_STATE_SENDING_REQUEST_WITH_PROGRESS,
585 static_cast<int>((100 * upload_position_) / upload_size_));
586 else
587 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
[email protected]96d185d2009-04-24 03:28:54588 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
589 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
590 load_state_host_);
591 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
592 case net::LOAD_STATE_IDLE:
593 case net::LOAD_STATE_READING_RESPONSE:
594 break;
595 }
596
597 return std::wstring();
598}
599
[email protected]d5f942ba2008-09-26 19:30:34600void TabContents::SetIsCrashed(bool state) {
601 if (state == is_crashed_)
602 return;
603
604 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50605 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34606}
607
[email protected]744ef172009-10-16 21:53:46608void TabContents::PageActionStateChanged() {
609 NotifyNavigationStateChanged(TabContents::INVALIDATE_PAGE_ACTIONS);
[email protected]d7eaf572009-07-01 21:57:00610}
[email protected]ce5c4502009-05-06 16:46:11611
[email protected]d5f942ba2008-09-26 19:30:34612void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
613 if (delegate_)
614 delegate_->NavigationStateChanged(this, changed_flags);
615}
616
[email protected]96d185d2009-04-24 03:28:54617void TabContents::DidBecomeSelected() {
618 controller_.SetActive(true);
[email protected]789e9152009-08-04 21:59:43619 if (render_widget_host_view()) {
[email protected]96d185d2009-04-24 03:28:54620 render_widget_host_view()->DidBecomeSelected();
[email protected]789e9152009-08-04 21:59:43621#if defined(OS_MACOSX)
622 render_widget_host_view()->SetActive(true);
623#endif
624 }
[email protected]96d185d2009-04-24 03:28:54625
[email protected]76543b92009-08-31 17:27:45626 WebCacheManager::GetInstance()->ObserveActivity(process()->id());
[email protected]96d185d2009-04-24 03:28:54627}
628
629void TabContents::WasHidden() {
630 if (!capturing_contents()) {
631 // |render_view_host()| can be NULL if the user middle clicks a link to open
632 // a tab in then background, then closes the tab before selecting it. This
633 // is because closing the tab calls TabContents::Destroy(), which removes
634 // the |render_view_host()|; then when we actually destroy the window,
635 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
636 if (render_widget_host_view())
637 render_widget_host_view()->WasHidden();
[email protected]96d185d2009-04-24 03:28:54638 }
639
640 NotificationService::current()->Notify(
641 NotificationType::TAB_CONTENTS_HIDDEN,
642 Source<TabContents>(this),
643 NotificationService::NoDetails());
644}
645
[email protected]d5f942ba2008-09-26 19:30:34646void TabContents::Activate() {
647 if (delegate_)
648 delegate_->ActivateContents(this);
649}
650
[email protected]96d185d2009-04-24 03:28:54651void TabContents::ShowContents() {
652 if (render_widget_host_view())
653 render_widget_host_view()->DidBecomeSelected();
[email protected]96d185d2009-04-24 03:28:54654}
655
656void TabContents::HideContents() {
657 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
658 // our superclass HideContents(), because some callers want to be very picky
659 // about the order in which these get called. In addition to making the code
660 // here practically impossible to understand, this also means we end up
661 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34662 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54663 WasHidden();
664}
665
[email protected]c0588052008-10-27 23:01:50666void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34667 WindowOpenDisposition disposition,
668 PageTransition::Type transition) {
669 if (delegate_)
[email protected]c0588052008-10-27 23:01:50670 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34671}
672
673bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54674 const NavigationEntry& entry = *controller_.pending_entry();
675
676 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
677 if (!dest_render_view_host)
678 return false; // Unable to create the desired render view host.
679
680 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]d9f9b792009-06-24 13:17:12681 DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
[email protected]7e8e6b62009-05-08 11:28:32682 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41683 devtools_manager->OnNavigatingToPendingEntry(
684 render_view_host(),
685 dest_render_view_host,
686 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32687 }
[email protected]96d185d2009-04-24 03:28:54688
689 // Used for page load time metrics.
690 current_load_start_ = base::TimeTicks::Now();
691
692 // Navigate in the desired RenderViewHost.
[email protected]056de2d2009-06-26 16:41:34693 ViewMsg_Navigate_Params navigate_params;
694 MakeNavigateParams(entry, reload, &navigate_params);
695 dest_render_view_host->Navigate(navigate_params);
[email protected]96d185d2009-04-24 03:28:54696
697 if (entry.page_id() == -1) {
698 // HACK!! This code suppresses javascript: URLs from being added to
699 // session history, which is what we want to do for javascript: URLs that
700 // do not generate content. What we really need is a message from the
701 // renderer telling us that a new page was not created. The same message
702 // could be used for mailto: URLs and the like.
703 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
704 return false;
705 }
706
707 // Clear any provisional password saves - this stops password infobars
708 // showing up on pages the user navigates to while the right page is
709 // loading.
710 GetPasswordManager()->ClearProvisionalSave();
711
712 if (reload && !profile()->IsOffTheRecord()) {
[email protected]0189bc722009-08-28 21:56:48713 FaviconService* favicon_service =
714 profile()->GetFaviconService(Profile::IMPLICIT_ACCESS);
715 if (favicon_service)
716 favicon_service->SetFaviconOutOfDateForPage(entry.url());
[email protected]96d185d2009-04-24 03:28:54717 }
718
[email protected]d5f942ba2008-09-26 19:30:34719 return true;
720}
721
[email protected]96d185d2009-04-24 03:28:54722void TabContents::Stop() {
723 render_manager_.Stop();
724 printing_.Stop();
725}
726
727void TabContents::Cut() {
728 render_view_host()->Cut();
729}
730
731void TabContents::Copy() {
732 render_view_host()->Copy();
733}
734
[email protected]c0cc3092009-09-12 08:27:27735#if defined(OS_MACOSX)
[email protected]a954bf72009-09-12 07:30:35736void TabContents::CopyToFindPboard() {
737 render_view_host()->CopyToFindPboard();
738}
[email protected]c0cc3092009-09-12 08:27:27739#endif
[email protected]a954bf72009-09-12 07:30:35740
[email protected]96d185d2009-04-24 03:28:54741void TabContents::Paste() {
742 render_view_host()->Paste();
743}
744
745void TabContents::DisassociateFromPopupCount() {
746 render_view_host()->DisassociateFromPopupCount();
747}
748
749TabContents* TabContents::Clone() {
750 // We create a new SiteInstance so that the new tab won't share processes
751 // with the old one. This can be changed in the future if we need it to share
752 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32753 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54754 SiteInstance::CreateSiteInstance(profile()),
[email protected]12636df2009-09-28 22:32:21755 MSG_ROUTING_NONE, this);
[email protected]96d185d2009-04-24 03:28:54756 tc->controller().CopyStateFrom(controller_);
757 return tc;
758}
759
[email protected]420ae012009-04-24 05:16:32760void TabContents::CreateShortcut() {
761 NavigationEntry* entry = controller_.GetLastCommittedEntry();
762 if (!entry)
763 return;
764
[email protected]70b8d6b2009-08-20 16:56:24765#if defined(OS_LINUX) && !defined(TOOLKIT_VIEWS)
[email protected]0b303cc2009-09-28 22:35:15766 SkBitmap bitmap;
767 if (FavIconIsValid())
768 bitmap = GetFavIcon();
[email protected]0ba5c5e2009-08-20 16:47:13769 CreateApplicationShortcutsDialogGtk::Show(view()->GetTopLevelNativeWindow(),
[email protected]0b303cc2009-09-28 22:35:15770 GetURL(), GetTitle(), bitmap);
[email protected]b96aa932009-08-12 21:34:49771#else
[email protected]420ae012009-04-24 05:16:32772 // We only allow one pending install request. By resetting the page id we
773 // effectively cancel the pending install request.
774 pending_install_.page_id = entry->page_id();
775 pending_install_.icon = GetFavIcon();
[email protected]00e3f152009-10-20 19:25:42776 pending_install_.title = GetTitle();
[email protected]420ae012009-04-24 05:16:32777 pending_install_.url = GetURL();
778 if (pending_install_.callback_functor) {
779 pending_install_.callback_functor->Cancel();
780 pending_install_.callback_functor = NULL;
781 }
782 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
783 if (pending_install_.title.empty())
[email protected]00e3f152009-10-20 19:25:42784 pending_install_.title = UTF8ToUTF16(GetURL().spec());
[email protected]420ae012009-04-24 05:16:32785
786 // Request the application info. When done OnDidGetApplicationInfo is invoked
787 // and we'll create the shortcut.
788 render_view_host()->GetApplicationInfo(pending_install_.page_id);
[email protected]b96aa932009-08-12 21:34:49789#endif
[email protected]420ae012009-04-24 05:16:32790}
791
[email protected]4d677202009-07-19 07:37:12792void TabContents::ShowPageInfo(const GURL& url,
793 const NavigationEntry::SSLStatus& ssl,
794 bool show_history) {
795 if (!delegate_)
796 return;
797
[email protected]bb678332009-07-21 00:15:50798 delegate_->ShowPageInfo(profile(), url, ssl, show_history);
[email protected]4d677202009-07-19 07:37:12799}
800
initial.commit09911bf2008-07-26 23:55:29801ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]e8382172009-06-19 22:16:28802 ConstrainedWindowDelegate* delegate) {
initial.commit09911bf2008-07-26 23:55:29803 ConstrainedWindow* window =
[email protected]e8382172009-06-19 22:16:28804 ConstrainedWindow::CreateConstrainedDialog(this, delegate);
initial.commit09911bf2008-07-26 23:55:29805 child_windows_.push_back(window);
806 return window;
807}
808
809void TabContents::AddNewContents(TabContents* new_contents,
810 WindowOpenDisposition disposition,
811 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22812 bool user_gesture,
813 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29814 if (!delegate_)
815 return;
816
[email protected]35f7d212009-04-29 21:19:27817 if ((disposition == NEW_POPUP) && !user_gesture &&
818 !CommandLine::ForCurrentProcess()->HasSwitch(
819 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22820 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31821 // the whitelist. The popup owner will handle checking this.
822 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
823 initial_pos,
824 creator_url.is_valid() ? creator_url.host() : std::string());
825 } else {
[email protected]304f8792009-08-19 21:28:09826#if defined(OS_CHROMEOS)
827 if (disposition == NEW_POPUP) {
828 // If the popup is bigger than a given factor of the screen, then
829 // turn it into a foreground tab (on chrome os only)
830 GdkScreen* screen = gdk_screen_get_default();
831 int max_width = gdk_screen_get_width(screen) * kMaxWidthFactor;
832 int max_height = gdk_screen_get_height(screen) * kMaxHeightFactor;
833 if (initial_pos.width() > max_width ||
834 initial_pos.height() > max_height) {
835 disposition = NEW_FOREGROUND_TAB;
836 }
837 }
838#endif
839
[email protected]0aa55312008-10-17 21:53:08840 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29841 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
842 user_gesture);
[email protected]7f37dd92009-09-15 16:35:49843 NotificationService::current()->Notify(
844 NotificationType::TAB_ADDED,
845 Source<TabContentsDelegate>(delegate_),
846 Details<TabContents>(this));
initial.commit09911bf2008-07-26 23:55:29847 }
[email protected]b6c874582009-05-08 19:38:31848 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
initial.commit09911bf2008-07-26 23:55:29849}
850
initial.commit09911bf2008-07-26 23:55:29851void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25852 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22853 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29854}
855
[email protected]912256b32009-09-18 09:47:35856void TabContents::ExecuteCode(int request_id, const std::string& extension_id,
857 bool is_js_code, const std::string& code_string) {
858 render_view_host()->Send(
859 new ViewMsg_ExecuteCode(render_view_host()->routing_id(), request_id,
860 extension_id, is_js_code, code_string));
861}
862
[email protected]96d185d2009-04-24 03:28:54863void TabContents::PopupNotificationVisibilityChanged(bool visible) {
864 render_view_host()->PopupNotificationVisibilityChanged(visible);
865}
866
[email protected]5c9e97a2009-09-09 23:48:30867gfx::NativeView TabContents::GetContentNativeView() const {
[email protected]96d185d2009-04-24 03:28:54868 return view_->GetContentNativeView();
869}
870
871gfx::NativeView TabContents::GetNativeView() const {
872 return view_->GetNativeView();
873}
874
875void TabContents::GetContainerBounds(gfx::Rect *out) const {
876 view_->GetContainerBounds(out);
877}
878
879void TabContents::Focus() {
880 view_->Focus();
881}
882
[email protected]90daadb42009-06-08 21:27:28883void TabContents::FocusThroughTabTraversal(bool reverse) {
[email protected]7e383692009-06-12 19:14:54884 if (showing_interstitial_page()) {
885 render_manager_.interstitial_page()->FocusThroughTabTraversal(reverse);
886 return;
887 }
[email protected]96d185d2009-04-24 03:28:54888 render_view_host()->SetInitialFocus(reverse);
889}
890
891bool TabContents::FocusLocationBarByDefault() {
892 DOMUI* dom_ui = GetDOMUIForCurrentState();
893 if (dom_ui)
894 return dom_ui->focus_location_bar_by_default();
[email protected]3e3f0eb2009-06-22 18:33:43895 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]e0d481582009-09-15 21:06:25896 if (entry && entry->url() == GURL(chrome::kAboutBlankURL))
[email protected]3e3f0eb2009-06-22 18:33:43897 return true;
[email protected]96d185d2009-04-24 03:28:54898 return false;
899}
900
[email protected]616ed5a2008-11-21 22:27:24901void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
902 // Look through the existing InfoBarDelegates we have for a match. If we've
903 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05904 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24905 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
906 return;
907 }
908
909 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56910 NotificationService::current()->Notify(
911 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
912 Source<TabContents>(this),
913 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24914
915 // Add ourselves as an observer for navigations the first time a delegate is
916 // added. We use this notification to expire InfoBars that need to expire on
917 // page transitions.
918 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56919 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57920 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24921 }
922}
923
924void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
925 std::vector<InfoBarDelegate*>::iterator it =
926 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
927 if (it != infobar_delegates_.end()) {
928 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56929 NotificationService::current()->Notify(
930 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
931 Source<TabContents>(this),
932 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05933 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24934
[email protected]6a02963e2009-01-06 16:58:03935 // Remove ourselves as an observer if we are tracking no more InfoBars.
936 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56937 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57938 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03939 }
[email protected]616ed5a2008-11-21 22:27:24940 }
941}
[email protected]3edd9522009-03-04 22:19:41942
[email protected]f81821c2009-08-07 01:29:47943void TabContents::ReplaceInfoBar(InfoBarDelegate* old_delegate,
944 InfoBarDelegate* new_delegate) {
945 std::vector<InfoBarDelegate*>::iterator it =
946 find(infobar_delegates_.begin(), infobar_delegates_.end(), old_delegate);
947 DCHECK(it != infobar_delegates_.end());
948
949 // Notify the container about the change of plans.
950 scoped_ptr<std::pair<InfoBarDelegate*, InfoBarDelegate*> > details(
951 new std::pair<InfoBarDelegate*, InfoBarDelegate*>(
952 old_delegate, new_delegate));
953 NotificationService::current()->Notify(
954 NotificationType::TAB_CONTENTS_INFOBAR_REPLACED,
955 Source<TabContents>(this),
956 Details<std::pair<InfoBarDelegate*, InfoBarDelegate*> >(details.get()));
957
958 // Remove the old one.
959 infobar_delegates_.erase(it);
960
961 // Add the new one.
962 infobar_delegates_.push_back(new_delegate);
963}
964
[email protected]20ede072009-10-06 00:28:35965bool TabContents::ShouldShowBookmarkBar() {
[email protected]aa9196f2009-10-22 16:20:27966 if (showing_interstitial_page())
967 return false;
968
[email protected]96d185d2009-04-24 03:28:54969 // See GetDOMUIForCurrentState() comment for more info. This case is very
970 // similar, but for non-first loads, we want to use the committed entry. This
971 // is so the bookmarks bar disappears at the same time the page does.
972 if (controller_.GetLastCommittedEntry()) {
973 // Not the first load, always use the committed DOM UI.
974 if (render_manager_.dom_ui())
975 return render_manager_.dom_ui()->force_bookmark_bar_visible();
976 return false; // Default.
977 }
978
979 // When it's the first load, we know either the pending one or the committed
980 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
981 // of them will be valid, so we can just check both.
982 if (render_manager_.pending_dom_ui())
983 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
984 if (render_manager_.dom_ui())
985 return render_manager_.dom_ui()->force_bookmark_bar_visible();
986 return false; // Default.
987}
988
[email protected]d8f16ae2009-08-30 03:47:26989bool TabContents::IsExtensionShelfAlwaysVisible() {
990 // See GetDOMUIForCurrentState() comment for more info. This case is very
991 // similar, but for non-first loads, we want to use the committed entry. This
992 // is so the bookmarks bar disappears at the same time the page does.
993 if (controller_.GetLastCommittedEntry()) {
994 // Not the first load, always use the committed DOM UI.
995 if (render_manager_.dom_ui())
996 return render_manager_.dom_ui()->force_extension_shelf_visible();
997 return false; // Default.
998 }
999
1000 // When it's the first load, we know either the pending one or the committed
1001 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
1002 // of them will be valid, so we can just check both.
1003 if (render_manager_.pending_dom_ui())
1004 return render_manager_.pending_dom_ui()->force_extension_shelf_visible();
1005 if (render_manager_.dom_ui())
1006 return render_manager_.dom_ui()->force_extension_shelf_visible();
1007 return false; // Default.
1008}
1009
[email protected]3edd9522009-03-04 22:19:411010void TabContents::ToolbarSizeChanged(bool is_animating) {
1011 TabContentsDelegate* d = delegate();
1012 if (d)
1013 d->ToolbarSizeChanged(this, is_animating);
1014}
[email protected]616ed5a2008-11-21 22:27:241015
[email protected]d5f942ba2008-09-26 19:30:341016void TabContents::OnStartDownload(DownloadItem* download) {
1017 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:341018
1019 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:311020 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:341021
[email protected]59560e0b2009-06-04 03:30:221022 if (tab_contents && tab_contents->delegate())
1023 tab_contents->delegate()->OnStartDownload(download);
[email protected]3edd9522009-03-04 22:19:411024}
[email protected]3edd9522009-03-04 22:19:411025
[email protected]d5f942ba2008-09-26 19:30:341026void TabContents::WillClose(ConstrainedWindow* window) {
1027 ConstrainedWindowList::iterator it =
1028 find(child_windows_.begin(), child_windows_.end(), window);
1029 if (it != child_windows_.end())
1030 child_windows_.erase(it);
[email protected]66ba4932009-06-04 19:22:131031}
[email protected]d5f942ba2008-09-26 19:30:341032
[email protected]66ba4932009-06-04 19:22:131033void TabContents::WillCloseBlockedPopupContainer(
1034 BlockedPopupContainer* container) {
1035 DCHECK(blocked_popups_ == container);
1036 blocked_popups_ = NULL;
[email protected]d5f942ba2008-09-26 19:30:341037}
1038
[email protected]d5f942ba2008-09-26 19:30:341039void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:351040#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:061041 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:351042#endif
[email protected]d5f942ba2008-09-26 19:30:341043}
1044
[email protected]e491f1c2009-05-22 20:28:121045void TabContents::StartFinding(string16 find_text,
1046 bool forward_direction,
1047 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:011048 // If find_text is empty, it means FindNext was pressed with a keyboard
1049 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:121050 if (find_text.empty() && find_text_.empty()) {
1051 if (last_search_prepopulate_text_->empty())
1052 return;
1053 // Try whatever we searched for last in any tab.
1054 find_text = *last_search_prepopulate_text_;
1055 }
[email protected]6e95706d2009-04-23 22:55:011056
[email protected]101c90e2009-10-26 21:14:441057 // Keep track of the previous search.
1058 previous_find_text_ = find_text_;
1059
[email protected]6e95706d2009-04-23 22:55:011060 // This is a FindNext operation if we are searching for the same text again,
1061 // or if the passed in search text is empty (FindNext keyboard shortcut). The
1062 // exception to this is if the Find was aborted (then we don't want FindNext
1063 // because the highlighting has been cleared and we need it to reappear). We
1064 // therefore treat FindNext after an aborted Find operation as a full fledged
1065 // Find.
1066 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:121067 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:011068 !find_op_aborted_;
1069 if (!find_next)
1070 current_find_request_id_ = find_request_id_counter_++;
1071
1072 if (!find_text.empty())
1073 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:121074 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:011075
1076 find_op_aborted_ = false;
1077
1078 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:121079 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:011080
1081 render_view_host()->StartFinding(current_find_request_id_,
1082 find_text_,
1083 forward_direction,
[email protected]e491f1c2009-05-22 20:28:121084 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:011085 find_next);
1086}
1087
1088void TabContents::StopFinding(bool clear_selection) {
[email protected]2d2dffc2009-06-09 21:41:001089 // When |clear_selection| is true, it means the find string has been cleared
1090 // by the user, but the UI has not been dismissed.
1091 if (!clear_selection)
1092 find_ui_active_ = false;
[email protected]101c90e2009-10-26 21:14:441093 find_text_.clear();
[email protected]6e95706d2009-04-23 22:55:011094 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:121095 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:011096 render_view_host()->StopFinding(clear_selection);
1097}
1098
[email protected]5c4266922009-07-10 16:41:271099void TabContents::GetPageLanguage() {
1100 render_view_host()->GetPageLanguage();
1101}
1102
[email protected]420ae012009-04-24 05:16:321103void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
1104 bool success,
1105 const std::wstring& prompt) {
1106 last_javascript_message_dismissal_ = base::TimeTicks::Now();
[email protected]7ab1e7d62009-10-14 23:32:011107 if (is_showing_before_unload_dialog_ && !success) {
1108 // If a beforeunload dialog is canceled, we need to stop the throbber from
1109 // spinning, since we forced it to start spinning in Navigate.
1110 DidStopLoading();
1111
1112 tab_close_start_time_ = base::TimeTicks();
1113 }
1114 is_showing_before_unload_dialog_ = false;
1115 render_view_host()->JavaScriptMessageBoxClosed(reply_msg, success, prompt);
[email protected]420ae012009-04-24 05:16:321116}
1117
1118void TabContents::OnSavePage() {
1119 // If we can not save the page, try to download it.
1120 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1121 DownloadManager* dlm = profile()->GetDownloadManager();
1122 const GURL& current_page_url = GetURL();
1123 if (dlm && current_page_url.is_valid())
[email protected]d82ed61e2009-06-16 02:46:221124 dlm->DownloadUrl(current_page_url, GURL(), "", this);
[email protected]420ae012009-04-24 05:16:321125 return;
1126 }
1127
1128 Stop();
1129
1130 // Create the save package and possibly prompt the user for the name to save
1131 // the page as. The user prompt is an asynchronous operation that runs on
1132 // another thread.
[email protected]d82ed61e2009-06-16 02:46:221133 save_package_ = new SavePackage(this);
[email protected]420ae012009-04-24 05:16:321134 save_package_->GetSaveInfo();
1135}
1136
1137// Used in automated testing to bypass prompting the user for file names.
1138// Instead, the names and paths are hard coded rather than running them through
1139// file name sanitation and extension / mime checking.
[email protected]828cabe2009-09-26 22:47:111140bool TabContents::SavePage(const FilePath& main_file, const FilePath& dir_path,
[email protected]420ae012009-04-24 05:16:321141 SavePackage::SavePackageType save_type) {
1142 // Stop the page from navigating.
1143 Stop();
1144
[email protected]828cabe2009-09-26 22:47:111145 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
[email protected]cdf6cc82009-08-04 21:48:591146 return save_package_->Init();
[email protected]420ae012009-04-24 05:16:321147}
1148
1149void TabContents::PrintPreview() {
1150 // We don't show the print preview yet, only the print dialog.
1151 PrintNow();
1152}
1153
1154bool TabContents::PrintNow() {
1155 // We can't print interstitial page for now.
1156 if (showing_interstitial_page())
1157 return false;
1158
1159 return render_view_host()->PrintPages();
1160}
1161
[email protected]82270452009-06-19 15:58:011162void TabContents::PrintingDone(int document_cookie, bool success) {
1163 render_view_host()->PrintingDone(document_cookie, success);
1164}
1165
[email protected]420ae012009-04-24 05:16:321166bool TabContents::IsActiveEntry(int32 page_id) {
1167 NavigationEntry* active_entry = controller_.GetActiveEntry();
1168 return (active_entry != NULL &&
1169 active_entry->site_instance() == GetSiteInstance() &&
1170 active_entry->page_id() == page_id);
1171}
1172
[email protected]3f8eb7f2009-10-02 23:58:051173void TabContents::LogNewTabTime(const std::string& event_name) {
1174 // Not all new tab pages get timed. In those cases, we don't have a
1175 // new_tab_start_time_.
1176 if (new_tab_start_time_.is_null())
1177 return;
1178
1179 base::TimeDelta duration = base::TimeTicks::Now() - new_tab_start_time_;
[email protected]84abba62009-10-07 17:01:441180 MetricEventDurationDetails details(event_name,
1181 static_cast<int>(duration.InMilliseconds()));
1182
[email protected]7ab1e7d62009-10-14 23:32:011183 if (event_name == "Tab.NewTabScriptStart") {
1184 UMA_HISTOGRAM_TIMES("Tab.NewTabScriptStart", duration);
1185 } else if (event_name == "Tab.NewTabDOMContentLoaded") {
1186 UMA_HISTOGRAM_TIMES("Tab.NewTabDOMContentLoaded", duration);
1187 } else if (event_name == "Tab.NewTabOnload") {
1188 UMA_HISTOGRAM_TIMES("Tab.NewTabOnload", duration);
[email protected]3f8eb7f2009-10-02 23:58:051189 // The new tab page has finished loading; reset it.
1190 new_tab_start_time_ = base::TimeTicks();
[email protected]84abba62009-10-07 17:01:441191 } else {
1192 NOTREACHED();
[email protected]3f8eb7f2009-10-02 23:58:051193 }
[email protected]84abba62009-10-07 17:01:441194 NotificationService::current()->Notify(
1195 NotificationType::METRIC_EVENT_DURATION,
1196 Source<TabContents>(this),
1197 Details<MetricEventDurationDetails>(&details));
[email protected]3f8eb7f2009-10-02 23:58:051198}
1199
[email protected]7ab1e7d62009-10-14 23:32:011200void TabContents::OnCloseStarted() {
1201 if (tab_close_start_time_.is_null())
1202 tab_close_start_time_ = base::TimeTicks::Now();
1203}
1204
[email protected]96d185d2009-04-24 03:28:541205// Notifies the RenderWidgetHost instance about the fact that the page is
1206// loading, or done loading and calls the base implementation.
1207void TabContents::SetIsLoading(bool is_loading,
1208 LoadNotificationDetails* details) {
1209 if (is_loading == is_loading_)
1210 return;
1211
1212 if (!is_loading) {
1213 load_state_ = net::LOAD_STATE_IDLE;
1214 load_state_host_.clear();
[email protected]094e5b22009-09-25 04:23:561215 upload_size_ = 0;
1216 upload_position_ = 0;
[email protected]96d185d2009-04-24 03:28:541217 }
1218
1219 render_manager_.SetIsLoading(is_loading);
1220
1221 is_loading_ = is_loading;
1222 waiting_for_response_ = is_loading;
1223
1224 if (delegate_)
1225 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351226 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541227
1228 NotificationType type = is_loading ? NotificationType::LOAD_START :
1229 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111230 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541231 if (details)
1232 det = Details<LoadNotificationDetails>(details);
1233 NotificationService::current()->Notify(type,
1234 Source<NavigationController>(&controller_),
1235 det);
1236}
1237
[email protected]2c4410d2009-05-06 23:46:221238void TabContents::CreateBlockedPopupContainerIfNecessary() {
1239 if (blocked_popups_)
1240 return;
1241
[email protected]4d4c0b92009-06-08 23:13:011242 blocked_popups_ = BlockedPopupContainer::Create(this, profile());
[email protected]2c4410d2009-05-06 23:46:221243}
1244
[email protected]b6c874582009-05-08 19:38:311245void TabContents::AddPopup(TabContents* new_contents,
1246 const gfx::Rect& initial_pos,
1247 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221248 CreateBlockedPopupContainerIfNecessary();
1249 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221250}
1251
[email protected]e69bce3dd2009-04-20 22:05:121252// TODO(brettw) This should be on the TabContentsView.
[email protected]66ba4932009-06-04 19:22:131253void TabContents::RepositionSupressedPopupsToFit() {
[email protected]d6598c052008-11-05 19:03:251254 if (blocked_popups_)
[email protected]4d4c0b92009-06-08 23:13:011255 blocked_popups_->RepositionBlockedPopupContainer();
[email protected]d5f942ba2008-09-26 19:30:341256}
1257
[email protected]b9681312008-11-07 00:08:261258bool TabContents::ShowingBlockedPopupNotification() const {
1259 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221260 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261261}
[email protected]616ed5a2008-11-21 22:27:241262
1263namespace {
1264bool TransitionIsReload(PageTransition::Type transition) {
1265 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1266}
1267}
1268
1269void TabContents::ExpireInfoBars(
1270 const NavigationController::LoadCommittedDetails& details) {
1271 // Only hide InfoBars when the user has done something that makes the main
1272 // frame load. We don't want various automatic or subframe navigations making
1273 // it disappear.
1274 if (!details.is_user_initiated_main_frame_load())
1275 return;
1276
[email protected]f86a07022008-11-25 01:06:051277 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241278 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051279 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241280 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241281 }
1282}
[email protected]fdd61c62009-04-22 19:22:571283
1284void TabContents::OnGearsCreateShortcutDone(
1285 const GearsShortcutData2& shortcut_data, bool success) {
1286 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1287 bool same_page =
1288 current_entry && pending_install_.page_id == current_entry->page_id();
1289
1290 if (success && same_page) {
1291 // Only switch to app mode if the user chose to create a shortcut and
1292 // we're still on the same page that it corresponded to.
1293 if (delegate())
1294 delegate()->ConvertContentsToApplication(this);
1295 }
1296
1297 // Reset the page id to indicate no requests are pending.
1298 pending_install_.page_id = 0;
1299 pending_install_.callback_functor = NULL;
1300}
[email protected]96d185d2009-04-24 03:28:541301
1302DOMUI* TabContents::GetDOMUIForCurrentState() {
1303 // When there is a pending navigation entry, we want to use the pending DOMUI
1304 // that goes along with it to control the basic flags. For example, we want to
1305 // show the pending URL in the URL bar, so we want the display_url flag to
1306 // be from the pending entry.
1307 //
1308 // The confusion comes because there are multiple possibilities for the
1309 // initial load in a tab as a side effect of the way the RenderViewHostManager
1310 // works.
1311 //
1312 // - For the very first tab the load looks "normal". The new tab DOM UI is
1313 // the pending one, and we want it to apply here.
1314 //
1315 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1316 // get switched to the one previously associated with the new tab pages.
1317 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1318 // have a committed DOM UI in this case.
1319 //
1320 // This condition handles all of these cases:
1321 //
1322 // - First load in first tab: no committed nav entry + pending nav entry +
1323 // pending dom ui:
1324 // -> Use pending DOM UI if any.
1325 //
1326 // - First load in second tab: no committed nav entry + pending nav entry +
1327 // no pending DOM UI:
1328 // -> Use the committed DOM UI if any.
1329 //
1330 // - Second navigation in any tab: committed nav entry + pending nav entry:
1331 // -> Use pending DOM UI if any.
1332 //
1333 // - Normal state with no load: committed nav entry + no pending nav entry:
1334 // -> Use committed DOM UI.
1335 if (controller_.pending_entry() &&
1336 (controller_.GetLastCommittedEntry() ||
1337 render_manager_.pending_dom_ui()))
1338 return render_manager_.pending_dom_ui();
1339 return render_manager_.dom_ui();
1340}
[email protected]420ae012009-04-24 05:16:321341
1342void TabContents::DidNavigateMainFramePostCommit(
1343 const NavigationController::LoadCommittedDetails& details,
1344 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]c2e74fe82009-09-03 17:57:441345 if (opener_dom_ui_type_ != DOMUIFactory::kNoDOMUI) {
1346 // If this is a window.open navigation, use the same DOMUI as the renderer
1347 // that opened the window, as long as both renderers have the same
1348 // privileges.
1349 if (opener_dom_ui_type_ == DOMUIFactory::GetDOMUIType(GetURL())) {
1350 DOMUI* dom_ui = DOMUIFactory::CreateDOMUIForURL(this, GetURL());
1351 // dom_ui might be NULL if the URL refers to a non-existent extension.
1352 if (dom_ui) {
1353 render_manager_.SetDOMUIPostCommit(dom_ui);
1354 dom_ui->RenderViewCreated(render_view_host());
1355 }
1356 }
1357 opener_dom_ui_type_ = DOMUIFactory::kNoDOMUI;
1358 }
1359
[email protected]420ae012009-04-24 05:16:321360 if (details.is_user_initiated_main_frame_load()) {
1361 // Clear the status bubble. This is a workaround for a bug where WebKit
1362 // doesn't let us know that the cursor left an element during a
1363 // transition (this is also why the mouse cursor remains as a hand after
1364 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1365 // clear the bubble when a user navigates to a named anchor in the same
1366 // page.
1367 UpdateTargetURL(details.entry->page_id(), GURL());
1368
1369 // UpdateHelpersForDidNavigate will handle the case where the password_form
1370 // origin is valid.
1371 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1372 // cleaned up and covered by tests.
1373 if (!params.password_form.origin.is_valid())
1374 GetPasswordManager()->DidNavigate();
1375 }
1376
1377 // The keyword generator uses the navigation entries, so must be called after
1378 // the commit.
1379 GenerateKeywordIfNecessary(params);
1380
1381 // Allow the new page to set the title again.
1382 received_page_title_ = false;
1383
1384 // Get the favicon, either from history or request it from the net.
1385 fav_icon_helper_.FetchFavIcon(details.entry->url());
1386
[email protected]56ce6e52009-10-27 00:10:521387 // Clear all page and browser action state for this tab, unless this is an
1388 // in-page navigation.
[email protected]92c6f9b92009-10-24 04:35:081389 url_canon::Replacements<char> replacements;
1390 replacements.ClearRef();
1391 if (params.url.ReplaceComponents(replacements) !=
1392 params.referrer.ReplaceComponents(replacements)) {
[email protected]92c6f9b92009-10-24 04:35:081393 ExtensionsService* service = profile()->GetExtensionsService();
1394 if (service) {
1395 for (size_t i = 0; i < service->extensions()->size(); ++i) {
[email protected]5d246db22009-10-27 06:17:571396 ExtensionAction* browser_action =
[email protected]92c6f9b92009-10-24 04:35:081397 service->extensions()->at(i)->browser_action();
[email protected]56ce6e52009-10-27 00:10:521398 if (browser_action) {
1399 browser_action->ClearAllValuesForTab(controller().session_id().id());
1400 NotificationService::current()->Notify(
1401 NotificationType::EXTENSION_BROWSER_ACTION_UPDATED,
[email protected]5d246db22009-10-27 06:17:571402 Source<ExtensionAction>(browser_action),
[email protected]56ce6e52009-10-27 00:10:521403 NotificationService::NoDetails());
1404 }
[email protected]92c6f9b92009-10-24 04:35:081405
[email protected]5d246db22009-10-27 06:17:571406 ExtensionAction* page_action =
[email protected]56ce6e52009-10-27 00:10:521407 service->extensions()->at(i)->page_action();
1408 if (page_action) {
1409 page_action->ClearAllValuesForTab(controller().session_id().id());
1410 PageActionStateChanged();
1411 }
[email protected]92c6f9b92009-10-24 04:35:081412 }
[email protected]aece2c7f2009-08-27 20:43:171413 }
1414 }
[email protected]ce5c4502009-05-06 16:46:111415
[email protected]420ae012009-04-24 05:16:321416 // Close constrained popups if necessary.
1417 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1418
1419 // Update the starred state.
1420 UpdateStarredStateForCurrentURL();
1421}
1422
1423void TabContents::DidNavigateAnyFramePostCommit(
1424 RenderViewHost* render_view_host,
1425 const NavigationController::LoadCommittedDetails& details,
1426 const ViewHostMsg_FrameNavigate_Params& params) {
1427 // If we navigate, start showing messages again. This does nothing to prevent
1428 // a malicious script from spamming messages, since the script could just
1429 // reload the page to stop blocking.
1430 suppress_javascript_messages_ = false;
1431
[email protected]420ae012009-04-24 05:16:321432 // Notify the password manager of the navigation or form submit.
1433 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1434 // cleaned up and covered by tests.
1435 if (params.password_form.origin.is_valid())
1436 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1437}
1438
1439void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1440 const GURL& current_url) {
1441 if (net::RegistryControlledDomainService::SameDomainOrHost(
1442 previous_url, current_url))
1443 return;
1444
1445 // Clear out any child windows since we are leaving this page entirely.
1446 // We use indices instead of iterators in case CloseWindow does something
1447 // that may invalidate an iterator.
1448 int size = static_cast<int>(child_windows_.size());
1449 for (int i = size - 1; i >= 0; --i) {
1450 ConstrainedWindow* window = child_windows_[i];
1451 if (window)
1452 window->CloseConstrainedWindow();
1453 }
[email protected]e29300cd2009-07-23 21:14:591454
1455 // Close the popup container.
1456 if (blocked_popups_) {
1457 blocked_popups_->Destroy();
1458 blocked_popups_ = NULL;
1459 }
[email protected]420ae012009-04-24 05:16:321460}
1461
1462void TabContents::UpdateStarredStateForCurrentURL() {
1463 BookmarkModel* model = profile()->GetBookmarkModel();
1464 const bool old_state = is_starred_;
1465 is_starred_ = (model && model->IsBookmarked(GetURL()));
1466
1467 if (is_starred_ != old_state && delegate())
1468 delegate()->URLStarredChanged(this, is_starred_);
1469}
1470
1471void TabContents::UpdateAlternateErrorPageURL() {
1472 GURL url = GetAlternateErrorPageURL();
1473 render_view_host()->SetAlternateErrorPageURL(url);
1474}
1475
1476void TabContents::UpdateWebPreferences() {
1477 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1478}
1479
1480void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1481 RenderViewHost* rvh) {
1482 // If we are creating a RVH for a restored controller, then we might
1483 // have more page IDs than the SiteInstance's current max page ID. We must
1484 // make sure that the max page ID is larger than any restored page ID.
1485 // Note that it is ok for conflicting page IDs to exist in another tab
1486 // (i.e., NavigationController), but if any page ID is larger than the max,
1487 // the back/forward list will get confused.
1488 int max_restored_page_id = controller_.max_restored_page_id();
1489 if (max_restored_page_id > 0) {
1490 int curr_max_page_id = site_instance->max_page_id();
1491 if (max_restored_page_id > curr_max_page_id) {
1492 // Need to update the site instance immediately.
1493 site_instance->UpdateMaxPageID(max_restored_page_id);
1494
1495 // Also tell the renderer to update its internal representation. We
1496 // need to reserve enough IDs to make all restored page IDs less than
1497 // the max.
1498 if (curr_max_page_id < 0)
1499 curr_max_page_id = 0;
1500 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1501 }
1502 }
1503}
1504
1505void TabContents::UpdateHistoryForNavigation(
[email protected]ebe89e062009-08-13 23:16:541506 const GURL& virtual_url,
[email protected]befd8d822009-07-01 04:51:471507 const NavigationController::LoadCommittedDetails& details,
[email protected]420ae012009-04-24 05:16:321508 const ViewHostMsg_FrameNavigate_Params& params) {
1509 if (profile()->IsOffTheRecord())
1510 return;
1511
1512 // Add to history service.
1513 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1514 if (hs) {
1515 if (PageTransition::IsMainFrame(params.transition) &&
[email protected]ebe89e062009-08-13 23:16:541516 virtual_url != params.url) {
1517 // Hack on the "virtual" URL so that it will appear in history. For some
[email protected]420ae012009-04-24 05:16:321518 // types of URLs, we will display a magic URL that is different from where
1519 // the page is actually navigated. We want the user to see in history
[email protected]ebe89e062009-08-13 23:16:541520 // what they saw in the URL bar, so we add the virtual URL as a redirect.
1521 // This only applies to the main frame, as the virtual URL doesn't apply
[email protected]420ae012009-04-24 05:16:321522 // to sub-frames.
1523 std::vector<GURL> redirects = params.redirects;
1524 if (!redirects.empty())
[email protected]ebe89e062009-08-13 23:16:541525 redirects.back() = virtual_url;
1526 hs->AddPage(virtual_url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471527 params.transition, redirects, details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321528 } else {
1529 hs->AddPage(params.url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471530 params.transition, params.redirects,
1531 details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321532 }
1533 }
1534}
1535
1536bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1537 const std::wstring& title) {
1538 // For file URLs without a title, use the pathname instead. In the case of a
1539 // synthesized title, we don't want the update to count toward the "one set
1540 // per page of the title to history."
1541 std::wstring final_title;
1542 bool explicit_set;
1543 if (entry->url().SchemeIsFile() && title.empty()) {
1544 final_title = UTF8ToWide(entry->url().ExtractFileName());
1545 explicit_set = false; // Don't count synthetic titles toward the set limit.
1546 } else {
1547 TrimWhitespace(title, TRIM_ALL, &final_title);
1548 explicit_set = true;
1549 }
1550
1551 if (final_title == UTF16ToWideHack(entry->title()))
1552 return false; // Nothing changed, don't bother.
1553
1554 entry->set_title(WideToUTF16Hack(final_title));
1555
1556 // Update the history system for this page.
1557 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1558 HistoryService* hs =
1559 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1560 if (hs)
[email protected]ebe89e062009-08-13 23:16:541561 hs->SetPageTitle(entry->virtual_url(), final_title);
[email protected]420ae012009-04-24 05:16:321562
1563 // Don't allow the title to be saved again for explicitly set ones.
1564 received_page_title_ = explicit_set;
1565 }
1566
1567 // Lastly, set the title for the view.
1568 view_->SetPageTitle(final_title);
1569
1570 return true;
1571}
1572
1573void TabContents::NotifySwapped() {
1574 // After sending out a swap notification, we need to send a disconnect
1575 // notification so that clients that pick up a pointer to |this| can NULL the
1576 // pointer. See Bug 1230284.
1577 notify_disconnection_ = true;
1578 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341579 NotificationType::TAB_CONTENTS_SWAPPED,
[email protected]d82ed61e2009-06-16 02:46:221580 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321581 NotificationService::NoDetails());
1582}
1583
1584void TabContents::NotifyConnected() {
1585 notify_disconnection_ = true;
1586 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341587 NotificationType::TAB_CONTENTS_CONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221588 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321589 NotificationService::NoDetails());
1590}
1591
1592void TabContents::NotifyDisconnected() {
1593 if (!notify_disconnection_)
1594 return;
1595
1596 notify_disconnection_ = false;
1597 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341598 NotificationType::TAB_CONTENTS_DISCONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221599 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321600 NotificationService::NoDetails());
1601}
1602
1603void TabContents::GenerateKeywordIfNecessary(
1604 const ViewHostMsg_FrameNavigate_Params& params) {
1605 if (!params.searchable_form_url.is_valid())
1606 return;
1607
1608 if (profile()->IsOffTheRecord())
1609 return;
1610
1611 int last_index = controller_.last_committed_entry_index();
1612 // When there was no previous page, the last index will be 0. This is
1613 // normally due to a form submit that opened in a new tab.
1614 // TODO(brettw) bug 916126: we should support keywords when form submits
1615 // happen in new tabs.
1616 if (last_index <= 0)
1617 return;
1618 const NavigationEntry* previous_entry =
1619 controller_.GetEntryAtIndex(last_index - 1);
1620 if (IsFormSubmit(previous_entry)) {
1621 // Only generate a keyword if the previous page wasn't itself a form
1622 // submit.
1623 return;
1624 }
1625
1626 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1627 previous_entry->user_typed_url() : previous_entry->url();
1628 std::wstring keyword =
1629 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1630 if (keyword.empty())
1631 return;
1632
1633 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1634 if (!url_model)
1635 return;
1636
1637 if (!url_model->loaded()) {
1638 url_model->Load();
1639 return;
1640 }
1641
1642 const TemplateURL* current_url;
1643 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1644 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1645 return;
1646
1647 if (current_url) {
1648 if (current_url->originating_url().is_valid()) {
1649 // The existing keyword was generated from an OpenSearch description
1650 // document, don't regenerate.
1651 return;
1652 }
1653 url_model->Remove(current_url);
1654 }
1655 TemplateURL* new_url = new TemplateURL();
1656 new_url->set_keyword(keyword);
1657 new_url->set_short_name(keyword);
1658 new_url->SetURL(url, 0, 0);
1659 new_url->add_input_encoding(params.searchable_form_encoding);
1660 DCHECK(controller_.GetLastCommittedEntry());
1661 const GURL& favicon_url =
1662 controller_.GetLastCommittedEntry()->favicon().url();
1663 if (favicon_url.is_valid()) {
1664 new_url->SetFavIconURL(favicon_url);
1665 } else {
1666 // The favicon url isn't valid. This means there really isn't a favicon,
1667 // or the favicon url wasn't obtained before the load started. This assumes
1668 // the later.
1669 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1670 // its url.
1671 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1672 }
1673 new_url->set_safe_for_autoreplace(true);
1674 url_model->Add(new_url);
1675}
1676
[email protected]bf5c2ff392009-07-08 16:24:331677void TabContents::OnUserGesture() {
1678 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
1679 DownloadRequestManager* drm = g_browser_process->download_request_manager();
1680 if (drm)
1681 drm->OnUserGesture(this);
[email protected]e7eaedde2009-09-25 20:09:491682 ExternalProtocolHandler::OnUserGesture();
[email protected]bf5c2ff392009-07-08 16:24:331683 controller_.OnUserGesture();
1684}
1685
1686void TabContents::OnFindReply(int request_id,
1687 int number_of_matches,
1688 const gfx::Rect& selection_rect,
1689 int active_match_ordinal,
1690 bool final_update) {
[email protected]3ce7ced2009-07-24 18:52:421691 // Ignore responses for requests that have been aborted.
1692 if (find_op_aborted_)
1693 return;
1694
[email protected]bf5c2ff392009-07-08 16:24:331695 // Ignore responses for requests other than the one we have most recently
1696 // issued. That way we won't act on stale results when the user has
1697 // already typed in another query.
1698 if (request_id != current_find_request_id_)
1699 return;
1700
1701 if (number_of_matches == -1)
1702 number_of_matches = last_search_result_.number_of_matches();
1703 if (active_match_ordinal == -1)
1704 active_match_ordinal = last_search_result_.active_match_ordinal();
1705
1706 gfx::Rect selection = selection_rect;
1707 if (selection.IsEmpty())
1708 selection = last_search_result_.selection_rect();
1709
1710 // Notify the UI, automation and any other observers that a find result was
1711 // found.
1712 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
1713 selection, active_match_ordinal,
1714 final_update);
1715 NotificationService::current()->Notify(
1716 NotificationType::FIND_RESULT_AVAILABLE,
1717 Source<TabContents>(this),
1718 Details<FindNotificationDetails>(&last_search_result_));
1719}
1720
1721void TabContents::GoToEntryAtOffset(int offset) {
[email protected]f9cc4c452009-10-13 14:56:381722 if (!delegate_ || delegate_->OnGoToEntryOffset(offset))
1723 controller_.GoToOffset(offset);
[email protected]bf5c2ff392009-07-08 16:24:331724}
1725
1726void TabContents::GetHistoryListCount(int* back_list_count,
1727 int* forward_list_count) {
1728 int current_index = controller_.last_committed_entry_index();
1729 *back_list_count = current_index;
1730 *forward_list_count = controller_.entry_count() - current_index - 1;
1731}
1732
1733void TabContents::OnMissingPluginStatus(int status) {
1734#if defined(OS_WIN)
1735// TODO(PORT): pull in when plug-ins work
1736 GetPluginInstaller()->OnMissingPluginStatus(status);
1737#endif
1738}
1739
1740void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
[email protected]bf5c2ff392009-07-08 16:24:331741 DCHECK(!plugin_path.value().empty());
1742
1743 std::wstring plugin_name = plugin_path.ToWStringHack();
[email protected]d32d46182009-07-23 00:09:351744#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]bf5c2ff392009-07-08 16:24:331745 scoped_ptr<FileVersionInfo> version_info(
1746 FileVersionInfo::CreateFileVersionInfo(plugin_path));
1747 if (version_info.get()) {
1748 const std::wstring& product_name = version_info->product_name();
[email protected]996fd702009-09-04 19:12:371749 if (!product_name.empty()) {
[email protected]bf5c2ff392009-07-08 16:24:331750 plugin_name = product_name;
[email protected]996fd702009-09-04 19:12:371751#if defined(OS_MACOSX)
1752 // Many plugins on the Mac have .plugin in the actual name, which looks
1753 // terrible, so look for that and strip it off if present.
1754 const std::wstring plugin_extension(L".plugin");
1755 if (EndsWith(plugin_name, plugin_extension, true))
1756 plugin_name.erase(plugin_name.length() - plugin_extension.length());
1757#endif // OS_MACOSX
1758 }
[email protected]bf5c2ff392009-07-08 16:24:331759 }
[email protected]4a560ed2009-07-13 23:35:261760#else
1761 NOTIMPLEMENTED() << " convert plugin path to plugin name";
1762#endif
[email protected]bf5c2ff392009-07-08 16:24:331763 AddInfoBar(new SimpleAlertInfoBarDelegate(
1764 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
1765 NULL));
[email protected]bf5c2ff392009-07-08 16:24:331766}
1767
1768void TabContents::OnCrashedWorker() {
1769 AddInfoBar(new SimpleAlertInfoBarDelegate(
1770 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
1771 NULL));
1772}
1773
1774void TabContents::OnDidGetApplicationInfo(
1775 int32 page_id,
1776 const webkit_glue::WebApplicationInfo& info) {
1777 if (pending_install_.page_id != page_id)
1778 return; // The user clicked create on a separate page. Ignore this.
1779
1780 pending_install_.callback_functor =
1781 new GearsCreateShortcutCallbackFunctor(this);
1782 GearsCreateShortcut(
1783 info, pending_install_.title, pending_install_.url, pending_install_.icon,
1784 NewCallback(pending_install_.callback_functor,
1785 &GearsCreateShortcutCallbackFunctor::Run));
1786}
1787
1788void TabContents::DidStartProvisionalLoadForFrame(
1789 RenderViewHost* render_view_host,
1790 bool is_main_frame,
1791 const GURL& url) {
1792 ProvisionalLoadDetails details(is_main_frame,
1793 controller_.IsURLInPageNavigation(url),
1794 url, std::string(), false);
1795 NotificationService::current()->Notify(
1796 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1797 Source<NavigationController>(&controller_),
1798 Details<ProvisionalLoadDetails>(&details));
1799}
1800
1801void TabContents::DidStartReceivingResourceResponse(
1802 ResourceRequestDetails* details) {
1803 NotificationService::current()->Notify(
1804 NotificationType::RESOURCE_RESPONSE_STARTED,
1805 Source<NavigationController>(&controller()),
1806 Details<ResourceRequestDetails>(details));
1807}
1808
1809void TabContents::DidRedirectResource(ResourceRequestDetails* details) {
1810 NotificationService::current()->Notify(
1811 NotificationType::RESOURCE_RECEIVED_REDIRECT,
1812 Source<NavigationController>(&controller()),
1813 Details<ResourceRequestDetails>(details));
1814}
1815
1816void TabContents::DidLoadResourceFromMemoryCache(
1817 const GURL& url,
1818 const std::string& frame_origin,
1819 const std::string& main_frame_origin,
1820 const std::string& security_info) {
1821 // Send out a notification that we loaded a resource from our memory cache.
1822 int cert_id = 0, cert_status = 0, security_bits = 0;
1823 SSLManager::DeserializeSecurityInfo(security_info,
1824 &cert_id, &cert_status,
1825 &security_bits);
1826 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]76543b92009-08-31 17:27:451827 process()->id(), cert_id, cert_status);
[email protected]bf5c2ff392009-07-08 16:24:331828
1829 NotificationService::current()->Notify(
1830 NotificationType::LOAD_FROM_MEMORY_CACHE,
1831 Source<NavigationController>(&controller_),
1832 Details<LoadFromMemoryCacheDetails>(&details));
1833}
1834
[email protected]e3d60e5d2009-09-25 21:08:291835void TabContents::DidDisplayInsecureContent() {
[email protected]09843b5f2009-09-26 08:30:591836 controller_.ssl_manager()->DidDisplayInsecureContent();
[email protected]e3d60e5d2009-09-25 21:08:291837}
1838
1839void TabContents::DidRunInsecureContent(const std::string& security_origin) {
[email protected]09843b5f2009-09-26 08:30:591840 controller_.ssl_manager()->DidRunInsecureContent(security_origin);
[email protected]e3d60e5d2009-09-25 21:08:291841}
1842
[email protected]bf5c2ff392009-07-08 16:24:331843void TabContents::DidFailProvisionalLoadWithError(
1844 RenderViewHost* render_view_host,
1845 bool is_main_frame,
1846 int error_code,
1847 const GURL& url,
1848 bool showing_repost_interstitial) {
1849 if (net::ERR_ABORTED == error_code) {
1850 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1851 // This means that the interstitial won't be torn down properly, which is
1852 // bad. But if we have an interstitial, go back to another tab type, and
1853 // then load the same interstitial again, we could end up getting the first
1854 // interstitial's "failed" message (as a result of the cancel) when we're on
1855 // the second one.
1856 //
1857 // We can't tell this apart, so we think we're tearing down the current page
1858 // which will cause a crash later one. There is also some code in
1859 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1860 // out because of this problem.
1861 //
1862 // http://code.google.com/p/chromium/issues/detail?id=2855
1863 // Because this will not tear down the interstitial properly, if "back" is
1864 // back to another tab type, the interstitial will still be somewhat alive
1865 // in the previous tab type. If you navigate somewhere that activates the
1866 // tab with the interstitial again, you'll see a flash before the new load
1867 // commits of the interstitial page.
1868 if (showing_interstitial_page()) {
1869 LOG(WARNING) << "Discarding message during interstitial.";
1870 return;
1871 }
1872
1873 // This will discard our pending entry if we cancelled the load (e.g., if we
1874 // decided to download the file instead of load it). Only discard the
1875 // pending entry if the URLs match, otherwise the user initiated a navigate
1876 // before the page loaded so that the discard would discard the wrong entry.
1877 NavigationEntry* pending_entry = controller_.pending_entry();
1878 if (pending_entry && pending_entry->url() == url) {
1879 controller_.DiscardNonCommittedEntries();
1880 // Update the URL display.
1881 NotifyNavigationStateChanged(TabContents::INVALIDATE_URL);
1882 }
1883
1884 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1885 }
1886
1887 // Send out a notification that we failed a provisional load with an error.
1888 ProvisionalLoadDetails details(is_main_frame,
1889 controller_.IsURLInPageNavigation(url),
1890 url, std::string(), false);
1891 details.set_error_code(error_code);
1892
1893 NotificationService::current()->Notify(
1894 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1895 Source<NavigationController>(&controller_),
1896 Details<ProvisionalLoadDetails>(&details));
1897}
1898
1899void TabContents::DocumentLoadedInFrame() {
1900 controller_.DocumentLoadedInFrame();
1901}
1902
[email protected]8d3347f2009-07-09 22:00:211903RenderViewHostDelegate::View* TabContents::GetViewDelegate() {
[email protected]420ae012009-04-24 05:16:321904 return view_.get();
1905}
1906
[email protected]8d3347f2009-07-09 22:00:211907RenderViewHostDelegate::RendererManagement*
1908TabContents::GetRendererManagementDelegate() {
1909 return &render_manager_;
1910}
1911
[email protected]bf5c2ff392009-07-08 16:24:331912RenderViewHostDelegate::BrowserIntegration*
[email protected]8d3347f2009-07-09 22:00:211913 TabContents::GetBrowserIntegrationDelegate() {
1914 return this;
[email protected]bf5c2ff392009-07-08 16:24:331915}
1916
[email protected]8d3347f2009-07-09 22:00:211917RenderViewHostDelegate::Resource* TabContents::GetResourceDelegate() {
1918 return this;
[email protected]bf5c2ff392009-07-08 16:24:331919}
1920
[email protected]8d3347f2009-07-09 22:00:211921RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() {
[email protected]420ae012009-04-24 05:16:321922 return save_package_.get(); // May be NULL, but we can return NULL.
1923}
1924
[email protected]8d3347f2009-07-09 22:00:211925RenderViewHostDelegate::Printing* TabContents::GetPrintingDelegate() {
1926 return &printing_;
1927}
1928
1929RenderViewHostDelegate::FavIcon* TabContents::GetFavIconDelegate() {
1930 return &fav_icon_helper_;
1931}
1932
[email protected]c54d269e2009-10-21 18:07:381933RenderViewHostDelegate::FormFieldHistory*
1934TabContents::GetFormFieldHistoryDelegate() {
[email protected]19289d02009-10-21 21:47:001935 if (form_field_history_manager_.get() == NULL)
1936 form_field_history_manager_.reset(new FormFieldHistoryManager(this));
1937 return form_field_history_manager_.get();
[email protected]bf5c2ff392009-07-08 16:24:331938}
1939
[email protected]80d96fa2009-06-10 22:34:511940RendererPreferences TabContents::GetRendererPrefs() const {
[email protected]840b1512009-07-21 16:53:461941 return renderer_preferences_;
[email protected]80d96fa2009-06-10 22:34:511942}
1943
[email protected]57c6a652009-05-04 07:58:341944TabContents* TabContents::GetAsTabContents() {
1945 return this;
1946}
1947
[email protected]3e7cf1362009-08-21 17:47:081948void TabContents::AddBlockedNotice(const GURL& url, const string16& reason) {
1949 CreateBlockedPopupContainerIfNecessary();
1950 blocked_popups_->AddBlockedNotice(url, reason);
1951}
1952
[email protected]7b291f92009-08-14 05:43:531953ViewType::Type TabContents::GetRenderViewType() const {
1954 return ViewType::TAB_CONTENTS;
1955}
1956
1957int TabContents::GetBrowserWindowID() const {
1958 return controller().window_id().id();
1959}
1960
[email protected]420ae012009-04-24 05:16:321961void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
[email protected]2e4633c2009-07-09 16:58:061962 NotificationService::current()->Notify(
1963 NotificationType::RENDER_VIEW_HOST_CREATED_FOR_TAB,
1964 Source<TabContents>(this),
1965 Details<RenderViewHost>(render_view_host));
[email protected]420ae012009-04-24 05:16:321966 NavigationEntry* entry = controller_.GetActiveEntry();
1967 if (!entry)
1968 return;
1969
1970 // When we're creating views, we're still doing initial setup, so we always
1971 // use the pending DOM UI rather than any possibly existing committed one.
1972 if (render_manager_.pending_dom_ui()) {
1973 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1974 }
1975
1976 if (entry->IsViewSourceMode()) {
1977 // Put the renderer in view source mode.
1978 render_view_host->Send(
1979 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1980 }
[email protected]0666aef2009-05-13 19:48:081981
1982 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321983}
1984
1985void TabContents::RenderViewReady(RenderViewHost* rvh) {
1986 if (rvh != render_view_host()) {
1987 // Don't notify the world, since this came from a renderer in the
1988 // background.
1989 return;
1990 }
1991
1992 NotifyConnected();
[email protected]9d8a4642009-07-29 17:25:301993 bool was_crashed = is_crashed();
[email protected]420ae012009-04-24 05:16:321994 SetIsCrashed(false);
[email protected]9d8a4642009-07-29 17:25:301995
1996 // Restore the focus to the tab (otherwise the focus will be on the top
1997 // window).
1998 if (was_crashed && !FocusLocationBarByDefault())
1999 Focus();
[email protected]420ae012009-04-24 05:16:322000}
2001
2002void TabContents::RenderViewGone(RenderViewHost* rvh) {
2003 // Ask the print preview if this renderer was valuable.
2004 if (!printing_.OnRenderViewGone(rvh))
2005 return;
2006 if (rvh != render_view_host()) {
2007 // The pending page's RenderViewHost is gone.
2008 return;
2009 }
2010
2011 SetIsLoading(false, NULL);
2012 NotifyDisconnected();
2013 SetIsCrashed(true);
2014
[email protected]8e537302009-06-10 21:19:582015 // Tell the view that we've crashed so it can prepare the sad tab page.
2016 view_->OnTabCrashed();
[email protected]420ae012009-04-24 05:16:322017
2018 // Hide any visible hung renderer warning for this web contents' process.
[email protected]d82ed61e2009-06-16 02:46:222019 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:322020}
2021
[email protected]2e4633c2009-07-09 16:58:062022void TabContents::RenderViewDeleted(RenderViewHost* rvh) {
2023 NotificationService::current()->Notify(
2024 NotificationType::RENDER_VIEW_HOST_DELETED,
2025 Source<TabContents>(this),
2026 Details<RenderViewHost>(rvh));
2027}
2028
[email protected]420ae012009-04-24 05:16:322029void TabContents::DidNavigate(RenderViewHost* rvh,
2030 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]8030f012009-09-25 18:09:372031 int extra_invalidate_flags = 0;
2032
2033 if (PageTransition::IsMainFrame(params.transition)) {
[email protected]20ede072009-10-06 00:28:352034 bool was_bookmark_bar_visible = ShouldShowBookmarkBar();
[email protected]8030f012009-09-25 18:09:372035 bool was_extension_shelf_visible = IsExtensionShelfAlwaysVisible();
2036
[email protected]420ae012009-04-24 05:16:322037 render_manager_.DidNavigateMainFrame(rvh);
2038
[email protected]20ede072009-10-06 00:28:352039 if (was_bookmark_bar_visible != ShouldShowBookmarkBar())
[email protected]8030f012009-09-25 18:09:372040 extra_invalidate_flags |= INVALIDATE_BOOKMARK_BAR;
2041 if (was_extension_shelf_visible != IsExtensionShelfAlwaysVisible())
2042 extra_invalidate_flags |= INVALIDATE_EXTENSION_SHELF;
2043 }
2044
[email protected]420ae012009-04-24 05:16:322045 // Update the site of the SiteInstance if it doesn't have one yet.
2046 if (!GetSiteInstance()->has_site())
2047 GetSiteInstance()->SetSite(params.url);
2048
2049 // Need to update MIME type here because it's referred to in
2050 // UpdateNavigationCommands() called by RendererDidNavigate() to
2051 // determine whether or not to enable the encoding menu.
2052 // It's updated only for the main frame. For a subframe,
2053 // RenderView::UpdateURL does not set params.contents_mime_type.
2054 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
2055 // TODO(jungshik): Add a test for the encoding menu to avoid
2056 // regressing it again.
2057 if (PageTransition::IsMainFrame(params.transition))
2058 contents_mime_type_ = params.contents_mime_type;
2059
2060 NavigationController::LoadCommittedDetails details;
[email protected]8030f012009-09-25 18:09:372061 bool did_navigate = controller_.RendererDidNavigate(
2062 params, extra_invalidate_flags, &details);
[email protected]3e90d4a2009-07-03 17:38:392063
2064 // Update history. Note that this needs to happen after the entry is complete,
2065 // which WillNavigate[Main,Sub]Frame will do before this function is called.
[email protected]2e29d922009-10-22 22:13:352066 if (params.should_update_history &&
2067 (!delegate() || delegate()->ShouldAddNavigationsToHistory())) {
[email protected]3e90d4a2009-07-03 17:38:392068 // Most of the time, the displayURL matches the loaded URL, but for about:
2069 // URLs, we use a data: URL as the real value. We actually want to save
2070 // the about: URL to the history db and keep the data: URL hidden. This is
2071 // what the TabContents' URL getter does.
2072 UpdateHistoryForNavigation(GetURL(), details, params);
2073 }
2074
[email protected]76543b92009-08-31 17:27:452075 if (!did_navigate)
2076 return; // No navigation happened.
[email protected]420ae012009-04-24 05:16:322077
2078 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
2079 // for the appropriate notification (best) or you can add it to
2080 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
2081 // necessary, please).
2082
2083 // Run post-commit tasks.
2084 if (details.is_main_frame)
2085 DidNavigateMainFramePostCommit(details, params);
2086 DidNavigateAnyFramePostCommit(rvh, details, params);
2087}
2088
2089void TabContents::UpdateState(RenderViewHost* rvh,
2090 int32 page_id,
2091 const std::string& state) {
2092 DCHECK(rvh == render_view_host());
2093
2094 // We must be prepared to handle state updates for any page, these occur
2095 // when the user is scrolling and entering form data, as well as when we're
2096 // leaving a page, in which case our state may have already been moved to
2097 // the next page. The navigation controller will look up the appropriate
2098 // NavigationEntry and update it when it is notified via the delegate.
2099
2100 int entry_index = controller_.GetEntryIndexWithPageID(
2101 GetSiteInstance(), page_id);
2102 if (entry_index < 0)
2103 return;
2104 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
2105
2106 if (state == entry->content_state())
2107 return; // Nothing to update.
2108 entry->set_content_state(state);
2109 controller_.NotifyEntryChanged(entry, entry_index);
2110}
2111
2112void TabContents::UpdateTitle(RenderViewHost* rvh,
2113 int32 page_id, const std::wstring& title) {
2114 // If we have a title, that's a pretty good indication that we've started
2115 // getting useful data.
2116 SetNotWaitingForResponse();
2117
2118 DCHECK(rvh == render_view_host());
2119 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
2120 page_id);
2121 if (!entry || !UpdateTitleForEntry(entry, title))
2122 return;
2123
2124 // Broadcast notifications when the UI should be updated.
2125 if (entry == controller_.GetEntryAtOffset(0))
[email protected]f1cd5e82009-10-23 17:19:032126 NotifyNavigationStateChanged(INVALIDATE_TITLE);
[email protected]420ae012009-04-24 05:16:322127}
2128
[email protected]420ae012009-04-24 05:16:322129void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
[email protected]41fc0322009-09-04 22:23:402130 const std::string& encoding) {
[email protected]420ae012009-04-24 05:16:322131 set_encoding(encoding);
2132}
2133
2134void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
2135 if (delegate())
2136 delegate()->UpdateTargetURL(this, url);
2137}
2138
2139void TabContents::UpdateThumbnail(const GURL& url,
2140 const SkBitmap& bitmap,
2141 const ThumbnailScore& score) {
2142 // Tell History about this thumbnail
[email protected]449478302009-06-09 20:04:282143 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kThumbnailStore)) {
[email protected]72d0fc72009-07-09 17:30:492144 if (!profile()->IsOffTheRecord())
[email protected]42339402009-07-17 17:27:192145 profile()->GetThumbnailStore()->SetPageThumbnail(url, bitmap,
2146 score, true);
[email protected]449478302009-06-09 20:04:282147 } else {
2148 HistoryService* hs;
2149 if (!profile()->IsOffTheRecord() &&
2150 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
2151 hs->SetPageThumbnail(url, bitmap, score);
2152 }
[email protected]420ae012009-04-24 05:16:322153 }
2154}
2155
[email protected]8922e1f2009-10-03 05:01:262156void TabContents::UpdateInspectorSettings(const std::string& raw_settings) {
[email protected]0df30122009-06-03 12:13:082157 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
[email protected]8922e1f2009-10-03 05:01:262158 UTF8ToWide(raw_settings));
[email protected]0df30122009-06-03 12:13:082159}
2160
[email protected]420ae012009-04-24 05:16:322161void TabContents::Close(RenderViewHost* rvh) {
[email protected]24a4d1062009-07-10 23:10:422162 // If we close the tab while we're in the middle of a drag, we'll crash.
2163 // Instead, cancel the drag and close it as soon as the drag ends.
2164 if (view()->IsDoingDrag()) {
2165 view()->CancelDragAndCloseTab();
2166 return;
2167 }
2168
[email protected]420ae012009-04-24 05:16:322169 // Ignore this if it comes from a RenderViewHost that we aren't showing.
2170 if (delegate() && rvh == render_view_host())
2171 delegate()->CloseContents(this);
2172}
2173
2174void TabContents::RequestMove(const gfx::Rect& new_bounds) {
2175 if (delegate() && delegate()->IsPopup(this))
2176 delegate()->MoveContents(this, new_bounds);
2177}
2178
[email protected]7ab1e7d62009-10-14 23:32:012179void TabContents::DidStartLoading() {
[email protected]420ae012009-04-24 05:16:322180 SetIsLoading(true, NULL);
2181}
2182
[email protected]7ab1e7d62009-10-14 23:32:012183void TabContents::DidStopLoading() {
[email protected]420ae012009-04-24 05:16:322184 scoped_ptr<LoadNotificationDetails> details;
2185
2186 NavigationEntry* entry = controller_.GetActiveEntry();
2187 // An entry may not exist for a stop when loading an initial blank page or
2188 // if an iframe injected by script into a blank page finishes loading.
2189 if (entry) {
2190 scoped_ptr<base::ProcessMetrics> metrics(
2191 base::ProcessMetrics::CreateProcessMetrics(
2192 process()->process().handle()));
2193
2194 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
2195
2196 details.reset(new LoadNotificationDetails(
[email protected]ebe89e062009-08-13 23:16:542197 entry->virtual_url(),
[email protected]420ae012009-04-24 05:16:322198 entry->transition_type(),
2199 elapsed,
2200 &controller_,
2201 controller_.GetCurrentEntryIndex()));
2202 }
2203
2204 // Tell PasswordManager we've finished a page load, which serves as a
2205 // green light to save pending passwords and reset itself.
2206 GetPasswordManager()->DidStopLoading();
2207
2208 SetIsLoading(false, details.get());
2209}
2210
[email protected]420ae012009-04-24 05:16:322211void TabContents::DidRedirectProvisionalLoad(int32 page_id,
2212 const GURL& source_url,
2213 const GURL& target_url) {
2214 NavigationEntry* entry;
2215 if (page_id == -1)
2216 entry = controller_.pending_entry();
2217 else
2218 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
2219 if (!entry || entry->url() != source_url)
2220 return;
2221 entry->set_url(target_url);
2222}
2223
[email protected]420ae012009-04-24 05:16:322224void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
2225 WindowOpenDisposition disposition) {
2226 if (render_manager_.dom_ui()) {
2227 // When we're a DOM UI, it will provide a page transition type for us (this
2228 // is so the new tab page can specify AUTO_BOOKMARK for automatically
2229 // generated suggestions).
2230 //
2231 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:162232 // want web sites to see a referrer of "chrome://blah" (and some
2233 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:322234 // send to the site), so we send no referrer.
2235 OpenURL(url, GURL(), disposition,
2236 render_manager_.dom_ui()->link_transition_type());
2237 } else {
2238 OpenURL(url, referrer, disposition, PageTransition::LINK);
2239 }
2240}
2241
[email protected]1ee614862009-07-06 20:29:182242void TabContents::DomOperationResponse(const std::string& json_string,
2243 int automation_id) {
2244}
2245
[email protected]420ae012009-04-24 05:16:322246void TabContents::ProcessDOMUIMessage(const std::string& message,
[email protected]e4dad9fb2009-10-06 18:15:582247 const Value* content,
[email protected]811bfe32009-07-01 08:46:252248 int request_id,
2249 bool has_callback) {
[email protected]420ae012009-04-24 05:16:322250 if (!render_manager_.dom_ui()) {
[email protected]c2e74fe82009-09-03 17:57:442251 // This can happen if someone uses window.open() to open an extension URL
2252 // from a non-extension context.
2253 render_view_host()->BlockExtensionRequest(request_id);
[email protected]420ae012009-04-24 05:16:322254 return;
2255 }
[email protected]811bfe32009-07-01 08:46:252256 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content, request_id,
2257 has_callback);
[email protected]420ae012009-04-24 05:16:322258}
2259
2260void TabContents::ProcessExternalHostMessage(const std::string& message,
2261 const std::string& origin,
2262 const std::string& target) {
2263 if (delegate())
2264 delegate()->ForwardMessageToExternalHost(message, origin, target);
2265}
2266
[email protected]420ae012009-04-24 05:16:322267void TabContents::RunFileChooser(bool multiple_files,
2268 const string16& title,
2269 const FilePath& default_file) {
2270 if (!select_file_dialog_.get())
2271 select_file_dialog_ = SelectFileDialog::Create(this);
2272 SelectFileDialog::Type dialog_type =
2273 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
2274 SelectFileDialog::SELECT_OPEN_FILE;
2275 select_file_dialog_->SelectFile(dialog_type, title, default_file,
2276 NULL, 0, FILE_PATH_LITERAL(""),
2277 view_->GetTopLevelNativeWindow(), NULL);
2278}
2279
2280void TabContents::RunJavaScriptMessage(
2281 const std::wstring& message,
2282 const std::wstring& default_prompt,
2283 const GURL& frame_url,
2284 const int flags,
2285 IPC::Message* reply_msg,
2286 bool* did_suppress_message) {
2287 // Suppress javascript messages when requested and when inside a constrained
2288 // popup window (because that activates them and breaks them out of the
2289 // constrained window jail).
[email protected]91ed49a2009-07-07 21:29:552290 // Also suppress messages when showing an interstitial. The interstitial is
2291 // shown over the previous page, we don't want the hidden page dialogs to
2292 // interfere with the interstitial.
2293 bool suppress_this_message = suppress_javascript_messages_ ||
2294 showing_interstitial_page();
[email protected]420ae012009-04-24 05:16:322295 if (delegate())
2296 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:312297 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:322298
2299 *did_suppress_message = suppress_this_message;
2300
2301 if (!suppress_this_message) {
2302 base::TimeDelta time_since_last_message(
2303 base::TimeTicks::Now() - last_javascript_message_dismissal_);
2304 bool show_suppress_checkbox = false;
2305 // Show a checkbox offering to suppress further messages if this message is
2306 // being displayed within kJavascriptMessageExpectedDelay of the last one.
2307 if (time_since_last_message <
2308 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
2309 show_suppress_checkbox = true;
2310
[email protected]d82ed61e2009-06-16 02:46:222311 RunJavascriptMessageBox(this, frame_url, flags, message, default_prompt,
[email protected]420ae012009-04-24 05:16:322312 show_suppress_checkbox, reply_msg);
2313 } else {
2314 // If we are suppressing messages, just reply as is if the user immediately
2315 // pressed "Cancel".
2316 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
2317 }
2318}
2319
2320void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
2321 IPC::Message* reply_msg) {
[email protected]7ab1e7d62009-10-14 23:32:012322 is_showing_before_unload_dialog_ = true;
[email protected]d82ed61e2009-06-16 02:46:222323 RunBeforeUnloadDialog(this, message, reply_msg);
[email protected]420ae012009-04-24 05:16:322324}
2325
2326void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
2327 const std::string& json_arguments,
2328 IPC::Message* reply_msg) {
2329 if (delegate()) {
2330 HtmlDialogUIDelegate* dialog_delegate =
2331 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
[email protected]d82ed61e2009-06-16 02:46:222332 reply_msg, this);
[email protected]420ae012009-04-24 05:16:322333 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
2334 }
2335}
2336
2337void TabContents::PasswordFormsSeen(
[email protected]ed3fb032009-06-16 19:50:562338 const std::vector<webkit_glue::PasswordForm>& forms) {
[email protected]420ae012009-04-24 05:16:322339 GetPasswordManager()->PasswordFormsSeen(forms);
2340}
2341
[email protected]420ae012009-04-24 05:16:322342// Checks to see if we should generate a keyword based on the OSDD, and if
2343// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2344void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2345 int32 page_id, const GURL& url,
2346 bool autodetected) {
2347 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2348 DCHECK(url.is_valid());
2349 if (!IsActiveEntry(page_id))
2350 return;
2351 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2352 if (!url_model)
2353 return;
2354 if (!url_model->loaded()) {
2355 url_model->Load();
2356 return;
2357 }
2358 if (!profile()->GetTemplateURLFetcher())
2359 return;
2360
2361 if (profile()->IsOffTheRecord())
2362 return;
2363
2364 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2365 DCHECK(entry);
2366
2367 const NavigationEntry* base_entry = entry;
2368 if (IsFormSubmit(base_entry)) {
2369 // If the current page is a form submit, find the last page that was not
2370 // a form submit and use its url to generate the keyword from.
2371 int index = controller_.last_committed_entry_index() - 1;
2372 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2373 index--;
2374 if (index >= 0)
2375 base_entry = controller_.GetEntryAtIndex(index);
2376 else
2377 base_entry = NULL;
2378 }
2379
2380 // We want to use the user typed URL if available since that represents what
2381 // the user typed to get here, and fall back on the regular URL if not.
2382 if (!base_entry)
2383 return;
2384 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2385 base_entry->user_typed_url() : base_entry->url();
2386 if (!keyword_url.is_valid())
2387 return;
2388 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2389 autodetected);
2390 if (keyword.empty())
2391 return;
2392 const TemplateURL* template_url =
2393 url_model->GetTemplateURLForKeyword(keyword);
2394 if (template_url && (!template_url->safe_for_autoreplace() ||
2395 template_url->originating_url() == url)) {
2396 // Either there is a user created TemplateURL for this keyword, or the
2397 // keyword has the same OSDD url and we've parsed it.
2398 return;
2399 }
2400
2401 // Download the OpenSearch description document. If this is successful a
2402 // new keyword will be created when done.
[email protected]420ae012009-04-24 05:16:322403 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2404 keyword,
2405 url,
2406 base_entry->favicon().url(),
[email protected]d0cc9fb52009-06-23 02:26:162407 this,
[email protected]420ae012009-04-24 05:16:322408 autodetected);
2409}
2410
[email protected]420ae012009-04-24 05:16:322411GURL TabContents::GetAlternateErrorPageURL() const {
2412 GURL url;
2413 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2414 if (profile()->IsOffTheRecord())
2415 return url;
2416
2417 PrefService* prefs = profile()->GetPrefs();
2418 DCHECK(prefs);
2419 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
[email protected]a33457b82009-09-21 23:07:152420 url = google_util::AppendGoogleLocaleParam(
2421 GURL(google_util::kLinkDoctorBaseURL));
[email protected]420ae012009-04-24 05:16:322422 url = google_util::AppendGoogleTLDParam(url);
2423 }
2424 return url;
2425}
2426
2427WebPreferences TabContents::GetWebkitPrefs() {
2428 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
[email protected]7ccddb8c2009-08-04 17:36:552429 bool is_dom_ui = false;
2430 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, is_dom_ui);
[email protected]420ae012009-04-24 05:16:322431}
2432
[email protected]420ae012009-04-24 05:16:322433void TabContents::OnJSOutOfMemory() {
2434 AddInfoBar(new SimpleAlertInfoBarDelegate(
2435 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2436}
2437
[email protected]420ae012009-04-24 05:16:322438void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2439 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342440 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322441 // delivered to a pending RenderViewHost. We must first run the onunload
2442 // handler of the old RenderViewHost before we can allow it to proceed.
2443 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2444 new_request_id);
2445}
2446
2447bool TabContents::CanBlur() const {
2448 return delegate() ? delegate()->CanBlur() : true;
2449}
2450
2451gfx::Rect TabContents::GetRootWindowResizerRect() const {
2452 if (delegate())
2453 return delegate()->GetRootWindowResizerRect();
2454 return gfx::Rect();
2455}
2456
2457void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2458 bool is_during_unload) {
2459 if (is_during_unload) {
2460 // Hang occurred while firing the beforeunload/unload handler.
2461 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112462 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322463
2464 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2465 return;
2466
2467 // If the tab hangs in the beforeunload/unload handler there's really
2468 // nothing we can do to recover. Pretend the unload listeners have
2469 // all fired and close the tab. If the hang is in the beforeunload handler
2470 // then the user will not have the option of cancelling the close.
2471 Close(rvh);
2472 return;
2473 }
2474
2475 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]d82ed61e2009-06-16 02:46:222476 HungRendererDialog::ShowForTabContents(this);
[email protected]420ae012009-04-24 05:16:322477}
2478
2479void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]d82ed61e2009-06-16 02:46:222480 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:322481}
2482
2483void TabContents::LoadStateChanged(const GURL& url,
[email protected]094e5b22009-09-25 04:23:562484 net::LoadState load_state,
2485 uint64 upload_position,
2486 uint64 upload_size) {
[email protected]420ae012009-04-24 05:16:322487 load_state_ = load_state;
[email protected]094e5b22009-09-25 04:23:562488 upload_position_ = upload_position;
2489 upload_size_ = upload_size;
[email protected]d686e812009-06-03 19:10:292490 std::wstring languages =
2491 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2492 load_state_host_.clear();
2493 std::string host = url.host();
2494 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322495 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2496 SetNotWaitingForResponse();
2497 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502498 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322499}
2500
[email protected]1ee614862009-07-06 20:29:182501bool TabContents::IsExternalTabContainer() const {
2502 if (!delegate())
2503 return false;
2504
2505 return delegate()->IsExternalTabContainer();
2506}
2507
[email protected]1ee614862009-07-06 20:29:182508void TabContents::DidInsertCSS() {
2509 // This RVHDelegate function is used for extensions and not us.
[email protected]420ae012009-04-24 05:16:322510}
2511
[email protected]130efb02009-09-18 18:54:352512void TabContents::FocusedNodeChanged() {
2513 NotificationService::current()->Notify(
2514 NotificationType::FOCUS_CHANGED_IN_PAGE,
2515 Source<RenderViewHost>(render_view_host()),
2516 NotificationService::NoDetails());
2517}
2518
[email protected]420ae012009-04-24 05:16:322519void TabContents::FileSelected(const FilePath& path,
2520 int index, void* params) {
2521 render_view_host()->FileSelected(path);
2522}
2523
2524void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2525 void* params) {
2526 render_view_host()->MultiFilesSelected(files);
2527}
2528
2529void TabContents::FileSelectionCanceled(void* params) {
2530 // If the user cancels choosing a file to upload we pass back an
2531 // empty vector.
2532 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2533}
2534
2535void TabContents::BeforeUnloadFiredFromRenderManager(
2536 bool proceed,
2537 bool* proceed_to_fire_unload) {
2538 if (delegate())
2539 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2540}
2541
2542void TabContents::UpdateRenderViewSizeForRenderManager() {
2543 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2544 view_->SizeContents(view_->GetContainerSize());
2545}
2546
2547DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
[email protected]d82ed61e2009-06-16 02:46:222548 return DOMUIFactory::CreateDOMUIForURL(this, url);
[email protected]420ae012009-04-24 05:16:322549}
2550
2551NavigationEntry*
2552TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2553 return controller_.GetLastCommittedEntry();
2554}
2555
2556bool TabContents::CreateRenderViewForRenderManager(
2557 RenderViewHost* render_view_host) {
[email protected]811bfe32009-07-01 08:46:252558 // If the pending navigation is to a DOMUI, tell the RenderView about any
2559 // bindings it will need enabled.
[email protected]420ae012009-04-24 05:16:322560 if (render_manager_.pending_dom_ui())
[email protected]811bfe32009-07-01 08:46:252561 render_view_host->AllowBindings(
2562 render_manager_.pending_dom_ui()->bindings());
[email protected]1adff062009-06-02 18:39:552563
[email protected]420ae012009-04-24 05:16:322564 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2565 if (!render_view_host->CreateRenderView())
2566 return false;
2567
2568 // Now that the RenderView has been created, we need to tell it its size.
2569 rwh_view->SetSize(view_->GetContainerSize());
2570
2571 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2572 render_view_host);
2573 return true;
2574}
2575
2576void TabContents::Observe(NotificationType type,
2577 const NotificationSource& source,
2578 const NotificationDetails& details) {
2579 switch (type.value) {
2580 case NotificationType::BOOKMARK_MODEL_LOADED:
2581 // BookmarkModel finished loading, fall through to update starred state.
2582 case NotificationType::URLS_STARRED: {
2583 // Somewhere, a URL has been starred.
2584 // Ignore notifications for profiles other than our current one.
2585 Profile* source_profile = Source<Profile>(source).ptr();
2586 if (!source_profile || !source_profile->IsSameProfile(profile()))
2587 return;
2588
2589 UpdateStarredStateForCurrentURL();
2590 break;
2591 }
2592 case NotificationType::PREF_CHANGED: {
2593 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2594 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2595 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2596 UpdateAlternateErrorPageURL();
2597 } else if (*pref_name_in == prefs::kDefaultCharset ||
2598 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2599 ) {
2600 UpdateWebPreferences();
2601 } else {
2602 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2603 }
2604 break;
2605 }
2606 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2607 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2608 break;
2609
2610 case NotificationType::NAV_ENTRY_COMMITTED: {
2611 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2612
2613 NavigationController::LoadCommittedDetails& committed_details =
2614 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2615 ExpireInfoBars(committed_details);
2616 break;
2617 }
2618
[email protected]d3ba77272009-09-03 00:06:092619#if defined(OS_LINUX)
2620 case NotificationType::BROWSER_THEME_CHANGED: {
2621 render_view_host()->SyncRendererPrefs();
2622 break;
2623 }
2624#endif
2625
[email protected]420ae012009-04-24 05:16:322626 default:
2627 NOTREACHED();
2628 }
2629}
[email protected]aacd7cc2009-09-02 14:51:102630
[email protected]41fc0322009-09-04 22:23:402631void TabContents::set_encoding(const std::string& encoding) {
[email protected]aacd7cc2009-09-02 14:51:102632 encoding_ = CharacterEncoding::GetCanonicalEncodingNameByAliasName(encoding);
2633}