blob: 5b816f19cac031aa2d5200a6ef4a9df1e6695121 [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"
12#include "base/time.h"
[email protected]fdd61c62009-04-22 19:22:5713#include "chrome/browser/autofill_manager.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]96d185d2009-04-24 03:28:5418#include "chrome/browser/debugger/devtools_manager.h"
[email protected]420ae012009-04-24 05:16:3219#include "chrome/browser/dom_operation_notification_details.h"
[email protected]96d185d2009-04-24 03:28:5420#include "chrome/browser/dom_ui/dom_ui.h"
21#include "chrome/browser/dom_ui/dom_ui_factory.h"
[email protected]bcef0dc02009-02-28 00:35:0222#include "chrome/browser/download/download_item_model.h"
[email protected]420ae012009-04-24 05:16:3223#include "chrome/browser/download/download_manager.h"
24#include "chrome/browser/download/download_request_manager.h"
[email protected]420ae012009-04-24 05:16:3225#include "chrome/browser/gears_integration.h"
26#include "chrome/browser/google_util.h"
[email protected]8897c382009-05-06 17:53:2627#include "chrome/browser/hung_renderer_dialog.h"
[email protected]420ae012009-04-24 05:16:3228#include "chrome/browser/jsmessage_box_handler.h"
29#include "chrome/browser/load_from_memory_cache_details.h"
30#include "chrome/browser/load_notification_details.h"
[email protected]c8865482009-07-23 20:40:1031#include "chrome/browser/omnibox_search_hint.h"
[email protected]fdd61c62009-04-22 19:22:5732#include "chrome/browser/password_manager/password_manager.h"
33#include "chrome/browser/plugin_installer.h"
[email protected]ce560f82009-06-03 09:39:4434#include "chrome/browser/profile.h"
[email protected]96d185d2009-04-24 03:28:5435#include "chrome/browser/renderer_host/render_widget_host_view.h"
[email protected]fd694982009-07-03 17:32:3736#include "chrome/browser/renderer_host/resource_request_details.h"
[email protected]96d185d2009-04-24 03:28:5437#include "chrome/browser/renderer_host/web_cache_manager.h"
[email protected]bd1ad682009-05-15 22:19:1738#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]7e383692009-06-12 19:14:5439#include "chrome/browser/tab_contents/interstitial_page.h"
[email protected]f3ec7742009-01-15 00:59:1640#include "chrome/browser/tab_contents/navigation_entry.h"
[email protected]de34a962009-06-26 23:22:4341#include "chrome/browser/tab_contents/provisional_load_details.h"
[email protected]f3ec7742009-01-15 00:59:1642#include "chrome/browser/tab_contents/tab_contents_delegate.h"
[email protected]fdd61c62009-04-22 19:22:5743#include "chrome/browser/tab_contents/tab_contents_view.h"
[email protected]58dca552009-06-17 00:35:0244#include "chrome/browser/tab_contents/thumbnail_generator.h"
[email protected]449478302009-06-09 20:04:2845#include "chrome/browser/thumbnail_store.h"
[email protected]420ae012009-04-24 05:16:3246#include "chrome/browser/search_engines/template_url_fetcher.h"
47#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2748#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5649#include "chrome/common/notification_service.h"
[email protected]ce5c4502009-05-06 16:46:1150#include "chrome/common/page_action.h"
initial.commit09911bf2008-07-26 23:55:2951#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0352#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3253#include "chrome/common/render_messages.h"
[email protected]1ee614862009-07-06 20:29:1854#include "chrome/common/renderer_preferences.h"
[email protected]96d185d2009-04-24 03:28:5455#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2656#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3257#include "grit/locale_settings.h"
58#include "net/base/mime_util.h"
59#include "net/base/net_errors.h"
[email protected]d686e812009-06-03 19:10:2960#include "net/base/net_util.h"
[email protected]420ae012009-04-24 05:16:3261#include "net/base/registry_controlled_domain.h"
[email protected]1ee614862009-07-06 20:29:1862#include "webkit/glue/password_form.h"
63#include "webkit/glue/webpreferences.h"
[email protected]3e45ba92009-02-20 21:09:0064
65#if defined(OS_WIN)
[email protected]66ba4932009-06-04 19:22:1366// For CRect
[email protected]9041a302009-06-04 19:36:3367#include <atlbase.h>
[email protected]326f7112009-06-04 19:30:2968#include <atlapp.h>
[email protected]66ba4932009-06-04 19:22:1369#include <atlmisc.h>
[email protected]3e45ba92009-02-20 21:09:0070// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3271#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]2362e4f2009-05-08 00:34:0572#include "views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0073#endif
initial.commit09911bf2008-07-26 23:55:2974
[email protected]420ae012009-04-24 05:16:3275// Cross-Site Navigations
76//
77// If a TabContents is told to navigate to a different web site (as determined
78// by SiteInstance), it will replace its current RenderViewHost with a new
79// RenderViewHost dedicated to the new SiteInstance. This works as follows:
80//
81// - Navigate determines whether the destination is cross-site, and if so,
82// it creates a pending_render_view_host_ and moves into the PENDING
83// RendererState.
84// - The pending RVH is "suspended," so that no navigation messages are sent to
85// its renderer until the onbeforeunload JavaScript handler has a chance to
86// run in the current RVH.
87// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
88// that it has a pending cross-site request. ResourceDispatcherHost will
89// check for this when the response arrives.
90// - The current RVH runs its onbeforeunload handler. If it returns false, we
91// cancel all the pending logic and go back to NORMAL. Otherwise we allow
92// the pending RVH to send the navigation request to its renderer.
93// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
94// checks CrossSiteRequestManager to see that the RVH responsible has a
95// pending cross-site request, and then installs a CrossSiteEventHandler.
96// - When RDH receives a response, the BufferedEventHandler determines whether
97// it is a download. If so, it sends a message to the new renderer causing
98// it to cancel the request, and the download proceeds in the download
99// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:34100// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:32101// doesn't affect any functionality.
102// - After RDH receives a response and determines that it is safe and not a
103// download, it pauses the response to first run the old page's onunload
104// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:34105// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:32106// to the current RVH.
107// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
108// the ResourceDispatcherHost, who unpauses the response. Data is then sent
109// to the pending RVH.
110// - The pending renderer sends a FrameNavigate message that invokes the
111// DidNavigate method. This replaces the current RVH with the
112// pending RVH and goes back to the NORMAL RendererState.
113
114namespace {
115
116// Amount of time we wait between when a key event is received and the renderer
117// is queried for its state and pushed to the NavigationEntry.
118const int kQueryStateDelay = 5000;
119
120const int kSyncWaitDelay = 40;
121
122// If another javascript message box is displayed within
123// kJavascriptMessageExpectedDelay of a previous javascript message box being
124// dismissed, display an option to suppress future message boxes from this
125// contents.
126const int kJavascriptMessageExpectedDelay = 1000;
127
[email protected]420ae012009-04-24 05:16:32128const char kLinkDoctorBaseURL[] =
129 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
130
[email protected]420ae012009-04-24 05:16:32131// The list of prefs we want to observe.
132const wchar_t* kPrefsToObserve[] = {
133 prefs::kAlternateErrorPagesEnabled,
134 prefs::kWebKitJavaEnabled,
135 prefs::kWebKitJavascriptEnabled,
136 prefs::kWebKitLoadsImagesAutomatically,
137 prefs::kWebKitPluginsEnabled,
138 prefs::kWebKitUsesUniversalDetector,
139 prefs::kWebKitSerifFontFamily,
140 prefs::kWebKitSansSerifFontFamily,
141 prefs::kWebKitFixedFontFamily,
142 prefs::kWebKitDefaultFontSize,
143 prefs::kWebKitDefaultFixedFontSize,
144 prefs::kDefaultCharset
145 // kWebKitStandardFontIsSerif needs to be added
146 // if we let users pick which font to use, serif or sans-serif when
147 // no font is specified or a CSS generic family (serif or sans-serif)
148 // is not specified.
149};
150
151const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
152
[email protected]420ae012009-04-24 05:16:32153// Returns true if the entry's transition type is FORM_SUBMIT.
154bool IsFormSubmit(const NavigationEntry* entry) {
155 return (PageTransition::StripQualifier(entry->transition_type()) ==
156 PageTransition::FORM_SUBMIT);
157}
158
159#if defined(OS_WIN)
160
161BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
162 // Note: erase is required to properly paint some widgets borders. This can
163 // be seen with textfields.
164 InvalidateRect(hwnd, NULL, TRUE);
165 return TRUE;
166}
167#endif
168
[email protected]056de2d2009-06-26 16:41:34169void MakeNavigateParams(const NavigationEntry& entry, bool reload,
170 ViewMsg_Navigate_Params* params) {
171 params->page_id = entry.page_id();
172 params->url = entry.url();
173 params->referrer = entry.referrer();
174 params->transition = entry.transition_type();
175 params->state = entry.content_state();
176 params->reload = reload;
177 params->request_time = base::Time::Now();
178}
179
[email protected]420ae012009-04-24 05:16:32180} // namespace
181
182// -----------------------------------------------------------------------------
183
[email protected]fdd61c62009-04-22 19:22:57184// static
185int TabContents::find_request_id_counter_ = -1;
186
[email protected]420ae012009-04-24 05:16:32187class TabContents::GearsCreateShortcutCallbackFunctor {
188 public:
189 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
190 : contents_(contents) {}
191
192 void Run(const GearsShortcutData2& shortcut_data, bool success) {
193 if (contents_)
194 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
195 delete this;
196 }
197 void Cancel() {
198 contents_ = NULL;
199 }
200
201 private:
202 TabContents* contents_;
203};
204
[email protected]420ae012009-04-24 05:16:32205TabContents::TabContents(Profile* profile,
206 SiteInstance* site_instance,
207 int routing_id,
208 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42209 : delegate_(NULL),
[email protected]66ba4932009-06-04 19:22:13210 ALLOW_THIS_IN_INITIALIZER_LIST(controller_(this, profile)),
211 ALLOW_THIS_IN_INITIALIZER_LIST(view_(
[email protected]d82ed61e2009-06-16 02:46:22212 TabContentsView::Create(this))),
213 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(this, this)),
[email protected]fdd61c62009-04-22 19:22:57214 property_bag_(),
215 registrar_(),
[email protected]d82ed61e2009-06-16 02:46:22216 ALLOW_THIS_IN_INITIALIZER_LIST(printing_(*this)),
[email protected]fdd61c62009-04-22 19:22:57217 save_package_(),
218 cancelable_consumer_(),
219 autofill_manager_(),
220 password_manager_(),
221 plugin_installer_(),
[email protected]d82ed61e2009-06-16 02:46:22222 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(this)),
[email protected]fdd61c62009-04-22 19:22:57223 select_file_dialog_(),
224 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34225 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29226 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34227 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34228 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57229 current_load_start_(),
230 load_state_(net::LOAD_STATE_IDLE),
231 load_state_host_(),
232 received_page_title_(false),
233 is_starred_(false),
234 contents_mime_type_(),
235 encoding_(),
[email protected]332af7732009-03-11 13:21:35236 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57237 infobar_delegates_(),
[email protected]fdd61c62009-04-22 19:22:57238 find_ui_active_(false),
239 find_op_aborted_(false),
240 current_find_request_id_(find_request_id_counter_++),
241 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12242 last_search_case_sensitive_(false),
243 last_search_prepopulate_text_(NULL),
244 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57245 capturing_contents_(false),
246 is_being_destroyed_(false),
247 notify_disconnection_(false),
248 history_requests_(),
249#if defined(OS_WIN)
250 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
251#endif
252 last_javascript_message_dismissal_(),
253 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32254 pending_install_.page_id = 0;
255 pending_install_.callback_functor = NULL;
256
[email protected]16779842009-07-08 23:45:29257#if defined(OS_CHROMEOS)
[email protected]58dca552009-06-17 00:35:02258 // Make sure the thumbnailer is started before starting the render manager.
259 // The thumbnailer will want to listen for RVH creations, one of which will
260 // happen in RVHManager::Init.
261 ThumbnailGenerator* generator = g_browser_process->GetThumbnailGenerator();
262 if (generator)
263 generator->StartThumbnailing();
264#endif
265
[email protected]420ae012009-04-24 05:16:32266 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
267
268 view_->CreateView();
269
270 // Register for notifications about all interested prefs change.
271 PrefService* prefs = profile->GetPrefs();
272 if (prefs) {
273 for (int i = 0; i < kPrefsToObserveLength; ++i)
274 prefs->AddPrefObserver(kPrefsToObserve[i], this);
275 }
276
277 // Register for notifications about URL starredness changing on any profile.
278 registrar_.Add(this, NotificationType::URLS_STARRED,
279 NotificationService::AllSources());
280 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
281 NotificationService::AllSources());
282 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
283 NotificationService::AllSources());
284
285 // Keep a global copy of the previous search string (if any).
286 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12287 last_search_prepopulate_text_ = &global_last_search;
[email protected]840b1512009-07-21 16:53:46288
[email protected]c8865482009-07-23 20:40:10289 // Set-up the showing of the omnibox search infobar if applicable.
290 if (OmniboxSearchHint::IsEnabled(profile))
291 omnibox_search_hint_.reset(new OmniboxSearchHint(this));
292
[email protected]840b1512009-07-21 16:53:46293 view_->InitRendererPrefs(&renderer_preferences_);
[email protected]332af7732009-03-11 13:21:35294}
initial.commit09911bf2008-07-26 23:55:29295
296TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32297 is_being_destroyed_ = true;
298
299 // We don't want any notifications while we're runnign our destructor.
300 registrar_.RemoveAll();
301
302 // Unregister the notifications of all observed prefs change.
303 PrefService* prefs = profile()->GetPrefs();
304 if (prefs) {
305 for (int i = 0; i < kPrefsToObserveLength; ++i)
306 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
307 }
308
309 // Clean up subwindows like plugins and the find in page bar.
310 view_->OnContentsDestroy();
311
312 NotifyDisconnected();
[email protected]d82ed61e2009-06-16 02:46:22313 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:32314
315 if (pending_install_.callback_functor)
316 pending_install_.callback_functor->Cancel();
317
318 // First cleanly close all child windows.
319 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
320 // some of these to close. CloseWindows is async, so it might get called
321 // twice before it runs.
322 int size = static_cast<int>(child_windows_.size());
323 for (int i = size - 1; i >= 0; --i) {
324 ConstrainedWindow* window = child_windows_[i];
325 if (window)
326 window->CloseConstrainedWindow();
327 }
328
[email protected]66ba4932009-06-04 19:22:13329 if (blocked_popups_)
330 blocked_popups_->Destroy();
331
[email protected]420ae012009-04-24 05:16:32332 // Notify any observer that have a reference on this tab contents.
333 NotificationService::current()->Notify(
334 NotificationType::TAB_CONTENTS_DESTROYED,
335 Source<TabContents>(this),
336 NotificationService::NoDetails());
337
[email protected]1e5e74f2009-05-27 20:55:12338 // Notify any lasting InfobarDelegates that have not yet been removed that
339 // whatever infobar they were handling in this TabContents has closed,
340 // because the TabContents is going away entirely.
341 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
342 // notification may trigger infobars calls that access their delegate. (and
343 // some implementations of InfoBarDelegate do delete themselves on
344 // InfoBarClosed()).
345 for (int i = 0; i < infobar_delegate_count(); ++i) {
346 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
347 delegate->InfoBarClosed();
348 }
349 infobar_delegates_.clear();
350
[email protected]420ae012009-04-24 05:16:32351 // TODO(brettw) this should be moved to the view.
352#if defined(OS_WIN)
353 // If we still have a window handle, destroy it. GetNativeView can return
354 // NULL if this contents was part of a window that closed.
355 if (GetNativeView())
356 ::DestroyWindow(GetNativeView());
357#endif
initial.commit09911bf2008-07-26 23:55:29358}
359
[email protected]d5f942ba2008-09-26 19:30:34360// static
361void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32362 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
363
364 WebPreferences pref_defaults;
365 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
366 pref_defaults.javascript_enabled);
367 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
368 pref_defaults.web_security_enabled);
369 prefs->RegisterBooleanPref(
370 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
371 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
372 pref_defaults.loads_images_automatically);
373 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
374 pref_defaults.plugins_enabled);
375 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
376 pref_defaults.dom_paste_enabled);
377 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
378 pref_defaults.shrinks_standalone_images_to_fit);
[email protected]0df30122009-06-03 12:13:08379 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
380 pref_defaults.inspector_settings);
[email protected]420ae012009-04-24 05:16:32381 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
382 pref_defaults.text_areas_are_resizable);
383 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
384 pref_defaults.java_enabled);
385
386 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
387 IDS_ACCEPT_LANGUAGES);
388 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
389 IDS_DEFAULT_ENCODING);
390 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
391 IDS_STANDARD_FONT_IS_SERIF);
392 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
393 IDS_FIXED_FONT_FAMILY);
394 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
395 IDS_SERIF_FONT_FAMILY);
396 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
397 IDS_SANS_SERIF_FONT_FAMILY);
398 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
399 IDS_CURSIVE_FONT_FAMILY);
400 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
401 IDS_FANTASY_FONT_FAMILY);
402 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
403 IDS_DEFAULT_FONT_SIZE);
404 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
405 IDS_DEFAULT_FIXED_FONT_SIZE);
406 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
407 IDS_MINIMUM_FONT_SIZE);
408 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
409 IDS_MINIMUM_LOGICAL_FONT_SIZE);
410 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
411 IDS_USES_UNIVERSAL_DETECTOR);
412 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
413 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29414}
415
[email protected]13367f72009-07-08 16:39:02416// Returns true if contains content rendered by an extension.
417bool TabContents::HostsExtension() const {
418 return GetURL().SchemeIs(chrome::kExtensionScheme);
[email protected]d5f942ba2008-09-26 19:30:34419}
420
[email protected]6e95706d2009-04-23 22:55:01421PasswordManager* TabContents::GetPasswordManager() {
422 if (password_manager_.get() == NULL)
423 password_manager_.reset(new PasswordManager(this));
424 return password_manager_.get();
425}
426
427PluginInstaller* TabContents::GetPluginInstaller() {
428 if (plugin_installer_.get() == NULL)
429 plugin_installer_.reset(new PluginInstaller(this));
430 return plugin_installer_.get();
431}
432
[email protected]d5f942ba2008-09-26 19:30:34433const GURL& TabContents::GetURL() const {
434 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57435 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34436 return entry ? entry->display_url() : GURL::EmptyGURL();
437}
438
[email protected]96d185d2009-04-24 03:28:54439const string16& TabContents::GetTitle() const {
[email protected]4c6092c5b2009-06-06 00:23:55440 // Transient entries take precedence. They are used for interstitial pages
441 // that are shown on top of existing pages.
442 NavigationEntry* entry = controller_.GetTransientEntry();
443 if (entry)
444 return entry->GetTitleForDisplay(&controller_);
445
[email protected]96d185d2009-04-24 03:28:54446 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
447 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
448 if (our_dom_ui) {
449 // Don't override the title in view source mode.
[email protected]4c6092c5b2009-06-06 00:23:55450 entry = controller_.GetActiveEntry();
[email protected]96d185d2009-04-24 03:28:54451 if (!(entry && entry->IsViewSourceMode())) {
452 // Give the DOM UI the chance to override our title.
453 const string16& title = our_dom_ui->overridden_title();
454 if (!title.empty())
455 return title;
456 }
457 }
458
459 // We use the title for the last committed entry rather than a pending
460 // navigation entry. For example, when the user types in a URL, we want to
461 // keep the old page's title until the new load has committed and we get a new
462 // title.
[email protected]96d185d2009-04-24 03:28:54463 entry = controller_.GetLastCommittedEntry();
464 if (entry)
465 return entry->GetTitleForDisplay(&controller_);
466 else if (controller_.LoadingURLLazily())
467 return controller_.GetLazyTitle();
468 return EmptyString16();
469}
470
[email protected]d5f942ba2008-09-26 19:30:34471int32 TabContents::GetMaxPageID() {
472 if (GetSiteInstance())
473 return GetSiteInstance()->max_page_id();
474 else
475 return max_page_id_;
476}
477
478void TabContents::UpdateMaxPageID(int32 page_id) {
479 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34480 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34481 // testing.
482 if (GetSiteInstance())
483 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34484 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34485}
486
[email protected]96d185d2009-04-24 03:28:54487SiteInstance* TabContents::GetSiteInstance() const {
488 return render_manager_.current_host()->site_instance();
489}
490
[email protected]d5f942ba2008-09-26 19:30:34491const std::wstring TabContents::GetDefaultTitle() const {
492 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
493}
494
[email protected]96d185d2009-04-24 03:28:54495bool TabContents::ShouldDisplayURL() {
496 // Don't hide the url in view source mode.
497 NavigationEntry* entry = controller_.GetActiveEntry();
498 if (entry && entry->IsViewSourceMode())
499 return true;
[email protected]83e3895b2009-06-11 00:07:16500
[email protected]96d185d2009-04-24 03:28:54501 DOMUI* dom_ui = GetDOMUIForCurrentState();
502 if (dom_ui)
503 return !dom_ui->should_hide_url();
504 return true;
505}
506
[email protected]d5f942ba2008-09-26 19:30:34507SkBitmap TabContents::GetFavIcon() const {
508 // Like GetTitle(), we also want to use the favicon for the last committed
509 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57510 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47511 if (entry)
512 return entry->favicon().bitmap();
513
[email protected]ce3fa3c2009-04-20 19:55:57514 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34515 if (entry)
516 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57517 else if (controller_.LoadingURLLazily())
518 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34519 return SkBitmap();
520}
521
[email protected]96d185d2009-04-24 03:28:54522bool TabContents::ShouldDisplayFavIcon() {
523 // Always display a throbber during pending loads.
524 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
525 return true;
526
527 DOMUI* dom_ui = GetDOMUIForCurrentState();
528 if (dom_ui)
529 return !dom_ui->hide_favicon();
530 return true;
531}
532
[email protected]96d185d2009-04-24 03:28:54533std::wstring TabContents::GetStatusText() const {
534 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
535 return std::wstring();
536
537 switch (load_state_) {
538 case net::LOAD_STATE_WAITING_FOR_CACHE:
539 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
540 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
541 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
542 case net::LOAD_STATE_RESOLVING_HOST:
543 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
544 case net::LOAD_STATE_CONNECTING:
545 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
546 case net::LOAD_STATE_SENDING_REQUEST:
547 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
548 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
549 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
550 load_state_host_);
551 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
552 case net::LOAD_STATE_IDLE:
553 case net::LOAD_STATE_READING_RESPONSE:
554 break;
555 }
556
557 return std::wstring();
558}
559
[email protected]d5f942ba2008-09-26 19:30:34560void TabContents::SetIsCrashed(bool state) {
561 if (state == is_crashed_)
562 return;
563
564 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50565 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34566}
567
[email protected]f9b1a7b2009-06-22 17:26:38568void TabContents::SetPageActionEnabled(const PageAction* page_action,
[email protected]d7eaf572009-07-01 21:57:00569 bool enable,
570 const std::string& title,
571 int icon_id) {
[email protected]ce5c4502009-05-06 16:46:11572 DCHECK(page_action);
573
[email protected]d7eaf572009-07-01 21:57:00574 if (!enable &&
575 enabled_page_actions_.end() == enabled_page_actions_.find(page_action)) {
576 return; // Don't need to disable twice.
577 }
[email protected]ce5c4502009-05-06 16:46:11578
[email protected]d7eaf572009-07-01 21:57:00579 if (enable) {
580 enabled_page_actions_[page_action].reset(
581 new PageActionState(title, icon_id));
582 } else {
[email protected]f9b1a7b2009-06-22 17:26:38583 enabled_page_actions_.erase(page_action);
[email protected]d7eaf572009-07-01 21:57:00584 }
[email protected]ce5c4502009-05-06 16:46:11585}
586
[email protected]d7eaf572009-07-01 21:57:00587const PageActionState* TabContents::GetPageActionState(
588 const PageAction* page_action) {
589 if (enabled_page_actions_.end() == enabled_page_actions_.find(page_action))
590 return NULL;
[email protected]ce5c4502009-05-06 16:46:11591
[email protected]d7eaf572009-07-01 21:57:00592 return enabled_page_actions_[page_action].get();
593}
[email protected]ce5c4502009-05-06 16:46:11594
[email protected]d5f942ba2008-09-26 19:30:34595void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
596 if (delegate_)
597 delegate_->NavigationStateChanged(this, changed_flags);
598}
599
[email protected]96d185d2009-04-24 03:28:54600void TabContents::DidBecomeSelected() {
601 controller_.SetActive(true);
602
[email protected]789e9152009-08-04 21:59:43603 if (render_widget_host_view()) {
[email protected]96d185d2009-04-24 03:28:54604 render_widget_host_view()->DidBecomeSelected();
[email protected]789e9152009-08-04 21:59:43605#if defined(OS_MACOSX)
606 render_widget_host_view()->SetActive(true);
607#endif
608 }
[email protected]96d185d2009-04-24 03:28:54609
610 // If pid() is -1, that means the RenderProcessHost still hasn't been
611 // initialized. It'll register with CacheManagerHost when it is.
612 if (process()->pid() != -1)
613 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
614}
615
616void TabContents::WasHidden() {
617 if (!capturing_contents()) {
618 // |render_view_host()| can be NULL if the user middle clicks a link to open
619 // a tab in then background, then closes the tab before selecting it. This
620 // is because closing the tab calls TabContents::Destroy(), which removes
621 // the |render_view_host()|; then when we actually destroy the window,
622 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
623 if (render_widget_host_view())
624 render_widget_host_view()->WasHidden();
[email protected]96d185d2009-04-24 03:28:54625 }
626
627 NotificationService::current()->Notify(
628 NotificationType::TAB_CONTENTS_HIDDEN,
629 Source<TabContents>(this),
630 NotificationService::NoDetails());
631}
632
[email protected]d5f942ba2008-09-26 19:30:34633void TabContents::Activate() {
634 if (delegate_)
635 delegate_->ActivateContents(this);
636}
637
[email protected]96d185d2009-04-24 03:28:54638void TabContents::ShowContents() {
639 if (render_widget_host_view())
640 render_widget_host_view()->DidBecomeSelected();
[email protected]96d185d2009-04-24 03:28:54641}
642
643void TabContents::HideContents() {
644 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
645 // our superclass HideContents(), because some callers want to be very picky
646 // about the order in which these get called. In addition to making the code
647 // here practically impossible to understand, this also means we end up
648 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34649 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54650 WasHidden();
651}
652
[email protected]c0588052008-10-27 23:01:50653void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34654 WindowOpenDisposition disposition,
655 PageTransition::Type transition) {
656 if (delegate_)
[email protected]c0588052008-10-27 23:01:50657 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34658}
659
660bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54661 const NavigationEntry& entry = *controller_.pending_entry();
662
663 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
664 if (!dest_render_view_host)
665 return false; // Unable to create the desired render view host.
666
667 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]d9f9b792009-06-24 13:17:12668 DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
[email protected]7e8e6b62009-05-08 11:28:32669 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41670 devtools_manager->OnNavigatingToPendingEntry(
671 render_view_host(),
672 dest_render_view_host,
673 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32674 }
[email protected]96d185d2009-04-24 03:28:54675
676 // Used for page load time metrics.
677 current_load_start_ = base::TimeTicks::Now();
678
679 // Navigate in the desired RenderViewHost.
[email protected]056de2d2009-06-26 16:41:34680 ViewMsg_Navigate_Params navigate_params;
681 MakeNavigateParams(entry, reload, &navigate_params);
682 dest_render_view_host->Navigate(navigate_params);
[email protected]96d185d2009-04-24 03:28:54683
684 if (entry.page_id() == -1) {
685 // HACK!! This code suppresses javascript: URLs from being added to
686 // session history, which is what we want to do for javascript: URLs that
687 // do not generate content. What we really need is a message from the
688 // renderer telling us that a new page was not created. The same message
689 // could be used for mailto: URLs and the like.
690 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
691 return false;
692 }
693
694 // Clear any provisional password saves - this stops password infobars
695 // showing up on pages the user navigates to while the right page is
696 // loading.
697 GetPasswordManager()->ClearProvisionalSave();
698
699 if (reload && !profile()->IsOffTheRecord()) {
700 HistoryService* history =
701 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
702 if (history)
703 history->SetFavIconOutOfDateForPage(entry.url());
704 }
705
[email protected]d5f942ba2008-09-26 19:30:34706 return true;
707}
708
[email protected]96d185d2009-04-24 03:28:54709void TabContents::Stop() {
710 render_manager_.Stop();
711 printing_.Stop();
712}
713
714void TabContents::Cut() {
715 render_view_host()->Cut();
716}
717
718void TabContents::Copy() {
719 render_view_host()->Copy();
720}
721
722void TabContents::Paste() {
723 render_view_host()->Paste();
724}
725
726void TabContents::DisassociateFromPopupCount() {
727 render_view_host()->DisassociateFromPopupCount();
728}
729
730TabContents* TabContents::Clone() {
731 // We create a new SiteInstance so that the new tab won't share processes
732 // with the old one. This can be changed in the future if we need it to share
733 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32734 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54735 SiteInstance::CreateSiteInstance(profile()),
736 MSG_ROUTING_NONE, NULL);
737 tc->controller().CopyStateFrom(controller_);
738 return tc;
739}
740
[email protected]420ae012009-04-24 05:16:32741void TabContents::CreateShortcut() {
742 NavigationEntry* entry = controller_.GetLastCommittedEntry();
743 if (!entry)
744 return;
745
746 // We only allow one pending install request. By resetting the page id we
747 // effectively cancel the pending install request.
748 pending_install_.page_id = entry->page_id();
749 pending_install_.icon = GetFavIcon();
750 pending_install_.title = UTF16ToWideHack(GetTitle());
751 pending_install_.url = GetURL();
752 if (pending_install_.callback_functor) {
753 pending_install_.callback_functor->Cancel();
754 pending_install_.callback_functor = NULL;
755 }
756 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
757 if (pending_install_.title.empty())
758 pending_install_.title = UTF8ToWide(GetURL().spec());
759
760 // Request the application info. When done OnDidGetApplicationInfo is invoked
761 // and we'll create the shortcut.
762 render_view_host()->GetApplicationInfo(pending_install_.page_id);
763}
764
[email protected]4d677202009-07-19 07:37:12765void TabContents::ShowPageInfo(const GURL& url,
766 const NavigationEntry::SSLStatus& ssl,
767 bool show_history) {
768 if (!delegate_)
769 return;
770
[email protected]bb678332009-07-21 00:15:50771 delegate_->ShowPageInfo(profile(), url, ssl, show_history);
[email protected]4d677202009-07-19 07:37:12772}
773
[email protected]e8382172009-06-19 22:16:28774#if defined(OS_WIN) || defined(OS_LINUX)
initial.commit09911bf2008-07-26 23:55:29775ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]e8382172009-06-19 22:16:28776 ConstrainedWindowDelegate* delegate) {
initial.commit09911bf2008-07-26 23:55:29777 ConstrainedWindow* window =
[email protected]e8382172009-06-19 22:16:28778 ConstrainedWindow::CreateConstrainedDialog(this, delegate);
initial.commit09911bf2008-07-26 23:55:29779 child_windows_.push_back(window);
780 return window;
781}
[email protected]f3332e12009-03-23 15:28:57782#endif
initial.commit09911bf2008-07-26 23:55:29783
784void TabContents::AddNewContents(TabContents* new_contents,
785 WindowOpenDisposition disposition,
786 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22787 bool user_gesture,
788 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29789 if (!delegate_)
790 return;
791
[email protected]35f7d212009-04-29 21:19:27792 if ((disposition == NEW_POPUP) && !user_gesture &&
793 !CommandLine::ForCurrentProcess()->HasSwitch(
794 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22795 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31796 // the whitelist. The popup owner will handle checking this.
797 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
798 initial_pos,
799 creator_url.is_valid() ? creator_url.host() : std::string());
800 } else {
[email protected]0aa55312008-10-17 21:53:08801 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29802 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
803 user_gesture);
804 }
[email protected]b6c874582009-05-08 19:38:31805 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
initial.commit09911bf2008-07-26 23:55:29806}
807
initial.commit09911bf2008-07-26 23:55:29808void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25809 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22810 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29811}
812
[email protected]96d185d2009-04-24 03:28:54813void TabContents::PopupNotificationVisibilityChanged(bool visible) {
814 render_view_host()->PopupNotificationVisibilityChanged(visible);
815}
816
817gfx::NativeView TabContents::GetContentNativeView() {
818 return view_->GetContentNativeView();
819}
820
821gfx::NativeView TabContents::GetNativeView() const {
822 return view_->GetNativeView();
823}
824
825void TabContents::GetContainerBounds(gfx::Rect *out) const {
826 view_->GetContainerBounds(out);
827}
828
829void TabContents::Focus() {
830 view_->Focus();
831}
832
[email protected]90daadb42009-06-08 21:27:28833void TabContents::FocusThroughTabTraversal(bool reverse) {
[email protected]7e383692009-06-12 19:14:54834 if (showing_interstitial_page()) {
835 render_manager_.interstitial_page()->FocusThroughTabTraversal(reverse);
836 return;
837 }
[email protected]96d185d2009-04-24 03:28:54838 render_view_host()->SetInitialFocus(reverse);
839}
840
841bool TabContents::FocusLocationBarByDefault() {
842 DOMUI* dom_ui = GetDOMUIForCurrentState();
843 if (dom_ui)
844 return dom_ui->focus_location_bar_by_default();
[email protected]3e3f0eb2009-06-22 18:33:43845 NavigationEntry* entry = controller_.GetActiveEntry();
846 if (entry && entry->url() == GURL("about:blank"))
847 return true;
[email protected]96d185d2009-04-24 03:28:54848 return false;
849}
850
[email protected]616ed5a2008-11-21 22:27:24851void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
852 // Look through the existing InfoBarDelegates we have for a match. If we've
853 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05854 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24855 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
856 return;
857 }
858
859 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56860 NotificationService::current()->Notify(
861 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
862 Source<TabContents>(this),
863 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24864
865 // Add ourselves as an observer for navigations the first time a delegate is
866 // added. We use this notification to expire InfoBars that need to expire on
867 // page transitions.
868 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56869 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57870 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24871 }
872}
873
874void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
875 std::vector<InfoBarDelegate*>::iterator it =
876 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
877 if (it != infobar_delegates_.end()) {
878 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56879 NotificationService::current()->Notify(
880 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
881 Source<TabContents>(this),
882 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05883 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24884
[email protected]6a02963e2009-01-06 16:58:03885 // Remove ourselves as an observer if we are tracking no more InfoBars.
886 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56887 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57888 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03889 }
[email protected]616ed5a2008-11-21 22:27:24890 }
891}
[email protected]3edd9522009-03-04 22:19:41892
[email protected]96d185d2009-04-24 03:28:54893bool TabContents::IsBookmarkBarAlwaysVisible() {
894 // See GetDOMUIForCurrentState() comment for more info. This case is very
895 // similar, but for non-first loads, we want to use the committed entry. This
896 // is so the bookmarks bar disappears at the same time the page does.
897 if (controller_.GetLastCommittedEntry()) {
898 // Not the first load, always use the committed DOM UI.
899 if (render_manager_.dom_ui())
900 return render_manager_.dom_ui()->force_bookmark_bar_visible();
901 return false; // Default.
902 }
903
904 // When it's the first load, we know either the pending one or the committed
905 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
906 // of them will be valid, so we can just check both.
907 if (render_manager_.pending_dom_ui())
908 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
909 if (render_manager_.dom_ui())
910 return render_manager_.dom_ui()->force_bookmark_bar_visible();
911 return false; // Default.
912}
913
[email protected]3edd9522009-03-04 22:19:41914void TabContents::ToolbarSizeChanged(bool is_animating) {
915 TabContentsDelegate* d = delegate();
916 if (d)
917 d->ToolbarSizeChanged(this, is_animating);
918}
[email protected]616ed5a2008-11-21 22:27:24919
[email protected]d5f942ba2008-09-26 19:30:34920void TabContents::OnStartDownload(DownloadItem* download) {
921 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34922
923 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31924 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34925
[email protected]59560e0b2009-06-04 03:30:22926 if (tab_contents && tab_contents->delegate())
927 tab_contents->delegate()->OnStartDownload(download);
[email protected]3edd9522009-03-04 22:19:41928}
[email protected]3edd9522009-03-04 22:19:41929
[email protected]d5f942ba2008-09-26 19:30:34930void TabContents::WillClose(ConstrainedWindow* window) {
931 ConstrainedWindowList::iterator it =
932 find(child_windows_.begin(), child_windows_.end(), window);
933 if (it != child_windows_.end())
934 child_windows_.erase(it);
[email protected]66ba4932009-06-04 19:22:13935}
[email protected]d5f942ba2008-09-26 19:30:34936
[email protected]66ba4932009-06-04 19:22:13937void TabContents::WillCloseBlockedPopupContainer(
938 BlockedPopupContainer* container) {
939 DCHECK(blocked_popups_ == container);
940 blocked_popups_ = NULL;
[email protected]d5f942ba2008-09-26 19:30:34941}
942
[email protected]d5f942ba2008-09-26 19:30:34943void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:35944#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:06945 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:35946#endif
[email protected]d5f942ba2008-09-26 19:30:34947}
948
[email protected]e491f1c2009-05-22 20:28:12949void TabContents::StartFinding(string16 find_text,
950 bool forward_direction,
951 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:01952 // If find_text is empty, it means FindNext was pressed with a keyboard
953 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:12954 if (find_text.empty() && find_text_.empty()) {
955 if (last_search_prepopulate_text_->empty())
956 return;
957 // Try whatever we searched for last in any tab.
958 find_text = *last_search_prepopulate_text_;
959 }
[email protected]6e95706d2009-04-23 22:55:01960
961 // This is a FindNext operation if we are searching for the same text again,
962 // or if the passed in search text is empty (FindNext keyboard shortcut). The
963 // exception to this is if the Find was aborted (then we don't want FindNext
964 // because the highlighting has been cleared and we need it to reappear). We
965 // therefore treat FindNext after an aborted Find operation as a full fledged
966 // Find.
967 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:12968 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:01969 !find_op_aborted_;
970 if (!find_next)
971 current_find_request_id_ = find_request_id_counter_++;
972
973 if (!find_text.empty())
974 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:12975 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:01976
977 find_op_aborted_ = false;
978
979 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:12980 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:01981
982 render_view_host()->StartFinding(current_find_request_id_,
983 find_text_,
984 forward_direction,
[email protected]e491f1c2009-05-22 20:28:12985 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:01986 find_next);
987}
988
989void TabContents::StopFinding(bool clear_selection) {
[email protected]2d2dffc2009-06-09 21:41:00990 // When |clear_selection| is true, it means the find string has been cleared
991 // by the user, but the UI has not been dismissed.
992 if (!clear_selection)
993 find_ui_active_ = false;
[email protected]6e95706d2009-04-23 22:55:01994 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:12995 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:01996 render_view_host()->StopFinding(clear_selection);
997}
998
[email protected]5c4266922009-07-10 16:41:27999void TabContents::GetPageLanguage() {
1000 render_view_host()->GetPageLanguage();
1001}
1002
[email protected]420ae012009-04-24 05:16:321003void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
1004 bool success,
1005 const std::wstring& prompt) {
1006 last_javascript_message_dismissal_ = base::TimeTicks::Now();
1007 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
1008}
1009
[email protected]571e31152009-05-15 19:34:021010void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
1011 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
1012}
1013
[email protected]420ae012009-04-24 05:16:321014void TabContents::OnSavePage() {
1015 // If we can not save the page, try to download it.
1016 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1017 DownloadManager* dlm = profile()->GetDownloadManager();
1018 const GURL& current_page_url = GetURL();
1019 if (dlm && current_page_url.is_valid())
[email protected]d82ed61e2009-06-16 02:46:221020 dlm->DownloadUrl(current_page_url, GURL(), "", this);
[email protected]420ae012009-04-24 05:16:321021 return;
1022 }
1023
1024 Stop();
1025
1026 // Create the save package and possibly prompt the user for the name to save
1027 // the page as. The user prompt is an asynchronous operation that runs on
1028 // another thread.
[email protected]d82ed61e2009-06-16 02:46:221029 save_package_ = new SavePackage(this);
[email protected]420ae012009-04-24 05:16:321030 save_package_->GetSaveInfo();
1031}
1032
1033// Used in automated testing to bypass prompting the user for file names.
1034// Instead, the names and paths are hard coded rather than running them through
1035// file name sanitation and extension / mime checking.
[email protected]cdf6cc82009-08-04 21:48:591036bool TabContents::SavePage(const std::wstring& main_file,
[email protected]420ae012009-04-24 05:16:321037 const std::wstring& dir_path,
1038 SavePackage::SavePackageType save_type) {
1039 // Stop the page from navigating.
1040 Stop();
1041
[email protected]d82ed61e2009-06-16 02:46:221042 save_package_ = new SavePackage(this, save_type,
[email protected]420ae012009-04-24 05:16:321043 FilePath::FromWStringHack(main_file),
1044 FilePath::FromWStringHack(dir_path));
[email protected]cdf6cc82009-08-04 21:48:591045 return save_package_->Init();
[email protected]420ae012009-04-24 05:16:321046}
1047
1048void TabContents::PrintPreview() {
1049 // We don't show the print preview yet, only the print dialog.
1050 PrintNow();
1051}
1052
1053bool TabContents::PrintNow() {
1054 // We can't print interstitial page for now.
1055 if (showing_interstitial_page())
1056 return false;
1057
1058 return render_view_host()->PrintPages();
1059}
1060
[email protected]82270452009-06-19 15:58:011061void TabContents::PrintingDone(int document_cookie, bool success) {
1062 render_view_host()->PrintingDone(document_cookie, success);
1063}
1064
[email protected]420ae012009-04-24 05:16:321065bool TabContents::IsActiveEntry(int32 page_id) {
1066 NavigationEntry* active_entry = controller_.GetActiveEntry();
1067 return (active_entry != NULL &&
1068 active_entry->site_instance() == GetSiteInstance() &&
1069 active_entry->page_id() == page_id);
1070}
1071
[email protected]96d185d2009-04-24 03:28:541072// Notifies the RenderWidgetHost instance about the fact that the page is
1073// loading, or done loading and calls the base implementation.
1074void TabContents::SetIsLoading(bool is_loading,
1075 LoadNotificationDetails* details) {
1076 if (is_loading == is_loading_)
1077 return;
1078
1079 if (!is_loading) {
1080 load_state_ = net::LOAD_STATE_IDLE;
1081 load_state_host_.clear();
1082 }
1083
1084 render_manager_.SetIsLoading(is_loading);
1085
1086 is_loading_ = is_loading;
1087 waiting_for_response_ = is_loading;
1088
1089 if (delegate_)
1090 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351091 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541092
1093 NotificationType type = is_loading ? NotificationType::LOAD_START :
1094 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111095 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541096 if (details)
1097 det = Details<LoadNotificationDetails>(details);
1098 NotificationService::current()->Notify(type,
1099 Source<NavigationController>(&controller_),
1100 det);
1101}
1102
[email protected]2c4410d2009-05-06 23:46:221103void TabContents::CreateBlockedPopupContainerIfNecessary() {
1104 if (blocked_popups_)
1105 return;
1106
[email protected]4d4c0b92009-06-08 23:13:011107 blocked_popups_ = BlockedPopupContainer::Create(this, profile());
[email protected]2c4410d2009-05-06 23:46:221108}
1109
[email protected]b6c874582009-05-08 19:38:311110void TabContents::AddPopup(TabContents* new_contents,
1111 const gfx::Rect& initial_pos,
1112 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221113 CreateBlockedPopupContainerIfNecessary();
1114 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221115}
1116
[email protected]e69bce3dd2009-04-20 22:05:121117// TODO(brettw) This should be on the TabContentsView.
[email protected]66ba4932009-06-04 19:22:131118void TabContents::RepositionSupressedPopupsToFit() {
[email protected]d6598c052008-11-05 19:03:251119 if (blocked_popups_)
[email protected]4d4c0b92009-06-08 23:13:011120 blocked_popups_->RepositionBlockedPopupContainer();
[email protected]d5f942ba2008-09-26 19:30:341121}
1122
[email protected]b9681312008-11-07 00:08:261123bool TabContents::ShowingBlockedPopupNotification() const {
1124 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221125 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261126}
[email protected]616ed5a2008-11-21 22:27:241127
1128namespace {
1129bool TransitionIsReload(PageTransition::Type transition) {
1130 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1131}
1132}
1133
1134void TabContents::ExpireInfoBars(
1135 const NavigationController::LoadCommittedDetails& details) {
1136 // Only hide InfoBars when the user has done something that makes the main
1137 // frame load. We don't want various automatic or subframe navigations making
1138 // it disappear.
1139 if (!details.is_user_initiated_main_frame_load())
1140 return;
1141
[email protected]f86a07022008-11-25 01:06:051142 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241143 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051144 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241145 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241146 }
1147}
[email protected]fdd61c62009-04-22 19:22:571148
1149void TabContents::OnGearsCreateShortcutDone(
1150 const GearsShortcutData2& shortcut_data, bool success) {
1151 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1152 bool same_page =
1153 current_entry && pending_install_.page_id == current_entry->page_id();
1154
1155 if (success && same_page) {
1156 // Only switch to app mode if the user chose to create a shortcut and
1157 // we're still on the same page that it corresponded to.
1158 if (delegate())
1159 delegate()->ConvertContentsToApplication(this);
1160 }
1161
1162 // Reset the page id to indicate no requests are pending.
1163 pending_install_.page_id = 0;
1164 pending_install_.callback_functor = NULL;
1165}
[email protected]96d185d2009-04-24 03:28:541166
1167DOMUI* TabContents::GetDOMUIForCurrentState() {
1168 // When there is a pending navigation entry, we want to use the pending DOMUI
1169 // that goes along with it to control the basic flags. For example, we want to
1170 // show the pending URL in the URL bar, so we want the display_url flag to
1171 // be from the pending entry.
1172 //
1173 // The confusion comes because there are multiple possibilities for the
1174 // initial load in a tab as a side effect of the way the RenderViewHostManager
1175 // works.
1176 //
1177 // - For the very first tab the load looks "normal". The new tab DOM UI is
1178 // the pending one, and we want it to apply here.
1179 //
1180 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1181 // get switched to the one previously associated with the new tab pages.
1182 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1183 // have a committed DOM UI in this case.
1184 //
1185 // This condition handles all of these cases:
1186 //
1187 // - First load in first tab: no committed nav entry + pending nav entry +
1188 // pending dom ui:
1189 // -> Use pending DOM UI if any.
1190 //
1191 // - First load in second tab: no committed nav entry + pending nav entry +
1192 // no pending DOM UI:
1193 // -> Use the committed DOM UI if any.
1194 //
1195 // - Second navigation in any tab: committed nav entry + pending nav entry:
1196 // -> Use pending DOM UI if any.
1197 //
1198 // - Normal state with no load: committed nav entry + no pending nav entry:
1199 // -> Use committed DOM UI.
1200 if (controller_.pending_entry() &&
1201 (controller_.GetLastCommittedEntry() ||
1202 render_manager_.pending_dom_ui()))
1203 return render_manager_.pending_dom_ui();
1204 return render_manager_.dom_ui();
1205}
[email protected]420ae012009-04-24 05:16:321206
1207void TabContents::DidNavigateMainFramePostCommit(
1208 const NavigationController::LoadCommittedDetails& details,
1209 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]420ae012009-04-24 05:16:321210 if (details.is_user_initiated_main_frame_load()) {
1211 // Clear the status bubble. This is a workaround for a bug where WebKit
1212 // doesn't let us know that the cursor left an element during a
1213 // transition (this is also why the mouse cursor remains as a hand after
1214 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1215 // clear the bubble when a user navigates to a named anchor in the same
1216 // page.
1217 UpdateTargetURL(details.entry->page_id(), GURL());
1218
1219 // UpdateHelpersForDidNavigate will handle the case where the password_form
1220 // origin is valid.
1221 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1222 // cleaned up and covered by tests.
1223 if (!params.password_form.origin.is_valid())
1224 GetPasswordManager()->DidNavigate();
1225 }
1226
1227 // The keyword generator uses the navigation entries, so must be called after
1228 // the commit.
1229 GenerateKeywordIfNecessary(params);
1230
1231 // Allow the new page to set the title again.
1232 received_page_title_ = false;
1233
1234 // Get the favicon, either from history or request it from the net.
1235 fav_icon_helper_.FetchFavIcon(details.entry->url());
1236
[email protected]ce5c4502009-05-06 16:46:111237 // Disable all page actions.
1238 enabled_page_actions_.clear();
1239
[email protected]420ae012009-04-24 05:16:321240 // Close constrained popups if necessary.
1241 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1242
1243 // Update the starred state.
1244 UpdateStarredStateForCurrentURL();
1245}
1246
1247void TabContents::DidNavigateAnyFramePostCommit(
1248 RenderViewHost* render_view_host,
1249 const NavigationController::LoadCommittedDetails& details,
1250 const ViewHostMsg_FrameNavigate_Params& params) {
1251 // If we navigate, start showing messages again. This does nothing to prevent
1252 // a malicious script from spamming messages, since the script could just
1253 // reload the page to stop blocking.
1254 suppress_javascript_messages_ = false;
1255
[email protected]420ae012009-04-24 05:16:321256 // Notify the password manager of the navigation or form submit.
1257 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1258 // cleaned up and covered by tests.
1259 if (params.password_form.origin.is_valid())
1260 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1261}
1262
1263void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1264 const GURL& current_url) {
1265 if (net::RegistryControlledDomainService::SameDomainOrHost(
1266 previous_url, current_url))
1267 return;
1268
1269 // Clear out any child windows since we are leaving this page entirely.
1270 // We use indices instead of iterators in case CloseWindow does something
1271 // that may invalidate an iterator.
1272 int size = static_cast<int>(child_windows_.size());
1273 for (int i = size - 1; i >= 0; --i) {
1274 ConstrainedWindow* window = child_windows_[i];
1275 if (window)
1276 window->CloseConstrainedWindow();
1277 }
[email protected]e29300cd2009-07-23 21:14:591278
1279 // Close the popup container.
1280 if (blocked_popups_) {
1281 blocked_popups_->Destroy();
1282 blocked_popups_ = NULL;
1283 }
[email protected]420ae012009-04-24 05:16:321284}
1285
1286void TabContents::UpdateStarredStateForCurrentURL() {
1287 BookmarkModel* model = profile()->GetBookmarkModel();
1288 const bool old_state = is_starred_;
1289 is_starred_ = (model && model->IsBookmarked(GetURL()));
1290
1291 if (is_starred_ != old_state && delegate())
1292 delegate()->URLStarredChanged(this, is_starred_);
1293}
1294
1295void TabContents::UpdateAlternateErrorPageURL() {
1296 GURL url = GetAlternateErrorPageURL();
1297 render_view_host()->SetAlternateErrorPageURL(url);
1298}
1299
1300void TabContents::UpdateWebPreferences() {
1301 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1302}
1303
1304void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1305 RenderViewHost* rvh) {
1306 // If we are creating a RVH for a restored controller, then we might
1307 // have more page IDs than the SiteInstance's current max page ID. We must
1308 // make sure that the max page ID is larger than any restored page ID.
1309 // Note that it is ok for conflicting page IDs to exist in another tab
1310 // (i.e., NavigationController), but if any page ID is larger than the max,
1311 // the back/forward list will get confused.
1312 int max_restored_page_id = controller_.max_restored_page_id();
1313 if (max_restored_page_id > 0) {
1314 int curr_max_page_id = site_instance->max_page_id();
1315 if (max_restored_page_id > curr_max_page_id) {
1316 // Need to update the site instance immediately.
1317 site_instance->UpdateMaxPageID(max_restored_page_id);
1318
1319 // Also tell the renderer to update its internal representation. We
1320 // need to reserve enough IDs to make all restored page IDs less than
1321 // the max.
1322 if (curr_max_page_id < 0)
1323 curr_max_page_id = 0;
1324 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1325 }
1326 }
1327}
1328
1329void TabContents::UpdateHistoryForNavigation(
1330 const GURL& display_url,
[email protected]befd8d822009-07-01 04:51:471331 const NavigationController::LoadCommittedDetails& details,
[email protected]420ae012009-04-24 05:16:321332 const ViewHostMsg_FrameNavigate_Params& params) {
1333 if (profile()->IsOffTheRecord())
1334 return;
1335
1336 // Add to history service.
1337 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1338 if (hs) {
1339 if (PageTransition::IsMainFrame(params.transition) &&
1340 display_url != params.url) {
1341 // Hack on the "display" URL so that it will appear in history. For some
1342 // types of URLs, we will display a magic URL that is different from where
1343 // the page is actually navigated. We want the user to see in history
1344 // what they saw in the URL bar, so we add the display URL as a redirect.
1345 // This only applies to the main frame, as the display URL doesn't apply
1346 // to sub-frames.
1347 std::vector<GURL> redirects = params.redirects;
1348 if (!redirects.empty())
1349 redirects.back() = display_url;
1350 hs->AddPage(display_url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471351 params.transition, redirects, details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321352 } else {
1353 hs->AddPage(params.url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471354 params.transition, params.redirects,
1355 details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321356 }
1357 }
1358}
1359
1360bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1361 const std::wstring& title) {
1362 // For file URLs without a title, use the pathname instead. In the case of a
1363 // synthesized title, we don't want the update to count toward the "one set
1364 // per page of the title to history."
1365 std::wstring final_title;
1366 bool explicit_set;
1367 if (entry->url().SchemeIsFile() && title.empty()) {
1368 final_title = UTF8ToWide(entry->url().ExtractFileName());
1369 explicit_set = false; // Don't count synthetic titles toward the set limit.
1370 } else {
1371 TrimWhitespace(title, TRIM_ALL, &final_title);
1372 explicit_set = true;
1373 }
1374
1375 if (final_title == UTF16ToWideHack(entry->title()))
1376 return false; // Nothing changed, don't bother.
1377
1378 entry->set_title(WideToUTF16Hack(final_title));
1379
1380 // Update the history system for this page.
1381 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1382 HistoryService* hs =
1383 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1384 if (hs)
1385 hs->SetPageTitle(entry->display_url(), final_title);
1386
1387 // Don't allow the title to be saved again for explicitly set ones.
1388 received_page_title_ = explicit_set;
1389 }
1390
1391 // Lastly, set the title for the view.
1392 view_->SetPageTitle(final_title);
1393
1394 return true;
1395}
1396
1397void TabContents::NotifySwapped() {
1398 // After sending out a swap notification, we need to send a disconnect
1399 // notification so that clients that pick up a pointer to |this| can NULL the
1400 // pointer. See Bug 1230284.
1401 notify_disconnection_ = true;
1402 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341403 NotificationType::TAB_CONTENTS_SWAPPED,
[email protected]d82ed61e2009-06-16 02:46:221404 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321405 NotificationService::NoDetails());
1406}
1407
1408void TabContents::NotifyConnected() {
1409 notify_disconnection_ = true;
1410 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341411 NotificationType::TAB_CONTENTS_CONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221412 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321413 NotificationService::NoDetails());
1414}
1415
1416void TabContents::NotifyDisconnected() {
1417 if (!notify_disconnection_)
1418 return;
1419
1420 notify_disconnection_ = false;
1421 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341422 NotificationType::TAB_CONTENTS_DISCONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221423 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321424 NotificationService::NoDetails());
1425}
1426
1427void TabContents::GenerateKeywordIfNecessary(
1428 const ViewHostMsg_FrameNavigate_Params& params) {
1429 if (!params.searchable_form_url.is_valid())
1430 return;
1431
1432 if (profile()->IsOffTheRecord())
1433 return;
1434
1435 int last_index = controller_.last_committed_entry_index();
1436 // When there was no previous page, the last index will be 0. This is
1437 // normally due to a form submit that opened in a new tab.
1438 // TODO(brettw) bug 916126: we should support keywords when form submits
1439 // happen in new tabs.
1440 if (last_index <= 0)
1441 return;
1442 const NavigationEntry* previous_entry =
1443 controller_.GetEntryAtIndex(last_index - 1);
1444 if (IsFormSubmit(previous_entry)) {
1445 // Only generate a keyword if the previous page wasn't itself a form
1446 // submit.
1447 return;
1448 }
1449
1450 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1451 previous_entry->user_typed_url() : previous_entry->url();
1452 std::wstring keyword =
1453 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1454 if (keyword.empty())
1455 return;
1456
1457 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1458 if (!url_model)
1459 return;
1460
1461 if (!url_model->loaded()) {
1462 url_model->Load();
1463 return;
1464 }
1465
1466 const TemplateURL* current_url;
1467 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1468 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1469 return;
1470
1471 if (current_url) {
1472 if (current_url->originating_url().is_valid()) {
1473 // The existing keyword was generated from an OpenSearch description
1474 // document, don't regenerate.
1475 return;
1476 }
1477 url_model->Remove(current_url);
1478 }
1479 TemplateURL* new_url = new TemplateURL();
1480 new_url->set_keyword(keyword);
1481 new_url->set_short_name(keyword);
1482 new_url->SetURL(url, 0, 0);
1483 new_url->add_input_encoding(params.searchable_form_encoding);
1484 DCHECK(controller_.GetLastCommittedEntry());
1485 const GURL& favicon_url =
1486 controller_.GetLastCommittedEntry()->favicon().url();
1487 if (favicon_url.is_valid()) {
1488 new_url->SetFavIconURL(favicon_url);
1489 } else {
1490 // The favicon url isn't valid. This means there really isn't a favicon,
1491 // or the favicon url wasn't obtained before the load started. This assumes
1492 // the later.
1493 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1494 // its url.
1495 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1496 }
1497 new_url->set_safe_for_autoreplace(true);
1498 url_model->Add(new_url);
1499}
1500
[email protected]bf5c2ff392009-07-08 16:24:331501void TabContents::OnUserGesture() {
1502 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
1503 DownloadRequestManager* drm = g_browser_process->download_request_manager();
1504 if (drm)
1505 drm->OnUserGesture(this);
1506 controller_.OnUserGesture();
1507}
1508
1509void TabContents::OnFindReply(int request_id,
1510 int number_of_matches,
1511 const gfx::Rect& selection_rect,
1512 int active_match_ordinal,
1513 bool final_update) {
[email protected]3ce7ced2009-07-24 18:52:421514 // Ignore responses for requests that have been aborted.
1515 if (find_op_aborted_)
1516 return;
1517
[email protected]bf5c2ff392009-07-08 16:24:331518 // Ignore responses for requests other than the one we have most recently
1519 // issued. That way we won't act on stale results when the user has
1520 // already typed in another query.
1521 if (request_id != current_find_request_id_)
1522 return;
1523
1524 if (number_of_matches == -1)
1525 number_of_matches = last_search_result_.number_of_matches();
1526 if (active_match_ordinal == -1)
1527 active_match_ordinal = last_search_result_.active_match_ordinal();
1528
1529 gfx::Rect selection = selection_rect;
1530 if (selection.IsEmpty())
1531 selection = last_search_result_.selection_rect();
1532
1533 // Notify the UI, automation and any other observers that a find result was
1534 // found.
1535 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
1536 selection, active_match_ordinal,
1537 final_update);
1538 NotificationService::current()->Notify(
1539 NotificationType::FIND_RESULT_AVAILABLE,
1540 Source<TabContents>(this),
1541 Details<FindNotificationDetails>(&last_search_result_));
1542}
1543
1544void TabContents::GoToEntryAtOffset(int offset) {
1545 controller_.GoToOffset(offset);
1546}
1547
1548void TabContents::GetHistoryListCount(int* back_list_count,
1549 int* forward_list_count) {
1550 int current_index = controller_.last_committed_entry_index();
1551 *back_list_count = current_index;
1552 *forward_list_count = controller_.entry_count() - current_index - 1;
1553}
1554
1555void TabContents::OnMissingPluginStatus(int status) {
1556#if defined(OS_WIN)
1557// TODO(PORT): pull in when plug-ins work
1558 GetPluginInstaller()->OnMissingPluginStatus(status);
1559#endif
1560}
1561
1562void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
[email protected]bf5c2ff392009-07-08 16:24:331563 DCHECK(!plugin_path.value().empty());
1564
1565 std::wstring plugin_name = plugin_path.ToWStringHack();
[email protected]d32d46182009-07-23 00:09:351566#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]bf5c2ff392009-07-08 16:24:331567 scoped_ptr<FileVersionInfo> version_info(
1568 FileVersionInfo::CreateFileVersionInfo(plugin_path));
1569 if (version_info.get()) {
1570 const std::wstring& product_name = version_info->product_name();
1571 if (!product_name.empty())
1572 plugin_name = product_name;
1573 }
[email protected]4a560ed2009-07-13 23:35:261574#else
1575 NOTIMPLEMENTED() << " convert plugin path to plugin name";
1576#endif
[email protected]bf5c2ff392009-07-08 16:24:331577 AddInfoBar(new SimpleAlertInfoBarDelegate(
1578 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
1579 NULL));
[email protected]bf5c2ff392009-07-08 16:24:331580}
1581
1582void TabContents::OnCrashedWorker() {
1583 AddInfoBar(new SimpleAlertInfoBarDelegate(
1584 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
1585 NULL));
1586}
1587
1588void TabContents::OnDidGetApplicationInfo(
1589 int32 page_id,
1590 const webkit_glue::WebApplicationInfo& info) {
1591 if (pending_install_.page_id != page_id)
1592 return; // The user clicked create on a separate page. Ignore this.
1593
1594 pending_install_.callback_functor =
1595 new GearsCreateShortcutCallbackFunctor(this);
1596 GearsCreateShortcut(
1597 info, pending_install_.title, pending_install_.url, pending_install_.icon,
1598 NewCallback(pending_install_.callback_functor,
1599 &GearsCreateShortcutCallbackFunctor::Run));
1600}
1601
1602void TabContents::DidStartProvisionalLoadForFrame(
1603 RenderViewHost* render_view_host,
1604 bool is_main_frame,
1605 const GURL& url) {
1606 ProvisionalLoadDetails details(is_main_frame,
1607 controller_.IsURLInPageNavigation(url),
1608 url, std::string(), false);
1609 NotificationService::current()->Notify(
1610 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1611 Source<NavigationController>(&controller_),
1612 Details<ProvisionalLoadDetails>(&details));
1613}
1614
1615void TabContents::DidStartReceivingResourceResponse(
1616 ResourceRequestDetails* details) {
1617 NotificationService::current()->Notify(
1618 NotificationType::RESOURCE_RESPONSE_STARTED,
1619 Source<NavigationController>(&controller()),
1620 Details<ResourceRequestDetails>(details));
1621}
1622
1623void TabContents::DidRedirectResource(ResourceRequestDetails* details) {
1624 NotificationService::current()->Notify(
1625 NotificationType::RESOURCE_RECEIVED_REDIRECT,
1626 Source<NavigationController>(&controller()),
1627 Details<ResourceRequestDetails>(details));
1628}
1629
1630void TabContents::DidLoadResourceFromMemoryCache(
1631 const GURL& url,
1632 const std::string& frame_origin,
1633 const std::string& main_frame_origin,
1634 const std::string& security_info) {
1635 // Send out a notification that we loaded a resource from our memory cache.
1636 int cert_id = 0, cert_status = 0, security_bits = 0;
1637 SSLManager::DeserializeSecurityInfo(security_info,
1638 &cert_id, &cert_status,
1639 &security_bits);
1640 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
1641 process()->pid(), cert_id, cert_status);
1642
1643 NotificationService::current()->Notify(
1644 NotificationType::LOAD_FROM_MEMORY_CACHE,
1645 Source<NavigationController>(&controller_),
1646 Details<LoadFromMemoryCacheDetails>(&details));
1647}
1648
1649void TabContents::DidFailProvisionalLoadWithError(
1650 RenderViewHost* render_view_host,
1651 bool is_main_frame,
1652 int error_code,
1653 const GURL& url,
1654 bool showing_repost_interstitial) {
1655 if (net::ERR_ABORTED == error_code) {
1656 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1657 // This means that the interstitial won't be torn down properly, which is
1658 // bad. But if we have an interstitial, go back to another tab type, and
1659 // then load the same interstitial again, we could end up getting the first
1660 // interstitial's "failed" message (as a result of the cancel) when we're on
1661 // the second one.
1662 //
1663 // We can't tell this apart, so we think we're tearing down the current page
1664 // which will cause a crash later one. There is also some code in
1665 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1666 // out because of this problem.
1667 //
1668 // http://code.google.com/p/chromium/issues/detail?id=2855
1669 // Because this will not tear down the interstitial properly, if "back" is
1670 // back to another tab type, the interstitial will still be somewhat alive
1671 // in the previous tab type. If you navigate somewhere that activates the
1672 // tab with the interstitial again, you'll see a flash before the new load
1673 // commits of the interstitial page.
1674 if (showing_interstitial_page()) {
1675 LOG(WARNING) << "Discarding message during interstitial.";
1676 return;
1677 }
1678
1679 // This will discard our pending entry if we cancelled the load (e.g., if we
1680 // decided to download the file instead of load it). Only discard the
1681 // pending entry if the URLs match, otherwise the user initiated a navigate
1682 // before the page loaded so that the discard would discard the wrong entry.
1683 NavigationEntry* pending_entry = controller_.pending_entry();
1684 if (pending_entry && pending_entry->url() == url) {
1685 controller_.DiscardNonCommittedEntries();
1686 // Update the URL display.
1687 NotifyNavigationStateChanged(TabContents::INVALIDATE_URL);
1688 }
1689
1690 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1691 }
1692
1693 // Send out a notification that we failed a provisional load with an error.
1694 ProvisionalLoadDetails details(is_main_frame,
1695 controller_.IsURLInPageNavigation(url),
1696 url, std::string(), false);
1697 details.set_error_code(error_code);
1698
1699 NotificationService::current()->Notify(
1700 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1701 Source<NavigationController>(&controller_),
1702 Details<ProvisionalLoadDetails>(&details));
1703}
1704
1705void TabContents::DocumentLoadedInFrame() {
1706 controller_.DocumentLoadedInFrame();
1707}
1708
[email protected]8d3347f2009-07-09 22:00:211709RenderViewHostDelegate::View* TabContents::GetViewDelegate() {
[email protected]420ae012009-04-24 05:16:321710 return view_.get();
1711}
1712
[email protected]8d3347f2009-07-09 22:00:211713RenderViewHostDelegate::RendererManagement*
1714TabContents::GetRendererManagementDelegate() {
1715 return &render_manager_;
1716}
1717
[email protected]bf5c2ff392009-07-08 16:24:331718RenderViewHostDelegate::BrowserIntegration*
[email protected]8d3347f2009-07-09 22:00:211719 TabContents::GetBrowserIntegrationDelegate() {
1720 return this;
[email protected]bf5c2ff392009-07-08 16:24:331721}
1722
[email protected]8d3347f2009-07-09 22:00:211723RenderViewHostDelegate::Resource* TabContents::GetResourceDelegate() {
1724 return this;
[email protected]bf5c2ff392009-07-08 16:24:331725}
1726
[email protected]8d3347f2009-07-09 22:00:211727RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() {
[email protected]420ae012009-04-24 05:16:321728 return save_package_.get(); // May be NULL, but we can return NULL.
1729}
1730
[email protected]8d3347f2009-07-09 22:00:211731RenderViewHostDelegate::Printing* TabContents::GetPrintingDelegate() {
1732 return &printing_;
1733}
1734
1735RenderViewHostDelegate::FavIcon* TabContents::GetFavIconDelegate() {
1736 return &fav_icon_helper_;
1737}
1738
1739RenderViewHostDelegate::Autofill* TabContents::GetAutofillDelegate() {
1740 if (autofill_manager_.get() == NULL)
1741 autofill_manager_.reset(new AutofillManager(this));
1742 return autofill_manager_.get();
[email protected]bf5c2ff392009-07-08 16:24:331743}
1744
[email protected]80d96fa2009-06-10 22:34:511745RendererPreferences TabContents::GetRendererPrefs() const {
[email protected]840b1512009-07-21 16:53:461746 return renderer_preferences_;
[email protected]80d96fa2009-06-10 22:34:511747}
1748
[email protected]57c6a652009-05-04 07:58:341749TabContents* TabContents::GetAsTabContents() {
1750 return this;
1751}
1752
[email protected]420ae012009-04-24 05:16:321753void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
[email protected]2e4633c2009-07-09 16:58:061754 NotificationService::current()->Notify(
1755 NotificationType::RENDER_VIEW_HOST_CREATED_FOR_TAB,
1756 Source<TabContents>(this),
1757 Details<RenderViewHost>(render_view_host));
1758
[email protected]420ae012009-04-24 05:16:321759 NavigationEntry* entry = controller_.GetActiveEntry();
1760 if (!entry)
1761 return;
1762
1763 // When we're creating views, we're still doing initial setup, so we always
1764 // use the pending DOM UI rather than any possibly existing committed one.
1765 if (render_manager_.pending_dom_ui()) {
1766 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1767 }
1768
1769 if (entry->IsViewSourceMode()) {
1770 // Put the renderer in view source mode.
1771 render_view_host->Send(
1772 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1773 }
[email protected]0666aef2009-05-13 19:48:081774
1775 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321776}
1777
1778void TabContents::RenderViewReady(RenderViewHost* rvh) {
1779 if (rvh != render_view_host()) {
1780 // Don't notify the world, since this came from a renderer in the
1781 // background.
1782 return;
1783 }
1784
1785 NotifyConnected();
[email protected]9d8a4642009-07-29 17:25:301786 bool was_crashed = is_crashed();
[email protected]420ae012009-04-24 05:16:321787 SetIsCrashed(false);
[email protected]9d8a4642009-07-29 17:25:301788
1789 // Restore the focus to the tab (otherwise the focus will be on the top
1790 // window).
1791 if (was_crashed && !FocusLocationBarByDefault())
1792 Focus();
[email protected]420ae012009-04-24 05:16:321793}
1794
1795void TabContents::RenderViewGone(RenderViewHost* rvh) {
1796 // Ask the print preview if this renderer was valuable.
1797 if (!printing_.OnRenderViewGone(rvh))
1798 return;
1799 if (rvh != render_view_host()) {
1800 // The pending page's RenderViewHost is gone.
1801 return;
1802 }
1803
1804 SetIsLoading(false, NULL);
1805 NotifyDisconnected();
1806 SetIsCrashed(true);
1807
[email protected]8e537302009-06-10 21:19:581808 // Tell the view that we've crashed so it can prepare the sad tab page.
1809 view_->OnTabCrashed();
[email protected]420ae012009-04-24 05:16:321810
1811 // Hide any visible hung renderer warning for this web contents' process.
[email protected]d82ed61e2009-06-16 02:46:221812 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:321813}
1814
[email protected]2e4633c2009-07-09 16:58:061815void TabContents::RenderViewDeleted(RenderViewHost* rvh) {
1816 NotificationService::current()->Notify(
1817 NotificationType::RENDER_VIEW_HOST_DELETED,
1818 Source<TabContents>(this),
1819 Details<RenderViewHost>(rvh));
1820}
1821
[email protected]420ae012009-04-24 05:16:321822void TabContents::DidNavigate(RenderViewHost* rvh,
1823 const ViewHostMsg_FrameNavigate_Params& params) {
1824 if (PageTransition::IsMainFrame(params.transition))
1825 render_manager_.DidNavigateMainFrame(rvh);
1826
1827 // Update the site of the SiteInstance if it doesn't have one yet.
1828 if (!GetSiteInstance()->has_site())
1829 GetSiteInstance()->SetSite(params.url);
1830
1831 // Need to update MIME type here because it's referred to in
1832 // UpdateNavigationCommands() called by RendererDidNavigate() to
1833 // determine whether or not to enable the encoding menu.
1834 // It's updated only for the main frame. For a subframe,
1835 // RenderView::UpdateURL does not set params.contents_mime_type.
1836 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1837 // TODO(jungshik): Add a test for the encoding menu to avoid
1838 // regressing it again.
1839 if (PageTransition::IsMainFrame(params.transition))
1840 contents_mime_type_ = params.contents_mime_type;
1841
1842 NavigationController::LoadCommittedDetails details;
[email protected]3e90d4a2009-07-03 17:38:391843 bool did_navigate = controller_.RendererDidNavigate(params, &details);
1844
1845 // Update history. Note that this needs to happen after the entry is complete,
1846 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1847 if (params.should_update_history) {
1848 // Most of the time, the displayURL matches the loaded URL, but for about:
1849 // URLs, we use a data: URL as the real value. We actually want to save
1850 // the about: URL to the history db and keep the data: URL hidden. This is
1851 // what the TabContents' URL getter does.
1852 UpdateHistoryForNavigation(GetURL(), details, params);
1853 }
1854
1855 if (!did_navigate)
1856 return; // No navigation happened.
[email protected]420ae012009-04-24 05:16:321857
1858 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1859 // for the appropriate notification (best) or you can add it to
1860 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1861 // necessary, please).
1862
1863 // Run post-commit tasks.
1864 if (details.is_main_frame)
1865 DidNavigateMainFramePostCommit(details, params);
1866 DidNavigateAnyFramePostCommit(rvh, details, params);
1867}
1868
1869void TabContents::UpdateState(RenderViewHost* rvh,
1870 int32 page_id,
1871 const std::string& state) {
1872 DCHECK(rvh == render_view_host());
1873
1874 // We must be prepared to handle state updates for any page, these occur
1875 // when the user is scrolling and entering form data, as well as when we're
1876 // leaving a page, in which case our state may have already been moved to
1877 // the next page. The navigation controller will look up the appropriate
1878 // NavigationEntry and update it when it is notified via the delegate.
1879
1880 int entry_index = controller_.GetEntryIndexWithPageID(
1881 GetSiteInstance(), page_id);
1882 if (entry_index < 0)
1883 return;
1884 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1885
1886 if (state == entry->content_state())
1887 return; // Nothing to update.
1888 entry->set_content_state(state);
1889 controller_.NotifyEntryChanged(entry, entry_index);
1890}
1891
1892void TabContents::UpdateTitle(RenderViewHost* rvh,
1893 int32 page_id, const std::wstring& title) {
1894 // If we have a title, that's a pretty good indication that we've started
1895 // getting useful data.
1896 SetNotWaitingForResponse();
1897
1898 DCHECK(rvh == render_view_host());
1899 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1900 page_id);
1901 if (!entry || !UpdateTitleForEntry(entry, title))
1902 return;
1903
1904 // Broadcast notifications when the UI should be updated.
1905 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501906 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321907}
1908
[email protected]420ae012009-04-24 05:16:321909void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1910 const std::wstring& encoding) {
1911 set_encoding(encoding);
1912}
1913
1914void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1915 if (delegate())
1916 delegate()->UpdateTargetURL(this, url);
1917}
1918
1919void TabContents::UpdateThumbnail(const GURL& url,
1920 const SkBitmap& bitmap,
1921 const ThumbnailScore& score) {
1922 // Tell History about this thumbnail
[email protected]449478302009-06-09 20:04:281923 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kThumbnailStore)) {
[email protected]72d0fc72009-07-09 17:30:491924 if (!profile()->IsOffTheRecord())
[email protected]42339402009-07-17 17:27:191925 profile()->GetThumbnailStore()->SetPageThumbnail(url, bitmap,
1926 score, true);
[email protected]449478302009-06-09 20:04:281927 } else {
1928 HistoryService* hs;
1929 if (!profile()->IsOffTheRecord() &&
1930 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1931 hs->SetPageThumbnail(url, bitmap, score);
1932 }
[email protected]420ae012009-04-24 05:16:321933 }
1934}
1935
[email protected]0df30122009-06-03 12:13:081936void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
1937 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
1938 raw_settings);
1939}
1940
[email protected]420ae012009-04-24 05:16:321941void TabContents::Close(RenderViewHost* rvh) {
[email protected]24a4d1062009-07-10 23:10:421942 // If we close the tab while we're in the middle of a drag, we'll crash.
1943 // Instead, cancel the drag and close it as soon as the drag ends.
1944 if (view()->IsDoingDrag()) {
1945 view()->CancelDragAndCloseTab();
1946 return;
1947 }
1948
[email protected]420ae012009-04-24 05:16:321949 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1950 if (delegate() && rvh == render_view_host())
1951 delegate()->CloseContents(this);
1952}
1953
1954void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1955 if (delegate() && delegate()->IsPopup(this))
1956 delegate()->MoveContents(this, new_bounds);
1957}
1958
[email protected]329581b2009-04-28 06:52:351959void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321960 SetIsLoading(true, NULL);
1961}
1962
[email protected]329581b2009-04-28 06:52:351963void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321964 scoped_ptr<LoadNotificationDetails> details;
1965
1966 NavigationEntry* entry = controller_.GetActiveEntry();
1967 // An entry may not exist for a stop when loading an initial blank page or
1968 // if an iframe injected by script into a blank page finishes loading.
1969 if (entry) {
1970 scoped_ptr<base::ProcessMetrics> metrics(
1971 base::ProcessMetrics::CreateProcessMetrics(
1972 process()->process().handle()));
1973
1974 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1975
1976 details.reset(new LoadNotificationDetails(
1977 entry->display_url(),
1978 entry->transition_type(),
1979 elapsed,
1980 &controller_,
1981 controller_.GetCurrentEntryIndex()));
1982 }
1983
1984 // Tell PasswordManager we've finished a page load, which serves as a
1985 // green light to save pending passwords and reset itself.
1986 GetPasswordManager()->DidStopLoading();
1987
1988 SetIsLoading(false, details.get());
1989}
1990
[email protected]420ae012009-04-24 05:16:321991void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1992 const GURL& source_url,
1993 const GURL& target_url) {
1994 NavigationEntry* entry;
1995 if (page_id == -1)
1996 entry = controller_.pending_entry();
1997 else
1998 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1999 if (!entry || entry->url() != source_url)
2000 return;
2001 entry->set_url(target_url);
2002}
2003
[email protected]420ae012009-04-24 05:16:322004void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
2005 WindowOpenDisposition disposition) {
2006 if (render_manager_.dom_ui()) {
2007 // When we're a DOM UI, it will provide a page transition type for us (this
2008 // is so the new tab page can specify AUTO_BOOKMARK for automatically
2009 // generated suggestions).
2010 //
2011 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:162012 // want web sites to see a referrer of "chrome://blah" (and some
2013 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:322014 // send to the site), so we send no referrer.
2015 OpenURL(url, GURL(), disposition,
2016 render_manager_.dom_ui()->link_transition_type());
2017 } else {
2018 OpenURL(url, referrer, disposition, PageTransition::LINK);
2019 }
2020}
2021
[email protected]1ee614862009-07-06 20:29:182022void TabContents::DomOperationResponse(const std::string& json_string,
2023 int automation_id) {
2024}
2025
[email protected]420ae012009-04-24 05:16:322026void TabContents::ProcessDOMUIMessage(const std::string& message,
[email protected]811bfe32009-07-01 08:46:252027 const std::string& content,
2028 int request_id,
2029 bool has_callback) {
[email protected]420ae012009-04-24 05:16:322030 if (!render_manager_.dom_ui()) {
2031 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
2032 // Because the renderer might be owned and sending random messages, we need
2033 // to ignore these inproper ones.
2034 NOTREACHED();
2035 return;
2036 }
[email protected]811bfe32009-07-01 08:46:252037 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content, request_id,
2038 has_callback);
[email protected]420ae012009-04-24 05:16:322039}
2040
2041void TabContents::ProcessExternalHostMessage(const std::string& message,
2042 const std::string& origin,
2043 const std::string& target) {
2044 if (delegate())
2045 delegate()->ForwardMessageToExternalHost(message, origin, target);
2046}
2047
[email protected]420ae012009-04-24 05:16:322048void TabContents::RunFileChooser(bool multiple_files,
2049 const string16& title,
2050 const FilePath& default_file) {
2051 if (!select_file_dialog_.get())
2052 select_file_dialog_ = SelectFileDialog::Create(this);
2053 SelectFileDialog::Type dialog_type =
2054 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
2055 SelectFileDialog::SELECT_OPEN_FILE;
2056 select_file_dialog_->SelectFile(dialog_type, title, default_file,
2057 NULL, 0, FILE_PATH_LITERAL(""),
2058 view_->GetTopLevelNativeWindow(), NULL);
2059}
2060
2061void TabContents::RunJavaScriptMessage(
2062 const std::wstring& message,
2063 const std::wstring& default_prompt,
2064 const GURL& frame_url,
2065 const int flags,
2066 IPC::Message* reply_msg,
2067 bool* did_suppress_message) {
2068 // Suppress javascript messages when requested and when inside a constrained
2069 // popup window (because that activates them and breaks them out of the
2070 // constrained window jail).
[email protected]91ed49a2009-07-07 21:29:552071 // Also suppress messages when showing an interstitial. The interstitial is
2072 // shown over the previous page, we don't want the hidden page dialogs to
2073 // interfere with the interstitial.
2074 bool suppress_this_message = suppress_javascript_messages_ ||
2075 showing_interstitial_page();
[email protected]420ae012009-04-24 05:16:322076 if (delegate())
2077 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:312078 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:322079
2080 *did_suppress_message = suppress_this_message;
2081
2082 if (!suppress_this_message) {
2083 base::TimeDelta time_since_last_message(
2084 base::TimeTicks::Now() - last_javascript_message_dismissal_);
2085 bool show_suppress_checkbox = false;
2086 // Show a checkbox offering to suppress further messages if this message is
2087 // being displayed within kJavascriptMessageExpectedDelay of the last one.
2088 if (time_since_last_message <
2089 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
2090 show_suppress_checkbox = true;
2091
[email protected]d82ed61e2009-06-16 02:46:222092 RunJavascriptMessageBox(this, frame_url, flags, message, default_prompt,
[email protected]420ae012009-04-24 05:16:322093 show_suppress_checkbox, reply_msg);
2094 } else {
2095 // If we are suppressing messages, just reply as is if the user immediately
2096 // pressed "Cancel".
2097 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
2098 }
2099}
2100
2101void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
2102 IPC::Message* reply_msg) {
[email protected]d82ed61e2009-06-16 02:46:222103 RunBeforeUnloadDialog(this, message, reply_msg);
[email protected]420ae012009-04-24 05:16:322104}
2105
2106void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
2107 const std::string& json_arguments,
2108 IPC::Message* reply_msg) {
2109 if (delegate()) {
2110 HtmlDialogUIDelegate* dialog_delegate =
2111 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
[email protected]d82ed61e2009-06-16 02:46:222112 reply_msg, this);
[email protected]420ae012009-04-24 05:16:322113 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
2114 }
2115}
2116
2117void TabContents::PasswordFormsSeen(
[email protected]ed3fb032009-06-16 19:50:562118 const std::vector<webkit_glue::PasswordForm>& forms) {
[email protected]420ae012009-04-24 05:16:322119 GetPasswordManager()->PasswordFormsSeen(forms);
2120}
2121
[email protected]420ae012009-04-24 05:16:322122// Checks to see if we should generate a keyword based on the OSDD, and if
2123// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2124void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2125 int32 page_id, const GURL& url,
2126 bool autodetected) {
2127 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2128 DCHECK(url.is_valid());
2129 if (!IsActiveEntry(page_id))
2130 return;
2131 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2132 if (!url_model)
2133 return;
2134 if (!url_model->loaded()) {
2135 url_model->Load();
2136 return;
2137 }
2138 if (!profile()->GetTemplateURLFetcher())
2139 return;
2140
2141 if (profile()->IsOffTheRecord())
2142 return;
2143
2144 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2145 DCHECK(entry);
2146
2147 const NavigationEntry* base_entry = entry;
2148 if (IsFormSubmit(base_entry)) {
2149 // If the current page is a form submit, find the last page that was not
2150 // a form submit and use its url to generate the keyword from.
2151 int index = controller_.last_committed_entry_index() - 1;
2152 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2153 index--;
2154 if (index >= 0)
2155 base_entry = controller_.GetEntryAtIndex(index);
2156 else
2157 base_entry = NULL;
2158 }
2159
2160 // We want to use the user typed URL if available since that represents what
2161 // the user typed to get here, and fall back on the regular URL if not.
2162 if (!base_entry)
2163 return;
2164 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2165 base_entry->user_typed_url() : base_entry->url();
2166 if (!keyword_url.is_valid())
2167 return;
2168 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2169 autodetected);
2170 if (keyword.empty())
2171 return;
2172 const TemplateURL* template_url =
2173 url_model->GetTemplateURLForKeyword(keyword);
2174 if (template_url && (!template_url->safe_for_autoreplace() ||
2175 template_url->originating_url() == url)) {
2176 // Either there is a user created TemplateURL for this keyword, or the
2177 // keyword has the same OSDD url and we've parsed it.
2178 return;
2179 }
2180
2181 // Download the OpenSearch description document. If this is successful a
2182 // new keyword will be created when done.
[email protected]420ae012009-04-24 05:16:322183 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2184 keyword,
2185 url,
2186 base_entry->favicon().url(),
[email protected]d0cc9fb52009-06-23 02:26:162187 this,
[email protected]420ae012009-04-24 05:16:322188 autodetected);
2189}
2190
[email protected]420ae012009-04-24 05:16:322191GURL TabContents::GetAlternateErrorPageURL() const {
2192 GURL url;
2193 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2194 if (profile()->IsOffTheRecord())
2195 return url;
2196
2197 PrefService* prefs = profile()->GetPrefs();
2198 DCHECK(prefs);
2199 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2200 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2201 url = google_util::AppendGoogleTLDParam(url);
2202 }
2203 return url;
2204}
2205
2206WebPreferences TabContents::GetWebkitPrefs() {
2207 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
[email protected]7ccddb8c2009-08-04 17:36:552208 bool is_dom_ui = false;
2209 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, is_dom_ui);
[email protected]420ae012009-04-24 05:16:322210}
2211
[email protected]420ae012009-04-24 05:16:322212void TabContents::OnJSOutOfMemory() {
2213 AddInfoBar(new SimpleAlertInfoBarDelegate(
2214 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2215}
2216
[email protected]420ae012009-04-24 05:16:322217void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2218 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342219 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322220 // delivered to a pending RenderViewHost. We must first run the onunload
2221 // handler of the old RenderViewHost before we can allow it to proceed.
2222 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2223 new_request_id);
2224}
2225
2226bool TabContents::CanBlur() const {
2227 return delegate() ? delegate()->CanBlur() : true;
2228}
2229
2230gfx::Rect TabContents::GetRootWindowResizerRect() const {
2231 if (delegate())
2232 return delegate()->GetRootWindowResizerRect();
2233 return gfx::Rect();
2234}
2235
2236void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2237 bool is_during_unload) {
2238 if (is_during_unload) {
2239 // Hang occurred while firing the beforeunload/unload handler.
2240 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112241 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322242
2243 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2244 return;
2245
2246 // If the tab hangs in the beforeunload/unload handler there's really
2247 // nothing we can do to recover. Pretend the unload listeners have
2248 // all fired and close the tab. If the hang is in the beforeunload handler
2249 // then the user will not have the option of cancelling the close.
2250 Close(rvh);
2251 return;
2252 }
2253
2254 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]d82ed61e2009-06-16 02:46:222255 HungRendererDialog::ShowForTabContents(this);
[email protected]420ae012009-04-24 05:16:322256}
2257
2258void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]d82ed61e2009-06-16 02:46:222259 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:322260}
2261
2262void TabContents::LoadStateChanged(const GURL& url,
2263 net::LoadState load_state) {
2264 load_state_ = load_state;
[email protected]d686e812009-06-03 19:10:292265 std::wstring languages =
2266 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2267 load_state_host_.clear();
2268 std::string host = url.host();
2269 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322270 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2271 SetNotWaitingForResponse();
2272 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502273 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322274}
2275
[email protected]1ee614862009-07-06 20:29:182276bool TabContents::IsExternalTabContainer() const {
2277 if (!delegate())
2278 return false;
2279
2280 return delegate()->IsExternalTabContainer();
2281}
2282
[email protected]1ee614862009-07-06 20:29:182283void TabContents::DidInsertCSS() {
2284 // This RVHDelegate function is used for extensions and not us.
[email protected]420ae012009-04-24 05:16:322285}
2286
2287void TabContents::FileSelected(const FilePath& path,
2288 int index, void* params) {
2289 render_view_host()->FileSelected(path);
2290}
2291
2292void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2293 void* params) {
2294 render_view_host()->MultiFilesSelected(files);
2295}
2296
2297void TabContents::FileSelectionCanceled(void* params) {
2298 // If the user cancels choosing a file to upload we pass back an
2299 // empty vector.
2300 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2301}
2302
2303void TabContents::BeforeUnloadFiredFromRenderManager(
2304 bool proceed,
2305 bool* proceed_to_fire_unload) {
2306 if (delegate())
2307 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2308}
2309
2310void TabContents::UpdateRenderViewSizeForRenderManager() {
2311 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2312 view_->SizeContents(view_->GetContainerSize());
2313}
2314
2315DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
[email protected]d82ed61e2009-06-16 02:46:222316 return DOMUIFactory::CreateDOMUIForURL(this, url);
[email protected]420ae012009-04-24 05:16:322317}
2318
2319NavigationEntry*
2320TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2321 return controller_.GetLastCommittedEntry();
2322}
2323
2324bool TabContents::CreateRenderViewForRenderManager(
2325 RenderViewHost* render_view_host) {
[email protected]811bfe32009-07-01 08:46:252326 // If the pending navigation is to a DOMUI, tell the RenderView about any
2327 // bindings it will need enabled.
[email protected]420ae012009-04-24 05:16:322328 if (render_manager_.pending_dom_ui())
[email protected]811bfe32009-07-01 08:46:252329 render_view_host->AllowBindings(
2330 render_manager_.pending_dom_ui()->bindings());
[email protected]1adff062009-06-02 18:39:552331
[email protected]420ae012009-04-24 05:16:322332 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2333 if (!render_view_host->CreateRenderView())
2334 return false;
2335
2336 // Now that the RenderView has been created, we need to tell it its size.
2337 rwh_view->SetSize(view_->GetContainerSize());
2338
2339 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2340 render_view_host);
2341 return true;
2342}
2343
2344void TabContents::Observe(NotificationType type,
2345 const NotificationSource& source,
2346 const NotificationDetails& details) {
2347 switch (type.value) {
2348 case NotificationType::BOOKMARK_MODEL_LOADED:
2349 // BookmarkModel finished loading, fall through to update starred state.
2350 case NotificationType::URLS_STARRED: {
2351 // Somewhere, a URL has been starred.
2352 // Ignore notifications for profiles other than our current one.
2353 Profile* source_profile = Source<Profile>(source).ptr();
2354 if (!source_profile || !source_profile->IsSameProfile(profile()))
2355 return;
2356
2357 UpdateStarredStateForCurrentURL();
2358 break;
2359 }
2360 case NotificationType::PREF_CHANGED: {
2361 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2362 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2363 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2364 UpdateAlternateErrorPageURL();
2365 } else if (*pref_name_in == prefs::kDefaultCharset ||
2366 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2367 ) {
2368 UpdateWebPreferences();
2369 } else {
2370 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2371 }
2372 break;
2373 }
2374 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2375 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2376 break;
2377
2378 case NotificationType::NAV_ENTRY_COMMITTED: {
2379 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2380
2381 NavigationController::LoadCommittedDetails& committed_details =
2382 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2383 ExpireInfoBars(committed_details);
2384 break;
2385 }
2386
2387 default:
2388 NOTREACHED();
2389 }
2390}