blob: b0d5b716789c4d96e450fbdab0f06ada2b7c1fdf [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]420ae012009-04-24 05:16:3214#include "chrome/browser/bookmarks/bookmark_model.h"
[email protected]96d185d2009-04-24 03:28:5415#include "chrome/browser/browser_process.h"
initial.commit09911bf2008-07-26 23:55:2916#include "chrome/browser/cert_store.h"
[email protected]96d185d2009-04-24 03:28:5417#include "chrome/browser/debugger/devtools_manager.h"
[email protected]420ae012009-04-24 05:16:3218#include "chrome/browser/dom_operation_notification_details.h"
[email protected]96d185d2009-04-24 03:28:5419#include "chrome/browser/dom_ui/dom_ui.h"
20#include "chrome/browser/dom_ui/dom_ui_factory.h"
[email protected]bcef0dc02009-02-28 00:35:0221#include "chrome/browser/download/download_item_model.h"
[email protected]420ae012009-04-24 05:16:3222#include "chrome/browser/download/download_manager.h"
23#include "chrome/browser/download/download_request_manager.h"
[email protected]bcef0dc02009-02-28 00:35:0224#include "chrome/browser/download/download_shelf.h"
[email protected]bd1ad682009-05-15 22:19:1725#include "chrome/browser/download/download_started_animation.h"
[email protected]420ae012009-04-24 05:16:3226#include "chrome/browser/gears_integration.h"
27#include "chrome/browser/google_util.h"
[email protected]8897c382009-05-06 17:53:2628#include "chrome/browser/hung_renderer_dialog.h"
[email protected]420ae012009-04-24 05:16:3229#include "chrome/browser/jsmessage_box_handler.h"
30#include "chrome/browser/load_from_memory_cache_details.h"
31#include "chrome/browser/load_notification_details.h"
[email protected]fdd61c62009-04-22 19:22:5732#include "chrome/browser/password_manager/password_manager.h"
33#include "chrome/browser/plugin_installer.h"
[email protected]ce560f82009-06-03 09:39:4434#include "chrome/browser/profile.h"
[email protected]96d185d2009-04-24 03:28:5435#include "chrome/browser/renderer_host/render_widget_host_view.h"
36#include "chrome/browser/renderer_host/web_cache_manager.h"
[email protected]bd1ad682009-05-15 22:19:1737#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]f3ec7742009-01-15 00:59:1638#include "chrome/browser/tab_contents/navigation_entry.h"
39#include "chrome/browser/tab_contents/tab_contents_delegate.h"
[email protected]fdd61c62009-04-22 19:22:5740#include "chrome/browser/tab_contents/tab_contents_view.h"
[email protected]420ae012009-04-24 05:16:3241#include "chrome/browser/search_engines/template_url_fetcher.h"
42#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2743#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5644#include "chrome/common/notification_service.h"
[email protected]ce5c4502009-05-06 16:46:1145#include "chrome/common/page_action.h"
[email protected]bd1ad682009-05-15 22:19:1746#include "chrome/common/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2947#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0348#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3249#include "chrome/common/render_messages.h"
[email protected]96d185d2009-04-24 03:28:5450#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2651#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3252#include "grit/locale_settings.h"
53#include "net/base/mime_util.h"
54#include "net/base/net_errors.h"
55#include "net/base/registry_controlled_domain.h"
[email protected]3e45ba92009-02-20 21:09:0056
57#if defined(OS_WIN)
58// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3259#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]3e45ba92009-02-20 21:09:0060#include "chrome/browser/views/blocked_popup_container.h"
[email protected]2362e4f2009-05-08 00:34:0561#include "views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0062#endif
initial.commit09911bf2008-07-26 23:55:2963
[email protected]420ae012009-04-24 05:16:3264// Cross-Site Navigations
65//
66// If a TabContents is told to navigate to a different web site (as determined
67// by SiteInstance), it will replace its current RenderViewHost with a new
68// RenderViewHost dedicated to the new SiteInstance. This works as follows:
69//
70// - Navigate determines whether the destination is cross-site, and if so,
71// it creates a pending_render_view_host_ and moves into the PENDING
72// RendererState.
73// - The pending RVH is "suspended," so that no navigation messages are sent to
74// its renderer until the onbeforeunload JavaScript handler has a chance to
75// run in the current RVH.
76// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
77// that it has a pending cross-site request. ResourceDispatcherHost will
78// check for this when the response arrives.
79// - The current RVH runs its onbeforeunload handler. If it returns false, we
80// cancel all the pending logic and go back to NORMAL. Otherwise we allow
81// the pending RVH to send the navigation request to its renderer.
82// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
83// checks CrossSiteRequestManager to see that the RVH responsible has a
84// pending cross-site request, and then installs a CrossSiteEventHandler.
85// - When RDH receives a response, the BufferedEventHandler determines whether
86// it is a download. If so, it sends a message to the new renderer causing
87// it to cancel the request, and the download proceeds in the download
88// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:3489// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:3290// doesn't affect any functionality.
91// - After RDH receives a response and determines that it is safe and not a
92// download, it pauses the response to first run the old page's onunload
93// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:3494// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:3295// to the current RVH.
96// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
97// the ResourceDispatcherHost, who unpauses the response. Data is then sent
98// to the pending RVH.
99// - The pending renderer sends a FrameNavigate message that invokes the
100// DidNavigate method. This replaces the current RVH with the
101// pending RVH and goes back to the NORMAL RendererState.
102
103namespace {
104
105// Amount of time we wait between when a key event is received and the renderer
106// is queried for its state and pushed to the NavigationEntry.
107const int kQueryStateDelay = 5000;
108
109const int kSyncWaitDelay = 40;
110
111// If another javascript message box is displayed within
112// kJavascriptMessageExpectedDelay of a previous javascript message box being
113// dismissed, display an option to suppress future message boxes from this
114// contents.
115const int kJavascriptMessageExpectedDelay = 1000;
116
117// Minimum amount of time in ms that has to elapse since the download shelf was
118// shown for us to hide it when navigating away from the current page.
119const int kDownloadShelfHideDelay = 5000;
120
121const char kLinkDoctorBaseURL[] =
122 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
123
124// The printer icon in shell32.dll. That's a standard icon user will quickly
125// recognize.
126const int kShell32PrinterIcon = 17;
127
128// The list of prefs we want to observe.
129const wchar_t* kPrefsToObserve[] = {
130 prefs::kAlternateErrorPagesEnabled,
131 prefs::kWebKitJavaEnabled,
132 prefs::kWebKitJavascriptEnabled,
133 prefs::kWebKitLoadsImagesAutomatically,
134 prefs::kWebKitPluginsEnabled,
135 prefs::kWebKitUsesUniversalDetector,
[email protected]96d3fb52009-05-27 14:51:21136 prefs::kWebKitDeveloperExtrasEnabled,
[email protected]420ae012009-04-24 05:16:32137 prefs::kWebKitSerifFontFamily,
138 prefs::kWebKitSansSerifFontFamily,
139 prefs::kWebKitFixedFontFamily,
140 prefs::kWebKitDefaultFontSize,
141 prefs::kWebKitDefaultFixedFontSize,
142 prefs::kDefaultCharset
143 // kWebKitStandardFontIsSerif needs to be added
144 // if we let users pick which font to use, serif or sans-serif when
145 // no font is specified or a CSS generic family (serif or sans-serif)
146 // is not specified.
147};
148
149const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
150
151// Limit on the number of suggestions to appear in the pop-up menu under an
152// text input element in a form.
153const int kMaxAutofillMenuItems = 6;
154
155// Returns true if the entry's transition type is FORM_SUBMIT.
156bool IsFormSubmit(const NavigationEntry* entry) {
157 return (PageTransition::StripQualifier(entry->transition_type()) ==
158 PageTransition::FORM_SUBMIT);
159}
160
161#if defined(OS_WIN)
162
163BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
164 // Note: erase is required to properly paint some widgets borders. This can
165 // be seen with textfields.
166 InvalidateRect(hwnd, NULL, TRUE);
167 return TRUE;
168}
169#endif
170
[email protected]57c6a652009-05-04 07:58:34171// TODO(brettw) TabContents should be removed, then this hack is unnecessary.
172TabContents* AsWC(TabContents* tc) {
173 return static_cast<TabContents*>(tc);
[email protected]420ae012009-04-24 05:16:32174}
175
176} // namespace
177
178// -----------------------------------------------------------------------------
179
[email protected]fdd61c62009-04-22 19:22:57180// static
181int TabContents::find_request_id_counter_ = -1;
182
[email protected]420ae012009-04-24 05:16:32183class TabContents::GearsCreateShortcutCallbackFunctor {
184 public:
185 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
186 : contents_(contents) {}
187
188 void Run(const GearsShortcutData2& shortcut_data, bool success) {
189 if (contents_)
190 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
191 delete this;
192 }
193 void Cancel() {
194 contents_ = NULL;
195 }
196
197 private:
198 TabContents* contents_;
199};
200
[email protected]57c6a652009-05-04 07:58:34201// TODO(brettw) many of the data members here have casts to TabContents.
202// This object is the same as TabContents and is currently being merged.
[email protected]fdd61c62009-04-22 19:22:57203// When this merge is done, the casts can be removed.
[email protected]420ae012009-04-24 05:16:32204TabContents::TabContents(Profile* profile,
205 SiteInstance* site_instance,
206 int routing_id,
207 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42208 : delegate_(NULL),
[email protected]ce3fa3c2009-04-20 19:55:57209 controller_(this, profile),
[email protected]57c6a652009-05-04 07:58:34210 view_(TabContentsView::Create(static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57211 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(
[email protected]57c6a652009-05-04 07:58:34212 static_cast<TabContents*>(this),
213 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57214 property_bag_(),
215 registrar_(),
[email protected]57c6a652009-05-04 07:58:34216 printing_(*static_cast<TabContents*>(this)),
[email protected]fdd61c62009-04-22 19:22:57217 save_package_(),
218 cancelable_consumer_(),
219 autofill_manager_(),
220 password_manager_(),
221 plugin_installer_(),
222 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(
[email protected]57c6a652009-05-04 07:58:34223 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57224 select_file_dialog_(),
225 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34226 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29227 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34228 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34229 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57230 current_load_start_(),
231 load_state_(net::LOAD_STATE_IDLE),
232 load_state_host_(),
233 received_page_title_(false),
234 is_starred_(false),
235 contents_mime_type_(),
236 encoding_(),
237 download_shelf_(),
238 shelf_visible_(false),
[email protected]332af7732009-03-11 13:21:35239 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57240 infobar_delegates_(),
241 last_download_shelf_show_(),
242 find_ui_active_(false),
243 find_op_aborted_(false),
244 current_find_request_id_(find_request_id_counter_++),
245 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12246 last_search_case_sensitive_(false),
247 last_search_prepopulate_text_(NULL),
248 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57249 capturing_contents_(false),
250 is_being_destroyed_(false),
251 notify_disconnection_(false),
252 history_requests_(),
253#if defined(OS_WIN)
254 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
255#endif
256 last_javascript_message_dismissal_(),
257 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32258 pending_install_.page_id = 0;
259 pending_install_.callback_functor = NULL;
260
261 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
262
263 view_->CreateView();
264
265 // Register for notifications about all interested prefs change.
266 PrefService* prefs = profile->GetPrefs();
267 if (prefs) {
268 for (int i = 0; i < kPrefsToObserveLength; ++i)
269 prefs->AddPrefObserver(kPrefsToObserve[i], this);
270 }
271
272 // Register for notifications about URL starredness changing on any profile.
273 registrar_.Add(this, NotificationType::URLS_STARRED,
274 NotificationService::AllSources());
275 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
276 NotificationService::AllSources());
277 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
278 NotificationService::AllSources());
279
280 // Keep a global copy of the previous search string (if any).
281 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12282 last_search_prepopulate_text_ = &global_last_search;
[email protected]332af7732009-03-11 13:21:35283}
initial.commit09911bf2008-07-26 23:55:29284
285TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32286 is_being_destroyed_ = true;
287
288 // We don't want any notifications while we're runnign our destructor.
289 registrar_.RemoveAll();
290
291 // Unregister the notifications of all observed prefs change.
292 PrefService* prefs = profile()->GetPrefs();
293 if (prefs) {
294 for (int i = 0; i < kPrefsToObserveLength; ++i)
295 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
296 }
297
298 // Clean up subwindows like plugins and the find in page bar.
299 view_->OnContentsDestroy();
300
301 NotifyDisconnected();
[email protected]8897c382009-05-06 17:53:26302 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:32303
304 if (pending_install_.callback_functor)
305 pending_install_.callback_functor->Cancel();
306
307 // First cleanly close all child windows.
308 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
309 // some of these to close. CloseWindows is async, so it might get called
310 // twice before it runs.
311 int size = static_cast<int>(child_windows_.size());
312 for (int i = size - 1; i >= 0; --i) {
313 ConstrainedWindow* window = child_windows_[i];
314 if (window)
315 window->CloseConstrainedWindow();
316 }
317
[email protected]420ae012009-04-24 05:16:32318 // Notify any observer that have a reference on this tab contents.
319 NotificationService::current()->Notify(
320 NotificationType::TAB_CONTENTS_DESTROYED,
321 Source<TabContents>(this),
322 NotificationService::NoDetails());
323
[email protected]1e5e74f2009-05-27 20:55:12324 // Notify any lasting InfobarDelegates that have not yet been removed that
325 // whatever infobar they were handling in this TabContents has closed,
326 // because the TabContents is going away entirely.
327 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
328 // notification may trigger infobars calls that access their delegate. (and
329 // some implementations of InfoBarDelegate do delete themselves on
330 // InfoBarClosed()).
331 for (int i = 0; i < infobar_delegate_count(); ++i) {
332 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
333 delegate->InfoBarClosed();
334 }
335 infobar_delegates_.clear();
336
[email protected]420ae012009-04-24 05:16:32337 // TODO(brettw) this should be moved to the view.
338#if defined(OS_WIN)
339 // If we still have a window handle, destroy it. GetNativeView can return
340 // NULL if this contents was part of a window that closed.
341 if (GetNativeView())
342 ::DestroyWindow(GetNativeView());
343#endif
initial.commit09911bf2008-07-26 23:55:29344}
345
[email protected]d5f942ba2008-09-26 19:30:34346// static
347void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32348 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
349
350 WebPreferences pref_defaults;
351 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
352 pref_defaults.javascript_enabled);
353 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
354 pref_defaults.web_security_enabled);
355 prefs->RegisterBooleanPref(
356 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
357 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
358 pref_defaults.loads_images_automatically);
359 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
360 pref_defaults.plugins_enabled);
361 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
362 pref_defaults.dom_paste_enabled);
363 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
364 pref_defaults.shrinks_standalone_images_to_fit);
365 prefs->RegisterBooleanPref(prefs::kWebKitDeveloperExtrasEnabled,
[email protected]96d3fb52009-05-27 14:51:21366 pref_defaults.developer_extras_enabled);
[email protected]420ae012009-04-24 05:16:32367 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
368 pref_defaults.text_areas_are_resizable);
369 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
370 pref_defaults.java_enabled);
371
372 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
373 IDS_ACCEPT_LANGUAGES);
374 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
375 IDS_DEFAULT_ENCODING);
376 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
377 IDS_STANDARD_FONT_IS_SERIF);
378 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
379 IDS_FIXED_FONT_FAMILY);
380 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
381 IDS_SERIF_FONT_FAMILY);
382 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
383 IDS_SANS_SERIF_FONT_FAMILY);
384 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
385 IDS_CURSIVE_FONT_FAMILY);
386 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
387 IDS_FANTASY_FONT_FAMILY);
388 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
389 IDS_DEFAULT_FONT_SIZE);
390 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
391 IDS_DEFAULT_FIXED_FONT_SIZE);
392 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
393 IDS_MINIMUM_FONT_SIZE);
394 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
395 IDS_MINIMUM_LOGICAL_FONT_SIZE);
396 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
397 IDS_USES_UNIVERSAL_DETECTOR);
398 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
399 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29400}
401
[email protected]d5f942ba2008-09-26 19:30:34402bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01403 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55404 return true;
[email protected]d5f942ba2008-09-26 19:30:34405}
406
[email protected]6e95706d2009-04-23 22:55:01407AutofillManager* TabContents::GetAutofillManager() {
408 if (autofill_manager_.get() == NULL)
409 autofill_manager_.reset(new AutofillManager(this));
410 return autofill_manager_.get();
411}
412
413PasswordManager* TabContents::GetPasswordManager() {
414 if (password_manager_.get() == NULL)
415 password_manager_.reset(new PasswordManager(this));
416 return password_manager_.get();
417}
418
419PluginInstaller* TabContents::GetPluginInstaller() {
420 if (plugin_installer_.get() == NULL)
421 plugin_installer_.reset(new PluginInstaller(this));
422 return plugin_installer_.get();
423}
424
[email protected]d5f942ba2008-09-26 19:30:34425const GURL& TabContents::GetURL() const {
426 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57427 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34428 return entry ? entry->display_url() : GURL::EmptyGURL();
429}
430
[email protected]96d185d2009-04-24 03:28:54431const string16& TabContents::GetTitle() const {
432 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
433 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
434 if (our_dom_ui) {
435 // Don't override the title in view source mode.
436 NavigationEntry* entry = controller_.GetActiveEntry();
437 if (!(entry && entry->IsViewSourceMode())) {
438 // Give the DOM UI the chance to override our title.
439 const string16& title = our_dom_ui->overridden_title();
440 if (!title.empty())
441 return title;
442 }
443 }
444
445 // We use the title for the last committed entry rather than a pending
446 // navigation entry. For example, when the user types in a URL, we want to
447 // keep the old page's title until the new load has committed and we get a new
448 // title.
449 // The exception is with transient pages, for which we really want to use
450 // their title, as they are not committed.
451 NavigationEntry* entry = controller_.GetTransientEntry();
452 if (entry)
453 return entry->GetTitleForDisplay(&controller_);
454
455 entry = controller_.GetLastCommittedEntry();
456 if (entry)
457 return entry->GetTitleForDisplay(&controller_);
458 else if (controller_.LoadingURLLazily())
459 return controller_.GetLazyTitle();
460 return EmptyString16();
461}
462
[email protected]d5f942ba2008-09-26 19:30:34463int32 TabContents::GetMaxPageID() {
464 if (GetSiteInstance())
465 return GetSiteInstance()->max_page_id();
466 else
467 return max_page_id_;
468}
469
470void TabContents::UpdateMaxPageID(int32 page_id) {
471 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34472 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34473 // testing.
474 if (GetSiteInstance())
475 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34476 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34477}
478
[email protected]96d185d2009-04-24 03:28:54479SiteInstance* TabContents::GetSiteInstance() const {
480 return render_manager_.current_host()->site_instance();
481}
482
[email protected]d5f942ba2008-09-26 19:30:34483const std::wstring TabContents::GetDefaultTitle() const {
484 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
485}
486
[email protected]96d185d2009-04-24 03:28:54487bool TabContents::ShouldDisplayURL() {
488 // Don't hide the url in view source mode.
489 NavigationEntry* entry = controller_.GetActiveEntry();
490 if (entry && entry->IsViewSourceMode())
491 return true;
492 DOMUI* dom_ui = GetDOMUIForCurrentState();
493 if (dom_ui)
494 return !dom_ui->should_hide_url();
495 return true;
496}
497
[email protected]d5f942ba2008-09-26 19:30:34498SkBitmap TabContents::GetFavIcon() const {
499 // Like GetTitle(), we also want to use the favicon for the last committed
500 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57501 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47502 if (entry)
503 return entry->favicon().bitmap();
504
[email protected]ce3fa3c2009-04-20 19:55:57505 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34506 if (entry)
507 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57508 else if (controller_.LoadingURLLazily())
509 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34510 return SkBitmap();
511}
512
[email protected]96d185d2009-04-24 03:28:54513bool TabContents::ShouldDisplayFavIcon() {
514 // Always display a throbber during pending loads.
515 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
516 return true;
517
518 DOMUI* dom_ui = GetDOMUIForCurrentState();
519 if (dom_ui)
520 return !dom_ui->hide_favicon();
521 return true;
522}
523
[email protected]3e45ba92009-02-20 21:09:00524#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34525SecurityStyle TabContents::GetSecurityStyle() const {
526 // We may not have a navigation entry yet.
[email protected]ce3fa3c2009-04-20 19:55:57527 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34528 return entry ? entry->ssl().security_style() : SECURITY_STYLE_UNKNOWN;
529}
530
531bool TabContents::GetSSLEVText(std::wstring* ev_text,
532 std::wstring* ev_tooltip_text) const {
533 DCHECK(ev_text && ev_tooltip_text);
534 ev_text->clear();
535 ev_tooltip_text->clear();
536
[email protected]ce3fa3c2009-04-20 19:55:57537 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34538 if (!entry ||
539 net::IsCertStatusError(entry->ssl().cert_status()) ||
540 ((entry->ssl().cert_status() & net::CERT_STATUS_IS_EV) == 0))
541 return false;
542
543 scoped_refptr<net::X509Certificate> cert;
544 CertStore::GetSharedInstance()->RetrieveCert(entry->ssl().cert_id(), &cert);
545 if (!cert.get()) {
546 NOTREACHED();
547 return false;
548 }
549
550 return SSLManager::GetEVCertNames(*cert, ev_text, ev_tooltip_text);
551}
[email protected]76f68dc2009-03-10 20:31:32552#endif
[email protected]d5f942ba2008-09-26 19:30:34553
[email protected]96d185d2009-04-24 03:28:54554std::wstring TabContents::GetStatusText() const {
555 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
556 return std::wstring();
557
558 switch (load_state_) {
559 case net::LOAD_STATE_WAITING_FOR_CACHE:
560 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
561 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
562 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
563 case net::LOAD_STATE_RESOLVING_HOST:
564 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
565 case net::LOAD_STATE_CONNECTING:
566 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
567 case net::LOAD_STATE_SENDING_REQUEST:
568 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
569 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
570 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
571 load_state_host_);
572 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
573 case net::LOAD_STATE_IDLE:
574 case net::LOAD_STATE_READING_RESPONSE:
575 break;
576 }
577
578 return std::wstring();
579}
580
[email protected]d5f942ba2008-09-26 19:30:34581void TabContents::SetIsCrashed(bool state) {
582 if (state == is_crashed_)
583 return;
584
585 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50586 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34587}
588
[email protected]ce5c4502009-05-06 16:46:11589void TabContents::EnablePageAction(const PageAction* page_action) {
590 DCHECK(page_action);
591
592 if (IsPageActionEnabled(page_action))
593 return; // Already enabled.
594
595 enabled_page_actions_.insert(page_action);
596}
597
598bool TabContents::IsPageActionEnabled(const PageAction* page_action) {
599 DCHECK(page_action);
600 return enabled_page_actions_.end() != enabled_page_actions_.find(page_action);
601}
602
603
[email protected]d5f942ba2008-09-26 19:30:34604void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
605 if (delegate_)
606 delegate_->NavigationStateChanged(this, changed_flags);
607}
608
[email protected]96d185d2009-04-24 03:28:54609void TabContents::DidBecomeSelected() {
610 controller_.SetActive(true);
611
612 if (render_widget_host_view())
613 render_widget_host_view()->DidBecomeSelected();
614
615 // If pid() is -1, that means the RenderProcessHost still hasn't been
616 // initialized. It'll register with CacheManagerHost when it is.
617 if (process()->pid() != -1)
618 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
619}
620
621void TabContents::WasHidden() {
622 if (!capturing_contents()) {
623 // |render_view_host()| can be NULL if the user middle clicks a link to open
624 // a tab in then background, then closes the tab before selecting it. This
625 // is because closing the tab calls TabContents::Destroy(), which removes
626 // the |render_view_host()|; then when we actually destroy the window,
627 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
628 if (render_widget_host_view())
629 render_widget_host_view()->WasHidden();
630
631 // Loop through children and send WasHidden to them, too.
632 int count = static_cast<int>(child_windows_.size());
633 for (int i = count - 1; i >= 0; --i) {
634 ConstrainedWindow* window = child_windows_.at(i);
635 window->WasHidden();
636 }
637 }
638
639 NotificationService::current()->Notify(
640 NotificationType::TAB_CONTENTS_HIDDEN,
641 Source<TabContents>(this),
642 NotificationService::NoDetails());
643}
644
[email protected]d5f942ba2008-09-26 19:30:34645void TabContents::Activate() {
646 if (delegate_)
647 delegate_->ActivateContents(this);
648}
649
[email protected]96d185d2009-04-24 03:28:54650void TabContents::ShowContents() {
651 if (render_widget_host_view())
652 render_widget_host_view()->DidBecomeSelected();
653
654 // Loop through children and send DidBecomeSelected to them, too.
655 int count = static_cast<int>(child_windows_.size());
656 for (int i = count - 1; i >= 0; --i) {
657 ConstrainedWindow* window = child_windows_.at(i);
658 window->DidBecomeSelected();
659 }
660}
661
662void TabContents::HideContents() {
663 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
664 // our superclass HideContents(), because some callers want to be very picky
665 // about the order in which these get called. In addition to making the code
666 // here practically impossible to understand, this also means we end up
667 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34668 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54669 WasHidden();
670}
671
[email protected]c0588052008-10-27 23:01:50672void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34673 WindowOpenDisposition disposition,
674 PageTransition::Type transition) {
675 if (delegate_)
[email protected]c0588052008-10-27 23:01:50676 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34677}
678
679bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54680 const NavigationEntry& entry = *controller_.pending_entry();
681
682 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
683 if (!dest_render_view_host)
684 return false; // Unable to create the desired render view host.
685
686 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]684b4ba22009-05-07 06:27:41687 DevToolsManager* devtools_manager = g_browser_process->devtools_manager();
[email protected]7e8e6b62009-05-08 11:28:32688 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41689 devtools_manager->OnNavigatingToPendingEntry(
690 render_view_host(),
691 dest_render_view_host,
692 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32693 }
[email protected]96d185d2009-04-24 03:28:54694
695 // Used for page load time metrics.
696 current_load_start_ = base::TimeTicks::Now();
697
698 // Navigate in the desired RenderViewHost.
699 dest_render_view_host->NavigateToEntry(entry, reload);
700
701 if (entry.page_id() == -1) {
702 // HACK!! This code suppresses javascript: URLs from being added to
703 // session history, which is what we want to do for javascript: URLs that
704 // do not generate content. What we really need is a message from the
705 // renderer telling us that a new page was not created. The same message
706 // could be used for mailto: URLs and the like.
707 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
708 return false;
709 }
710
711 // Clear any provisional password saves - this stops password infobars
712 // showing up on pages the user navigates to while the right page is
713 // loading.
714 GetPasswordManager()->ClearProvisionalSave();
715
716 if (reload && !profile()->IsOffTheRecord()) {
717 HistoryService* history =
718 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
719 if (history)
720 history->SetFavIconOutOfDateForPage(entry.url());
721 }
722
[email protected]d5f942ba2008-09-26 19:30:34723 return true;
724}
725
[email protected]96d185d2009-04-24 03:28:54726void TabContents::Stop() {
727 render_manager_.Stop();
728 printing_.Stop();
729}
730
731void TabContents::Cut() {
732 render_view_host()->Cut();
733}
734
735void TabContents::Copy() {
736 render_view_host()->Copy();
737}
738
739void TabContents::Paste() {
740 render_view_host()->Paste();
741}
742
743void TabContents::DisassociateFromPopupCount() {
744 render_view_host()->DisassociateFromPopupCount();
745}
746
747TabContents* TabContents::Clone() {
748 // We create a new SiteInstance so that the new tab won't share processes
749 // with the old one. This can be changed in the future if we need it to share
750 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32751 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54752 SiteInstance::CreateSiteInstance(profile()),
753 MSG_ROUTING_NONE, NULL);
754 tc->controller().CopyStateFrom(controller_);
755 return tc;
756}
757
[email protected]420ae012009-04-24 05:16:32758void TabContents::CreateShortcut() {
759 NavigationEntry* entry = controller_.GetLastCommittedEntry();
760 if (!entry)
761 return;
762
763 // We only allow one pending install request. By resetting the page id we
764 // effectively cancel the pending install request.
765 pending_install_.page_id = entry->page_id();
766 pending_install_.icon = GetFavIcon();
767 pending_install_.title = UTF16ToWideHack(GetTitle());
768 pending_install_.url = GetURL();
769 if (pending_install_.callback_functor) {
770 pending_install_.callback_functor->Cancel();
771 pending_install_.callback_functor = NULL;
772 }
773 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
774 if (pending_install_.title.empty())
775 pending_install_.title = UTF8ToWide(GetURL().spec());
776
777 // Request the application info. When done OnDidGetApplicationInfo is invoked
778 // and we'll create the shortcut.
779 render_view_host()->GetApplicationInfo(pending_install_.page_id);
780}
781
[email protected]76f68dc2009-03-10 20:31:32782#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29783ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]c2dacc92008-10-16 23:51:38784 views::WindowDelegate* window_delegate,
785 views::View* contents_view) {
initial.commit09911bf2008-07-26 23:55:29786 ConstrainedWindow* window =
787 ConstrainedWindow::CreateConstrainedDialog(
788 this, gfx::Rect(), contents_view, window_delegate);
789 child_windows_.push_back(window);
790 return window;
791}
[email protected]f3332e12009-03-23 15:28:57792#endif
initial.commit09911bf2008-07-26 23:55:29793
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]f3332e12009-03-23 15:28:57802#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:22803 bool constrain_popup = false;
[email protected]35f7d212009-04-29 21:19:27804 if ((disposition == NEW_POPUP) && !user_gesture &&
805 !CommandLine::ForCurrentProcess()->HasSwitch(
806 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22807 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31808 // the whitelist. The popup owner will handle checking this.
809 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
810 initial_pos,
811 creator_url.is_valid() ? creator_url.host() : std::string());
812 } else {
[email protected]0aa55312008-10-17 21:53:08813 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29814 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
815 user_gesture);
816 }
[email protected]b6c874582009-05-08 19:38:31817 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
[email protected]f3332e12009-03-23 15:28:57818#else
819 // TODO(port): implement the popup blocker stuff
820 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
821 user_gesture);
822#endif
initial.commit09911bf2008-07-26 23:55:29823}
824
[email protected]f3332e12009-03-23 15:28:57825#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29826void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25827 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22828 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29829}
[email protected]332af7732009-03-11 13:21:35830#endif
initial.commit09911bf2008-07-26 23:55:29831
[email protected]96d185d2009-04-24 03:28:54832void TabContents::PopupNotificationVisibilityChanged(bool visible) {
833 render_view_host()->PopupNotificationVisibilityChanged(visible);
834}
835
836gfx::NativeView TabContents::GetContentNativeView() {
837 return view_->GetContentNativeView();
838}
839
840gfx::NativeView TabContents::GetNativeView() const {
841 return view_->GetNativeView();
842}
843
844void TabContents::GetContainerBounds(gfx::Rect *out) const {
845 view_->GetContainerBounds(out);
846}
847
848void TabContents::Focus() {
849 view_->Focus();
850}
851
852void TabContents::SetInitialFocus(bool reverse) {
853 render_view_host()->SetInitialFocus(reverse);
854}
855
856bool TabContents::FocusLocationBarByDefault() {
857 DOMUI* dom_ui = GetDOMUIForCurrentState();
858 if (dom_ui)
859 return dom_ui->focus_location_bar_by_default();
860 return false;
861}
862
[email protected]616ed5a2008-11-21 22:27:24863void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
864 // Look through the existing InfoBarDelegates we have for a match. If we've
865 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05866 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24867 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
868 return;
869 }
870
871 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56872 NotificationService::current()->Notify(
873 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
874 Source<TabContents>(this),
875 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24876
877 // Add ourselves as an observer for navigations the first time a delegate is
878 // added. We use this notification to expire InfoBars that need to expire on
879 // page transitions.
880 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56881 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57882 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24883 }
884}
885
886void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
887 std::vector<InfoBarDelegate*>::iterator it =
888 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
889 if (it != infobar_delegates_.end()) {
890 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56891 NotificationService::current()->Notify(
892 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
893 Source<TabContents>(this),
894 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05895 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24896
[email protected]6a02963e2009-01-06 16:58:03897 // Remove ourselves as an observer if we are tracking no more InfoBars.
898 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56899 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57900 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03901 }
[email protected]616ed5a2008-11-21 22:27:24902 }
903}
[email protected]3edd9522009-03-04 22:19:41904
[email protected]96d185d2009-04-24 03:28:54905bool TabContents::IsBookmarkBarAlwaysVisible() {
906 // See GetDOMUIForCurrentState() comment for more info. This case is very
907 // similar, but for non-first loads, we want to use the committed entry. This
908 // is so the bookmarks bar disappears at the same time the page does.
909 if (controller_.GetLastCommittedEntry()) {
910 // Not the first load, always use the committed DOM UI.
911 if (render_manager_.dom_ui())
912 return render_manager_.dom_ui()->force_bookmark_bar_visible();
913 return false; // Default.
914 }
915
916 // When it's the first load, we know either the pending one or the committed
917 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
918 // of them will be valid, so we can just check both.
919 if (render_manager_.pending_dom_ui())
920 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
921 if (render_manager_.dom_ui())
922 return render_manager_.dom_ui()->force_bookmark_bar_visible();
923 return false; // Default.
924}
925
926void TabContents::SetDownloadShelfVisible(bool visible) {
927 if (shelf_visible_ != visible) {
928 if (visible) {
929 // Invoke GetDownloadShelf to force the shelf to be created.
[email protected]0a2aeb82009-05-15 21:52:48930 GetDownloadShelf(true);
[email protected]96d185d2009-04-24 03:28:54931 }
932 shelf_visible_ = visible;
933
[email protected]c9cd2222009-05-06 05:16:50934 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]3a6a3b62009-05-27 21:36:20935
936 if (delegate())
937 delegate()->UpdateDownloadShelfVisibility(visible);
[email protected]96d185d2009-04-24 03:28:54938 }
939
940 // SetShelfVisible can force-close the shelf, so make sure we lay out
941 // everything correctly, as if the animation had finished. This doesn't
942 // matter for showing the shelf, as the show animation will do it.
943 ToolbarSizeChanged(false);
944
945 if (visible) {
946 // Always set this value as it reflects the last time the download shelf
947 // was made visible (even if it was already visible).
948 last_download_shelf_show_ = base::TimeTicks::Now();
949 }
950}
951
[email protected]3edd9522009-03-04 22:19:41952void TabContents::ToolbarSizeChanged(bool is_animating) {
953 TabContentsDelegate* d = delegate();
954 if (d)
955 d->ToolbarSizeChanged(this, is_animating);
956}
[email protected]616ed5a2008-11-21 22:27:24957
[email protected]d5f942ba2008-09-26 19:30:34958void TabContents::OnStartDownload(DownloadItem* download) {
959 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34960
961 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31962 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34963
[email protected]bcef0dc02009-02-28 00:35:02964 // GetDownloadShelf creates the download shelf if it was not yet created.
[email protected]0a2aeb82009-05-15 21:52:48965 tab_contents->GetDownloadShelf(true)->AddDownload(
[email protected]bcef0dc02009-02-28 00:35:02966 new DownloadItemModel(download));
[email protected]d5f942ba2008-09-26 19:30:34967 tab_contents->SetDownloadShelfVisible(true);
968
[email protected]bd1ad682009-05-15 22:19:17969// TODO(port): port for mac.
970#if defined(OS_WIN) || defined(OS_LINUX)
971 // We make this check for the case of minimized windows, unit tests, etc.
972 if (platform_util::IsVisible(GetNativeView())) {
973 DownloadStartedAnimation::Show(tab_contents);
[email protected]d5f942ba2008-09-26 19:30:34974 }
[email protected]3edd9522009-03-04 22:19:41975#endif
[email protected]d5f942ba2008-09-26 19:30:34976}
977
[email protected]0a2aeb82009-05-15 21:52:48978DownloadShelf* TabContents::GetDownloadShelf(bool create) {
979 if (!download_shelf_.get() && create)
[email protected]bcef0dc02009-02-28 00:35:02980 download_shelf_.reset(DownloadShelf::Create(this));
981 return download_shelf_.get();
initial.commit09911bf2008-07-26 23:55:29982}
983
[email protected]bcef0dc02009-02-28 00:35:02984void TabContents::MigrateShelfFrom(TabContents* tab_contents) {
[email protected]0a2aeb82009-05-15 21:52:48985 download_shelf_.reset(tab_contents->GetDownloadShelf(true));
[email protected]bcef0dc02009-02-28 00:35:02986 download_shelf_->ChangeTabContents(tab_contents, this);
987 tab_contents->ReleaseDownloadShelf();
initial.commit09911bf2008-07-26 23:55:29988}
989
[email protected]3edd9522009-03-04 22:19:41990void TabContents::ReleaseDownloadShelf() {
991 download_shelf_.release();
992}
993
994// static
995void TabContents::MigrateShelf(TabContents* from, TabContents* to) {
996 bool was_shelf_visible = from->IsDownloadShelfVisible();
997 if (was_shelf_visible)
998 to->MigrateShelfFrom(from);
999 to->SetDownloadShelfVisible(was_shelf_visible);
1000}
[email protected]3edd9522009-03-04 22:19:411001
[email protected]d5f942ba2008-09-26 19:30:341002void TabContents::WillClose(ConstrainedWindow* window) {
1003 ConstrainedWindowList::iterator it =
1004 find(child_windows_.begin(), child_windows_.end(), window);
1005 if (it != child_windows_.end())
1006 child_windows_.erase(it);
1007
[email protected]332af7732009-03-11 13:21:351008#if defined(OS_WIN)
[email protected]d6598c052008-11-05 19:03:251009 if (window == blocked_popups_)
1010 blocked_popups_ = NULL;
1011
[email protected]92edc472009-02-10 20:32:061012 if (::IsWindow(GetNativeView())) {
[email protected]d5f942ba2008-09-26 19:30:341013 CRect client_rect;
[email protected]92edc472009-02-10 20:32:061014 GetClientRect(GetNativeView(), &client_rect);
[email protected]d5f942ba2008-09-26 19:30:341015 RepositionSupressedPopupsToFit(
1016 gfx::Size(client_rect.Width(), client_rect.Height()));
1017 }
[email protected]332af7732009-03-11 13:21:351018#endif
[email protected]d5f942ba2008-09-26 19:30:341019}
1020
[email protected]d5f942ba2008-09-26 19:30:341021void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:351022#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:061023 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:351024#endif
[email protected]d5f942ba2008-09-26 19:30:341025}
1026
[email protected]e491f1c2009-05-22 20:28:121027void TabContents::StartFinding(string16 find_text,
1028 bool forward_direction,
1029 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:011030 // If find_text is empty, it means FindNext was pressed with a keyboard
1031 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:121032 if (find_text.empty() && find_text_.empty()) {
1033 if (last_search_prepopulate_text_->empty())
1034 return;
1035 // Try whatever we searched for last in any tab.
1036 find_text = *last_search_prepopulate_text_;
1037 }
[email protected]6e95706d2009-04-23 22:55:011038
1039 // This is a FindNext operation if we are searching for the same text again,
1040 // or if the passed in search text is empty (FindNext keyboard shortcut). The
1041 // exception to this is if the Find was aborted (then we don't want FindNext
1042 // because the highlighting has been cleared and we need it to reappear). We
1043 // therefore treat FindNext after an aborted Find operation as a full fledged
1044 // Find.
1045 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:121046 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:011047 !find_op_aborted_;
1048 if (!find_next)
1049 current_find_request_id_ = find_request_id_counter_++;
1050
1051 if (!find_text.empty())
1052 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:121053 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:011054
1055 find_op_aborted_ = false;
1056
1057 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:121058 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:011059
1060 render_view_host()->StartFinding(current_find_request_id_,
1061 find_text_,
1062 forward_direction,
[email protected]e491f1c2009-05-22 20:28:121063 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:011064 find_next);
1065}
1066
1067void TabContents::StopFinding(bool clear_selection) {
1068 find_ui_active_ = false;
1069 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:121070 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:011071 render_view_host()->StopFinding(clear_selection);
1072}
1073
[email protected]420ae012009-04-24 05:16:321074void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
1075 bool success,
1076 const std::wstring& prompt) {
1077 last_javascript_message_dismissal_ = base::TimeTicks::Now();
1078 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
1079}
1080
[email protected]571e31152009-05-15 19:34:021081void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
1082 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
1083}
1084
[email protected]420ae012009-04-24 05:16:321085void TabContents::OnSavePage() {
1086 // If we can not save the page, try to download it.
1087 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1088 DownloadManager* dlm = profile()->GetDownloadManager();
1089 const GURL& current_page_url = GetURL();
1090 if (dlm && current_page_url.is_valid())
[email protected]c9825a42009-05-01 22:51:501091 dlm->DownloadUrl(current_page_url, GURL(), "", AsWC(this));
[email protected]420ae012009-04-24 05:16:321092 return;
1093 }
1094
1095 Stop();
1096
1097 // Create the save package and possibly prompt the user for the name to save
1098 // the page as. The user prompt is an asynchronous operation that runs on
1099 // another thread.
1100 save_package_ = new SavePackage(AsWC(this));
1101 save_package_->GetSaveInfo();
1102}
1103
1104// Used in automated testing to bypass prompting the user for file names.
1105// Instead, the names and paths are hard coded rather than running them through
1106// file name sanitation and extension / mime checking.
1107void TabContents::SavePage(const std::wstring& main_file,
1108 const std::wstring& dir_path,
1109 SavePackage::SavePackageType save_type) {
1110 // Stop the page from navigating.
1111 Stop();
1112
1113 save_package_ = new SavePackage(AsWC(this), save_type,
1114 FilePath::FromWStringHack(main_file),
1115 FilePath::FromWStringHack(dir_path));
1116 save_package_->Init();
1117}
1118
1119void TabContents::PrintPreview() {
1120 // We don't show the print preview yet, only the print dialog.
1121 PrintNow();
1122}
1123
1124bool TabContents::PrintNow() {
1125 // We can't print interstitial page for now.
1126 if (showing_interstitial_page())
1127 return false;
1128
1129 return render_view_host()->PrintPages();
1130}
1131
1132bool TabContents::IsActiveEntry(int32 page_id) {
1133 NavigationEntry* active_entry = controller_.GetActiveEntry();
1134 return (active_entry != NULL &&
1135 active_entry->site_instance() == GetSiteInstance() &&
1136 active_entry->page_id() == page_id);
1137}
1138
[email protected]96d185d2009-04-24 03:28:541139// Notifies the RenderWidgetHost instance about the fact that the page is
1140// loading, or done loading and calls the base implementation.
1141void TabContents::SetIsLoading(bool is_loading,
1142 LoadNotificationDetails* details) {
1143 if (is_loading == is_loading_)
1144 return;
1145
1146 if (!is_loading) {
1147 load_state_ = net::LOAD_STATE_IDLE;
1148 load_state_host_.clear();
1149 }
1150
1151 render_manager_.SetIsLoading(is_loading);
1152
1153 is_loading_ = is_loading;
1154 waiting_for_response_ = is_loading;
1155
1156 if (delegate_)
1157 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351158 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541159
1160 NotificationType type = is_loading ? NotificationType::LOAD_START :
1161 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111162 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541163 if (details)
1164 det = Details<LoadNotificationDetails>(details);
1165 NotificationService::current()->Notify(type,
1166 Source<NavigationController>(&controller_),
1167 det);
1168}
1169
[email protected]76f68dc2009-03-10 20:31:321170#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:221171void TabContents::CreateBlockedPopupContainerIfNecessary() {
1172 if (blocked_popups_)
1173 return;
1174
1175 CRect client_rect;
1176 GetClientRect(GetNativeView(), &client_rect);
1177 gfx::Point anchor_position(
1178 client_rect.Width() - views::NativeScrollBar::GetVerticalScrollBarWidth(),
1179 client_rect.Height());
1180 blocked_popups_ = BlockedPopupContainer::Create(this, profile(),
1181 anchor_position);
1182 child_windows_.push_back(blocked_popups_);
1183}
1184
[email protected]b6c874582009-05-08 19:38:311185void TabContents::AddPopup(TabContents* new_contents,
1186 const gfx::Rect& initial_pos,
1187 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221188 CreateBlockedPopupContainerIfNecessary();
1189 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221190}
1191
[email protected]e69bce3dd2009-04-20 22:05:121192// TODO(brettw) This should be on the TabContentsView.
[email protected]d5f942ba2008-09-26 19:30:341193void TabContents::RepositionSupressedPopupsToFit(const gfx::Size& new_size) {
1194 // TODO(erg): There's no way to detect whether scroll bars are
1195 // visible, so for beta, we're just going to assume that the
1196 // vertical scroll bar is visible, and not care about covering up
1197 // the horizontal scroll bar. Fixing this is half of
1198 // http://b/1118139.
1199 gfx::Point anchor_position(
1200 new_size.width() -
[email protected]c2dacc92008-10-16 23:51:381201 views::NativeScrollBar::GetVerticalScrollBarWidth(),
[email protected]d5f942ba2008-09-26 19:30:341202 new_size.height());
[email protected]d6598c052008-11-05 19:03:251203
1204 if (blocked_popups_)
1205 blocked_popups_->RepositionConstrainedWindowTo(anchor_position);
[email protected]d5f942ba2008-09-26 19:30:341206}
1207
[email protected]b9681312008-11-07 00:08:261208bool TabContents::ShowingBlockedPopupNotification() const {
1209 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221210 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261211}
[email protected]332af7732009-03-11 13:21:351212#endif // defined(OS_WIN)
[email protected]616ed5a2008-11-21 22:27:241213
1214namespace {
1215bool TransitionIsReload(PageTransition::Type transition) {
1216 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1217}
1218}
1219
1220void TabContents::ExpireInfoBars(
1221 const NavigationController::LoadCommittedDetails& details) {
1222 // Only hide InfoBars when the user has done something that makes the main
1223 // frame load. We don't want various automatic or subframe navigations making
1224 // it disappear.
1225 if (!details.is_user_initiated_main_frame_load())
1226 return;
1227
[email protected]f86a07022008-11-25 01:06:051228 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241229 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051230 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241231 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241232 }
1233}
[email protected]fdd61c62009-04-22 19:22:571234
1235void TabContents::OnGearsCreateShortcutDone(
1236 const GearsShortcutData2& shortcut_data, bool success) {
1237 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1238 bool same_page =
1239 current_entry && pending_install_.page_id == current_entry->page_id();
1240
1241 if (success && same_page) {
1242 // Only switch to app mode if the user chose to create a shortcut and
1243 // we're still on the same page that it corresponded to.
1244 if (delegate())
1245 delegate()->ConvertContentsToApplication(this);
1246 }
1247
1248 // Reset the page id to indicate no requests are pending.
1249 pending_install_.page_id = 0;
1250 pending_install_.callback_functor = NULL;
1251}
[email protected]96d185d2009-04-24 03:28:541252
1253DOMUI* TabContents::GetDOMUIForCurrentState() {
1254 // When there is a pending navigation entry, we want to use the pending DOMUI
1255 // that goes along with it to control the basic flags. For example, we want to
1256 // show the pending URL in the URL bar, so we want the display_url flag to
1257 // be from the pending entry.
1258 //
1259 // The confusion comes because there are multiple possibilities for the
1260 // initial load in a tab as a side effect of the way the RenderViewHostManager
1261 // works.
1262 //
1263 // - For the very first tab the load looks "normal". The new tab DOM UI is
1264 // the pending one, and we want it to apply here.
1265 //
1266 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1267 // get switched to the one previously associated with the new tab pages.
1268 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1269 // have a committed DOM UI in this case.
1270 //
1271 // This condition handles all of these cases:
1272 //
1273 // - First load in first tab: no committed nav entry + pending nav entry +
1274 // pending dom ui:
1275 // -> Use pending DOM UI if any.
1276 //
1277 // - First load in second tab: no committed nav entry + pending nav entry +
1278 // no pending DOM UI:
1279 // -> Use the committed DOM UI if any.
1280 //
1281 // - Second navigation in any tab: committed nav entry + pending nav entry:
1282 // -> Use pending DOM UI if any.
1283 //
1284 // - Normal state with no load: committed nav entry + no pending nav entry:
1285 // -> Use committed DOM UI.
1286 if (controller_.pending_entry() &&
1287 (controller_.GetLastCommittedEntry() ||
1288 render_manager_.pending_dom_ui()))
1289 return render_manager_.pending_dom_ui();
1290 return render_manager_.dom_ui();
1291}
[email protected]420ae012009-04-24 05:16:321292
1293void TabContents::DidNavigateMainFramePostCommit(
1294 const NavigationController::LoadCommittedDetails& details,
1295 const ViewHostMsg_FrameNavigate_Params& params) {
1296 // Hide the download shelf if all the following conditions are true:
1297 // - there are no active downloads.
1298 // - this is a navigation to a different TLD.
1299 // - at least 5 seconds have elapsed since the download shelf was shown.
1300 // TODO(jcampan): bug 1156075 when user gestures are reliable, they should
1301 // be used to ensure we are hiding only on user initiated
1302 // navigations.
1303 DownloadManager* download_manager = profile()->GetDownloadManager();
1304 // download_manager can be NULL in unit test context.
1305 if (download_manager && download_manager->in_progress_count() == 0 &&
1306 !details.previous_url.is_empty() &&
1307 !net::RegistryControlledDomainService::SameDomainOrHost(
1308 details.previous_url, details.entry->url())) {
1309 base::TimeDelta time_delta(
1310 base::TimeTicks::Now() - last_download_shelf_show_);
1311 if (time_delta >
1312 base::TimeDelta::FromMilliseconds(kDownloadShelfHideDelay)) {
1313 SetDownloadShelfVisible(false);
1314 }
1315 }
1316
1317 if (details.is_user_initiated_main_frame_load()) {
1318 // Clear the status bubble. This is a workaround for a bug where WebKit
1319 // doesn't let us know that the cursor left an element during a
1320 // transition (this is also why the mouse cursor remains as a hand after
1321 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1322 // clear the bubble when a user navigates to a named anchor in the same
1323 // page.
1324 UpdateTargetURL(details.entry->page_id(), GURL());
1325
1326 // UpdateHelpersForDidNavigate will handle the case where the password_form
1327 // origin is valid.
1328 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1329 // cleaned up and covered by tests.
1330 if (!params.password_form.origin.is_valid())
1331 GetPasswordManager()->DidNavigate();
1332 }
1333
1334 // The keyword generator uses the navigation entries, so must be called after
1335 // the commit.
1336 GenerateKeywordIfNecessary(params);
1337
1338 // Allow the new page to set the title again.
1339 received_page_title_ = false;
1340
1341 // Get the favicon, either from history or request it from the net.
1342 fav_icon_helper_.FetchFavIcon(details.entry->url());
1343
[email protected]ce5c4502009-05-06 16:46:111344 // Disable all page actions.
1345 enabled_page_actions_.clear();
1346
[email protected]420ae012009-04-24 05:16:321347 // Close constrained popups if necessary.
1348 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1349
1350 // Update the starred state.
1351 UpdateStarredStateForCurrentURL();
1352}
1353
1354void TabContents::DidNavigateAnyFramePostCommit(
1355 RenderViewHost* render_view_host,
1356 const NavigationController::LoadCommittedDetails& details,
1357 const ViewHostMsg_FrameNavigate_Params& params) {
1358 // If we navigate, start showing messages again. This does nothing to prevent
1359 // a malicious script from spamming messages, since the script could just
1360 // reload the page to stop blocking.
1361 suppress_javascript_messages_ = false;
1362
1363 // Update history. Note that this needs to happen after the entry is complete,
1364 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1365 if (params.should_update_history) {
1366 // Most of the time, the displayURL matches the loaded URL, but for about:
1367 // URLs, we use a data: URL as the real value. We actually want to save
1368 // the about: URL to the history db and keep the data: URL hidden. This is
1369 // what the TabContents' URL getter does.
1370 UpdateHistoryForNavigation(GetURL(), params);
1371 }
1372
1373 // Notify the password manager of the navigation or form submit.
1374 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1375 // cleaned up and covered by tests.
1376 if (params.password_form.origin.is_valid())
1377 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1378}
1379
1380void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1381 const GURL& current_url) {
1382 if (net::RegistryControlledDomainService::SameDomainOrHost(
1383 previous_url, current_url))
1384 return;
1385
1386 // Clear out any child windows since we are leaving this page entirely.
1387 // We use indices instead of iterators in case CloseWindow does something
1388 // that may invalidate an iterator.
1389 int size = static_cast<int>(child_windows_.size());
1390 for (int i = size - 1; i >= 0; --i) {
1391 ConstrainedWindow* window = child_windows_[i];
1392 if (window)
1393 window->CloseConstrainedWindow();
1394 }
1395}
1396
1397void TabContents::UpdateStarredStateForCurrentURL() {
1398 BookmarkModel* model = profile()->GetBookmarkModel();
1399 const bool old_state = is_starred_;
1400 is_starred_ = (model && model->IsBookmarked(GetURL()));
1401
1402 if (is_starred_ != old_state && delegate())
1403 delegate()->URLStarredChanged(this, is_starred_);
1404}
1405
1406void TabContents::UpdateAlternateErrorPageURL() {
1407 GURL url = GetAlternateErrorPageURL();
1408 render_view_host()->SetAlternateErrorPageURL(url);
1409}
1410
1411void TabContents::UpdateWebPreferences() {
1412 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1413}
1414
1415void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1416 RenderViewHost* rvh) {
1417 // If we are creating a RVH for a restored controller, then we might
1418 // have more page IDs than the SiteInstance's current max page ID. We must
1419 // make sure that the max page ID is larger than any restored page ID.
1420 // Note that it is ok for conflicting page IDs to exist in another tab
1421 // (i.e., NavigationController), but if any page ID is larger than the max,
1422 // the back/forward list will get confused.
1423 int max_restored_page_id = controller_.max_restored_page_id();
1424 if (max_restored_page_id > 0) {
1425 int curr_max_page_id = site_instance->max_page_id();
1426 if (max_restored_page_id > curr_max_page_id) {
1427 // Need to update the site instance immediately.
1428 site_instance->UpdateMaxPageID(max_restored_page_id);
1429
1430 // Also tell the renderer to update its internal representation. We
1431 // need to reserve enough IDs to make all restored page IDs less than
1432 // the max.
1433 if (curr_max_page_id < 0)
1434 curr_max_page_id = 0;
1435 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1436 }
1437 }
1438}
1439
1440void TabContents::UpdateHistoryForNavigation(
1441 const GURL& display_url,
1442 const ViewHostMsg_FrameNavigate_Params& params) {
1443 if (profile()->IsOffTheRecord())
1444 return;
1445
1446 // Add to history service.
1447 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1448 if (hs) {
1449 if (PageTransition::IsMainFrame(params.transition) &&
1450 display_url != params.url) {
1451 // Hack on the "display" URL so that it will appear in history. For some
1452 // types of URLs, we will display a magic URL that is different from where
1453 // the page is actually navigated. We want the user to see in history
1454 // what they saw in the URL bar, so we add the display URL as a redirect.
1455 // This only applies to the main frame, as the display URL doesn't apply
1456 // to sub-frames.
1457 std::vector<GURL> redirects = params.redirects;
1458 if (!redirects.empty())
1459 redirects.back() = display_url;
1460 hs->AddPage(display_url, this, params.page_id, params.referrer,
1461 params.transition, redirects);
1462 } else {
1463 hs->AddPage(params.url, this, params.page_id, params.referrer,
1464 params.transition, params.redirects);
1465 }
1466 }
1467}
1468
1469bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1470 const std::wstring& title) {
1471 // For file URLs without a title, use the pathname instead. In the case of a
1472 // synthesized title, we don't want the update to count toward the "one set
1473 // per page of the title to history."
1474 std::wstring final_title;
1475 bool explicit_set;
1476 if (entry->url().SchemeIsFile() && title.empty()) {
1477 final_title = UTF8ToWide(entry->url().ExtractFileName());
1478 explicit_set = false; // Don't count synthetic titles toward the set limit.
1479 } else {
1480 TrimWhitespace(title, TRIM_ALL, &final_title);
1481 explicit_set = true;
1482 }
1483
1484 if (final_title == UTF16ToWideHack(entry->title()))
1485 return false; // Nothing changed, don't bother.
1486
1487 entry->set_title(WideToUTF16Hack(final_title));
1488
1489 // Update the history system for this page.
1490 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1491 HistoryService* hs =
1492 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1493 if (hs)
1494 hs->SetPageTitle(entry->display_url(), final_title);
1495
1496 // Don't allow the title to be saved again for explicitly set ones.
1497 received_page_title_ = explicit_set;
1498 }
1499
1500 // Lastly, set the title for the view.
1501 view_->SetPageTitle(final_title);
1502
1503 return true;
1504}
1505
1506void TabContents::NotifySwapped() {
1507 // After sending out a swap notification, we need to send a disconnect
1508 // notification so that clients that pick up a pointer to |this| can NULL the
1509 // pointer. See Bug 1230284.
1510 notify_disconnection_ = true;
1511 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341512 NotificationType::TAB_CONTENTS_SWAPPED,
1513 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321514 NotificationService::NoDetails());
1515}
1516
1517void TabContents::NotifyConnected() {
1518 notify_disconnection_ = true;
1519 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341520 NotificationType::TAB_CONTENTS_CONNECTED,
1521 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321522 NotificationService::NoDetails());
1523}
1524
1525void TabContents::NotifyDisconnected() {
1526 if (!notify_disconnection_)
1527 return;
1528
1529 notify_disconnection_ = false;
1530 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341531 NotificationType::TAB_CONTENTS_DISCONNECTED,
1532 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321533 NotificationService::NoDetails());
1534}
1535
1536void TabContents::GenerateKeywordIfNecessary(
1537 const ViewHostMsg_FrameNavigate_Params& params) {
1538 if (!params.searchable_form_url.is_valid())
1539 return;
1540
1541 if (profile()->IsOffTheRecord())
1542 return;
1543
1544 int last_index = controller_.last_committed_entry_index();
1545 // When there was no previous page, the last index will be 0. This is
1546 // normally due to a form submit that opened in a new tab.
1547 // TODO(brettw) bug 916126: we should support keywords when form submits
1548 // happen in new tabs.
1549 if (last_index <= 0)
1550 return;
1551 const NavigationEntry* previous_entry =
1552 controller_.GetEntryAtIndex(last_index - 1);
1553 if (IsFormSubmit(previous_entry)) {
1554 // Only generate a keyword if the previous page wasn't itself a form
1555 // submit.
1556 return;
1557 }
1558
1559 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1560 previous_entry->user_typed_url() : previous_entry->url();
1561 std::wstring keyword =
1562 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1563 if (keyword.empty())
1564 return;
1565
1566 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1567 if (!url_model)
1568 return;
1569
1570 if (!url_model->loaded()) {
1571 url_model->Load();
1572 return;
1573 }
1574
1575 const TemplateURL* current_url;
1576 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1577 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1578 return;
1579
1580 if (current_url) {
1581 if (current_url->originating_url().is_valid()) {
1582 // The existing keyword was generated from an OpenSearch description
1583 // document, don't regenerate.
1584 return;
1585 }
1586 url_model->Remove(current_url);
1587 }
1588 TemplateURL* new_url = new TemplateURL();
1589 new_url->set_keyword(keyword);
1590 new_url->set_short_name(keyword);
1591 new_url->SetURL(url, 0, 0);
1592 new_url->add_input_encoding(params.searchable_form_encoding);
1593 DCHECK(controller_.GetLastCommittedEntry());
1594 const GURL& favicon_url =
1595 controller_.GetLastCommittedEntry()->favicon().url();
1596 if (favicon_url.is_valid()) {
1597 new_url->SetFavIconURL(favicon_url);
1598 } else {
1599 // The favicon url isn't valid. This means there really isn't a favicon,
1600 // or the favicon url wasn't obtained before the load started. This assumes
1601 // the later.
1602 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1603 // its url.
1604 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1605 }
1606 new_url->set_safe_for_autoreplace(true);
1607 url_model->Add(new_url);
1608}
1609
1610RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1611 return view_.get();
1612}
1613
1614RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1615 return save_package_.get(); // May be NULL, but we can return NULL.
1616}
1617
[email protected]6dfed102009-04-28 03:09:531618ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1619 RenderViewHost* render_view_host,
1620 const std::string& extension_id) {
1621 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1622 extension_id);
1623}
1624
[email protected]57c6a652009-05-04 07:58:341625TabContents* TabContents::GetAsTabContents() {
1626 return this;
1627}
1628
[email protected]420ae012009-04-24 05:16:321629void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1630 NavigationEntry* entry = controller_.GetActiveEntry();
1631 if (!entry)
1632 return;
1633
1634 // When we're creating views, we're still doing initial setup, so we always
1635 // use the pending DOM UI rather than any possibly existing committed one.
1636 if (render_manager_.pending_dom_ui()) {
1637 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1638 }
1639
1640 if (entry->IsViewSourceMode()) {
1641 // Put the renderer in view source mode.
1642 render_view_host->Send(
1643 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1644 }
[email protected]0666aef2009-05-13 19:48:081645
1646 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321647}
1648
1649void TabContents::RenderViewReady(RenderViewHost* rvh) {
1650 if (rvh != render_view_host()) {
1651 // Don't notify the world, since this came from a renderer in the
1652 // background.
1653 return;
1654 }
1655
1656 NotifyConnected();
1657 SetIsCrashed(false);
1658}
1659
1660void TabContents::RenderViewGone(RenderViewHost* rvh) {
1661 // Ask the print preview if this renderer was valuable.
1662 if (!printing_.OnRenderViewGone(rvh))
1663 return;
1664 if (rvh != render_view_host()) {
1665 // The pending page's RenderViewHost is gone.
1666 return;
1667 }
1668
1669 SetIsLoading(false, NULL);
1670 NotifyDisconnected();
1671 SetIsCrashed(true);
1672
1673 // Force an invalidation to render sad tab. The view will notice we crashed
1674 // when it paints.
1675 view_->Invalidate();
1676
1677 // Hide any visible hung renderer warning for this web contents' process.
[email protected]8897c382009-05-06 17:53:261678 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:321679}
1680
1681void TabContents::DidNavigate(RenderViewHost* rvh,
1682 const ViewHostMsg_FrameNavigate_Params& params) {
1683 if (PageTransition::IsMainFrame(params.transition))
1684 render_manager_.DidNavigateMainFrame(rvh);
1685
1686 // Update the site of the SiteInstance if it doesn't have one yet.
1687 if (!GetSiteInstance()->has_site())
1688 GetSiteInstance()->SetSite(params.url);
1689
1690 // Need to update MIME type here because it's referred to in
1691 // UpdateNavigationCommands() called by RendererDidNavigate() to
1692 // determine whether or not to enable the encoding menu.
1693 // It's updated only for the main frame. For a subframe,
1694 // RenderView::UpdateURL does not set params.contents_mime_type.
1695 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1696 // TODO(jungshik): Add a test for the encoding menu to avoid
1697 // regressing it again.
1698 if (PageTransition::IsMainFrame(params.transition))
1699 contents_mime_type_ = params.contents_mime_type;
1700
1701 NavigationController::LoadCommittedDetails details;
1702 if (!controller_.RendererDidNavigate(params, &details))
1703 return; // No navigation happened.
1704
1705 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1706 // for the appropriate notification (best) or you can add it to
1707 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1708 // necessary, please).
1709
1710 // Run post-commit tasks.
1711 if (details.is_main_frame)
1712 DidNavigateMainFramePostCommit(details, params);
1713 DidNavigateAnyFramePostCommit(rvh, details, params);
1714}
1715
1716void TabContents::UpdateState(RenderViewHost* rvh,
1717 int32 page_id,
1718 const std::string& state) {
1719 DCHECK(rvh == render_view_host());
1720
1721 // We must be prepared to handle state updates for any page, these occur
1722 // when the user is scrolling and entering form data, as well as when we're
1723 // leaving a page, in which case our state may have already been moved to
1724 // the next page. The navigation controller will look up the appropriate
1725 // NavigationEntry and update it when it is notified via the delegate.
1726
1727 int entry_index = controller_.GetEntryIndexWithPageID(
1728 GetSiteInstance(), page_id);
1729 if (entry_index < 0)
1730 return;
1731 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1732
1733 if (state == entry->content_state())
1734 return; // Nothing to update.
1735 entry->set_content_state(state);
1736 controller_.NotifyEntryChanged(entry, entry_index);
1737}
1738
1739void TabContents::UpdateTitle(RenderViewHost* rvh,
1740 int32 page_id, const std::wstring& title) {
1741 // If we have a title, that's a pretty good indication that we've started
1742 // getting useful data.
1743 SetNotWaitingForResponse();
1744
1745 DCHECK(rvh == render_view_host());
1746 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1747 page_id);
1748 if (!entry || !UpdateTitleForEntry(entry, title))
1749 return;
1750
1751 // Broadcast notifications when the UI should be updated.
1752 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501753 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321754}
1755
[email protected]420ae012009-04-24 05:16:321756void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1757 const std::wstring& encoding) {
1758 set_encoding(encoding);
1759}
1760
1761void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1762 if (delegate())
1763 delegate()->UpdateTargetURL(this, url);
1764}
1765
1766void TabContents::UpdateThumbnail(const GURL& url,
1767 const SkBitmap& bitmap,
1768 const ThumbnailScore& score) {
1769 // Tell History about this thumbnail
1770 HistoryService* hs;
1771 if (!profile()->IsOffTheRecord() &&
1772 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1773 hs->SetPageThumbnail(url, bitmap, score);
1774 }
1775}
1776
1777void TabContents::Close(RenderViewHost* rvh) {
1778 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1779 if (delegate() && rvh == render_view_host())
1780 delegate()->CloseContents(this);
1781}
1782
1783void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1784 if (delegate() && delegate()->IsPopup(this))
1785 delegate()->MoveContents(this, new_bounds);
1786}
1787
[email protected]329581b2009-04-28 06:52:351788void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321789 SetIsLoading(true, NULL);
1790}
1791
[email protected]329581b2009-04-28 06:52:351792void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321793 scoped_ptr<LoadNotificationDetails> details;
1794
1795 NavigationEntry* entry = controller_.GetActiveEntry();
1796 // An entry may not exist for a stop when loading an initial blank page or
1797 // if an iframe injected by script into a blank page finishes loading.
1798 if (entry) {
1799 scoped_ptr<base::ProcessMetrics> metrics(
1800 base::ProcessMetrics::CreateProcessMetrics(
1801 process()->process().handle()));
1802
1803 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1804
1805 details.reset(new LoadNotificationDetails(
1806 entry->display_url(),
1807 entry->transition_type(),
1808 elapsed,
1809 &controller_,
1810 controller_.GetCurrentEntryIndex()));
1811 }
1812
1813 // Tell PasswordManager we've finished a page load, which serves as a
1814 // green light to save pending passwords and reset itself.
1815 GetPasswordManager()->DidStopLoading();
1816
1817 SetIsLoading(false, details.get());
1818}
1819
1820void TabContents::DidStartProvisionalLoadForFrame(
1821 RenderViewHost* render_view_host,
1822 bool is_main_frame,
1823 const GURL& url) {
1824 ProvisionalLoadDetails details(is_main_frame,
1825 controller_.IsURLInPageNavigation(url),
1826 url, std::string(), false);
1827 NotificationService::current()->Notify(
1828 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1829 Source<NavigationController>(&controller_),
1830 Details<ProvisionalLoadDetails>(&details));
1831}
1832
1833void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1834 const GURL& source_url,
1835 const GURL& target_url) {
1836 NavigationEntry* entry;
1837 if (page_id == -1)
1838 entry = controller_.pending_entry();
1839 else
1840 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1841 if (!entry || entry->url() != source_url)
1842 return;
1843 entry->set_url(target_url);
1844}
1845
1846void TabContents::DidLoadResourceFromMemoryCache(
1847 const GURL& url,
1848 const std::string& frame_origin,
1849 const std::string& main_frame_origin,
1850 const std::string& security_info) {
1851 // Send out a notification that we loaded a resource from our memory cache.
1852 int cert_id = 0, cert_status = 0, security_bits = 0;
1853 SSLManager::DeserializeSecurityInfo(security_info,
1854 &cert_id, &cert_status,
1855 &security_bits);
1856 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]9ae66cbf2009-05-12 16:21:031857 process()->pid(), cert_id, cert_status);
[email protected]420ae012009-04-24 05:16:321858
1859 NotificationService::current()->Notify(
1860 NotificationType::LOAD_FROM_MEMORY_CACHE,
1861 Source<NavigationController>(&controller_),
1862 Details<LoadFromMemoryCacheDetails>(&details));
1863}
1864
1865void TabContents::DidFailProvisionalLoadWithError(
1866 RenderViewHost* render_view_host,
1867 bool is_main_frame,
1868 int error_code,
1869 const GURL& url,
1870 bool showing_repost_interstitial) {
1871 if (net::ERR_ABORTED == error_code) {
1872 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1873 // This means that the interstitial won't be torn down properly, which is
1874 // bad. But if we have an interstitial, go back to another tab type, and
1875 // then load the same interstitial again, we could end up getting the first
1876 // interstitial's "failed" message (as a result of the cancel) when we're on
1877 // the second one.
1878 //
1879 // We can't tell this apart, so we think we're tearing down the current page
1880 // which will cause a crash later one. There is also some code in
1881 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1882 // out because of this problem.
1883 //
1884 // http://code.google.com/p/chromium/issues/detail?id=2855
1885 // Because this will not tear down the interstitial properly, if "back" is
1886 // back to another tab type, the interstitial will still be somewhat alive
1887 // in the previous tab type. If you navigate somewhere that activates the
1888 // tab with the interstitial again, you'll see a flash before the new load
1889 // commits of the interstitial page.
1890 if (showing_interstitial_page()) {
1891 LOG(WARNING) << "Discarding message during interstitial.";
1892 return;
1893 }
1894
1895 // This will discard our pending entry if we cancelled the load (e.g., if we
1896 // decided to download the file instead of load it). Only discard the
1897 // pending entry if the URLs match, otherwise the user initiated a navigate
1898 // before the page loaded so that the discard would discard the wrong entry.
1899 NavigationEntry* pending_entry = controller_.pending_entry();
1900 if (pending_entry && pending_entry->url() == url)
1901 controller_.DiscardNonCommittedEntries();
1902
1903 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1904 }
1905
1906 // Send out a notification that we failed a provisional load with an error.
1907 ProvisionalLoadDetails details(is_main_frame,
1908 controller_.IsURLInPageNavigation(url),
1909 url, std::string(), false);
1910 details.set_error_code(error_code);
1911
1912 NotificationService::current()->Notify(
1913 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1914 Source<NavigationController>(&controller_),
1915 Details<ProvisionalLoadDetails>(&details));
1916}
1917
1918void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1919 int32 page_id,
1920 const GURL& icon_url) {
1921 fav_icon_helper_.SetFavIconURL(icon_url);
1922}
1923
1924void TabContents::DidDownloadImage(
1925 RenderViewHost* render_view_host,
1926 int id,
1927 const GURL& image_url,
1928 bool errored,
1929 const SkBitmap& image) {
1930 // A notification for downloading would be more flexible, but for now I'm
1931 // forwarding to the two places that could possibly have initiated the
1932 // request. If we end up with another place invoking DownloadImage, probably
1933 // best to refactor out into notification service, or something similar.
1934 if (errored)
1935 fav_icon_helper_.FavIconDownloadFailed(id);
1936 else
1937 fav_icon_helper_.SetFavIcon(id, image_url, image);
1938}
1939
1940void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1941 WindowOpenDisposition disposition) {
1942 if (render_manager_.dom_ui()) {
1943 // When we're a DOM UI, it will provide a page transition type for us (this
1944 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1945 // generated suggestions).
1946 //
1947 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161948 // want web sites to see a referrer of "chrome://blah" (and some
1949 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321950 // send to the site), so we send no referrer.
1951 OpenURL(url, GURL(), disposition,
1952 render_manager_.dom_ui()->link_transition_type());
1953 } else {
1954 OpenURL(url, referrer, disposition, PageTransition::LINK);
1955 }
1956}
1957
1958void TabContents::DomOperationResponse(const std::string& json_string,
1959 int automation_id) {
1960 DomOperationNotificationDetails details(json_string, automation_id);
1961 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341962 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321963 Details<DomOperationNotificationDetails>(&details));
1964}
1965
1966void TabContents::ProcessDOMUIMessage(const std::string& message,
1967 const std::string& content) {
1968 if (!render_manager_.dom_ui()) {
1969 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1970 // Because the renderer might be owned and sending random messages, we need
1971 // to ignore these inproper ones.
1972 NOTREACHED();
1973 return;
1974 }
1975 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1976}
1977
1978void TabContents::ProcessExternalHostMessage(const std::string& message,
1979 const std::string& origin,
1980 const std::string& target) {
1981 if (delegate())
1982 delegate()->ForwardMessageToExternalHost(message, origin, target);
1983}
1984
1985void TabContents::GoToEntryAtOffset(int offset) {
1986 controller_.GoToOffset(offset);
1987}
1988
1989void TabContents::GetHistoryListCount(int* back_list_count,
1990 int* forward_list_count) {
1991 int current_index = controller_.last_committed_entry_index();
1992 *back_list_count = current_index;
1993 *forward_list_count = controller_.entry_count() - current_index - 1;
1994}
1995
1996void TabContents::RunFileChooser(bool multiple_files,
1997 const string16& title,
1998 const FilePath& default_file) {
1999 if (!select_file_dialog_.get())
2000 select_file_dialog_ = SelectFileDialog::Create(this);
2001 SelectFileDialog::Type dialog_type =
2002 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
2003 SelectFileDialog::SELECT_OPEN_FILE;
2004 select_file_dialog_->SelectFile(dialog_type, title, default_file,
2005 NULL, 0, FILE_PATH_LITERAL(""),
2006 view_->GetTopLevelNativeWindow(), NULL);
2007}
2008
2009void TabContents::RunJavaScriptMessage(
2010 const std::wstring& message,
2011 const std::wstring& default_prompt,
2012 const GURL& frame_url,
2013 const int flags,
2014 IPC::Message* reply_msg,
2015 bool* did_suppress_message) {
2016 // Suppress javascript messages when requested and when inside a constrained
2017 // popup window (because that activates them and breaks them out of the
2018 // constrained window jail).
2019 bool suppress_this_message = suppress_javascript_messages_;
2020 if (delegate())
2021 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:312022 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:322023
2024 *did_suppress_message = suppress_this_message;
2025
2026 if (!suppress_this_message) {
2027 base::TimeDelta time_since_last_message(
2028 base::TimeTicks::Now() - last_javascript_message_dismissal_);
2029 bool show_suppress_checkbox = false;
2030 // Show a checkbox offering to suppress further messages if this message is
2031 // being displayed within kJavascriptMessageExpectedDelay of the last one.
2032 if (time_since_last_message <
2033 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
2034 show_suppress_checkbox = true;
2035
2036 RunJavascriptMessageBox(AsWC(this), frame_url, flags, message, default_prompt,
2037 show_suppress_checkbox, reply_msg);
2038 } else {
2039 // If we are suppressing messages, just reply as is if the user immediately
2040 // pressed "Cancel".
2041 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
2042 }
2043}
2044
2045void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
2046 IPC::Message* reply_msg) {
2047 RunBeforeUnloadDialog(AsWC(this), message, reply_msg);
2048}
2049
2050void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
2051 const std::string& json_arguments,
2052 IPC::Message* reply_msg) {
2053 if (delegate()) {
2054 HtmlDialogUIDelegate* dialog_delegate =
2055 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
2056 reply_msg, AsWC(this));
2057 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
2058 }
2059}
2060
2061void TabContents::PasswordFormsSeen(
2062 const std::vector<PasswordForm>& forms) {
2063 GetPasswordManager()->PasswordFormsSeen(forms);
2064}
2065
2066void TabContents::AutofillFormSubmitted(
2067 const AutofillForm& form) {
2068 GetAutofillManager()->AutofillFormSubmitted(form);
2069}
2070
2071void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
2072 const std::wstring& user_text, int64 node_id, int request_id) {
2073 GetAutofillManager()->FetchValuesForName(field_name, user_text,
2074 kMaxAutofillMenuItems, node_id, request_id);
2075}
2076
2077void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
2078 const std::wstring& value) {
2079 GetAutofillManager()->RemoveValueForName(field_name, value);
2080}
2081
2082// Checks to see if we should generate a keyword based on the OSDD, and if
2083// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2084void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2085 int32 page_id, const GURL& url,
2086 bool autodetected) {
2087 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2088 DCHECK(url.is_valid());
2089 if (!IsActiveEntry(page_id))
2090 return;
2091 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2092 if (!url_model)
2093 return;
2094 if (!url_model->loaded()) {
2095 url_model->Load();
2096 return;
2097 }
2098 if (!profile()->GetTemplateURLFetcher())
2099 return;
2100
2101 if (profile()->IsOffTheRecord())
2102 return;
2103
2104 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2105 DCHECK(entry);
2106
2107 const NavigationEntry* base_entry = entry;
2108 if (IsFormSubmit(base_entry)) {
2109 // If the current page is a form submit, find the last page that was not
2110 // a form submit and use its url to generate the keyword from.
2111 int index = controller_.last_committed_entry_index() - 1;
2112 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2113 index--;
2114 if (index >= 0)
2115 base_entry = controller_.GetEntryAtIndex(index);
2116 else
2117 base_entry = NULL;
2118 }
2119
2120 // We want to use the user typed URL if available since that represents what
2121 // the user typed to get here, and fall back on the regular URL if not.
2122 if (!base_entry)
2123 return;
2124 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2125 base_entry->user_typed_url() : base_entry->url();
2126 if (!keyword_url.is_valid())
2127 return;
2128 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2129 autodetected);
2130 if (keyword.empty())
2131 return;
2132 const TemplateURL* template_url =
2133 url_model->GetTemplateURLForKeyword(keyword);
2134 if (template_url && (!template_url->safe_for_autoreplace() ||
2135 template_url->originating_url() == url)) {
2136 // Either there is a user created TemplateURL for this keyword, or the
2137 // keyword has the same OSDD url and we've parsed it.
2138 return;
2139 }
2140
2141 // Download the OpenSearch description document. If this is successful a
2142 // new keyword will be created when done.
2143#if defined(OS_WIN)
2144 gfx::NativeView ancestor = GetAncestor(view_->GetNativeView(), GA_ROOT);
2145#else
2146 gfx::NativeView ancestor = NULL;
2147#endif
2148 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2149 keyword,
2150 url,
2151 base_entry->favicon().url(),
2152 ancestor,
2153 autodetected);
2154}
2155
2156void TabContents::InspectElementReply(int num_resources) {
2157 // We have received reply from inspect element request. Notify the
2158 // automation provider in case we need to notify automation client.
2159 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:342160 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:322161 Details<int>(&num_resources));
2162}
2163
2164void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2165 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2166}
2167
2168void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2169 printing_.DidPrintPage(params);
2170}
2171
2172GURL TabContents::GetAlternateErrorPageURL() const {
2173 GURL url;
2174 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2175 if (profile()->IsOffTheRecord())
2176 return url;
2177
2178 PrefService* prefs = profile()->GetPrefs();
2179 DCHECK(prefs);
2180 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2181 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2182 url = google_util::AppendGoogleTLDParam(url);
2183 }
2184 return url;
2185}
2186
2187WebPreferences TabContents::GetWebkitPrefs() {
2188 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2189 bool isDomUI = false;
2190 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2191}
2192
2193void TabContents::OnMissingPluginStatus(int status) {
2194#if defined(OS_WIN)
2195// TODO(PORT): pull in when plug-ins work
2196 GetPluginInstaller()->OnMissingPluginStatus(status);
2197#endif
2198}
2199
2200void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2201#if defined(OS_WIN)
2202// TODO(PORT): pull in when plug-ins work
2203 DCHECK(!plugin_path.value().empty());
2204
2205 std::wstring plugin_name = plugin_path.ToWStringHack();
2206 scoped_ptr<FileVersionInfo> version_info(
2207 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2208 if (version_info.get()) {
2209 const std::wstring& product_name = version_info->product_name();
2210 if (!product_name.empty())
2211 plugin_name = product_name;
2212 }
2213 AddInfoBar(new SimpleAlertInfoBarDelegate(
2214 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2215 NULL));
2216#endif
2217}
2218
2219void TabContents::OnCrashedWorker() {
2220 AddInfoBar(new SimpleAlertInfoBarDelegate(
2221 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2222 NULL));
2223}
2224
2225void TabContents::OnJSOutOfMemory() {
2226 AddInfoBar(new SimpleAlertInfoBarDelegate(
2227 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2228}
2229
2230void TabContents::ShouldClosePage(bool proceed) {
2231 render_manager_.ShouldClosePage(proceed);
2232}
2233
2234void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2235 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342236 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322237 // delivered to a pending RenderViewHost. We must first run the onunload
2238 // handler of the old RenderViewHost before we can allow it to proceed.
2239 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2240 new_request_id);
2241}
2242
2243bool TabContents::CanBlur() const {
2244 return delegate() ? delegate()->CanBlur() : true;
2245}
2246
2247gfx::Rect TabContents::GetRootWindowResizerRect() const {
2248 if (delegate())
2249 return delegate()->GetRootWindowResizerRect();
2250 return gfx::Rect();
2251}
2252
2253void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2254 bool is_during_unload) {
2255 if (is_during_unload) {
2256 // Hang occurred while firing the beforeunload/unload handler.
2257 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112258 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322259
2260 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2261 return;
2262
2263 // If the tab hangs in the beforeunload/unload handler there's really
2264 // nothing we can do to recover. Pretend the unload listeners have
2265 // all fired and close the tab. If the hang is in the beforeunload handler
2266 // then the user will not have the option of cancelling the close.
2267 Close(rvh);
2268 return;
2269 }
2270
2271 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]8897c382009-05-06 17:53:262272 HungRendererDialog::ShowForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322273}
2274
2275void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]8897c382009-05-06 17:53:262276 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322277}
2278
2279void TabContents::LoadStateChanged(const GURL& url,
2280 net::LoadState load_state) {
2281 load_state_ = load_state;
2282 load_state_host_ = UTF8ToWide(url.host());
2283 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2284 SetNotWaitingForResponse();
2285 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502286 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322287}
2288
2289void TabContents::OnDidGetApplicationInfo(
2290 int32 page_id,
2291 const webkit_glue::WebApplicationInfo& info) {
2292 if (pending_install_.page_id != page_id)
2293 return; // The user clicked create on a separate page. Ignore this.
2294
2295 pending_install_.callback_functor =
2296 new GearsCreateShortcutCallbackFunctor(this);
2297 GearsCreateShortcut(
2298 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2299 NewCallback(pending_install_.callback_functor,
2300 &GearsCreateShortcutCallbackFunctor::Run));
2301}
2302
[email protected]14ce83f2009-05-28 18:35:242303void TabContents::OnUserGesture() {
2304 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
2305#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]420ae012009-04-24 05:16:322306 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2307 if (drm)
2308 drm->OnUserGesture(this);
2309#endif
2310}
2311
2312void TabContents::OnFindReply(int request_id,
2313 int number_of_matches,
2314 const gfx::Rect& selection_rect,
2315 int active_match_ordinal,
2316 bool final_update) {
2317 // Ignore responses for requests other than the one we have most recently
2318 // issued. That way we won't act on stale results when the user has
2319 // already typed in another query.
2320 if (request_id != current_find_request_id_)
2321 return;
2322
2323 if (number_of_matches == -1)
[email protected]e491f1c2009-05-22 20:28:122324 number_of_matches = last_search_result_.number_of_matches();
[email protected]420ae012009-04-24 05:16:322325 if (active_match_ordinal == -1)
[email protected]e491f1c2009-05-22 20:28:122326 active_match_ordinal = last_search_result_.active_match_ordinal();
[email protected]420ae012009-04-24 05:16:322327
[email protected]2c355c282009-05-21 23:24:432328 gfx::Rect selection = selection_rect;
2329 if (selection.IsEmpty())
[email protected]e491f1c2009-05-22 20:28:122330 selection = last_search_result_.selection_rect();
[email protected]2c355c282009-05-21 23:24:432331
[email protected]420ae012009-04-24 05:16:322332 // Notify the UI, automation and any other observers that a find result was
2333 // found.
[email protected]e491f1c2009-05-22 20:28:122334 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
2335 selection, active_match_ordinal,
2336 final_update);
[email protected]420ae012009-04-24 05:16:322337 NotificationService::current()->Notify(
2338 NotificationType::FIND_RESULT_AVAILABLE,
2339 Source<TabContents>(this),
[email protected]e491f1c2009-05-22 20:28:122340 Details<FindNotificationDetails>(&last_search_result_));
[email protected]420ae012009-04-24 05:16:322341}
2342
[email protected]829e7612009-04-25 01:15:112343bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322344 if (!delegate())
[email protected]829e7612009-04-25 01:15:112345 return false;
[email protected]420ae012009-04-24 05:16:322346
[email protected]829e7612009-04-25 01:15:112347 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322348}
2349
2350void TabContents::FileSelected(const FilePath& path,
2351 int index, void* params) {
2352 render_view_host()->FileSelected(path);
2353}
2354
2355void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2356 void* params) {
2357 render_view_host()->MultiFilesSelected(files);
2358}
2359
2360void TabContents::FileSelectionCanceled(void* params) {
2361 // If the user cancels choosing a file to upload we pass back an
2362 // empty vector.
2363 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2364}
2365
2366void TabContents::BeforeUnloadFiredFromRenderManager(
2367 bool proceed,
2368 bool* proceed_to_fire_unload) {
2369 if (delegate())
2370 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2371}
2372
2373void TabContents::UpdateRenderViewSizeForRenderManager() {
2374 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2375 view_->SizeContents(view_->GetContainerSize());
2376}
2377
2378DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
2379 return DOMUIFactory::CreateDOMUIForURL(AsWC(this), url);
2380}
2381
2382NavigationEntry*
2383TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2384 return controller_.GetLastCommittedEntry();
2385}
2386
2387bool TabContents::CreateRenderViewForRenderManager(
2388 RenderViewHost* render_view_host) {
2389 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2390 // mode before CreateRenderView is called. When we're asked to create a
2391 // RenderView, that means it's for the pending entry, so we have to use the
2392 // pending DOM UI.
2393 if (render_manager_.pending_dom_ui())
2394 render_view_host->AllowDOMUIBindings();
2395
[email protected]1adff062009-06-02 18:39:552396 // Ditto for extension bindings.
2397 if (controller().pending_entry()->url().SchemeIs(chrome::kExtensionScheme))
2398 render_view_host->AllowExtensionBindings();
2399
[email protected]420ae012009-04-24 05:16:322400 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2401 if (!render_view_host->CreateRenderView())
2402 return false;
2403
2404 // Now that the RenderView has been created, we need to tell it its size.
2405 rwh_view->SetSize(view_->GetContainerSize());
2406
2407 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2408 render_view_host);
2409 return true;
2410}
2411
2412void TabContents::Observe(NotificationType type,
2413 const NotificationSource& source,
2414 const NotificationDetails& details) {
2415 switch (type.value) {
2416 case NotificationType::BOOKMARK_MODEL_LOADED:
2417 // BookmarkModel finished loading, fall through to update starred state.
2418 case NotificationType::URLS_STARRED: {
2419 // Somewhere, a URL has been starred.
2420 // Ignore notifications for profiles other than our current one.
2421 Profile* source_profile = Source<Profile>(source).ptr();
2422 if (!source_profile || !source_profile->IsSameProfile(profile()))
2423 return;
2424
2425 UpdateStarredStateForCurrentURL();
2426 break;
2427 }
2428 case NotificationType::PREF_CHANGED: {
2429 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2430 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2431 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2432 UpdateAlternateErrorPageURL();
2433 } else if (*pref_name_in == prefs::kDefaultCharset ||
2434 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2435 ) {
2436 UpdateWebPreferences();
2437 } else {
2438 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2439 }
2440 break;
2441 }
2442 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2443 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2444 break;
2445
2446 case NotificationType::NAV_ENTRY_COMMITTED: {
2447 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2448
2449 NavigationController::LoadCommittedDetails& committed_details =
2450 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2451 ExpireInfoBars(committed_details);
2452 break;
2453 }
2454
2455 default:
2456 NOTREACHED();
2457 }
2458}