blob: f9efc7ce1f34efecdd0838410f877c986e15b7e6 [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]ea0e80892009-08-22 00:36:0531#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]c8865482009-07-23 20:40:1032#include "chrome/browser/omnibox_search_hint.h"
[email protected]fdd61c62009-04-22 19:22:5733#include "chrome/browser/password_manager/password_manager.h"
34#include "chrome/browser/plugin_installer.h"
[email protected]ce560f82009-06-03 09:39:4435#include "chrome/browser/profile.h"
[email protected]96d185d2009-04-24 03:28:5436#include "chrome/browser/renderer_host/render_widget_host_view.h"
[email protected]fd694982009-07-03 17:32:3737#include "chrome/browser/renderer_host/resource_request_details.h"
[email protected]96d185d2009-04-24 03:28:5438#include "chrome/browser/renderer_host/web_cache_manager.h"
[email protected]bd1ad682009-05-15 22:19:1739#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]7e383692009-06-12 19:14:5440#include "chrome/browser/tab_contents/interstitial_page.h"
[email protected]f3ec7742009-01-15 00:59:1641#include "chrome/browser/tab_contents/navigation_entry.h"
[email protected]de34a962009-06-26 23:22:4342#include "chrome/browser/tab_contents/provisional_load_details.h"
[email protected]f3ec7742009-01-15 00:59:1643#include "chrome/browser/tab_contents/tab_contents_delegate.h"
[email protected]fdd61c62009-04-22 19:22:5744#include "chrome/browser/tab_contents/tab_contents_view.h"
[email protected]58dca552009-06-17 00:35:0245#include "chrome/browser/tab_contents/thumbnail_generator.h"
[email protected]449478302009-06-09 20:04:2846#include "chrome/browser/thumbnail_store.h"
[email protected]420ae012009-04-24 05:16:3247#include "chrome/browser/search_engines/template_url_fetcher.h"
48#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2749#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5650#include "chrome/common/notification_service.h"
[email protected]ce5c4502009-05-06 16:46:1151#include "chrome/common/page_action.h"
initial.commit09911bf2008-07-26 23:55:2952#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0353#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3254#include "chrome/common/render_messages.h"
[email protected]1ee614862009-07-06 20:29:1855#include "chrome/common/renderer_preferences.h"
[email protected]96d185d2009-04-24 03:28:5456#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2657#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3258#include "grit/locale_settings.h"
59#include "net/base/mime_util.h"
60#include "net/base/net_errors.h"
[email protected]d686e812009-06-03 19:10:2961#include "net/base/net_util.h"
[email protected]420ae012009-04-24 05:16:3262#include "net/base/registry_controlled_domain.h"
[email protected]1ee614862009-07-06 20:29:1863#include "webkit/glue/password_form.h"
64#include "webkit/glue/webpreferences.h"
[email protected]3e45ba92009-02-20 21:09:0065
[email protected]304f8792009-08-19 21:28:0966#if defined(OS_CHROMEOS)
67// For GdkScreen
68#include <gdk/gdk.h>
[email protected]0ba5c5e2009-08-20 16:47:1369#endif // defined(OS_CHROMEOS)
70
71#if defined(OS_LINUX)
72#include "chrome/browser/gtk/create_application_shortcuts_dialog_gtk.h"
73#endif // defined(OS_LINUX)
74
[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
[email protected]304f8792009-08-19 21:28:09122#if defined(OS_CHROMEOS)
123// If a popup window is bigger than this fraction of the screen on chrome os,
124// turn it into a tab
125const float kMaxWidthFactor = 0.5;
126const float kMaxHeightFactor = 0.6;
127#endif
128
[email protected]420ae012009-04-24 05:16:32129// If another javascript message box is displayed within
130// kJavascriptMessageExpectedDelay of a previous javascript message box being
131// dismissed, display an option to suppress future message boxes from this
132// contents.
133const int kJavascriptMessageExpectedDelay = 1000;
134
[email protected]2bd6ca1c2009-08-27 16:42:20135const char kLinkDoctorBaseURL[] =
136 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
137
[email protected]420ae012009-04-24 05:16:32138// The list of prefs we want to observe.
139const wchar_t* kPrefsToObserve[] = {
140 prefs::kAlternateErrorPagesEnabled,
141 prefs::kWebKitJavaEnabled,
142 prefs::kWebKitJavascriptEnabled,
143 prefs::kWebKitLoadsImagesAutomatically,
144 prefs::kWebKitPluginsEnabled,
145 prefs::kWebKitUsesUniversalDetector,
146 prefs::kWebKitSerifFontFamily,
147 prefs::kWebKitSansSerifFontFamily,
148 prefs::kWebKitFixedFontFamily,
149 prefs::kWebKitDefaultFontSize,
150 prefs::kWebKitDefaultFixedFontSize,
151 prefs::kDefaultCharset
152 // kWebKitStandardFontIsSerif needs to be added
153 // if we let users pick which font to use, serif or sans-serif when
154 // no font is specified or a CSS generic family (serif or sans-serif)
155 // is not specified.
156};
157
158const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
159
[email protected]420ae012009-04-24 05:16:32160// Returns true if the entry's transition type is FORM_SUBMIT.
161bool IsFormSubmit(const NavigationEntry* entry) {
162 return (PageTransition::StripQualifier(entry->transition_type()) ==
163 PageTransition::FORM_SUBMIT);
164}
165
166#if defined(OS_WIN)
167
168BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
169 // Note: erase is required to properly paint some widgets borders. This can
170 // be seen with textfields.
171 InvalidateRect(hwnd, NULL, TRUE);
172 return TRUE;
173}
174#endif
175
[email protected]056de2d2009-06-26 16:41:34176void MakeNavigateParams(const NavigationEntry& entry, bool reload,
177 ViewMsg_Navigate_Params* params) {
178 params->page_id = entry.page_id();
179 params->url = entry.url();
180 params->referrer = entry.referrer();
181 params->transition = entry.transition_type();
182 params->state = entry.content_state();
183 params->reload = reload;
184 params->request_time = base::Time::Now();
185}
186
[email protected]420ae012009-04-24 05:16:32187} // namespace
188
189// -----------------------------------------------------------------------------
190
[email protected]fdd61c62009-04-22 19:22:57191// static
192int TabContents::find_request_id_counter_ = -1;
193
[email protected]420ae012009-04-24 05:16:32194class TabContents::GearsCreateShortcutCallbackFunctor {
195 public:
196 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
197 : contents_(contents) {}
198
199 void Run(const GearsShortcutData2& shortcut_data, bool success) {
200 if (contents_)
201 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
202 delete this;
203 }
204 void Cancel() {
205 contents_ = NULL;
206 }
207
208 private:
209 TabContents* contents_;
210};
211
[email protected]420ae012009-04-24 05:16:32212TabContents::TabContents(Profile* profile,
213 SiteInstance* site_instance,
214 int routing_id,
215 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42216 : delegate_(NULL),
[email protected]66ba4932009-06-04 19:22:13217 ALLOW_THIS_IN_INITIALIZER_LIST(controller_(this, profile)),
218 ALLOW_THIS_IN_INITIALIZER_LIST(view_(
[email protected]d82ed61e2009-06-16 02:46:22219 TabContentsView::Create(this))),
220 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(this, this)),
[email protected]fdd61c62009-04-22 19:22:57221 property_bag_(),
222 registrar_(),
[email protected]d82ed61e2009-06-16 02:46:22223 ALLOW_THIS_IN_INITIALIZER_LIST(printing_(*this)),
[email protected]fdd61c62009-04-22 19:22:57224 save_package_(),
225 cancelable_consumer_(),
226 autofill_manager_(),
227 password_manager_(),
228 plugin_installer_(),
[email protected]d82ed61e2009-06-16 02:46:22229 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(this)),
[email protected]fdd61c62009-04-22 19:22:57230 select_file_dialog_(),
231 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34232 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29233 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34234 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34235 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57236 current_load_start_(),
237 load_state_(net::LOAD_STATE_IDLE),
238 load_state_host_(),
239 received_page_title_(false),
240 is_starred_(false),
241 contents_mime_type_(),
242 encoding_(),
[email protected]332af7732009-03-11 13:21:35243 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57244 infobar_delegates_(),
[email protected]fdd61c62009-04-22 19:22:57245 find_ui_active_(false),
246 find_op_aborted_(false),
247 current_find_request_id_(find_request_id_counter_++),
248 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12249 last_search_case_sensitive_(false),
250 last_search_prepopulate_text_(NULL),
251 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57252 capturing_contents_(false),
253 is_being_destroyed_(false),
254 notify_disconnection_(false),
255 history_requests_(),
256#if defined(OS_WIN)
257 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
258#endif
259 last_javascript_message_dismissal_(),
260 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32261 pending_install_.page_id = 0;
262 pending_install_.callback_functor = NULL;
263
[email protected]16779842009-07-08 23:45:29264#if defined(OS_CHROMEOS)
[email protected]58dca552009-06-17 00:35:02265 // Make sure the thumbnailer is started before starting the render manager.
266 // The thumbnailer will want to listen for RVH creations, one of which will
267 // happen in RVHManager::Init.
268 ThumbnailGenerator* generator = g_browser_process->GetThumbnailGenerator();
269 if (generator)
270 generator->StartThumbnailing();
271#endif
272
[email protected]420ae012009-04-24 05:16:32273 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
274
275 view_->CreateView();
276
277 // Register for notifications about all interested prefs change.
278 PrefService* prefs = profile->GetPrefs();
279 if (prefs) {
280 for (int i = 0; i < kPrefsToObserveLength; ++i)
281 prefs->AddPrefObserver(kPrefsToObserve[i], this);
282 }
283
284 // Register for notifications about URL starredness changing on any profile.
285 registrar_.Add(this, NotificationType::URLS_STARRED,
286 NotificationService::AllSources());
287 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
288 NotificationService::AllSources());
289 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
290 NotificationService::AllSources());
291
292 // Keep a global copy of the previous search string (if any).
293 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12294 last_search_prepopulate_text_ = &global_last_search;
[email protected]840b1512009-07-21 16:53:46295
[email protected]c8865482009-07-23 20:40:10296 // Set-up the showing of the omnibox search infobar if applicable.
297 if (OmniboxSearchHint::IsEnabled(profile))
298 omnibox_search_hint_.reset(new OmniboxSearchHint(this));
299
[email protected]840b1512009-07-21 16:53:46300 view_->InitRendererPrefs(&renderer_preferences_);
[email protected]332af7732009-03-11 13:21:35301}
initial.commit09911bf2008-07-26 23:55:29302
303TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32304 is_being_destroyed_ = true;
305
306 // We don't want any notifications while we're runnign our destructor.
307 registrar_.RemoveAll();
308
309 // Unregister the notifications of all observed prefs change.
310 PrefService* prefs = profile()->GetPrefs();
311 if (prefs) {
312 for (int i = 0; i < kPrefsToObserveLength; ++i)
313 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
314 }
315
316 // Clean up subwindows like plugins and the find in page bar.
317 view_->OnContentsDestroy();
318
319 NotifyDisconnected();
[email protected]d82ed61e2009-06-16 02:46:22320 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:32321
322 if (pending_install_.callback_functor)
323 pending_install_.callback_functor->Cancel();
324
325 // First cleanly close all child windows.
326 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
327 // some of these to close. CloseWindows is async, so it might get called
328 // twice before it runs.
329 int size = static_cast<int>(child_windows_.size());
330 for (int i = size - 1; i >= 0; --i) {
331 ConstrainedWindow* window = child_windows_[i];
332 if (window)
333 window->CloseConstrainedWindow();
334 }
335
[email protected]66ba4932009-06-04 19:22:13336 if (blocked_popups_)
337 blocked_popups_->Destroy();
338
[email protected]420ae012009-04-24 05:16:32339 // Notify any observer that have a reference on this tab contents.
340 NotificationService::current()->Notify(
341 NotificationType::TAB_CONTENTS_DESTROYED,
342 Source<TabContents>(this),
343 NotificationService::NoDetails());
344
[email protected]1e5e74f2009-05-27 20:55:12345 // Notify any lasting InfobarDelegates that have not yet been removed that
346 // whatever infobar they were handling in this TabContents has closed,
347 // because the TabContents is going away entirely.
348 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
349 // notification may trigger infobars calls that access their delegate. (and
350 // some implementations of InfoBarDelegate do delete themselves on
351 // InfoBarClosed()).
352 for (int i = 0; i < infobar_delegate_count(); ++i) {
353 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
354 delegate->InfoBarClosed();
355 }
356 infobar_delegates_.clear();
357
[email protected]420ae012009-04-24 05:16:32358 // TODO(brettw) this should be moved to the view.
359#if defined(OS_WIN)
360 // If we still have a window handle, destroy it. GetNativeView can return
361 // NULL if this contents was part of a window that closed.
362 if (GetNativeView())
363 ::DestroyWindow(GetNativeView());
364#endif
initial.commit09911bf2008-07-26 23:55:29365}
366
[email protected]d5f942ba2008-09-26 19:30:34367// static
368void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32369 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
370
371 WebPreferences pref_defaults;
372 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
373 pref_defaults.javascript_enabled);
374 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
375 pref_defaults.web_security_enabled);
376 prefs->RegisterBooleanPref(
377 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
378 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
379 pref_defaults.loads_images_automatically);
380 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
381 pref_defaults.plugins_enabled);
382 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
383 pref_defaults.dom_paste_enabled);
384 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
385 pref_defaults.shrinks_standalone_images_to_fit);
[email protected]0df30122009-06-03 12:13:08386 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
387 pref_defaults.inspector_settings);
[email protected]420ae012009-04-24 05:16:32388 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
389 pref_defaults.text_areas_are_resizable);
390 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
391 pref_defaults.java_enabled);
392
393 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
394 IDS_ACCEPT_LANGUAGES);
395 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
396 IDS_DEFAULT_ENCODING);
397 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
398 IDS_STANDARD_FONT_IS_SERIF);
399 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
400 IDS_FIXED_FONT_FAMILY);
401 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
402 IDS_SERIF_FONT_FAMILY);
403 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
404 IDS_SANS_SERIF_FONT_FAMILY);
405 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
406 IDS_CURSIVE_FONT_FAMILY);
407 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
408 IDS_FANTASY_FONT_FAMILY);
409 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
410 IDS_DEFAULT_FONT_SIZE);
411 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
412 IDS_DEFAULT_FIXED_FONT_SIZE);
413 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
414 IDS_MINIMUM_FONT_SIZE);
415 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
416 IDS_MINIMUM_LOGICAL_FONT_SIZE);
417 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
418 IDS_USES_UNIVERSAL_DETECTOR);
419 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
420 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29421}
422
[email protected]13367f72009-07-08 16:39:02423// Returns true if contains content rendered by an extension.
424bool TabContents::HostsExtension() const {
425 return GetURL().SchemeIs(chrome::kExtensionScheme);
[email protected]d5f942ba2008-09-26 19:30:34426}
427
[email protected]6e95706d2009-04-23 22:55:01428PasswordManager* TabContents::GetPasswordManager() {
429 if (password_manager_.get() == NULL)
430 password_manager_.reset(new PasswordManager(this));
431 return password_manager_.get();
432}
433
434PluginInstaller* TabContents::GetPluginInstaller() {
435 if (plugin_installer_.get() == NULL)
436 plugin_installer_.reset(new PluginInstaller(this));
437 return plugin_installer_.get();
438}
439
[email protected]d5f942ba2008-09-26 19:30:34440const GURL& TabContents::GetURL() const {
441 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57442 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]ebe89e062009-08-13 23:16:54443 return entry ? entry->virtual_url() : GURL::EmptyGURL();
[email protected]d5f942ba2008-09-26 19:30:34444}
445
[email protected]96d185d2009-04-24 03:28:54446const string16& TabContents::GetTitle() const {
[email protected]4c6092c5b2009-06-06 00:23:55447 // Transient entries take precedence. They are used for interstitial pages
448 // that are shown on top of existing pages.
449 NavigationEntry* entry = controller_.GetTransientEntry();
450 if (entry)
451 return entry->GetTitleForDisplay(&controller_);
452
[email protected]96d185d2009-04-24 03:28:54453 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
454 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
455 if (our_dom_ui) {
456 // Don't override the title in view source mode.
[email protected]4c6092c5b2009-06-06 00:23:55457 entry = controller_.GetActiveEntry();
[email protected]96d185d2009-04-24 03:28:54458 if (!(entry && entry->IsViewSourceMode())) {
459 // Give the DOM UI the chance to override our title.
460 const string16& title = our_dom_ui->overridden_title();
461 if (!title.empty())
462 return title;
463 }
464 }
465
466 // We use the title for the last committed entry rather than a pending
467 // navigation entry. For example, when the user types in a URL, we want to
468 // keep the old page's title until the new load has committed and we get a new
469 // title.
[email protected]96d185d2009-04-24 03:28:54470 entry = controller_.GetLastCommittedEntry();
471 if (entry)
472 return entry->GetTitleForDisplay(&controller_);
473 else if (controller_.LoadingURLLazily())
474 return controller_.GetLazyTitle();
475 return EmptyString16();
476}
477
[email protected]d5f942ba2008-09-26 19:30:34478int32 TabContents::GetMaxPageID() {
479 if (GetSiteInstance())
480 return GetSiteInstance()->max_page_id();
481 else
482 return max_page_id_;
483}
484
485void TabContents::UpdateMaxPageID(int32 page_id) {
486 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34487 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34488 // testing.
489 if (GetSiteInstance())
490 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34491 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34492}
493
[email protected]96d185d2009-04-24 03:28:54494SiteInstance* TabContents::GetSiteInstance() const {
495 return render_manager_.current_host()->site_instance();
496}
497
[email protected]d5f942ba2008-09-26 19:30:34498const std::wstring TabContents::GetDefaultTitle() const {
499 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
500}
501
[email protected]96d185d2009-04-24 03:28:54502bool TabContents::ShouldDisplayURL() {
503 // Don't hide the url in view source mode.
504 NavigationEntry* entry = controller_.GetActiveEntry();
505 if (entry && entry->IsViewSourceMode())
506 return true;
[email protected]83e3895b2009-06-11 00:07:16507
[email protected]96d185d2009-04-24 03:28:54508 DOMUI* dom_ui = GetDOMUIForCurrentState();
509 if (dom_ui)
510 return !dom_ui->should_hide_url();
511 return true;
512}
513
[email protected]d5f942ba2008-09-26 19:30:34514SkBitmap TabContents::GetFavIcon() const {
515 // Like GetTitle(), we also want to use the favicon for the last committed
516 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57517 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47518 if (entry)
519 return entry->favicon().bitmap();
520
[email protected]ce3fa3c2009-04-20 19:55:57521 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34522 if (entry)
523 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57524 else if (controller_.LoadingURLLazily())
525 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34526 return SkBitmap();
527}
528
[email protected]96d185d2009-04-24 03:28:54529bool TabContents::ShouldDisplayFavIcon() {
530 // Always display a throbber during pending loads.
531 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
532 return true;
533
534 DOMUI* dom_ui = GetDOMUIForCurrentState();
535 if (dom_ui)
536 return !dom_ui->hide_favicon();
537 return true;
538}
539
[email protected]96d185d2009-04-24 03:28:54540std::wstring TabContents::GetStatusText() const {
541 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
542 return std::wstring();
543
544 switch (load_state_) {
545 case net::LOAD_STATE_WAITING_FOR_CACHE:
546 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
547 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
548 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
549 case net::LOAD_STATE_RESOLVING_HOST:
550 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
551 case net::LOAD_STATE_CONNECTING:
552 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
553 case net::LOAD_STATE_SENDING_REQUEST:
554 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
555 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
556 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
557 load_state_host_);
558 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
559 case net::LOAD_STATE_IDLE:
560 case net::LOAD_STATE_READING_RESPONSE:
561 break;
562 }
563
564 return std::wstring();
565}
566
[email protected]d5f942ba2008-09-26 19:30:34567void TabContents::SetIsCrashed(bool state) {
568 if (state == is_crashed_)
569 return;
570
571 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50572 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34573}
574
[email protected]f9b1a7b2009-06-22 17:26:38575void TabContents::SetPageActionEnabled(const PageAction* page_action,
[email protected]d7eaf572009-07-01 21:57:00576 bool enable,
577 const std::string& title,
578 int icon_id) {
[email protected]ce5c4502009-05-06 16:46:11579 DCHECK(page_action);
580
[email protected]d7eaf572009-07-01 21:57:00581 if (!enable &&
582 enabled_page_actions_.end() == enabled_page_actions_.find(page_action)) {
583 return; // Don't need to disable twice.
584 }
[email protected]ce5c4502009-05-06 16:46:11585
[email protected]d7eaf572009-07-01 21:57:00586 if (enable) {
587 enabled_page_actions_[page_action].reset(
588 new PageActionState(title, icon_id));
589 } else {
[email protected]f9b1a7b2009-06-22 17:26:38590 enabled_page_actions_.erase(page_action);
[email protected]d7eaf572009-07-01 21:57:00591 }
[email protected]ce5c4502009-05-06 16:46:11592}
593
[email protected]d7eaf572009-07-01 21:57:00594const PageActionState* TabContents::GetPageActionState(
595 const PageAction* page_action) {
596 if (enabled_page_actions_.end() == enabled_page_actions_.find(page_action))
597 return NULL;
[email protected]ce5c4502009-05-06 16:46:11598
[email protected]d7eaf572009-07-01 21:57:00599 return enabled_page_actions_[page_action].get();
600}
[email protected]ce5c4502009-05-06 16:46:11601
[email protected]d5f942ba2008-09-26 19:30:34602void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
603 if (delegate_)
604 delegate_->NavigationStateChanged(this, changed_flags);
605}
606
[email protected]96d185d2009-04-24 03:28:54607void TabContents::DidBecomeSelected() {
608 controller_.SetActive(true);
609
[email protected]789e9152009-08-04 21:59:43610 if (render_widget_host_view()) {
[email protected]96d185d2009-04-24 03:28:54611 render_widget_host_view()->DidBecomeSelected();
[email protected]789e9152009-08-04 21:59:43612#if defined(OS_MACOSX)
613 render_widget_host_view()->SetActive(true);
614#endif
615 }
[email protected]96d185d2009-04-24 03:28:54616
617 // If pid() is -1, that means the RenderProcessHost still hasn't been
618 // initialized. It'll register with CacheManagerHost when it is.
619 if (process()->pid() != -1)
620 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
621}
622
623void TabContents::WasHidden() {
624 if (!capturing_contents()) {
625 // |render_view_host()| can be NULL if the user middle clicks a link to open
626 // a tab in then background, then closes the tab before selecting it. This
627 // is because closing the tab calls TabContents::Destroy(), which removes
628 // the |render_view_host()|; then when we actually destroy the window,
629 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
630 if (render_widget_host_view())
631 render_widget_host_view()->WasHidden();
[email protected]96d185d2009-04-24 03:28:54632 }
633
634 NotificationService::current()->Notify(
635 NotificationType::TAB_CONTENTS_HIDDEN,
636 Source<TabContents>(this),
637 NotificationService::NoDetails());
638}
639
[email protected]d5f942ba2008-09-26 19:30:34640void TabContents::Activate() {
641 if (delegate_)
642 delegate_->ActivateContents(this);
643}
644
[email protected]96d185d2009-04-24 03:28:54645void TabContents::ShowContents() {
646 if (render_widget_host_view())
647 render_widget_host_view()->DidBecomeSelected();
[email protected]96d185d2009-04-24 03:28:54648}
649
650void TabContents::HideContents() {
651 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
652 // our superclass HideContents(), because some callers want to be very picky
653 // about the order in which these get called. In addition to making the code
654 // here practically impossible to understand, this also means we end up
655 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34656 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54657 WasHidden();
658}
659
[email protected]c0588052008-10-27 23:01:50660void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34661 WindowOpenDisposition disposition,
662 PageTransition::Type transition) {
663 if (delegate_)
[email protected]c0588052008-10-27 23:01:50664 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34665}
666
667bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54668 const NavigationEntry& entry = *controller_.pending_entry();
669
670 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
671 if (!dest_render_view_host)
672 return false; // Unable to create the desired render view host.
673
674 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]d9f9b792009-06-24 13:17:12675 DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
[email protected]7e8e6b62009-05-08 11:28:32676 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41677 devtools_manager->OnNavigatingToPendingEntry(
678 render_view_host(),
679 dest_render_view_host,
680 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32681 }
[email protected]96d185d2009-04-24 03:28:54682
683 // Used for page load time metrics.
684 current_load_start_ = base::TimeTicks::Now();
685
686 // Navigate in the desired RenderViewHost.
[email protected]056de2d2009-06-26 16:41:34687 ViewMsg_Navigate_Params navigate_params;
688 MakeNavigateParams(entry, reload, &navigate_params);
689 dest_render_view_host->Navigate(navigate_params);
[email protected]96d185d2009-04-24 03:28:54690
691 if (entry.page_id() == -1) {
692 // HACK!! This code suppresses javascript: URLs from being added to
693 // session history, which is what we want to do for javascript: URLs that
694 // do not generate content. What we really need is a message from the
695 // renderer telling us that a new page was not created. The same message
696 // could be used for mailto: URLs and the like.
697 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
698 return false;
699 }
700
701 // Clear any provisional password saves - this stops password infobars
702 // showing up on pages the user navigates to while the right page is
703 // loading.
704 GetPasswordManager()->ClearProvisionalSave();
705
706 if (reload && !profile()->IsOffTheRecord()) {
707 HistoryService* history =
708 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
709 if (history)
710 history->SetFavIconOutOfDateForPage(entry.url());
711 }
712
[email protected]d5f942ba2008-09-26 19:30:34713 return true;
714}
715
[email protected]96d185d2009-04-24 03:28:54716void TabContents::Stop() {
717 render_manager_.Stop();
718 printing_.Stop();
719}
720
721void TabContents::Cut() {
722 render_view_host()->Cut();
723}
724
725void TabContents::Copy() {
726 render_view_host()->Copy();
727}
728
729void TabContents::Paste() {
730 render_view_host()->Paste();
731}
732
733void TabContents::DisassociateFromPopupCount() {
734 render_view_host()->DisassociateFromPopupCount();
735}
736
737TabContents* TabContents::Clone() {
738 // We create a new SiteInstance so that the new tab won't share processes
739 // with the old one. This can be changed in the future if we need it to share
740 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32741 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54742 SiteInstance::CreateSiteInstance(profile()),
743 MSG_ROUTING_NONE, NULL);
744 tc->controller().CopyStateFrom(controller_);
745 return tc;
746}
747
[email protected]420ae012009-04-24 05:16:32748void TabContents::CreateShortcut() {
749 NavigationEntry* entry = controller_.GetLastCommittedEntry();
750 if (!entry)
751 return;
752
[email protected]70b8d6b2009-08-20 16:56:24753#if defined(OS_LINUX) && !defined(TOOLKIT_VIEWS)
[email protected]0ba5c5e2009-08-20 16:47:13754 CreateApplicationShortcutsDialogGtk::Show(view()->GetTopLevelNativeWindow(),
755 GetURL(), GetTitle());
[email protected]b96aa932009-08-12 21:34:49756#else
[email protected]420ae012009-04-24 05:16:32757 // We only allow one pending install request. By resetting the page id we
758 // effectively cancel the pending install request.
759 pending_install_.page_id = entry->page_id();
760 pending_install_.icon = GetFavIcon();
761 pending_install_.title = UTF16ToWideHack(GetTitle());
762 pending_install_.url = GetURL();
763 if (pending_install_.callback_functor) {
764 pending_install_.callback_functor->Cancel();
765 pending_install_.callback_functor = NULL;
766 }
767 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
768 if (pending_install_.title.empty())
769 pending_install_.title = UTF8ToWide(GetURL().spec());
770
771 // Request the application info. When done OnDidGetApplicationInfo is invoked
772 // and we'll create the shortcut.
773 render_view_host()->GetApplicationInfo(pending_install_.page_id);
[email protected]b96aa932009-08-12 21:34:49774#endif
[email protected]420ae012009-04-24 05:16:32775}
776
[email protected]4d677202009-07-19 07:37:12777void TabContents::ShowPageInfo(const GURL& url,
778 const NavigationEntry::SSLStatus& ssl,
779 bool show_history) {
780 if (!delegate_)
781 return;
782
[email protected]bb678332009-07-21 00:15:50783 delegate_->ShowPageInfo(profile(), url, ssl, show_history);
[email protected]4d677202009-07-19 07:37:12784}
785
initial.commit09911bf2008-07-26 23:55:29786ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]e8382172009-06-19 22:16:28787 ConstrainedWindowDelegate* delegate) {
initial.commit09911bf2008-07-26 23:55:29788 ConstrainedWindow* window =
[email protected]e8382172009-06-19 22:16:28789 ConstrainedWindow::CreateConstrainedDialog(this, delegate);
initial.commit09911bf2008-07-26 23:55:29790 child_windows_.push_back(window);
791 return window;
792}
793
794void TabContents::AddNewContents(TabContents* new_contents,
795 WindowOpenDisposition disposition,
796 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22797 bool user_gesture,
798 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29799 if (!delegate_)
800 return;
801
[email protected]35f7d212009-04-29 21:19:27802 if ((disposition == NEW_POPUP) && !user_gesture &&
803 !CommandLine::ForCurrentProcess()->HasSwitch(
804 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22805 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31806 // the whitelist. The popup owner will handle checking this.
807 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
808 initial_pos,
809 creator_url.is_valid() ? creator_url.host() : std::string());
810 } else {
[email protected]304f8792009-08-19 21:28:09811#if defined(OS_CHROMEOS)
812 if (disposition == NEW_POPUP) {
813 // If the popup is bigger than a given factor of the screen, then
814 // turn it into a foreground tab (on chrome os only)
815 GdkScreen* screen = gdk_screen_get_default();
816 int max_width = gdk_screen_get_width(screen) * kMaxWidthFactor;
817 int max_height = gdk_screen_get_height(screen) * kMaxHeightFactor;
818 if (initial_pos.width() > max_width ||
819 initial_pos.height() > max_height) {
820 disposition = NEW_FOREGROUND_TAB;
821 }
822 }
823#endif
824
[email protected]0aa55312008-10-17 21:53:08825 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29826 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
827 user_gesture);
828 }
[email protected]b6c874582009-05-08 19:38:31829 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
initial.commit09911bf2008-07-26 23:55:29830}
831
initial.commit09911bf2008-07-26 23:55:29832void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25833 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22834 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29835}
836
[email protected]96d185d2009-04-24 03:28:54837void TabContents::PopupNotificationVisibilityChanged(bool visible) {
838 render_view_host()->PopupNotificationVisibilityChanged(visible);
839}
840
841gfx::NativeView TabContents::GetContentNativeView() {
842 return view_->GetContentNativeView();
843}
844
845gfx::NativeView TabContents::GetNativeView() const {
846 return view_->GetNativeView();
847}
848
849void TabContents::GetContainerBounds(gfx::Rect *out) const {
850 view_->GetContainerBounds(out);
851}
852
853void TabContents::Focus() {
854 view_->Focus();
855}
856
[email protected]90daadb42009-06-08 21:27:28857void TabContents::FocusThroughTabTraversal(bool reverse) {
[email protected]7e383692009-06-12 19:14:54858 if (showing_interstitial_page()) {
859 render_manager_.interstitial_page()->FocusThroughTabTraversal(reverse);
860 return;
861 }
[email protected]96d185d2009-04-24 03:28:54862 render_view_host()->SetInitialFocus(reverse);
863}
864
865bool TabContents::FocusLocationBarByDefault() {
866 DOMUI* dom_ui = GetDOMUIForCurrentState();
867 if (dom_ui)
868 return dom_ui->focus_location_bar_by_default();
[email protected]3e3f0eb2009-06-22 18:33:43869 NavigationEntry* entry = controller_.GetActiveEntry();
870 if (entry && entry->url() == GURL("about:blank"))
871 return true;
[email protected]96d185d2009-04-24 03:28:54872 return false;
873}
874
[email protected]616ed5a2008-11-21 22:27:24875void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
876 // Look through the existing InfoBarDelegates we have for a match. If we've
877 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05878 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24879 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
880 return;
881 }
882
883 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56884 NotificationService::current()->Notify(
885 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
886 Source<TabContents>(this),
887 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24888
889 // Add ourselves as an observer for navigations the first time a delegate is
890 // added. We use this notification to expire InfoBars that need to expire on
891 // page transitions.
892 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56893 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57894 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24895 }
896}
897
898void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
899 std::vector<InfoBarDelegate*>::iterator it =
900 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
901 if (it != infobar_delegates_.end()) {
902 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56903 NotificationService::current()->Notify(
904 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
905 Source<TabContents>(this),
906 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05907 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24908
[email protected]6a02963e2009-01-06 16:58:03909 // Remove ourselves as an observer if we are tracking no more InfoBars.
910 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56911 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57912 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03913 }
[email protected]616ed5a2008-11-21 22:27:24914 }
915}
[email protected]3edd9522009-03-04 22:19:41916
[email protected]f81821c2009-08-07 01:29:47917void TabContents::ReplaceInfoBar(InfoBarDelegate* old_delegate,
918 InfoBarDelegate* new_delegate) {
919 std::vector<InfoBarDelegate*>::iterator it =
920 find(infobar_delegates_.begin(), infobar_delegates_.end(), old_delegate);
921 DCHECK(it != infobar_delegates_.end());
922
923 // Notify the container about the change of plans.
924 scoped_ptr<std::pair<InfoBarDelegate*, InfoBarDelegate*> > details(
925 new std::pair<InfoBarDelegate*, InfoBarDelegate*>(
926 old_delegate, new_delegate));
927 NotificationService::current()->Notify(
928 NotificationType::TAB_CONTENTS_INFOBAR_REPLACED,
929 Source<TabContents>(this),
930 Details<std::pair<InfoBarDelegate*, InfoBarDelegate*> >(details.get()));
931
932 // Remove the old one.
933 infobar_delegates_.erase(it);
934
935 // Add the new one.
936 infobar_delegates_.push_back(new_delegate);
937}
938
[email protected]96d185d2009-04-24 03:28:54939bool TabContents::IsBookmarkBarAlwaysVisible() {
940 // See GetDOMUIForCurrentState() comment for more info. This case is very
941 // similar, but for non-first loads, we want to use the committed entry. This
942 // is so the bookmarks bar disappears at the same time the page does.
943 if (controller_.GetLastCommittedEntry()) {
944 // Not the first load, always use the committed DOM UI.
945 if (render_manager_.dom_ui())
946 return render_manager_.dom_ui()->force_bookmark_bar_visible();
947 return false; // Default.
948 }
949
950 // When it's the first load, we know either the pending one or the committed
951 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
952 // of them will be valid, so we can just check both.
953 if (render_manager_.pending_dom_ui())
954 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
955 if (render_manager_.dom_ui())
956 return render_manager_.dom_ui()->force_bookmark_bar_visible();
957 return false; // Default.
958}
959
[email protected]3edd9522009-03-04 22:19:41960void TabContents::ToolbarSizeChanged(bool is_animating) {
961 TabContentsDelegate* d = delegate();
962 if (d)
963 d->ToolbarSizeChanged(this, is_animating);
964}
[email protected]616ed5a2008-11-21 22:27:24965
[email protected]d5f942ba2008-09-26 19:30:34966void TabContents::OnStartDownload(DownloadItem* download) {
967 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34968
969 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31970 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34971
[email protected]59560e0b2009-06-04 03:30:22972 if (tab_contents && tab_contents->delegate())
973 tab_contents->delegate()->OnStartDownload(download);
[email protected]3edd9522009-03-04 22:19:41974}
[email protected]3edd9522009-03-04 22:19:41975
[email protected]d5f942ba2008-09-26 19:30:34976void TabContents::WillClose(ConstrainedWindow* window) {
977 ConstrainedWindowList::iterator it =
978 find(child_windows_.begin(), child_windows_.end(), window);
979 if (it != child_windows_.end())
980 child_windows_.erase(it);
[email protected]66ba4932009-06-04 19:22:13981}
[email protected]d5f942ba2008-09-26 19:30:34982
[email protected]66ba4932009-06-04 19:22:13983void TabContents::WillCloseBlockedPopupContainer(
984 BlockedPopupContainer* container) {
985 DCHECK(blocked_popups_ == container);
986 blocked_popups_ = NULL;
[email protected]d5f942ba2008-09-26 19:30:34987}
988
[email protected]d5f942ba2008-09-26 19:30:34989void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:35990#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:06991 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:35992#endif
[email protected]d5f942ba2008-09-26 19:30:34993}
994
[email protected]e491f1c2009-05-22 20:28:12995void TabContents::StartFinding(string16 find_text,
996 bool forward_direction,
997 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:01998 // If find_text is empty, it means FindNext was pressed with a keyboard
999 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:121000 if (find_text.empty() && find_text_.empty()) {
1001 if (last_search_prepopulate_text_->empty())
1002 return;
1003 // Try whatever we searched for last in any tab.
1004 find_text = *last_search_prepopulate_text_;
1005 }
[email protected]6e95706d2009-04-23 22:55:011006
1007 // This is a FindNext operation if we are searching for the same text again,
1008 // or if the passed in search text is empty (FindNext keyboard shortcut). The
1009 // exception to this is if the Find was aborted (then we don't want FindNext
1010 // because the highlighting has been cleared and we need it to reappear). We
1011 // therefore treat FindNext after an aborted Find operation as a full fledged
1012 // Find.
1013 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:121014 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:011015 !find_op_aborted_;
1016 if (!find_next)
1017 current_find_request_id_ = find_request_id_counter_++;
1018
1019 if (!find_text.empty())
1020 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:121021 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:011022
1023 find_op_aborted_ = false;
1024
1025 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:121026 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:011027
1028 render_view_host()->StartFinding(current_find_request_id_,
1029 find_text_,
1030 forward_direction,
[email protected]e491f1c2009-05-22 20:28:121031 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:011032 find_next);
1033}
1034
1035void TabContents::StopFinding(bool clear_selection) {
[email protected]2d2dffc2009-06-09 21:41:001036 // When |clear_selection| is true, it means the find string has been cleared
1037 // by the user, but the UI has not been dismissed.
1038 if (!clear_selection)
1039 find_ui_active_ = false;
[email protected]6e95706d2009-04-23 22:55:011040 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:121041 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:011042 render_view_host()->StopFinding(clear_selection);
1043}
1044
[email protected]5c4266922009-07-10 16:41:271045void TabContents::GetPageLanguage() {
1046 render_view_host()->GetPageLanguage();
1047}
1048
[email protected]420ae012009-04-24 05:16:321049void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
1050 bool success,
1051 const std::wstring& prompt) {
1052 last_javascript_message_dismissal_ = base::TimeTicks::Now();
1053 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
1054}
1055
[email protected]571e31152009-05-15 19:34:021056void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
1057 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
1058}
1059
[email protected]420ae012009-04-24 05:16:321060void TabContents::OnSavePage() {
1061 // If we can not save the page, try to download it.
1062 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1063 DownloadManager* dlm = profile()->GetDownloadManager();
1064 const GURL& current_page_url = GetURL();
1065 if (dlm && current_page_url.is_valid())
[email protected]d82ed61e2009-06-16 02:46:221066 dlm->DownloadUrl(current_page_url, GURL(), "", this);
[email protected]420ae012009-04-24 05:16:321067 return;
1068 }
1069
1070 Stop();
1071
1072 // Create the save package and possibly prompt the user for the name to save
1073 // the page as. The user prompt is an asynchronous operation that runs on
1074 // another thread.
[email protected]d82ed61e2009-06-16 02:46:221075 save_package_ = new SavePackage(this);
[email protected]420ae012009-04-24 05:16:321076 save_package_->GetSaveInfo();
1077}
1078
1079// Used in automated testing to bypass prompting the user for file names.
1080// Instead, the names and paths are hard coded rather than running them through
1081// file name sanitation and extension / mime checking.
[email protected]cdf6cc82009-08-04 21:48:591082bool TabContents::SavePage(const std::wstring& main_file,
[email protected]420ae012009-04-24 05:16:321083 const std::wstring& dir_path,
1084 SavePackage::SavePackageType save_type) {
1085 // Stop the page from navigating.
1086 Stop();
1087
[email protected]d82ed61e2009-06-16 02:46:221088 save_package_ = new SavePackage(this, save_type,
[email protected]420ae012009-04-24 05:16:321089 FilePath::FromWStringHack(main_file),
1090 FilePath::FromWStringHack(dir_path));
[email protected]cdf6cc82009-08-04 21:48:591091 return save_package_->Init();
[email protected]420ae012009-04-24 05:16:321092}
1093
1094void TabContents::PrintPreview() {
1095 // We don't show the print preview yet, only the print dialog.
1096 PrintNow();
1097}
1098
1099bool TabContents::PrintNow() {
1100 // We can't print interstitial page for now.
1101 if (showing_interstitial_page())
1102 return false;
1103
1104 return render_view_host()->PrintPages();
1105}
1106
[email protected]82270452009-06-19 15:58:011107void TabContents::PrintingDone(int document_cookie, bool success) {
1108 render_view_host()->PrintingDone(document_cookie, success);
1109}
1110
[email protected]420ae012009-04-24 05:16:321111bool TabContents::IsActiveEntry(int32 page_id) {
1112 NavigationEntry* active_entry = controller_.GetActiveEntry();
1113 return (active_entry != NULL &&
1114 active_entry->site_instance() == GetSiteInstance() &&
1115 active_entry->page_id() == page_id);
1116}
1117
[email protected]96d185d2009-04-24 03:28:541118// Notifies the RenderWidgetHost instance about the fact that the page is
1119// loading, or done loading and calls the base implementation.
1120void TabContents::SetIsLoading(bool is_loading,
1121 LoadNotificationDetails* details) {
1122 if (is_loading == is_loading_)
1123 return;
1124
1125 if (!is_loading) {
1126 load_state_ = net::LOAD_STATE_IDLE;
1127 load_state_host_.clear();
1128 }
1129
1130 render_manager_.SetIsLoading(is_loading);
1131
1132 is_loading_ = is_loading;
1133 waiting_for_response_ = is_loading;
1134
1135 if (delegate_)
1136 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351137 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541138
1139 NotificationType type = is_loading ? NotificationType::LOAD_START :
1140 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111141 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541142 if (details)
1143 det = Details<LoadNotificationDetails>(details);
1144 NotificationService::current()->Notify(type,
1145 Source<NavigationController>(&controller_),
1146 det);
1147}
1148
[email protected]2c4410d2009-05-06 23:46:221149void TabContents::CreateBlockedPopupContainerIfNecessary() {
1150 if (blocked_popups_)
1151 return;
1152
[email protected]4d4c0b92009-06-08 23:13:011153 blocked_popups_ = BlockedPopupContainer::Create(this, profile());
[email protected]2c4410d2009-05-06 23:46:221154}
1155
[email protected]b6c874582009-05-08 19:38:311156void TabContents::AddPopup(TabContents* new_contents,
1157 const gfx::Rect& initial_pos,
1158 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221159 CreateBlockedPopupContainerIfNecessary();
1160 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221161}
1162
[email protected]e69bce3dd2009-04-20 22:05:121163// TODO(brettw) This should be on the TabContentsView.
[email protected]66ba4932009-06-04 19:22:131164void TabContents::RepositionSupressedPopupsToFit() {
[email protected]d6598c052008-11-05 19:03:251165 if (blocked_popups_)
[email protected]4d4c0b92009-06-08 23:13:011166 blocked_popups_->RepositionBlockedPopupContainer();
[email protected]d5f942ba2008-09-26 19:30:341167}
1168
[email protected]b9681312008-11-07 00:08:261169bool TabContents::ShowingBlockedPopupNotification() const {
1170 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221171 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261172}
[email protected]616ed5a2008-11-21 22:27:241173
1174namespace {
1175bool TransitionIsReload(PageTransition::Type transition) {
1176 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1177}
1178}
1179
1180void TabContents::ExpireInfoBars(
1181 const NavigationController::LoadCommittedDetails& details) {
1182 // Only hide InfoBars when the user has done something that makes the main
1183 // frame load. We don't want various automatic or subframe navigations making
1184 // it disappear.
1185 if (!details.is_user_initiated_main_frame_load())
1186 return;
1187
[email protected]f86a07022008-11-25 01:06:051188 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241189 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051190 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241191 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241192 }
1193}
[email protected]fdd61c62009-04-22 19:22:571194
1195void TabContents::OnGearsCreateShortcutDone(
1196 const GearsShortcutData2& shortcut_data, bool success) {
1197 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1198 bool same_page =
1199 current_entry && pending_install_.page_id == current_entry->page_id();
1200
1201 if (success && same_page) {
1202 // Only switch to app mode if the user chose to create a shortcut and
1203 // we're still on the same page that it corresponded to.
1204 if (delegate())
1205 delegate()->ConvertContentsToApplication(this);
1206 }
1207
1208 // Reset the page id to indicate no requests are pending.
1209 pending_install_.page_id = 0;
1210 pending_install_.callback_functor = NULL;
1211}
[email protected]96d185d2009-04-24 03:28:541212
1213DOMUI* TabContents::GetDOMUIForCurrentState() {
1214 // When there is a pending navigation entry, we want to use the pending DOMUI
1215 // that goes along with it to control the basic flags. For example, we want to
1216 // show the pending URL in the URL bar, so we want the display_url flag to
1217 // be from the pending entry.
1218 //
1219 // The confusion comes because there are multiple possibilities for the
1220 // initial load in a tab as a side effect of the way the RenderViewHostManager
1221 // works.
1222 //
1223 // - For the very first tab the load looks "normal". The new tab DOM UI is
1224 // the pending one, and we want it to apply here.
1225 //
1226 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1227 // get switched to the one previously associated with the new tab pages.
1228 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1229 // have a committed DOM UI in this case.
1230 //
1231 // This condition handles all of these cases:
1232 //
1233 // - First load in first tab: no committed nav entry + pending nav entry +
1234 // pending dom ui:
1235 // -> Use pending DOM UI if any.
1236 //
1237 // - First load in second tab: no committed nav entry + pending nav entry +
1238 // no pending DOM UI:
1239 // -> Use the committed DOM UI if any.
1240 //
1241 // - Second navigation in any tab: committed nav entry + pending nav entry:
1242 // -> Use pending DOM UI if any.
1243 //
1244 // - Normal state with no load: committed nav entry + no pending nav entry:
1245 // -> Use committed DOM UI.
1246 if (controller_.pending_entry() &&
1247 (controller_.GetLastCommittedEntry() ||
1248 render_manager_.pending_dom_ui()))
1249 return render_manager_.pending_dom_ui();
1250 return render_manager_.dom_ui();
1251}
[email protected]420ae012009-04-24 05:16:321252
1253void TabContents::DidNavigateMainFramePostCommit(
1254 const NavigationController::LoadCommittedDetails& details,
1255 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]420ae012009-04-24 05:16:321256 if (details.is_user_initiated_main_frame_load()) {
1257 // Clear the status bubble. This is a workaround for a bug where WebKit
1258 // doesn't let us know that the cursor left an element during a
1259 // transition (this is also why the mouse cursor remains as a hand after
1260 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1261 // clear the bubble when a user navigates to a named anchor in the same
1262 // page.
1263 UpdateTargetURL(details.entry->page_id(), GURL());
1264
1265 // UpdateHelpersForDidNavigate will handle the case where the password_form
1266 // origin is valid.
1267 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1268 // cleaned up and covered by tests.
1269 if (!params.password_form.origin.is_valid())
1270 GetPasswordManager()->DidNavigate();
1271 }
1272
1273 // The keyword generator uses the navigation entries, so must be called after
1274 // the commit.
1275 GenerateKeywordIfNecessary(params);
1276
1277 // Allow the new page to set the title again.
1278 received_page_title_ = false;
1279
1280 // Get the favicon, either from history or request it from the net.
1281 fav_icon_helper_.FetchFavIcon(details.entry->url());
1282
[email protected]aece2c7f2009-08-27 20:43:171283 // Disable all page actions, unless this is an in-page navigation.
1284 if (!enabled_page_actions_.empty()) {
1285 url_canon::Replacements<char> replacements;
1286 replacements.ClearRef();
1287 if (params.url.ReplaceComponents(replacements) !=
1288 params.referrer.ReplaceComponents(replacements)) {
1289 enabled_page_actions_.clear();
1290 }
1291 }
[email protected]ce5c4502009-05-06 16:46:111292
[email protected]420ae012009-04-24 05:16:321293 // Close constrained popups if necessary.
1294 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1295
1296 // Update the starred state.
1297 UpdateStarredStateForCurrentURL();
1298}
1299
1300void TabContents::DidNavigateAnyFramePostCommit(
1301 RenderViewHost* render_view_host,
1302 const NavigationController::LoadCommittedDetails& details,
1303 const ViewHostMsg_FrameNavigate_Params& params) {
1304 // If we navigate, start showing messages again. This does nothing to prevent
1305 // a malicious script from spamming messages, since the script could just
1306 // reload the page to stop blocking.
1307 suppress_javascript_messages_ = false;
1308
[email protected]420ae012009-04-24 05:16:321309 // Notify the password manager of the navigation or form submit.
1310 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1311 // cleaned up and covered by tests.
1312 if (params.password_form.origin.is_valid())
1313 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1314}
1315
1316void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1317 const GURL& current_url) {
1318 if (net::RegistryControlledDomainService::SameDomainOrHost(
1319 previous_url, current_url))
1320 return;
1321
1322 // Clear out any child windows since we are leaving this page entirely.
1323 // We use indices instead of iterators in case CloseWindow does something
1324 // that may invalidate an iterator.
1325 int size = static_cast<int>(child_windows_.size());
1326 for (int i = size - 1; i >= 0; --i) {
1327 ConstrainedWindow* window = child_windows_[i];
1328 if (window)
1329 window->CloseConstrainedWindow();
1330 }
[email protected]e29300cd2009-07-23 21:14:591331
1332 // Close the popup container.
1333 if (blocked_popups_) {
1334 blocked_popups_->Destroy();
1335 blocked_popups_ = NULL;
1336 }
[email protected]420ae012009-04-24 05:16:321337}
1338
1339void TabContents::UpdateStarredStateForCurrentURL() {
1340 BookmarkModel* model = profile()->GetBookmarkModel();
1341 const bool old_state = is_starred_;
1342 is_starred_ = (model && model->IsBookmarked(GetURL()));
1343
1344 if (is_starred_ != old_state && delegate())
1345 delegate()->URLStarredChanged(this, is_starred_);
1346}
1347
1348void TabContents::UpdateAlternateErrorPageURL() {
1349 GURL url = GetAlternateErrorPageURL();
1350 render_view_host()->SetAlternateErrorPageURL(url);
1351}
1352
1353void TabContents::UpdateWebPreferences() {
1354 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1355}
1356
1357void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1358 RenderViewHost* rvh) {
1359 // If we are creating a RVH for a restored controller, then we might
1360 // have more page IDs than the SiteInstance's current max page ID. We must
1361 // make sure that the max page ID is larger than any restored page ID.
1362 // Note that it is ok for conflicting page IDs to exist in another tab
1363 // (i.e., NavigationController), but if any page ID is larger than the max,
1364 // the back/forward list will get confused.
1365 int max_restored_page_id = controller_.max_restored_page_id();
1366 if (max_restored_page_id > 0) {
1367 int curr_max_page_id = site_instance->max_page_id();
1368 if (max_restored_page_id > curr_max_page_id) {
1369 // Need to update the site instance immediately.
1370 site_instance->UpdateMaxPageID(max_restored_page_id);
1371
1372 // Also tell the renderer to update its internal representation. We
1373 // need to reserve enough IDs to make all restored page IDs less than
1374 // the max.
1375 if (curr_max_page_id < 0)
1376 curr_max_page_id = 0;
1377 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1378 }
1379 }
1380}
1381
1382void TabContents::UpdateHistoryForNavigation(
[email protected]ebe89e062009-08-13 23:16:541383 const GURL& virtual_url,
[email protected]befd8d822009-07-01 04:51:471384 const NavigationController::LoadCommittedDetails& details,
[email protected]420ae012009-04-24 05:16:321385 const ViewHostMsg_FrameNavigate_Params& params) {
1386 if (profile()->IsOffTheRecord())
1387 return;
1388
1389 // Add to history service.
1390 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1391 if (hs) {
1392 if (PageTransition::IsMainFrame(params.transition) &&
[email protected]ebe89e062009-08-13 23:16:541393 virtual_url != params.url) {
1394 // Hack on the "virtual" URL so that it will appear in history. For some
[email protected]420ae012009-04-24 05:16:321395 // types of URLs, we will display a magic URL that is different from where
1396 // the page is actually navigated. We want the user to see in history
[email protected]ebe89e062009-08-13 23:16:541397 // what they saw in the URL bar, so we add the virtual URL as a redirect.
1398 // This only applies to the main frame, as the virtual URL doesn't apply
[email protected]420ae012009-04-24 05:16:321399 // to sub-frames.
1400 std::vector<GURL> redirects = params.redirects;
1401 if (!redirects.empty())
[email protected]ebe89e062009-08-13 23:16:541402 redirects.back() = virtual_url;
1403 hs->AddPage(virtual_url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471404 params.transition, redirects, details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321405 } else {
1406 hs->AddPage(params.url, this, params.page_id, params.referrer,
[email protected]befd8d822009-07-01 04:51:471407 params.transition, params.redirects,
1408 details.did_replace_entry);
[email protected]420ae012009-04-24 05:16:321409 }
1410 }
1411}
1412
1413bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1414 const std::wstring& title) {
1415 // For file URLs without a title, use the pathname instead. In the case of a
1416 // synthesized title, we don't want the update to count toward the "one set
1417 // per page of the title to history."
1418 std::wstring final_title;
1419 bool explicit_set;
1420 if (entry->url().SchemeIsFile() && title.empty()) {
1421 final_title = UTF8ToWide(entry->url().ExtractFileName());
1422 explicit_set = false; // Don't count synthetic titles toward the set limit.
1423 } else {
1424 TrimWhitespace(title, TRIM_ALL, &final_title);
1425 explicit_set = true;
1426 }
1427
1428 if (final_title == UTF16ToWideHack(entry->title()))
1429 return false; // Nothing changed, don't bother.
1430
1431 entry->set_title(WideToUTF16Hack(final_title));
1432
1433 // Update the history system for this page.
1434 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1435 HistoryService* hs =
1436 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1437 if (hs)
[email protected]ebe89e062009-08-13 23:16:541438 hs->SetPageTitle(entry->virtual_url(), final_title);
[email protected]420ae012009-04-24 05:16:321439
1440 // Don't allow the title to be saved again for explicitly set ones.
1441 received_page_title_ = explicit_set;
1442 }
1443
1444 // Lastly, set the title for the view.
1445 view_->SetPageTitle(final_title);
1446
1447 return true;
1448}
1449
1450void TabContents::NotifySwapped() {
1451 // After sending out a swap notification, we need to send a disconnect
1452 // notification so that clients that pick up a pointer to |this| can NULL the
1453 // pointer. See Bug 1230284.
1454 notify_disconnection_ = true;
1455 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341456 NotificationType::TAB_CONTENTS_SWAPPED,
[email protected]d82ed61e2009-06-16 02:46:221457 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321458 NotificationService::NoDetails());
1459}
1460
1461void TabContents::NotifyConnected() {
1462 notify_disconnection_ = true;
1463 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341464 NotificationType::TAB_CONTENTS_CONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221465 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321466 NotificationService::NoDetails());
1467}
1468
1469void TabContents::NotifyDisconnected() {
1470 if (!notify_disconnection_)
1471 return;
1472
1473 notify_disconnection_ = false;
1474 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341475 NotificationType::TAB_CONTENTS_DISCONNECTED,
[email protected]d82ed61e2009-06-16 02:46:221476 Source<TabContents>(this),
[email protected]420ae012009-04-24 05:16:321477 NotificationService::NoDetails());
1478}
1479
1480void TabContents::GenerateKeywordIfNecessary(
1481 const ViewHostMsg_FrameNavigate_Params& params) {
1482 if (!params.searchable_form_url.is_valid())
1483 return;
1484
1485 if (profile()->IsOffTheRecord())
1486 return;
1487
1488 int last_index = controller_.last_committed_entry_index();
1489 // When there was no previous page, the last index will be 0. This is
1490 // normally due to a form submit that opened in a new tab.
1491 // TODO(brettw) bug 916126: we should support keywords when form submits
1492 // happen in new tabs.
1493 if (last_index <= 0)
1494 return;
1495 const NavigationEntry* previous_entry =
1496 controller_.GetEntryAtIndex(last_index - 1);
1497 if (IsFormSubmit(previous_entry)) {
1498 // Only generate a keyword if the previous page wasn't itself a form
1499 // submit.
1500 return;
1501 }
1502
1503 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1504 previous_entry->user_typed_url() : previous_entry->url();
1505 std::wstring keyword =
1506 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1507 if (keyword.empty())
1508 return;
1509
1510 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1511 if (!url_model)
1512 return;
1513
1514 if (!url_model->loaded()) {
1515 url_model->Load();
1516 return;
1517 }
1518
1519 const TemplateURL* current_url;
1520 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1521 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1522 return;
1523
1524 if (current_url) {
1525 if (current_url->originating_url().is_valid()) {
1526 // The existing keyword was generated from an OpenSearch description
1527 // document, don't regenerate.
1528 return;
1529 }
1530 url_model->Remove(current_url);
1531 }
1532 TemplateURL* new_url = new TemplateURL();
1533 new_url->set_keyword(keyword);
1534 new_url->set_short_name(keyword);
1535 new_url->SetURL(url, 0, 0);
1536 new_url->add_input_encoding(params.searchable_form_encoding);
1537 DCHECK(controller_.GetLastCommittedEntry());
1538 const GURL& favicon_url =
1539 controller_.GetLastCommittedEntry()->favicon().url();
1540 if (favicon_url.is_valid()) {
1541 new_url->SetFavIconURL(favicon_url);
1542 } else {
1543 // The favicon url isn't valid. This means there really isn't a favicon,
1544 // or the favicon url wasn't obtained before the load started. This assumes
1545 // the later.
1546 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1547 // its url.
1548 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1549 }
1550 new_url->set_safe_for_autoreplace(true);
1551 url_model->Add(new_url);
1552}
1553
[email protected]bf5c2ff392009-07-08 16:24:331554void TabContents::OnUserGesture() {
1555 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
1556 DownloadRequestManager* drm = g_browser_process->download_request_manager();
1557 if (drm)
1558 drm->OnUserGesture(this);
1559 controller_.OnUserGesture();
1560}
1561
1562void TabContents::OnFindReply(int request_id,
1563 int number_of_matches,
1564 const gfx::Rect& selection_rect,
1565 int active_match_ordinal,
1566 bool final_update) {
[email protected]3ce7ced2009-07-24 18:52:421567 // Ignore responses for requests that have been aborted.
1568 if (find_op_aborted_)
1569 return;
1570
[email protected]bf5c2ff392009-07-08 16:24:331571 // Ignore responses for requests other than the one we have most recently
1572 // issued. That way we won't act on stale results when the user has
1573 // already typed in another query.
1574 if (request_id != current_find_request_id_)
1575 return;
1576
1577 if (number_of_matches == -1)
1578 number_of_matches = last_search_result_.number_of_matches();
1579 if (active_match_ordinal == -1)
1580 active_match_ordinal = last_search_result_.active_match_ordinal();
1581
1582 gfx::Rect selection = selection_rect;
1583 if (selection.IsEmpty())
1584 selection = last_search_result_.selection_rect();
1585
1586 // Notify the UI, automation and any other observers that a find result was
1587 // found.
1588 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
1589 selection, active_match_ordinal,
1590 final_update);
1591 NotificationService::current()->Notify(
1592 NotificationType::FIND_RESULT_AVAILABLE,
1593 Source<TabContents>(this),
1594 Details<FindNotificationDetails>(&last_search_result_));
1595}
1596
1597void TabContents::GoToEntryAtOffset(int offset) {
1598 controller_.GoToOffset(offset);
1599}
1600
1601void TabContents::GetHistoryListCount(int* back_list_count,
1602 int* forward_list_count) {
1603 int current_index = controller_.last_committed_entry_index();
1604 *back_list_count = current_index;
1605 *forward_list_count = controller_.entry_count() - current_index - 1;
1606}
1607
1608void TabContents::OnMissingPluginStatus(int status) {
1609#if defined(OS_WIN)
1610// TODO(PORT): pull in when plug-ins work
1611 GetPluginInstaller()->OnMissingPluginStatus(status);
1612#endif
1613}
1614
1615void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
[email protected]bf5c2ff392009-07-08 16:24:331616 DCHECK(!plugin_path.value().empty());
1617
1618 std::wstring plugin_name = plugin_path.ToWStringHack();
[email protected]d32d46182009-07-23 00:09:351619#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]bf5c2ff392009-07-08 16:24:331620 scoped_ptr<FileVersionInfo> version_info(
1621 FileVersionInfo::CreateFileVersionInfo(plugin_path));
1622 if (version_info.get()) {
1623 const std::wstring& product_name = version_info->product_name();
1624 if (!product_name.empty())
1625 plugin_name = product_name;
1626 }
[email protected]4a560ed2009-07-13 23:35:261627#else
1628 NOTIMPLEMENTED() << " convert plugin path to plugin name";
1629#endif
[email protected]bf5c2ff392009-07-08 16:24:331630 AddInfoBar(new SimpleAlertInfoBarDelegate(
1631 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
1632 NULL));
[email protected]bf5c2ff392009-07-08 16:24:331633}
1634
1635void TabContents::OnCrashedWorker() {
1636 AddInfoBar(new SimpleAlertInfoBarDelegate(
1637 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
1638 NULL));
1639}
1640
1641void TabContents::OnDidGetApplicationInfo(
1642 int32 page_id,
1643 const webkit_glue::WebApplicationInfo& info) {
1644 if (pending_install_.page_id != page_id)
1645 return; // The user clicked create on a separate page. Ignore this.
1646
1647 pending_install_.callback_functor =
1648 new GearsCreateShortcutCallbackFunctor(this);
1649 GearsCreateShortcut(
1650 info, pending_install_.title, pending_install_.url, pending_install_.icon,
1651 NewCallback(pending_install_.callback_functor,
1652 &GearsCreateShortcutCallbackFunctor::Run));
1653}
1654
1655void TabContents::DidStartProvisionalLoadForFrame(
1656 RenderViewHost* render_view_host,
1657 bool is_main_frame,
1658 const GURL& url) {
1659 ProvisionalLoadDetails details(is_main_frame,
1660 controller_.IsURLInPageNavigation(url),
1661 url, std::string(), false);
1662 NotificationService::current()->Notify(
1663 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1664 Source<NavigationController>(&controller_),
1665 Details<ProvisionalLoadDetails>(&details));
1666}
1667
1668void TabContents::DidStartReceivingResourceResponse(
1669 ResourceRequestDetails* details) {
1670 NotificationService::current()->Notify(
1671 NotificationType::RESOURCE_RESPONSE_STARTED,
1672 Source<NavigationController>(&controller()),
1673 Details<ResourceRequestDetails>(details));
1674}
1675
1676void TabContents::DidRedirectResource(ResourceRequestDetails* details) {
1677 NotificationService::current()->Notify(
1678 NotificationType::RESOURCE_RECEIVED_REDIRECT,
1679 Source<NavigationController>(&controller()),
1680 Details<ResourceRequestDetails>(details));
1681}
1682
1683void TabContents::DidLoadResourceFromMemoryCache(
1684 const GURL& url,
1685 const std::string& frame_origin,
1686 const std::string& main_frame_origin,
1687 const std::string& security_info) {
1688 // Send out a notification that we loaded a resource from our memory cache.
1689 int cert_id = 0, cert_status = 0, security_bits = 0;
1690 SSLManager::DeserializeSecurityInfo(security_info,
1691 &cert_id, &cert_status,
1692 &security_bits);
1693 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
1694 process()->pid(), cert_id, cert_status);
1695
1696 NotificationService::current()->Notify(
1697 NotificationType::LOAD_FROM_MEMORY_CACHE,
1698 Source<NavigationController>(&controller_),
1699 Details<LoadFromMemoryCacheDetails>(&details));
1700}
1701
1702void TabContents::DidFailProvisionalLoadWithError(
1703 RenderViewHost* render_view_host,
1704 bool is_main_frame,
1705 int error_code,
1706 const GURL& url,
1707 bool showing_repost_interstitial) {
1708 if (net::ERR_ABORTED == error_code) {
1709 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1710 // This means that the interstitial won't be torn down properly, which is
1711 // bad. But if we have an interstitial, go back to another tab type, and
1712 // then load the same interstitial again, we could end up getting the first
1713 // interstitial's "failed" message (as a result of the cancel) when we're on
1714 // the second one.
1715 //
1716 // We can't tell this apart, so we think we're tearing down the current page
1717 // which will cause a crash later one. There is also some code in
1718 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1719 // out because of this problem.
1720 //
1721 // http://code.google.com/p/chromium/issues/detail?id=2855
1722 // Because this will not tear down the interstitial properly, if "back" is
1723 // back to another tab type, the interstitial will still be somewhat alive
1724 // in the previous tab type. If you navigate somewhere that activates the
1725 // tab with the interstitial again, you'll see a flash before the new load
1726 // commits of the interstitial page.
1727 if (showing_interstitial_page()) {
1728 LOG(WARNING) << "Discarding message during interstitial.";
1729 return;
1730 }
1731
1732 // This will discard our pending entry if we cancelled the load (e.g., if we
1733 // decided to download the file instead of load it). Only discard the
1734 // pending entry if the URLs match, otherwise the user initiated a navigate
1735 // before the page loaded so that the discard would discard the wrong entry.
1736 NavigationEntry* pending_entry = controller_.pending_entry();
1737 if (pending_entry && pending_entry->url() == url) {
1738 controller_.DiscardNonCommittedEntries();
1739 // Update the URL display.
1740 NotifyNavigationStateChanged(TabContents::INVALIDATE_URL);
1741 }
1742
1743 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1744 }
1745
1746 // Send out a notification that we failed a provisional load with an error.
1747 ProvisionalLoadDetails details(is_main_frame,
1748 controller_.IsURLInPageNavigation(url),
1749 url, std::string(), false);
1750 details.set_error_code(error_code);
1751
1752 NotificationService::current()->Notify(
1753 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1754 Source<NavigationController>(&controller_),
1755 Details<ProvisionalLoadDetails>(&details));
1756}
1757
1758void TabContents::DocumentLoadedInFrame() {
1759 controller_.DocumentLoadedInFrame();
1760}
1761
[email protected]8d3347f2009-07-09 22:00:211762RenderViewHostDelegate::View* TabContents::GetViewDelegate() {
[email protected]420ae012009-04-24 05:16:321763 return view_.get();
1764}
1765
[email protected]8d3347f2009-07-09 22:00:211766RenderViewHostDelegate::RendererManagement*
1767TabContents::GetRendererManagementDelegate() {
1768 return &render_manager_;
1769}
1770
[email protected]bf5c2ff392009-07-08 16:24:331771RenderViewHostDelegate::BrowserIntegration*
[email protected]8d3347f2009-07-09 22:00:211772 TabContents::GetBrowserIntegrationDelegate() {
1773 return this;
[email protected]bf5c2ff392009-07-08 16:24:331774}
1775
[email protected]8d3347f2009-07-09 22:00:211776RenderViewHostDelegate::Resource* TabContents::GetResourceDelegate() {
1777 return this;
[email protected]bf5c2ff392009-07-08 16:24:331778}
1779
[email protected]8d3347f2009-07-09 22:00:211780RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() {
[email protected]420ae012009-04-24 05:16:321781 return save_package_.get(); // May be NULL, but we can return NULL.
1782}
1783
[email protected]8d3347f2009-07-09 22:00:211784RenderViewHostDelegate::Printing* TabContents::GetPrintingDelegate() {
1785 return &printing_;
1786}
1787
1788RenderViewHostDelegate::FavIcon* TabContents::GetFavIconDelegate() {
1789 return &fav_icon_helper_;
1790}
1791
1792RenderViewHostDelegate::Autofill* TabContents::GetAutofillDelegate() {
1793 if (autofill_manager_.get() == NULL)
1794 autofill_manager_.reset(new AutofillManager(this));
1795 return autofill_manager_.get();
[email protected]bf5c2ff392009-07-08 16:24:331796}
1797
[email protected]80d96fa2009-06-10 22:34:511798RendererPreferences TabContents::GetRendererPrefs() const {
[email protected]840b1512009-07-21 16:53:461799 return renderer_preferences_;
[email protected]80d96fa2009-06-10 22:34:511800}
1801
[email protected]57c6a652009-05-04 07:58:341802TabContents* TabContents::GetAsTabContents() {
1803 return this;
1804}
1805
[email protected]3e7cf1362009-08-21 17:47:081806void TabContents::AddBlockedNotice(const GURL& url, const string16& reason) {
1807 CreateBlockedPopupContainerIfNecessary();
1808 blocked_popups_->AddBlockedNotice(url, reason);
1809}
1810
[email protected]7b291f92009-08-14 05:43:531811ViewType::Type TabContents::GetRenderViewType() const {
1812 return ViewType::TAB_CONTENTS;
1813}
1814
1815int TabContents::GetBrowserWindowID() const {
1816 return controller().window_id().id();
1817}
1818
[email protected]420ae012009-04-24 05:16:321819void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
[email protected]2e4633c2009-07-09 16:58:061820 NotificationService::current()->Notify(
1821 NotificationType::RENDER_VIEW_HOST_CREATED_FOR_TAB,
1822 Source<TabContents>(this),
1823 Details<RenderViewHost>(render_view_host));
[email protected]420ae012009-04-24 05:16:321824 NavigationEntry* entry = controller_.GetActiveEntry();
1825 if (!entry)
1826 return;
1827
1828 // When we're creating views, we're still doing initial setup, so we always
1829 // use the pending DOM UI rather than any possibly existing committed one.
1830 if (render_manager_.pending_dom_ui()) {
1831 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1832 }
1833
1834 if (entry->IsViewSourceMode()) {
1835 // Put the renderer in view source mode.
1836 render_view_host->Send(
1837 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1838 }
[email protected]0666aef2009-05-13 19:48:081839
1840 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321841}
1842
1843void TabContents::RenderViewReady(RenderViewHost* rvh) {
1844 if (rvh != render_view_host()) {
1845 // Don't notify the world, since this came from a renderer in the
1846 // background.
1847 return;
1848 }
1849
1850 NotifyConnected();
[email protected]9d8a4642009-07-29 17:25:301851 bool was_crashed = is_crashed();
[email protected]420ae012009-04-24 05:16:321852 SetIsCrashed(false);
[email protected]9d8a4642009-07-29 17:25:301853
1854 // Restore the focus to the tab (otherwise the focus will be on the top
1855 // window).
1856 if (was_crashed && !FocusLocationBarByDefault())
1857 Focus();
[email protected]420ae012009-04-24 05:16:321858}
1859
1860void TabContents::RenderViewGone(RenderViewHost* rvh) {
1861 // Ask the print preview if this renderer was valuable.
1862 if (!printing_.OnRenderViewGone(rvh))
1863 return;
1864 if (rvh != render_view_host()) {
1865 // The pending page's RenderViewHost is gone.
1866 return;
1867 }
1868
1869 SetIsLoading(false, NULL);
1870 NotifyDisconnected();
1871 SetIsCrashed(true);
1872
[email protected]8e537302009-06-10 21:19:581873 // Tell the view that we've crashed so it can prepare the sad tab page.
1874 view_->OnTabCrashed();
[email protected]420ae012009-04-24 05:16:321875
1876 // Hide any visible hung renderer warning for this web contents' process.
[email protected]d82ed61e2009-06-16 02:46:221877 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:321878}
1879
[email protected]2e4633c2009-07-09 16:58:061880void TabContents::RenderViewDeleted(RenderViewHost* rvh) {
1881 NotificationService::current()->Notify(
1882 NotificationType::RENDER_VIEW_HOST_DELETED,
1883 Source<TabContents>(this),
1884 Details<RenderViewHost>(rvh));
1885}
1886
[email protected]420ae012009-04-24 05:16:321887void TabContents::DidNavigate(RenderViewHost* rvh,
1888 const ViewHostMsg_FrameNavigate_Params& params) {
1889 if (PageTransition::IsMainFrame(params.transition))
1890 render_manager_.DidNavigateMainFrame(rvh);
1891
1892 // Update the site of the SiteInstance if it doesn't have one yet.
1893 if (!GetSiteInstance()->has_site())
1894 GetSiteInstance()->SetSite(params.url);
1895
1896 // Need to update MIME type here because it's referred to in
1897 // UpdateNavigationCommands() called by RendererDidNavigate() to
1898 // determine whether or not to enable the encoding menu.
1899 // It's updated only for the main frame. For a subframe,
1900 // RenderView::UpdateURL does not set params.contents_mime_type.
1901 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1902 // TODO(jungshik): Add a test for the encoding menu to avoid
1903 // regressing it again.
1904 if (PageTransition::IsMainFrame(params.transition))
1905 contents_mime_type_ = params.contents_mime_type;
1906
1907 NavigationController::LoadCommittedDetails details;
[email protected]3e90d4a2009-07-03 17:38:391908 bool did_navigate = controller_.RendererDidNavigate(params, &details);
1909
1910 // Update history. Note that this needs to happen after the entry is complete,
1911 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1912 if (params.should_update_history) {
1913 // Most of the time, the displayURL matches the loaded URL, but for about:
1914 // URLs, we use a data: URL as the real value. We actually want to save
1915 // the about: URL to the history db and keep the data: URL hidden. This is
1916 // what the TabContents' URL getter does.
1917 UpdateHistoryForNavigation(GetURL(), details, params);
1918 }
1919
1920 if (!did_navigate)
1921 return; // No navigation happened.
[email protected]420ae012009-04-24 05:16:321922
1923 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1924 // for the appropriate notification (best) or you can add it to
1925 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1926 // necessary, please).
1927
1928 // Run post-commit tasks.
1929 if (details.is_main_frame)
1930 DidNavigateMainFramePostCommit(details, params);
1931 DidNavigateAnyFramePostCommit(rvh, details, params);
1932}
1933
1934void TabContents::UpdateState(RenderViewHost* rvh,
1935 int32 page_id,
1936 const std::string& state) {
1937 DCHECK(rvh == render_view_host());
1938
1939 // We must be prepared to handle state updates for any page, these occur
1940 // when the user is scrolling and entering form data, as well as when we're
1941 // leaving a page, in which case our state may have already been moved to
1942 // the next page. The navigation controller will look up the appropriate
1943 // NavigationEntry and update it when it is notified via the delegate.
1944
1945 int entry_index = controller_.GetEntryIndexWithPageID(
1946 GetSiteInstance(), page_id);
1947 if (entry_index < 0)
1948 return;
1949 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1950
1951 if (state == entry->content_state())
1952 return; // Nothing to update.
1953 entry->set_content_state(state);
1954 controller_.NotifyEntryChanged(entry, entry_index);
1955}
1956
1957void TabContents::UpdateTitle(RenderViewHost* rvh,
1958 int32 page_id, const std::wstring& title) {
1959 // If we have a title, that's a pretty good indication that we've started
1960 // getting useful data.
1961 SetNotWaitingForResponse();
1962
1963 DCHECK(rvh == render_view_host());
1964 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1965 page_id);
1966 if (!entry || !UpdateTitleForEntry(entry, title))
1967 return;
1968
1969 // Broadcast notifications when the UI should be updated.
1970 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501971 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321972}
1973
[email protected]420ae012009-04-24 05:16:321974void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1975 const std::wstring& encoding) {
1976 set_encoding(encoding);
1977}
1978
1979void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1980 if (delegate())
1981 delegate()->UpdateTargetURL(this, url);
1982}
1983
1984void TabContents::UpdateThumbnail(const GURL& url,
1985 const SkBitmap& bitmap,
1986 const ThumbnailScore& score) {
1987 // Tell History about this thumbnail
[email protected]449478302009-06-09 20:04:281988 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kThumbnailStore)) {
[email protected]72d0fc72009-07-09 17:30:491989 if (!profile()->IsOffTheRecord())
[email protected]42339402009-07-17 17:27:191990 profile()->GetThumbnailStore()->SetPageThumbnail(url, bitmap,
1991 score, true);
[email protected]449478302009-06-09 20:04:281992 } else {
1993 HistoryService* hs;
1994 if (!profile()->IsOffTheRecord() &&
1995 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1996 hs->SetPageThumbnail(url, bitmap, score);
1997 }
[email protected]420ae012009-04-24 05:16:321998 }
1999}
2000
[email protected]0df30122009-06-03 12:13:082001void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
2002 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
2003 raw_settings);
2004}
2005
[email protected]420ae012009-04-24 05:16:322006void TabContents::Close(RenderViewHost* rvh) {
[email protected]24a4d1062009-07-10 23:10:422007 // If we close the tab while we're in the middle of a drag, we'll crash.
2008 // Instead, cancel the drag and close it as soon as the drag ends.
2009 if (view()->IsDoingDrag()) {
2010 view()->CancelDragAndCloseTab();
2011 return;
2012 }
2013
[email protected]420ae012009-04-24 05:16:322014 // Ignore this if it comes from a RenderViewHost that we aren't showing.
2015 if (delegate() && rvh == render_view_host())
2016 delegate()->CloseContents(this);
2017}
2018
2019void TabContents::RequestMove(const gfx::Rect& new_bounds) {
2020 if (delegate() && delegate()->IsPopup(this))
2021 delegate()->MoveContents(this, new_bounds);
2022}
2023
[email protected]329581b2009-04-28 06:52:352024void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:322025 SetIsLoading(true, NULL);
2026}
2027
[email protected]329581b2009-04-28 06:52:352028void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:322029 scoped_ptr<LoadNotificationDetails> details;
2030
2031 NavigationEntry* entry = controller_.GetActiveEntry();
2032 // An entry may not exist for a stop when loading an initial blank page or
2033 // if an iframe injected by script into a blank page finishes loading.
2034 if (entry) {
2035 scoped_ptr<base::ProcessMetrics> metrics(
2036 base::ProcessMetrics::CreateProcessMetrics(
2037 process()->process().handle()));
2038
2039 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
2040
2041 details.reset(new LoadNotificationDetails(
[email protected]ebe89e062009-08-13 23:16:542042 entry->virtual_url(),
[email protected]420ae012009-04-24 05:16:322043 entry->transition_type(),
2044 elapsed,
2045 &controller_,
2046 controller_.GetCurrentEntryIndex()));
2047 }
2048
2049 // Tell PasswordManager we've finished a page load, which serves as a
2050 // green light to save pending passwords and reset itself.
2051 GetPasswordManager()->DidStopLoading();
2052
2053 SetIsLoading(false, details.get());
2054}
2055
[email protected]420ae012009-04-24 05:16:322056void TabContents::DidRedirectProvisionalLoad(int32 page_id,
2057 const GURL& source_url,
2058 const GURL& target_url) {
2059 NavigationEntry* entry;
2060 if (page_id == -1)
2061 entry = controller_.pending_entry();
2062 else
2063 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
2064 if (!entry || entry->url() != source_url)
2065 return;
2066 entry->set_url(target_url);
2067}
2068
[email protected]420ae012009-04-24 05:16:322069void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
2070 WindowOpenDisposition disposition) {
2071 if (render_manager_.dom_ui()) {
2072 // When we're a DOM UI, it will provide a page transition type for us (this
2073 // is so the new tab page can specify AUTO_BOOKMARK for automatically
2074 // generated suggestions).
2075 //
2076 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:162077 // want web sites to see a referrer of "chrome://blah" (and some
2078 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:322079 // send to the site), so we send no referrer.
2080 OpenURL(url, GURL(), disposition,
2081 render_manager_.dom_ui()->link_transition_type());
2082 } else {
2083 OpenURL(url, referrer, disposition, PageTransition::LINK);
2084 }
2085}
2086
[email protected]1ee614862009-07-06 20:29:182087void TabContents::DomOperationResponse(const std::string& json_string,
2088 int automation_id) {
2089}
2090
[email protected]420ae012009-04-24 05:16:322091void TabContents::ProcessDOMUIMessage(const std::string& message,
[email protected]811bfe32009-07-01 08:46:252092 const std::string& content,
2093 int request_id,
2094 bool has_callback) {
[email protected]420ae012009-04-24 05:16:322095 if (!render_manager_.dom_ui()) {
2096 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
2097 // Because the renderer might be owned and sending random messages, we need
2098 // to ignore these inproper ones.
2099 NOTREACHED();
2100 return;
2101 }
[email protected]811bfe32009-07-01 08:46:252102 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content, request_id,
2103 has_callback);
[email protected]420ae012009-04-24 05:16:322104}
2105
2106void TabContents::ProcessExternalHostMessage(const std::string& message,
2107 const std::string& origin,
2108 const std::string& target) {
2109 if (delegate())
2110 delegate()->ForwardMessageToExternalHost(message, origin, target);
2111}
2112
[email protected]420ae012009-04-24 05:16:322113void TabContents::RunFileChooser(bool multiple_files,
2114 const string16& title,
2115 const FilePath& default_file) {
2116 if (!select_file_dialog_.get())
2117 select_file_dialog_ = SelectFileDialog::Create(this);
2118 SelectFileDialog::Type dialog_type =
2119 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
2120 SelectFileDialog::SELECT_OPEN_FILE;
2121 select_file_dialog_->SelectFile(dialog_type, title, default_file,
2122 NULL, 0, FILE_PATH_LITERAL(""),
2123 view_->GetTopLevelNativeWindow(), NULL);
2124}
2125
2126void TabContents::RunJavaScriptMessage(
2127 const std::wstring& message,
2128 const std::wstring& default_prompt,
2129 const GURL& frame_url,
2130 const int flags,
2131 IPC::Message* reply_msg,
2132 bool* did_suppress_message) {
2133 // Suppress javascript messages when requested and when inside a constrained
2134 // popup window (because that activates them and breaks them out of the
2135 // constrained window jail).
[email protected]91ed49a2009-07-07 21:29:552136 // Also suppress messages when showing an interstitial. The interstitial is
2137 // shown over the previous page, we don't want the hidden page dialogs to
2138 // interfere with the interstitial.
2139 bool suppress_this_message = suppress_javascript_messages_ ||
2140 showing_interstitial_page();
[email protected]420ae012009-04-24 05:16:322141 if (delegate())
2142 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:312143 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:322144
2145 *did_suppress_message = suppress_this_message;
2146
2147 if (!suppress_this_message) {
2148 base::TimeDelta time_since_last_message(
2149 base::TimeTicks::Now() - last_javascript_message_dismissal_);
2150 bool show_suppress_checkbox = false;
2151 // Show a checkbox offering to suppress further messages if this message is
2152 // being displayed within kJavascriptMessageExpectedDelay of the last one.
2153 if (time_since_last_message <
2154 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
2155 show_suppress_checkbox = true;
2156
[email protected]d82ed61e2009-06-16 02:46:222157 RunJavascriptMessageBox(this, frame_url, flags, message, default_prompt,
[email protected]420ae012009-04-24 05:16:322158 show_suppress_checkbox, reply_msg);
2159 } else {
2160 // If we are suppressing messages, just reply as is if the user immediately
2161 // pressed "Cancel".
2162 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
2163 }
2164}
2165
2166void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
2167 IPC::Message* reply_msg) {
[email protected]d82ed61e2009-06-16 02:46:222168 RunBeforeUnloadDialog(this, message, reply_msg);
[email protected]420ae012009-04-24 05:16:322169}
2170
2171void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
2172 const std::string& json_arguments,
2173 IPC::Message* reply_msg) {
2174 if (delegate()) {
2175 HtmlDialogUIDelegate* dialog_delegate =
2176 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
[email protected]d82ed61e2009-06-16 02:46:222177 reply_msg, this);
[email protected]420ae012009-04-24 05:16:322178 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
2179 }
2180}
2181
2182void TabContents::PasswordFormsSeen(
[email protected]ed3fb032009-06-16 19:50:562183 const std::vector<webkit_glue::PasswordForm>& forms) {
[email protected]420ae012009-04-24 05:16:322184 GetPasswordManager()->PasswordFormsSeen(forms);
2185}
2186
[email protected]420ae012009-04-24 05:16:322187// Checks to see if we should generate a keyword based on the OSDD, and if
2188// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2189void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2190 int32 page_id, const GURL& url,
2191 bool autodetected) {
2192 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2193 DCHECK(url.is_valid());
2194 if (!IsActiveEntry(page_id))
2195 return;
2196 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2197 if (!url_model)
2198 return;
2199 if (!url_model->loaded()) {
2200 url_model->Load();
2201 return;
2202 }
2203 if (!profile()->GetTemplateURLFetcher())
2204 return;
2205
2206 if (profile()->IsOffTheRecord())
2207 return;
2208
2209 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2210 DCHECK(entry);
2211
2212 const NavigationEntry* base_entry = entry;
2213 if (IsFormSubmit(base_entry)) {
2214 // If the current page is a form submit, find the last page that was not
2215 // a form submit and use its url to generate the keyword from.
2216 int index = controller_.last_committed_entry_index() - 1;
2217 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2218 index--;
2219 if (index >= 0)
2220 base_entry = controller_.GetEntryAtIndex(index);
2221 else
2222 base_entry = NULL;
2223 }
2224
2225 // We want to use the user typed URL if available since that represents what
2226 // the user typed to get here, and fall back on the regular URL if not.
2227 if (!base_entry)
2228 return;
2229 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2230 base_entry->user_typed_url() : base_entry->url();
2231 if (!keyword_url.is_valid())
2232 return;
2233 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2234 autodetected);
2235 if (keyword.empty())
2236 return;
2237 const TemplateURL* template_url =
2238 url_model->GetTemplateURLForKeyword(keyword);
2239 if (template_url && (!template_url->safe_for_autoreplace() ||
2240 template_url->originating_url() == url)) {
2241 // Either there is a user created TemplateURL for this keyword, or the
2242 // keyword has the same OSDD url and we've parsed it.
2243 return;
2244 }
2245
2246 // Download the OpenSearch description document. If this is successful a
2247 // new keyword will be created when done.
[email protected]420ae012009-04-24 05:16:322248 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2249 keyword,
2250 url,
2251 base_entry->favicon().url(),
[email protected]d0cc9fb52009-06-23 02:26:162252 this,
[email protected]420ae012009-04-24 05:16:322253 autodetected);
2254}
2255
[email protected]420ae012009-04-24 05:16:322256GURL TabContents::GetAlternateErrorPageURL() const {
2257 GURL url;
2258 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2259 if (profile()->IsOffTheRecord())
2260 return url;
2261
2262 PrefService* prefs = profile()->GetPrefs();
2263 DCHECK(prefs);
2264 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
[email protected]2bd6ca1c2009-08-27 16:42:202265 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
[email protected]420ae012009-04-24 05:16:322266 url = google_util::AppendGoogleTLDParam(url);
2267 }
2268 return url;
2269}
2270
2271WebPreferences TabContents::GetWebkitPrefs() {
2272 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
[email protected]7ccddb8c2009-08-04 17:36:552273 bool is_dom_ui = false;
2274 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, is_dom_ui);
[email protected]420ae012009-04-24 05:16:322275}
2276
[email protected]420ae012009-04-24 05:16:322277void TabContents::OnJSOutOfMemory() {
2278 AddInfoBar(new SimpleAlertInfoBarDelegate(
2279 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2280}
2281
[email protected]420ae012009-04-24 05:16:322282void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2283 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342284 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322285 // delivered to a pending RenderViewHost. We must first run the onunload
2286 // handler of the old RenderViewHost before we can allow it to proceed.
2287 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2288 new_request_id);
2289}
2290
2291bool TabContents::CanBlur() const {
2292 return delegate() ? delegate()->CanBlur() : true;
2293}
2294
2295gfx::Rect TabContents::GetRootWindowResizerRect() const {
2296 if (delegate())
2297 return delegate()->GetRootWindowResizerRect();
2298 return gfx::Rect();
2299}
2300
2301void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2302 bool is_during_unload) {
2303 if (is_during_unload) {
2304 // Hang occurred while firing the beforeunload/unload handler.
2305 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112306 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322307
2308 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2309 return;
2310
2311 // If the tab hangs in the beforeunload/unload handler there's really
2312 // nothing we can do to recover. Pretend the unload listeners have
2313 // all fired and close the tab. If the hang is in the beforeunload handler
2314 // then the user will not have the option of cancelling the close.
2315 Close(rvh);
2316 return;
2317 }
2318
2319 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]d82ed61e2009-06-16 02:46:222320 HungRendererDialog::ShowForTabContents(this);
[email protected]420ae012009-04-24 05:16:322321}
2322
2323void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]d82ed61e2009-06-16 02:46:222324 HungRendererDialog::HideForTabContents(this);
[email protected]420ae012009-04-24 05:16:322325}
2326
2327void TabContents::LoadStateChanged(const GURL& url,
2328 net::LoadState load_state) {
2329 load_state_ = load_state;
[email protected]d686e812009-06-03 19:10:292330 std::wstring languages =
2331 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2332 load_state_host_.clear();
2333 std::string host = url.host();
2334 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322335 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2336 SetNotWaitingForResponse();
2337 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502338 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322339}
2340
[email protected]1ee614862009-07-06 20:29:182341bool TabContents::IsExternalTabContainer() const {
2342 if (!delegate())
2343 return false;
2344
2345 return delegate()->IsExternalTabContainer();
2346}
2347
[email protected]1ee614862009-07-06 20:29:182348void TabContents::DidInsertCSS() {
2349 // This RVHDelegate function is used for extensions and not us.
[email protected]420ae012009-04-24 05:16:322350}
2351
2352void TabContents::FileSelected(const FilePath& path,
2353 int index, void* params) {
2354 render_view_host()->FileSelected(path);
2355}
2356
2357void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2358 void* params) {
2359 render_view_host()->MultiFilesSelected(files);
2360}
2361
2362void TabContents::FileSelectionCanceled(void* params) {
2363 // If the user cancels choosing a file to upload we pass back an
2364 // empty vector.
2365 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2366}
2367
2368void TabContents::BeforeUnloadFiredFromRenderManager(
2369 bool proceed,
2370 bool* proceed_to_fire_unload) {
2371 if (delegate())
2372 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2373}
2374
2375void TabContents::UpdateRenderViewSizeForRenderManager() {
2376 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2377 view_->SizeContents(view_->GetContainerSize());
2378}
2379
2380DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
[email protected]d82ed61e2009-06-16 02:46:222381 return DOMUIFactory::CreateDOMUIForURL(this, url);
[email protected]420ae012009-04-24 05:16:322382}
2383
2384NavigationEntry*
2385TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2386 return controller_.GetLastCommittedEntry();
2387}
2388
2389bool TabContents::CreateRenderViewForRenderManager(
2390 RenderViewHost* render_view_host) {
[email protected]811bfe32009-07-01 08:46:252391 // If the pending navigation is to a DOMUI, tell the RenderView about any
2392 // bindings it will need enabled.
[email protected]420ae012009-04-24 05:16:322393 if (render_manager_.pending_dom_ui())
[email protected]811bfe32009-07-01 08:46:252394 render_view_host->AllowBindings(
2395 render_manager_.pending_dom_ui()->bindings());
[email protected]1adff062009-06-02 18:39:552396
[email protected]420ae012009-04-24 05:16:322397 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2398 if (!render_view_host->CreateRenderView())
2399 return false;
2400
2401 // Now that the RenderView has been created, we need to tell it its size.
2402 rwh_view->SetSize(view_->GetContainerSize());
2403
2404 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2405 render_view_host);
2406 return true;
2407}
2408
2409void TabContents::Observe(NotificationType type,
2410 const NotificationSource& source,
2411 const NotificationDetails& details) {
2412 switch (type.value) {
2413 case NotificationType::BOOKMARK_MODEL_LOADED:
2414 // BookmarkModel finished loading, fall through to update starred state.
2415 case NotificationType::URLS_STARRED: {
2416 // Somewhere, a URL has been starred.
2417 // Ignore notifications for profiles other than our current one.
2418 Profile* source_profile = Source<Profile>(source).ptr();
2419 if (!source_profile || !source_profile->IsSameProfile(profile()))
2420 return;
2421
2422 UpdateStarredStateForCurrentURL();
2423 break;
2424 }
2425 case NotificationType::PREF_CHANGED: {
2426 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2427 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2428 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2429 UpdateAlternateErrorPageURL();
2430 } else if (*pref_name_in == prefs::kDefaultCharset ||
2431 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2432 ) {
2433 UpdateWebPreferences();
2434 } else {
2435 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2436 }
2437 break;
2438 }
2439 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2440 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2441 break;
2442
2443 case NotificationType::NAV_ENTRY_COMMITTED: {
2444 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2445
2446 NavigationController::LoadCommittedDetails& committed_details =
2447 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2448 ExpireInfoBars(committed_details);
2449 break;
2450 }
2451
2452 default:
2453 NOTREACHED();
2454 }
2455}