blob: db05c00aed27ae2358eac2c6ef096188fb786e7f [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]0c9ee992009-06-03 16:56:3860#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]0df30122009-06-03 12:13:08367 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
368 pref_defaults.inspector_settings);
[email protected]420ae012009-04-24 05:16:32369 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
370 pref_defaults.text_areas_are_resizable);
371 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
372 pref_defaults.java_enabled);
373
374 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
375 IDS_ACCEPT_LANGUAGES);
376 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
377 IDS_DEFAULT_ENCODING);
378 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
379 IDS_STANDARD_FONT_IS_SERIF);
380 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
381 IDS_FIXED_FONT_FAMILY);
382 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
383 IDS_SERIF_FONT_FAMILY);
384 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
385 IDS_SANS_SERIF_FONT_FAMILY);
386 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
387 IDS_CURSIVE_FONT_FAMILY);
388 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
389 IDS_FANTASY_FONT_FAMILY);
390 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
391 IDS_DEFAULT_FONT_SIZE);
392 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
393 IDS_DEFAULT_FIXED_FONT_SIZE);
394 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
395 IDS_MINIMUM_FONT_SIZE);
396 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
397 IDS_MINIMUM_LOGICAL_FONT_SIZE);
398 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
399 IDS_USES_UNIVERSAL_DETECTOR);
400 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
401 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29402}
403
[email protected]d5f942ba2008-09-26 19:30:34404bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01405 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55406 return true;
[email protected]d5f942ba2008-09-26 19:30:34407}
408
[email protected]6e95706d2009-04-23 22:55:01409AutofillManager* TabContents::GetAutofillManager() {
410 if (autofill_manager_.get() == NULL)
411 autofill_manager_.reset(new AutofillManager(this));
412 return autofill_manager_.get();
413}
414
415PasswordManager* TabContents::GetPasswordManager() {
416 if (password_manager_.get() == NULL)
417 password_manager_.reset(new PasswordManager(this));
418 return password_manager_.get();
419}
420
421PluginInstaller* TabContents::GetPluginInstaller() {
422 if (plugin_installer_.get() == NULL)
423 plugin_installer_.reset(new PluginInstaller(this));
424 return plugin_installer_.get();
425}
426
[email protected]d5f942ba2008-09-26 19:30:34427const GURL& TabContents::GetURL() const {
428 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57429 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34430 return entry ? entry->display_url() : GURL::EmptyGURL();
431}
432
[email protected]96d185d2009-04-24 03:28:54433const string16& TabContents::GetTitle() const {
434 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
435 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
436 if (our_dom_ui) {
437 // Don't override the title in view source mode.
438 NavigationEntry* entry = controller_.GetActiveEntry();
439 if (!(entry && entry->IsViewSourceMode())) {
440 // Give the DOM UI the chance to override our title.
441 const string16& title = our_dom_ui->overridden_title();
442 if (!title.empty())
443 return title;
444 }
445 }
446
447 // We use the title for the last committed entry rather than a pending
448 // navigation entry. For example, when the user types in a URL, we want to
449 // keep the old page's title until the new load has committed and we get a new
450 // title.
451 // The exception is with transient pages, for which we really want to use
452 // their title, as they are not committed.
453 NavigationEntry* entry = controller_.GetTransientEntry();
454 if (entry)
455 return entry->GetTitleForDisplay(&controller_);
456
457 entry = controller_.GetLastCommittedEntry();
458 if (entry)
459 return entry->GetTitleForDisplay(&controller_);
460 else if (controller_.LoadingURLLazily())
461 return controller_.GetLazyTitle();
462 return EmptyString16();
463}
464
[email protected]d5f942ba2008-09-26 19:30:34465int32 TabContents::GetMaxPageID() {
466 if (GetSiteInstance())
467 return GetSiteInstance()->max_page_id();
468 else
469 return max_page_id_;
470}
471
472void TabContents::UpdateMaxPageID(int32 page_id) {
473 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34474 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34475 // testing.
476 if (GetSiteInstance())
477 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34478 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34479}
480
[email protected]96d185d2009-04-24 03:28:54481SiteInstance* TabContents::GetSiteInstance() const {
482 return render_manager_.current_host()->site_instance();
483}
484
[email protected]d5f942ba2008-09-26 19:30:34485const std::wstring TabContents::GetDefaultTitle() const {
486 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
487}
488
[email protected]96d185d2009-04-24 03:28:54489bool TabContents::ShouldDisplayURL() {
490 // Don't hide the url in view source mode.
491 NavigationEntry* entry = controller_.GetActiveEntry();
492 if (entry && entry->IsViewSourceMode())
493 return true;
494 DOMUI* dom_ui = GetDOMUIForCurrentState();
495 if (dom_ui)
496 return !dom_ui->should_hide_url();
497 return true;
498}
499
[email protected]d5f942ba2008-09-26 19:30:34500SkBitmap TabContents::GetFavIcon() const {
501 // Like GetTitle(), we also want to use the favicon for the last committed
502 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57503 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47504 if (entry)
505 return entry->favicon().bitmap();
506
[email protected]ce3fa3c2009-04-20 19:55:57507 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34508 if (entry)
509 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57510 else if (controller_.LoadingURLLazily())
511 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34512 return SkBitmap();
513}
514
[email protected]96d185d2009-04-24 03:28:54515bool TabContents::ShouldDisplayFavIcon() {
516 // Always display a throbber during pending loads.
517 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
518 return true;
519
520 DOMUI* dom_ui = GetDOMUIForCurrentState();
521 if (dom_ui)
522 return !dom_ui->hide_favicon();
523 return true;
524}
525
[email protected]3e45ba92009-02-20 21:09:00526#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34527SecurityStyle TabContents::GetSecurityStyle() const {
528 // We may not have a navigation entry yet.
[email protected]ce3fa3c2009-04-20 19:55:57529 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34530 return entry ? entry->ssl().security_style() : SECURITY_STYLE_UNKNOWN;
531}
532
533bool TabContents::GetSSLEVText(std::wstring* ev_text,
534 std::wstring* ev_tooltip_text) const {
535 DCHECK(ev_text && ev_tooltip_text);
536 ev_text->clear();
537 ev_tooltip_text->clear();
538
[email protected]ce3fa3c2009-04-20 19:55:57539 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34540 if (!entry ||
541 net::IsCertStatusError(entry->ssl().cert_status()) ||
542 ((entry->ssl().cert_status() & net::CERT_STATUS_IS_EV) == 0))
543 return false;
544
545 scoped_refptr<net::X509Certificate> cert;
546 CertStore::GetSharedInstance()->RetrieveCert(entry->ssl().cert_id(), &cert);
547 if (!cert.get()) {
548 NOTREACHED();
549 return false;
550 }
551
552 return SSLManager::GetEVCertNames(*cert, ev_text, ev_tooltip_text);
553}
[email protected]76f68dc2009-03-10 20:31:32554#endif
[email protected]d5f942ba2008-09-26 19:30:34555
[email protected]96d185d2009-04-24 03:28:54556std::wstring TabContents::GetStatusText() const {
557 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
558 return std::wstring();
559
560 switch (load_state_) {
561 case net::LOAD_STATE_WAITING_FOR_CACHE:
562 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
563 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
564 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
565 case net::LOAD_STATE_RESOLVING_HOST:
566 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
567 case net::LOAD_STATE_CONNECTING:
568 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
569 case net::LOAD_STATE_SENDING_REQUEST:
570 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
571 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
572 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
573 load_state_host_);
574 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
575 case net::LOAD_STATE_IDLE:
576 case net::LOAD_STATE_READING_RESPONSE:
577 break;
578 }
579
580 return std::wstring();
581}
582
[email protected]d5f942ba2008-09-26 19:30:34583void TabContents::SetIsCrashed(bool state) {
584 if (state == is_crashed_)
585 return;
586
587 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50588 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34589}
590
[email protected]ce5c4502009-05-06 16:46:11591void TabContents::EnablePageAction(const PageAction* page_action) {
592 DCHECK(page_action);
593
594 if (IsPageActionEnabled(page_action))
595 return; // Already enabled.
596
597 enabled_page_actions_.insert(page_action);
598}
599
600bool TabContents::IsPageActionEnabled(const PageAction* page_action) {
601 DCHECK(page_action);
602 return enabled_page_actions_.end() != enabled_page_actions_.find(page_action);
603}
604
605
[email protected]d5f942ba2008-09-26 19:30:34606void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
607 if (delegate_)
608 delegate_->NavigationStateChanged(this, changed_flags);
609}
610
[email protected]96d185d2009-04-24 03:28:54611void TabContents::DidBecomeSelected() {
612 controller_.SetActive(true);
613
614 if (render_widget_host_view())
615 render_widget_host_view()->DidBecomeSelected();
616
617 // If pid() is -1, that means the RenderProcessHost still hasn't been
618 // initialized. It'll register with CacheManagerHost when it is.
619 if (process()->pid() != -1)
620 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
621}
622
623void TabContents::WasHidden() {
624 if (!capturing_contents()) {
625 // |render_view_host()| can be NULL if the user middle clicks a link to open
626 // a tab in then background, then closes the tab before selecting it. This
627 // is because closing the tab calls TabContents::Destroy(), which removes
628 // the |render_view_host()|; then when we actually destroy the window,
629 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
630 if (render_widget_host_view())
631 render_widget_host_view()->WasHidden();
632
633 // Loop through children and send WasHidden to them, too.
634 int count = static_cast<int>(child_windows_.size());
635 for (int i = count - 1; i >= 0; --i) {
636 ConstrainedWindow* window = child_windows_.at(i);
637 window->WasHidden();
638 }
639 }
640
641 NotificationService::current()->Notify(
642 NotificationType::TAB_CONTENTS_HIDDEN,
643 Source<TabContents>(this),
644 NotificationService::NoDetails());
645}
646
[email protected]d5f942ba2008-09-26 19:30:34647void TabContents::Activate() {
648 if (delegate_)
649 delegate_->ActivateContents(this);
650}
651
[email protected]96d185d2009-04-24 03:28:54652void TabContents::ShowContents() {
653 if (render_widget_host_view())
654 render_widget_host_view()->DidBecomeSelected();
655
656 // Loop through children and send DidBecomeSelected to them, too.
657 int count = static_cast<int>(child_windows_.size());
658 for (int i = count - 1; i >= 0; --i) {
659 ConstrainedWindow* window = child_windows_.at(i);
660 window->DidBecomeSelected();
661 }
662}
663
664void TabContents::HideContents() {
665 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
666 // our superclass HideContents(), because some callers want to be very picky
667 // about the order in which these get called. In addition to making the code
668 // here practically impossible to understand, this also means we end up
669 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34670 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54671 WasHidden();
672}
673
[email protected]c0588052008-10-27 23:01:50674void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34675 WindowOpenDisposition disposition,
676 PageTransition::Type transition) {
677 if (delegate_)
[email protected]c0588052008-10-27 23:01:50678 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34679}
680
681bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54682 const NavigationEntry& entry = *controller_.pending_entry();
683
684 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
685 if (!dest_render_view_host)
686 return false; // Unable to create the desired render view host.
687
688 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]684b4ba22009-05-07 06:27:41689 DevToolsManager* devtools_manager = g_browser_process->devtools_manager();
[email protected]7e8e6b62009-05-08 11:28:32690 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41691 devtools_manager->OnNavigatingToPendingEntry(
692 render_view_host(),
693 dest_render_view_host,
694 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32695 }
[email protected]96d185d2009-04-24 03:28:54696
697 // Used for page load time metrics.
698 current_load_start_ = base::TimeTicks::Now();
699
700 // Navigate in the desired RenderViewHost.
701 dest_render_view_host->NavigateToEntry(entry, reload);
702
703 if (entry.page_id() == -1) {
704 // HACK!! This code suppresses javascript: URLs from being added to
705 // session history, which is what we want to do for javascript: URLs that
706 // do not generate content. What we really need is a message from the
707 // renderer telling us that a new page was not created. The same message
708 // could be used for mailto: URLs and the like.
709 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
710 return false;
711 }
712
713 // Clear any provisional password saves - this stops password infobars
714 // showing up on pages the user navigates to while the right page is
715 // loading.
716 GetPasswordManager()->ClearProvisionalSave();
717
718 if (reload && !profile()->IsOffTheRecord()) {
719 HistoryService* history =
720 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
721 if (history)
722 history->SetFavIconOutOfDateForPage(entry.url());
723 }
724
[email protected]d5f942ba2008-09-26 19:30:34725 return true;
726}
727
[email protected]96d185d2009-04-24 03:28:54728void TabContents::Stop() {
729 render_manager_.Stop();
730 printing_.Stop();
731}
732
733void TabContents::Cut() {
734 render_view_host()->Cut();
735}
736
737void TabContents::Copy() {
738 render_view_host()->Copy();
739}
740
741void TabContents::Paste() {
742 render_view_host()->Paste();
743}
744
745void TabContents::DisassociateFromPopupCount() {
746 render_view_host()->DisassociateFromPopupCount();
747}
748
749TabContents* TabContents::Clone() {
750 // We create a new SiteInstance so that the new tab won't share processes
751 // with the old one. This can be changed in the future if we need it to share
752 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32753 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54754 SiteInstance::CreateSiteInstance(profile()),
755 MSG_ROUTING_NONE, NULL);
756 tc->controller().CopyStateFrom(controller_);
757 return tc;
758}
759
[email protected]420ae012009-04-24 05:16:32760void TabContents::CreateShortcut() {
761 NavigationEntry* entry = controller_.GetLastCommittedEntry();
762 if (!entry)
763 return;
764
765 // We only allow one pending install request. By resetting the page id we
766 // effectively cancel the pending install request.
767 pending_install_.page_id = entry->page_id();
768 pending_install_.icon = GetFavIcon();
769 pending_install_.title = UTF16ToWideHack(GetTitle());
770 pending_install_.url = GetURL();
771 if (pending_install_.callback_functor) {
772 pending_install_.callback_functor->Cancel();
773 pending_install_.callback_functor = NULL;
774 }
775 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
776 if (pending_install_.title.empty())
777 pending_install_.title = UTF8ToWide(GetURL().spec());
778
779 // Request the application info. When done OnDidGetApplicationInfo is invoked
780 // and we'll create the shortcut.
781 render_view_host()->GetApplicationInfo(pending_install_.page_id);
782}
783
[email protected]76f68dc2009-03-10 20:31:32784#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29785ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]c2dacc92008-10-16 23:51:38786 views::WindowDelegate* window_delegate,
787 views::View* contents_view) {
initial.commit09911bf2008-07-26 23:55:29788 ConstrainedWindow* window =
789 ConstrainedWindow::CreateConstrainedDialog(
790 this, gfx::Rect(), contents_view, window_delegate);
791 child_windows_.push_back(window);
792 return window;
793}
[email protected]f3332e12009-03-23 15:28:57794#endif
initial.commit09911bf2008-07-26 23:55:29795
796void TabContents::AddNewContents(TabContents* new_contents,
797 WindowOpenDisposition disposition,
798 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22799 bool user_gesture,
800 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29801 if (!delegate_)
802 return;
803
[email protected]f3332e12009-03-23 15:28:57804#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:22805 bool constrain_popup = false;
[email protected]35f7d212009-04-29 21:19:27806 if ((disposition == NEW_POPUP) && !user_gesture &&
807 !CommandLine::ForCurrentProcess()->HasSwitch(
808 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22809 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31810 // the whitelist. The popup owner will handle checking this.
811 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
812 initial_pos,
813 creator_url.is_valid() ? creator_url.host() : std::string());
814 } else {
[email protected]0aa55312008-10-17 21:53:08815 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29816 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
817 user_gesture);
818 }
[email protected]b6c874582009-05-08 19:38:31819 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
[email protected]f3332e12009-03-23 15:28:57820#else
821 // TODO(port): implement the popup blocker stuff
822 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
823 user_gesture);
824#endif
initial.commit09911bf2008-07-26 23:55:29825}
826
[email protected]0c9ee992009-06-03 16:56:38827#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29828void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25829 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22830 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29831}
[email protected]0c9ee992009-06-03 16:56:38832#endif
initial.commit09911bf2008-07-26 23:55:29833
[email protected]96d185d2009-04-24 03:28:54834void TabContents::PopupNotificationVisibilityChanged(bool visible) {
835 render_view_host()->PopupNotificationVisibilityChanged(visible);
836}
837
838gfx::NativeView TabContents::GetContentNativeView() {
839 return view_->GetContentNativeView();
840}
841
842gfx::NativeView TabContents::GetNativeView() const {
843 return view_->GetNativeView();
844}
845
846void TabContents::GetContainerBounds(gfx::Rect *out) const {
847 view_->GetContainerBounds(out);
848}
849
850void TabContents::Focus() {
851 view_->Focus();
852}
853
854void TabContents::SetInitialFocus(bool reverse) {
855 render_view_host()->SetInitialFocus(reverse);
856}
857
858bool TabContents::FocusLocationBarByDefault() {
859 DOMUI* dom_ui = GetDOMUIForCurrentState();
860 if (dom_ui)
861 return dom_ui->focus_location_bar_by_default();
862 return false;
863}
864
[email protected]616ed5a2008-11-21 22:27:24865void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
866 // Look through the existing InfoBarDelegates we have for a match. If we've
867 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05868 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24869 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
870 return;
871 }
872
873 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56874 NotificationService::current()->Notify(
875 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
876 Source<TabContents>(this),
877 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24878
879 // Add ourselves as an observer for navigations the first time a delegate is
880 // added. We use this notification to expire InfoBars that need to expire on
881 // page transitions.
882 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56883 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57884 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24885 }
886}
887
888void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
889 std::vector<InfoBarDelegate*>::iterator it =
890 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
891 if (it != infobar_delegates_.end()) {
892 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56893 NotificationService::current()->Notify(
894 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
895 Source<TabContents>(this),
896 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05897 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24898
[email protected]6a02963e2009-01-06 16:58:03899 // Remove ourselves as an observer if we are tracking no more InfoBars.
900 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56901 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57902 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03903 }
[email protected]616ed5a2008-11-21 22:27:24904 }
905}
[email protected]3edd9522009-03-04 22:19:41906
[email protected]96d185d2009-04-24 03:28:54907bool TabContents::IsBookmarkBarAlwaysVisible() {
908 // See GetDOMUIForCurrentState() comment for more info. This case is very
909 // similar, but for non-first loads, we want to use the committed entry. This
910 // is so the bookmarks bar disappears at the same time the page does.
911 if (controller_.GetLastCommittedEntry()) {
912 // Not the first load, always use the committed DOM UI.
913 if (render_manager_.dom_ui())
914 return render_manager_.dom_ui()->force_bookmark_bar_visible();
915 return false; // Default.
916 }
917
918 // When it's the first load, we know either the pending one or the committed
919 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
920 // of them will be valid, so we can just check both.
921 if (render_manager_.pending_dom_ui())
922 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
923 if (render_manager_.dom_ui())
924 return render_manager_.dom_ui()->force_bookmark_bar_visible();
925 return false; // Default.
926}
927
928void TabContents::SetDownloadShelfVisible(bool visible) {
929 if (shelf_visible_ != visible) {
930 if (visible) {
931 // Invoke GetDownloadShelf to force the shelf to be created.
[email protected]0a2aeb82009-05-15 21:52:48932 GetDownloadShelf(true);
[email protected]96d185d2009-04-24 03:28:54933 }
934 shelf_visible_ = visible;
935
[email protected]c9cd2222009-05-06 05:16:50936 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]3a6a3b62009-05-27 21:36:20937
938 if (delegate())
939 delegate()->UpdateDownloadShelfVisibility(visible);
[email protected]96d185d2009-04-24 03:28:54940 }
941
942 // SetShelfVisible can force-close the shelf, so make sure we lay out
943 // everything correctly, as if the animation had finished. This doesn't
944 // matter for showing the shelf, as the show animation will do it.
945 ToolbarSizeChanged(false);
946
947 if (visible) {
948 // Always set this value as it reflects the last time the download shelf
949 // was made visible (even if it was already visible).
950 last_download_shelf_show_ = base::TimeTicks::Now();
951 }
952}
953
[email protected]3edd9522009-03-04 22:19:41954void TabContents::ToolbarSizeChanged(bool is_animating) {
955 TabContentsDelegate* d = delegate();
956 if (d)
957 d->ToolbarSizeChanged(this, is_animating);
958}
[email protected]616ed5a2008-11-21 22:27:24959
[email protected]d5f942ba2008-09-26 19:30:34960void TabContents::OnStartDownload(DownloadItem* download) {
961 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34962
963 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31964 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34965
[email protected]bcef0dc02009-02-28 00:35:02966 // GetDownloadShelf creates the download shelf if it was not yet created.
[email protected]0a2aeb82009-05-15 21:52:48967 tab_contents->GetDownloadShelf(true)->AddDownload(
[email protected]bcef0dc02009-02-28 00:35:02968 new DownloadItemModel(download));
[email protected]d5f942ba2008-09-26 19:30:34969 tab_contents->SetDownloadShelfVisible(true);
970
[email protected]bd1ad682009-05-15 22:19:17971// TODO(port): port for mac.
972#if defined(OS_WIN) || defined(OS_LINUX)
973 // We make this check for the case of minimized windows, unit tests, etc.
974 if (platform_util::IsVisible(GetNativeView())) {
975 DownloadStartedAnimation::Show(tab_contents);
[email protected]d5f942ba2008-09-26 19:30:34976 }
[email protected]3edd9522009-03-04 22:19:41977#endif
[email protected]d5f942ba2008-09-26 19:30:34978}
979
[email protected]0a2aeb82009-05-15 21:52:48980DownloadShelf* TabContents::GetDownloadShelf(bool create) {
981 if (!download_shelf_.get() && create)
[email protected]bcef0dc02009-02-28 00:35:02982 download_shelf_.reset(DownloadShelf::Create(this));
983 return download_shelf_.get();
initial.commit09911bf2008-07-26 23:55:29984}
985
[email protected]bcef0dc02009-02-28 00:35:02986void TabContents::MigrateShelfFrom(TabContents* tab_contents) {
[email protected]0a2aeb82009-05-15 21:52:48987 download_shelf_.reset(tab_contents->GetDownloadShelf(true));
[email protected]bcef0dc02009-02-28 00:35:02988 download_shelf_->ChangeTabContents(tab_contents, this);
989 tab_contents->ReleaseDownloadShelf();
initial.commit09911bf2008-07-26 23:55:29990}
991
[email protected]3edd9522009-03-04 22:19:41992void TabContents::ReleaseDownloadShelf() {
993 download_shelf_.release();
994}
995
996// static
997void TabContents::MigrateShelf(TabContents* from, TabContents* to) {
998 bool was_shelf_visible = from->IsDownloadShelfVisible();
999 if (was_shelf_visible)
1000 to->MigrateShelfFrom(from);
1001 to->SetDownloadShelfVisible(was_shelf_visible);
1002}
[email protected]3edd9522009-03-04 22:19:411003
[email protected]d5f942ba2008-09-26 19:30:341004void TabContents::WillClose(ConstrainedWindow* window) {
1005 ConstrainedWindowList::iterator it =
1006 find(child_windows_.begin(), child_windows_.end(), window);
1007 if (it != child_windows_.end())
1008 child_windows_.erase(it);
1009
[email protected]0c9ee992009-06-03 16:56:381010#if defined(OS_WIN)
1011 if (window == blocked_popups_)
1012 blocked_popups_ = NULL;
1013
1014 if (::IsWindow(GetNativeView())) {
1015 CRect client_rect;
1016 GetClientRect(GetNativeView(), &client_rect);
1017 RepositionSupressedPopupsToFit(
1018 gfx::Size(client_rect.Width(), client_rect.Height()));
1019 }
1020#endif
[email protected]d5f942ba2008-09-26 19:30:341021}
1022
[email protected]d5f942ba2008-09-26 19:30:341023void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:351024#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:061025 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:351026#endif
[email protected]d5f942ba2008-09-26 19:30:341027}
1028
[email protected]e491f1c2009-05-22 20:28:121029void TabContents::StartFinding(string16 find_text,
1030 bool forward_direction,
1031 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:011032 // If find_text is empty, it means FindNext was pressed with a keyboard
1033 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:121034 if (find_text.empty() && find_text_.empty()) {
1035 if (last_search_prepopulate_text_->empty())
1036 return;
1037 // Try whatever we searched for last in any tab.
1038 find_text = *last_search_prepopulate_text_;
1039 }
[email protected]6e95706d2009-04-23 22:55:011040
1041 // This is a FindNext operation if we are searching for the same text again,
1042 // or if the passed in search text is empty (FindNext keyboard shortcut). The
1043 // exception to this is if the Find was aborted (then we don't want FindNext
1044 // because the highlighting has been cleared and we need it to reappear). We
1045 // therefore treat FindNext after an aborted Find operation as a full fledged
1046 // Find.
1047 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:121048 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:011049 !find_op_aborted_;
1050 if (!find_next)
1051 current_find_request_id_ = find_request_id_counter_++;
1052
1053 if (!find_text.empty())
1054 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:121055 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:011056
1057 find_op_aborted_ = false;
1058
1059 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:121060 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:011061
1062 render_view_host()->StartFinding(current_find_request_id_,
1063 find_text_,
1064 forward_direction,
[email protected]e491f1c2009-05-22 20:28:121065 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:011066 find_next);
1067}
1068
1069void TabContents::StopFinding(bool clear_selection) {
1070 find_ui_active_ = false;
1071 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:121072 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:011073 render_view_host()->StopFinding(clear_selection);
1074}
1075
[email protected]420ae012009-04-24 05:16:321076void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
1077 bool success,
1078 const std::wstring& prompt) {
1079 last_javascript_message_dismissal_ = base::TimeTicks::Now();
1080 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
1081}
1082
[email protected]571e31152009-05-15 19:34:021083void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
1084 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
1085}
1086
[email protected]420ae012009-04-24 05:16:321087void TabContents::OnSavePage() {
1088 // If we can not save the page, try to download it.
1089 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1090 DownloadManager* dlm = profile()->GetDownloadManager();
1091 const GURL& current_page_url = GetURL();
1092 if (dlm && current_page_url.is_valid())
[email protected]c9825a42009-05-01 22:51:501093 dlm->DownloadUrl(current_page_url, GURL(), "", AsWC(this));
[email protected]420ae012009-04-24 05:16:321094 return;
1095 }
1096
1097 Stop();
1098
1099 // Create the save package and possibly prompt the user for the name to save
1100 // the page as. The user prompt is an asynchronous operation that runs on
1101 // another thread.
1102 save_package_ = new SavePackage(AsWC(this));
1103 save_package_->GetSaveInfo();
1104}
1105
1106// Used in automated testing to bypass prompting the user for file names.
1107// Instead, the names and paths are hard coded rather than running them through
1108// file name sanitation and extension / mime checking.
1109void TabContents::SavePage(const std::wstring& main_file,
1110 const std::wstring& dir_path,
1111 SavePackage::SavePackageType save_type) {
1112 // Stop the page from navigating.
1113 Stop();
1114
1115 save_package_ = new SavePackage(AsWC(this), save_type,
1116 FilePath::FromWStringHack(main_file),
1117 FilePath::FromWStringHack(dir_path));
1118 save_package_->Init();
1119}
1120
1121void TabContents::PrintPreview() {
1122 // We don't show the print preview yet, only the print dialog.
1123 PrintNow();
1124}
1125
1126bool TabContents::PrintNow() {
1127 // We can't print interstitial page for now.
1128 if (showing_interstitial_page())
1129 return false;
1130
1131 return render_view_host()->PrintPages();
1132}
1133
1134bool TabContents::IsActiveEntry(int32 page_id) {
1135 NavigationEntry* active_entry = controller_.GetActiveEntry();
1136 return (active_entry != NULL &&
1137 active_entry->site_instance() == GetSiteInstance() &&
1138 active_entry->page_id() == page_id);
1139}
1140
[email protected]96d185d2009-04-24 03:28:541141// Notifies the RenderWidgetHost instance about the fact that the page is
1142// loading, or done loading and calls the base implementation.
1143void TabContents::SetIsLoading(bool is_loading,
1144 LoadNotificationDetails* details) {
1145 if (is_loading == is_loading_)
1146 return;
1147
1148 if (!is_loading) {
1149 load_state_ = net::LOAD_STATE_IDLE;
1150 load_state_host_.clear();
1151 }
1152
1153 render_manager_.SetIsLoading(is_loading);
1154
1155 is_loading_ = is_loading;
1156 waiting_for_response_ = is_loading;
1157
1158 if (delegate_)
1159 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351160 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541161
1162 NotificationType type = is_loading ? NotificationType::LOAD_START :
1163 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111164 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541165 if (details)
1166 det = Details<LoadNotificationDetails>(details);
1167 NotificationService::current()->Notify(type,
1168 Source<NavigationController>(&controller_),
1169 det);
1170}
1171
[email protected]76f68dc2009-03-10 20:31:321172#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:221173void TabContents::CreateBlockedPopupContainerIfNecessary() {
1174 if (blocked_popups_)
1175 return;
1176
1177 CRect client_rect;
1178 GetClientRect(GetNativeView(), &client_rect);
1179 gfx::Point anchor_position(
1180 client_rect.Width() - views::NativeScrollBar::GetVerticalScrollBarWidth(),
1181 client_rect.Height());
1182 blocked_popups_ = BlockedPopupContainer::Create(this, profile(),
1183 anchor_position);
[email protected]0c9ee992009-06-03 16:56:381184 child_windows_.push_back(blocked_popups_);
[email protected]2c4410d2009-05-06 23:46:221185}
1186
[email protected]b6c874582009-05-08 19:38:311187void TabContents::AddPopup(TabContents* new_contents,
1188 const gfx::Rect& initial_pos,
1189 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221190 CreateBlockedPopupContainerIfNecessary();
1191 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221192}
1193
[email protected]e69bce3dd2009-04-20 22:05:121194// TODO(brettw) This should be on the TabContentsView.
[email protected]0c9ee992009-06-03 16:56:381195void TabContents::RepositionSupressedPopupsToFit(const gfx::Size& new_size) {
1196 // TODO(erg): There's no way to detect whether scroll bars are
1197 // visible, so for beta, we're just going to assume that the
1198 // vertical scroll bar is visible, and not care about covering up
1199 // the horizontal scroll bar. Fixing this is half of
1200 // http://b/1118139.
1201 gfx::Point anchor_position(
1202 new_size.width() -
1203 views::NativeScrollBar::GetVerticalScrollBarWidth(),
1204 new_size.height());
1205
[email protected]d6598c052008-11-05 19:03:251206 if (blocked_popups_)
[email protected]0c9ee992009-06-03 16:56:381207 blocked_popups_->RepositionConstrainedWindowTo(anchor_position);
[email protected]d5f942ba2008-09-26 19:30:341208}
1209
[email protected]b9681312008-11-07 00:08:261210bool TabContents::ShowingBlockedPopupNotification() const {
1211 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221212 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261213}
[email protected]0c9ee992009-06-03 16:56:381214#endif // defined(OS_WIN)
[email protected]616ed5a2008-11-21 22:27:241215
1216namespace {
1217bool TransitionIsReload(PageTransition::Type transition) {
1218 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1219}
1220}
1221
1222void TabContents::ExpireInfoBars(
1223 const NavigationController::LoadCommittedDetails& details) {
1224 // Only hide InfoBars when the user has done something that makes the main
1225 // frame load. We don't want various automatic or subframe navigations making
1226 // it disappear.
1227 if (!details.is_user_initiated_main_frame_load())
1228 return;
1229
[email protected]f86a07022008-11-25 01:06:051230 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241231 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051232 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241233 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241234 }
1235}
[email protected]fdd61c62009-04-22 19:22:571236
1237void TabContents::OnGearsCreateShortcutDone(
1238 const GearsShortcutData2& shortcut_data, bool success) {
1239 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1240 bool same_page =
1241 current_entry && pending_install_.page_id == current_entry->page_id();
1242
1243 if (success && same_page) {
1244 // Only switch to app mode if the user chose to create a shortcut and
1245 // we're still on the same page that it corresponded to.
1246 if (delegate())
1247 delegate()->ConvertContentsToApplication(this);
1248 }
1249
1250 // Reset the page id to indicate no requests are pending.
1251 pending_install_.page_id = 0;
1252 pending_install_.callback_functor = NULL;
1253}
[email protected]96d185d2009-04-24 03:28:541254
1255DOMUI* TabContents::GetDOMUIForCurrentState() {
1256 // When there is a pending navigation entry, we want to use the pending DOMUI
1257 // that goes along with it to control the basic flags. For example, we want to
1258 // show the pending URL in the URL bar, so we want the display_url flag to
1259 // be from the pending entry.
1260 //
1261 // The confusion comes because there are multiple possibilities for the
1262 // initial load in a tab as a side effect of the way the RenderViewHostManager
1263 // works.
1264 //
1265 // - For the very first tab the load looks "normal". The new tab DOM UI is
1266 // the pending one, and we want it to apply here.
1267 //
1268 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1269 // get switched to the one previously associated with the new tab pages.
1270 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1271 // have a committed DOM UI in this case.
1272 //
1273 // This condition handles all of these cases:
1274 //
1275 // - First load in first tab: no committed nav entry + pending nav entry +
1276 // pending dom ui:
1277 // -> Use pending DOM UI if any.
1278 //
1279 // - First load in second tab: no committed nav entry + pending nav entry +
1280 // no pending DOM UI:
1281 // -> Use the committed DOM UI if any.
1282 //
1283 // - Second navigation in any tab: committed nav entry + pending nav entry:
1284 // -> Use pending DOM UI if any.
1285 //
1286 // - Normal state with no load: committed nav entry + no pending nav entry:
1287 // -> Use committed DOM UI.
1288 if (controller_.pending_entry() &&
1289 (controller_.GetLastCommittedEntry() ||
1290 render_manager_.pending_dom_ui()))
1291 return render_manager_.pending_dom_ui();
1292 return render_manager_.dom_ui();
1293}
[email protected]420ae012009-04-24 05:16:321294
1295void TabContents::DidNavigateMainFramePostCommit(
1296 const NavigationController::LoadCommittedDetails& details,
1297 const ViewHostMsg_FrameNavigate_Params& params) {
1298 // Hide the download shelf if all the following conditions are true:
1299 // - there are no active downloads.
1300 // - this is a navigation to a different TLD.
1301 // - at least 5 seconds have elapsed since the download shelf was shown.
1302 // TODO(jcampan): bug 1156075 when user gestures are reliable, they should
1303 // be used to ensure we are hiding only on user initiated
1304 // navigations.
1305 DownloadManager* download_manager = profile()->GetDownloadManager();
1306 // download_manager can be NULL in unit test context.
1307 if (download_manager && download_manager->in_progress_count() == 0 &&
1308 !details.previous_url.is_empty() &&
1309 !net::RegistryControlledDomainService::SameDomainOrHost(
1310 details.previous_url, details.entry->url())) {
1311 base::TimeDelta time_delta(
1312 base::TimeTicks::Now() - last_download_shelf_show_);
1313 if (time_delta >
1314 base::TimeDelta::FromMilliseconds(kDownloadShelfHideDelay)) {
1315 SetDownloadShelfVisible(false);
1316 }
1317 }
1318
1319 if (details.is_user_initiated_main_frame_load()) {
1320 // Clear the status bubble. This is a workaround for a bug where WebKit
1321 // doesn't let us know that the cursor left an element during a
1322 // transition (this is also why the mouse cursor remains as a hand after
1323 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1324 // clear the bubble when a user navigates to a named anchor in the same
1325 // page.
1326 UpdateTargetURL(details.entry->page_id(), GURL());
1327
1328 // UpdateHelpersForDidNavigate will handle the case where the password_form
1329 // origin is valid.
1330 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1331 // cleaned up and covered by tests.
1332 if (!params.password_form.origin.is_valid())
1333 GetPasswordManager()->DidNavigate();
1334 }
1335
1336 // The keyword generator uses the navigation entries, so must be called after
1337 // the commit.
1338 GenerateKeywordIfNecessary(params);
1339
1340 // Allow the new page to set the title again.
1341 received_page_title_ = false;
1342
1343 // Get the favicon, either from history or request it from the net.
1344 fav_icon_helper_.FetchFavIcon(details.entry->url());
1345
[email protected]ce5c4502009-05-06 16:46:111346 // Disable all page actions.
1347 enabled_page_actions_.clear();
1348
[email protected]420ae012009-04-24 05:16:321349 // Close constrained popups if necessary.
1350 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1351
1352 // Update the starred state.
1353 UpdateStarredStateForCurrentURL();
1354}
1355
1356void TabContents::DidNavigateAnyFramePostCommit(
1357 RenderViewHost* render_view_host,
1358 const NavigationController::LoadCommittedDetails& details,
1359 const ViewHostMsg_FrameNavigate_Params& params) {
1360 // If we navigate, start showing messages again. This does nothing to prevent
1361 // a malicious script from spamming messages, since the script could just
1362 // reload the page to stop blocking.
1363 suppress_javascript_messages_ = false;
1364
1365 // Update history. Note that this needs to happen after the entry is complete,
1366 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1367 if (params.should_update_history) {
1368 // Most of the time, the displayURL matches the loaded URL, but for about:
1369 // URLs, we use a data: URL as the real value. We actually want to save
1370 // the about: URL to the history db and keep the data: URL hidden. This is
1371 // what the TabContents' URL getter does.
1372 UpdateHistoryForNavigation(GetURL(), params);
1373 }
1374
1375 // Notify the password manager of the navigation or form submit.
1376 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1377 // cleaned up and covered by tests.
1378 if (params.password_form.origin.is_valid())
1379 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1380}
1381
1382void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1383 const GURL& current_url) {
1384 if (net::RegistryControlledDomainService::SameDomainOrHost(
1385 previous_url, current_url))
1386 return;
1387
1388 // Clear out any child windows since we are leaving this page entirely.
1389 // We use indices instead of iterators in case CloseWindow does something
1390 // that may invalidate an iterator.
1391 int size = static_cast<int>(child_windows_.size());
1392 for (int i = size - 1; i >= 0; --i) {
1393 ConstrainedWindow* window = child_windows_[i];
1394 if (window)
1395 window->CloseConstrainedWindow();
1396 }
1397}
1398
1399void TabContents::UpdateStarredStateForCurrentURL() {
1400 BookmarkModel* model = profile()->GetBookmarkModel();
1401 const bool old_state = is_starred_;
1402 is_starred_ = (model && model->IsBookmarked(GetURL()));
1403
1404 if (is_starred_ != old_state && delegate())
1405 delegate()->URLStarredChanged(this, is_starred_);
1406}
1407
1408void TabContents::UpdateAlternateErrorPageURL() {
1409 GURL url = GetAlternateErrorPageURL();
1410 render_view_host()->SetAlternateErrorPageURL(url);
1411}
1412
1413void TabContents::UpdateWebPreferences() {
1414 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1415}
1416
1417void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1418 RenderViewHost* rvh) {
1419 // If we are creating a RVH for a restored controller, then we might
1420 // have more page IDs than the SiteInstance's current max page ID. We must
1421 // make sure that the max page ID is larger than any restored page ID.
1422 // Note that it is ok for conflicting page IDs to exist in another tab
1423 // (i.e., NavigationController), but if any page ID is larger than the max,
1424 // the back/forward list will get confused.
1425 int max_restored_page_id = controller_.max_restored_page_id();
1426 if (max_restored_page_id > 0) {
1427 int curr_max_page_id = site_instance->max_page_id();
1428 if (max_restored_page_id > curr_max_page_id) {
1429 // Need to update the site instance immediately.
1430 site_instance->UpdateMaxPageID(max_restored_page_id);
1431
1432 // Also tell the renderer to update its internal representation. We
1433 // need to reserve enough IDs to make all restored page IDs less than
1434 // the max.
1435 if (curr_max_page_id < 0)
1436 curr_max_page_id = 0;
1437 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1438 }
1439 }
1440}
1441
1442void TabContents::UpdateHistoryForNavigation(
1443 const GURL& display_url,
1444 const ViewHostMsg_FrameNavigate_Params& params) {
1445 if (profile()->IsOffTheRecord())
1446 return;
1447
1448 // Add to history service.
1449 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1450 if (hs) {
1451 if (PageTransition::IsMainFrame(params.transition) &&
1452 display_url != params.url) {
1453 // Hack on the "display" URL so that it will appear in history. For some
1454 // types of URLs, we will display a magic URL that is different from where
1455 // the page is actually navigated. We want the user to see in history
1456 // what they saw in the URL bar, so we add the display URL as a redirect.
1457 // This only applies to the main frame, as the display URL doesn't apply
1458 // to sub-frames.
1459 std::vector<GURL> redirects = params.redirects;
1460 if (!redirects.empty())
1461 redirects.back() = display_url;
1462 hs->AddPage(display_url, this, params.page_id, params.referrer,
1463 params.transition, redirects);
1464 } else {
1465 hs->AddPage(params.url, this, params.page_id, params.referrer,
1466 params.transition, params.redirects);
1467 }
1468 }
1469}
1470
1471bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1472 const std::wstring& title) {
1473 // For file URLs without a title, use the pathname instead. In the case of a
1474 // synthesized title, we don't want the update to count toward the "one set
1475 // per page of the title to history."
1476 std::wstring final_title;
1477 bool explicit_set;
1478 if (entry->url().SchemeIsFile() && title.empty()) {
1479 final_title = UTF8ToWide(entry->url().ExtractFileName());
1480 explicit_set = false; // Don't count synthetic titles toward the set limit.
1481 } else {
1482 TrimWhitespace(title, TRIM_ALL, &final_title);
1483 explicit_set = true;
1484 }
1485
1486 if (final_title == UTF16ToWideHack(entry->title()))
1487 return false; // Nothing changed, don't bother.
1488
1489 entry->set_title(WideToUTF16Hack(final_title));
1490
1491 // Update the history system for this page.
1492 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1493 HistoryService* hs =
1494 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1495 if (hs)
1496 hs->SetPageTitle(entry->display_url(), final_title);
1497
1498 // Don't allow the title to be saved again for explicitly set ones.
1499 received_page_title_ = explicit_set;
1500 }
1501
1502 // Lastly, set the title for the view.
1503 view_->SetPageTitle(final_title);
1504
1505 return true;
1506}
1507
1508void TabContents::NotifySwapped() {
1509 // After sending out a swap notification, we need to send a disconnect
1510 // notification so that clients that pick up a pointer to |this| can NULL the
1511 // pointer. See Bug 1230284.
1512 notify_disconnection_ = true;
1513 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341514 NotificationType::TAB_CONTENTS_SWAPPED,
1515 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321516 NotificationService::NoDetails());
1517}
1518
1519void TabContents::NotifyConnected() {
1520 notify_disconnection_ = true;
1521 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341522 NotificationType::TAB_CONTENTS_CONNECTED,
1523 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321524 NotificationService::NoDetails());
1525}
1526
1527void TabContents::NotifyDisconnected() {
1528 if (!notify_disconnection_)
1529 return;
1530
1531 notify_disconnection_ = false;
1532 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341533 NotificationType::TAB_CONTENTS_DISCONNECTED,
1534 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321535 NotificationService::NoDetails());
1536}
1537
1538void TabContents::GenerateKeywordIfNecessary(
1539 const ViewHostMsg_FrameNavigate_Params& params) {
1540 if (!params.searchable_form_url.is_valid())
1541 return;
1542
1543 if (profile()->IsOffTheRecord())
1544 return;
1545
1546 int last_index = controller_.last_committed_entry_index();
1547 // When there was no previous page, the last index will be 0. This is
1548 // normally due to a form submit that opened in a new tab.
1549 // TODO(brettw) bug 916126: we should support keywords when form submits
1550 // happen in new tabs.
1551 if (last_index <= 0)
1552 return;
1553 const NavigationEntry* previous_entry =
1554 controller_.GetEntryAtIndex(last_index - 1);
1555 if (IsFormSubmit(previous_entry)) {
1556 // Only generate a keyword if the previous page wasn't itself a form
1557 // submit.
1558 return;
1559 }
1560
1561 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1562 previous_entry->user_typed_url() : previous_entry->url();
1563 std::wstring keyword =
1564 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1565 if (keyword.empty())
1566 return;
1567
1568 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1569 if (!url_model)
1570 return;
1571
1572 if (!url_model->loaded()) {
1573 url_model->Load();
1574 return;
1575 }
1576
1577 const TemplateURL* current_url;
1578 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1579 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1580 return;
1581
1582 if (current_url) {
1583 if (current_url->originating_url().is_valid()) {
1584 // The existing keyword was generated from an OpenSearch description
1585 // document, don't regenerate.
1586 return;
1587 }
1588 url_model->Remove(current_url);
1589 }
1590 TemplateURL* new_url = new TemplateURL();
1591 new_url->set_keyword(keyword);
1592 new_url->set_short_name(keyword);
1593 new_url->SetURL(url, 0, 0);
1594 new_url->add_input_encoding(params.searchable_form_encoding);
1595 DCHECK(controller_.GetLastCommittedEntry());
1596 const GURL& favicon_url =
1597 controller_.GetLastCommittedEntry()->favicon().url();
1598 if (favicon_url.is_valid()) {
1599 new_url->SetFavIconURL(favicon_url);
1600 } else {
1601 // The favicon url isn't valid. This means there really isn't a favicon,
1602 // or the favicon url wasn't obtained before the load started. This assumes
1603 // the later.
1604 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1605 // its url.
1606 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1607 }
1608 new_url->set_safe_for_autoreplace(true);
1609 url_model->Add(new_url);
1610}
1611
1612RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1613 return view_.get();
1614}
1615
1616RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1617 return save_package_.get(); // May be NULL, but we can return NULL.
1618}
1619
[email protected]6dfed102009-04-28 03:09:531620ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1621 RenderViewHost* render_view_host,
1622 const std::string& extension_id) {
1623 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1624 extension_id);
1625}
1626
[email protected]57c6a652009-05-04 07:58:341627TabContents* TabContents::GetAsTabContents() {
1628 return this;
1629}
1630
[email protected]420ae012009-04-24 05:16:321631void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1632 NavigationEntry* entry = controller_.GetActiveEntry();
1633 if (!entry)
1634 return;
1635
1636 // When we're creating views, we're still doing initial setup, so we always
1637 // use the pending DOM UI rather than any possibly existing committed one.
1638 if (render_manager_.pending_dom_ui()) {
1639 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1640 }
1641
1642 if (entry->IsViewSourceMode()) {
1643 // Put the renderer in view source mode.
1644 render_view_host->Send(
1645 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1646 }
[email protected]0666aef2009-05-13 19:48:081647
1648 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321649}
1650
1651void TabContents::RenderViewReady(RenderViewHost* rvh) {
1652 if (rvh != render_view_host()) {
1653 // Don't notify the world, since this came from a renderer in the
1654 // background.
1655 return;
1656 }
1657
1658 NotifyConnected();
1659 SetIsCrashed(false);
1660}
1661
1662void TabContents::RenderViewGone(RenderViewHost* rvh) {
1663 // Ask the print preview if this renderer was valuable.
1664 if (!printing_.OnRenderViewGone(rvh))
1665 return;
1666 if (rvh != render_view_host()) {
1667 // The pending page's RenderViewHost is gone.
1668 return;
1669 }
1670
1671 SetIsLoading(false, NULL);
1672 NotifyDisconnected();
1673 SetIsCrashed(true);
1674
1675 // Force an invalidation to render sad tab. The view will notice we crashed
1676 // when it paints.
1677 view_->Invalidate();
1678
1679 // Hide any visible hung renderer warning for this web contents' process.
[email protected]8897c382009-05-06 17:53:261680 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:321681}
1682
1683void TabContents::DidNavigate(RenderViewHost* rvh,
1684 const ViewHostMsg_FrameNavigate_Params& params) {
1685 if (PageTransition::IsMainFrame(params.transition))
1686 render_manager_.DidNavigateMainFrame(rvh);
1687
1688 // Update the site of the SiteInstance if it doesn't have one yet.
1689 if (!GetSiteInstance()->has_site())
1690 GetSiteInstance()->SetSite(params.url);
1691
1692 // Need to update MIME type here because it's referred to in
1693 // UpdateNavigationCommands() called by RendererDidNavigate() to
1694 // determine whether or not to enable the encoding menu.
1695 // It's updated only for the main frame. For a subframe,
1696 // RenderView::UpdateURL does not set params.contents_mime_type.
1697 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1698 // TODO(jungshik): Add a test for the encoding menu to avoid
1699 // regressing it again.
1700 if (PageTransition::IsMainFrame(params.transition))
1701 contents_mime_type_ = params.contents_mime_type;
1702
1703 NavigationController::LoadCommittedDetails details;
1704 if (!controller_.RendererDidNavigate(params, &details))
1705 return; // No navigation happened.
1706
1707 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1708 // for the appropriate notification (best) or you can add it to
1709 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1710 // necessary, please).
1711
1712 // Run post-commit tasks.
1713 if (details.is_main_frame)
1714 DidNavigateMainFramePostCommit(details, params);
1715 DidNavigateAnyFramePostCommit(rvh, details, params);
1716}
1717
1718void TabContents::UpdateState(RenderViewHost* rvh,
1719 int32 page_id,
1720 const std::string& state) {
1721 DCHECK(rvh == render_view_host());
1722
1723 // We must be prepared to handle state updates for any page, these occur
1724 // when the user is scrolling and entering form data, as well as when we're
1725 // leaving a page, in which case our state may have already been moved to
1726 // the next page. The navigation controller will look up the appropriate
1727 // NavigationEntry and update it when it is notified via the delegate.
1728
1729 int entry_index = controller_.GetEntryIndexWithPageID(
1730 GetSiteInstance(), page_id);
1731 if (entry_index < 0)
1732 return;
1733 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1734
1735 if (state == entry->content_state())
1736 return; // Nothing to update.
1737 entry->set_content_state(state);
1738 controller_.NotifyEntryChanged(entry, entry_index);
1739}
1740
1741void TabContents::UpdateTitle(RenderViewHost* rvh,
1742 int32 page_id, const std::wstring& title) {
1743 // If we have a title, that's a pretty good indication that we've started
1744 // getting useful data.
1745 SetNotWaitingForResponse();
1746
1747 DCHECK(rvh == render_view_host());
1748 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1749 page_id);
1750 if (!entry || !UpdateTitleForEntry(entry, title))
1751 return;
1752
1753 // Broadcast notifications when the UI should be updated.
1754 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501755 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321756}
1757
[email protected]420ae012009-04-24 05:16:321758void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1759 const std::wstring& encoding) {
1760 set_encoding(encoding);
1761}
1762
1763void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1764 if (delegate())
1765 delegate()->UpdateTargetURL(this, url);
1766}
1767
1768void TabContents::UpdateThumbnail(const GURL& url,
1769 const SkBitmap& bitmap,
1770 const ThumbnailScore& score) {
1771 // Tell History about this thumbnail
1772 HistoryService* hs;
1773 if (!profile()->IsOffTheRecord() &&
1774 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1775 hs->SetPageThumbnail(url, bitmap, score);
1776 }
1777}
1778
[email protected]0df30122009-06-03 12:13:081779void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
1780 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
1781 raw_settings);
1782}
1783
[email protected]420ae012009-04-24 05:16:321784void TabContents::Close(RenderViewHost* rvh) {
1785 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1786 if (delegate() && rvh == render_view_host())
1787 delegate()->CloseContents(this);
1788}
1789
1790void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1791 if (delegate() && delegate()->IsPopup(this))
1792 delegate()->MoveContents(this, new_bounds);
1793}
1794
[email protected]329581b2009-04-28 06:52:351795void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321796 SetIsLoading(true, NULL);
1797}
1798
[email protected]329581b2009-04-28 06:52:351799void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321800 scoped_ptr<LoadNotificationDetails> details;
1801
1802 NavigationEntry* entry = controller_.GetActiveEntry();
1803 // An entry may not exist for a stop when loading an initial blank page or
1804 // if an iframe injected by script into a blank page finishes loading.
1805 if (entry) {
1806 scoped_ptr<base::ProcessMetrics> metrics(
1807 base::ProcessMetrics::CreateProcessMetrics(
1808 process()->process().handle()));
1809
1810 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1811
1812 details.reset(new LoadNotificationDetails(
1813 entry->display_url(),
1814 entry->transition_type(),
1815 elapsed,
1816 &controller_,
1817 controller_.GetCurrentEntryIndex()));
1818 }
1819
1820 // Tell PasswordManager we've finished a page load, which serves as a
1821 // green light to save pending passwords and reset itself.
1822 GetPasswordManager()->DidStopLoading();
1823
1824 SetIsLoading(false, details.get());
1825}
1826
1827void TabContents::DidStartProvisionalLoadForFrame(
1828 RenderViewHost* render_view_host,
1829 bool is_main_frame,
1830 const GURL& url) {
1831 ProvisionalLoadDetails details(is_main_frame,
1832 controller_.IsURLInPageNavigation(url),
1833 url, std::string(), false);
1834 NotificationService::current()->Notify(
1835 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1836 Source<NavigationController>(&controller_),
1837 Details<ProvisionalLoadDetails>(&details));
1838}
1839
1840void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1841 const GURL& source_url,
1842 const GURL& target_url) {
1843 NavigationEntry* entry;
1844 if (page_id == -1)
1845 entry = controller_.pending_entry();
1846 else
1847 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1848 if (!entry || entry->url() != source_url)
1849 return;
1850 entry->set_url(target_url);
1851}
1852
1853void TabContents::DidLoadResourceFromMemoryCache(
1854 const GURL& url,
1855 const std::string& frame_origin,
1856 const std::string& main_frame_origin,
1857 const std::string& security_info) {
1858 // Send out a notification that we loaded a resource from our memory cache.
1859 int cert_id = 0, cert_status = 0, security_bits = 0;
1860 SSLManager::DeserializeSecurityInfo(security_info,
1861 &cert_id, &cert_status,
1862 &security_bits);
1863 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]9ae66cbf2009-05-12 16:21:031864 process()->pid(), cert_id, cert_status);
[email protected]420ae012009-04-24 05:16:321865
1866 NotificationService::current()->Notify(
1867 NotificationType::LOAD_FROM_MEMORY_CACHE,
1868 Source<NavigationController>(&controller_),
1869 Details<LoadFromMemoryCacheDetails>(&details));
1870}
1871
1872void TabContents::DidFailProvisionalLoadWithError(
1873 RenderViewHost* render_view_host,
1874 bool is_main_frame,
1875 int error_code,
1876 const GURL& url,
1877 bool showing_repost_interstitial) {
1878 if (net::ERR_ABORTED == error_code) {
1879 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1880 // This means that the interstitial won't be torn down properly, which is
1881 // bad. But if we have an interstitial, go back to another tab type, and
1882 // then load the same interstitial again, we could end up getting the first
1883 // interstitial's "failed" message (as a result of the cancel) when we're on
1884 // the second one.
1885 //
1886 // We can't tell this apart, so we think we're tearing down the current page
1887 // which will cause a crash later one. There is also some code in
1888 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1889 // out because of this problem.
1890 //
1891 // http://code.google.com/p/chromium/issues/detail?id=2855
1892 // Because this will not tear down the interstitial properly, if "back" is
1893 // back to another tab type, the interstitial will still be somewhat alive
1894 // in the previous tab type. If you navigate somewhere that activates the
1895 // tab with the interstitial again, you'll see a flash before the new load
1896 // commits of the interstitial page.
1897 if (showing_interstitial_page()) {
1898 LOG(WARNING) << "Discarding message during interstitial.";
1899 return;
1900 }
1901
1902 // This will discard our pending entry if we cancelled the load (e.g., if we
1903 // decided to download the file instead of load it). Only discard the
1904 // pending entry if the URLs match, otherwise the user initiated a navigate
1905 // before the page loaded so that the discard would discard the wrong entry.
1906 NavigationEntry* pending_entry = controller_.pending_entry();
1907 if (pending_entry && pending_entry->url() == url)
1908 controller_.DiscardNonCommittedEntries();
1909
1910 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1911 }
1912
1913 // Send out a notification that we failed a provisional load with an error.
1914 ProvisionalLoadDetails details(is_main_frame,
1915 controller_.IsURLInPageNavigation(url),
1916 url, std::string(), false);
1917 details.set_error_code(error_code);
1918
1919 NotificationService::current()->Notify(
1920 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1921 Source<NavigationController>(&controller_),
1922 Details<ProvisionalLoadDetails>(&details));
1923}
1924
1925void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1926 int32 page_id,
1927 const GURL& icon_url) {
1928 fav_icon_helper_.SetFavIconURL(icon_url);
1929}
1930
1931void TabContents::DidDownloadImage(
1932 RenderViewHost* render_view_host,
1933 int id,
1934 const GURL& image_url,
1935 bool errored,
1936 const SkBitmap& image) {
1937 // A notification for downloading would be more flexible, but for now I'm
1938 // forwarding to the two places that could possibly have initiated the
1939 // request. If we end up with another place invoking DownloadImage, probably
1940 // best to refactor out into notification service, or something similar.
1941 if (errored)
1942 fav_icon_helper_.FavIconDownloadFailed(id);
1943 else
1944 fav_icon_helper_.SetFavIcon(id, image_url, image);
1945}
1946
1947void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1948 WindowOpenDisposition disposition) {
1949 if (render_manager_.dom_ui()) {
1950 // When we're a DOM UI, it will provide a page transition type for us (this
1951 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1952 // generated suggestions).
1953 //
1954 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161955 // want web sites to see a referrer of "chrome://blah" (and some
1956 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321957 // send to the site), so we send no referrer.
1958 OpenURL(url, GURL(), disposition,
1959 render_manager_.dom_ui()->link_transition_type());
1960 } else {
1961 OpenURL(url, referrer, disposition, PageTransition::LINK);
1962 }
1963}
1964
1965void TabContents::DomOperationResponse(const std::string& json_string,
1966 int automation_id) {
1967 DomOperationNotificationDetails details(json_string, automation_id);
1968 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341969 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321970 Details<DomOperationNotificationDetails>(&details));
1971}
1972
1973void TabContents::ProcessDOMUIMessage(const std::string& message,
1974 const std::string& content) {
1975 if (!render_manager_.dom_ui()) {
1976 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1977 // Because the renderer might be owned and sending random messages, we need
1978 // to ignore these inproper ones.
1979 NOTREACHED();
1980 return;
1981 }
1982 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1983}
1984
1985void TabContents::ProcessExternalHostMessage(const std::string& message,
1986 const std::string& origin,
1987 const std::string& target) {
1988 if (delegate())
1989 delegate()->ForwardMessageToExternalHost(message, origin, target);
1990}
1991
1992void TabContents::GoToEntryAtOffset(int offset) {
1993 controller_.GoToOffset(offset);
1994}
1995
1996void TabContents::GetHistoryListCount(int* back_list_count,
1997 int* forward_list_count) {
1998 int current_index = controller_.last_committed_entry_index();
1999 *back_list_count = current_index;
2000 *forward_list_count = controller_.entry_count() - current_index - 1;
2001}
2002
2003void TabContents::RunFileChooser(bool multiple_files,
2004 const string16& title,
2005 const FilePath& default_file) {
2006 if (!select_file_dialog_.get())
2007 select_file_dialog_ = SelectFileDialog::Create(this);
2008 SelectFileDialog::Type dialog_type =
2009 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
2010 SelectFileDialog::SELECT_OPEN_FILE;
2011 select_file_dialog_->SelectFile(dialog_type, title, default_file,
2012 NULL, 0, FILE_PATH_LITERAL(""),
2013 view_->GetTopLevelNativeWindow(), NULL);
2014}
2015
2016void TabContents::RunJavaScriptMessage(
2017 const std::wstring& message,
2018 const std::wstring& default_prompt,
2019 const GURL& frame_url,
2020 const int flags,
2021 IPC::Message* reply_msg,
2022 bool* did_suppress_message) {
2023 // Suppress javascript messages when requested and when inside a constrained
2024 // popup window (because that activates them and breaks them out of the
2025 // constrained window jail).
2026 bool suppress_this_message = suppress_javascript_messages_;
2027 if (delegate())
2028 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:312029 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:322030
2031 *did_suppress_message = suppress_this_message;
2032
2033 if (!suppress_this_message) {
2034 base::TimeDelta time_since_last_message(
2035 base::TimeTicks::Now() - last_javascript_message_dismissal_);
2036 bool show_suppress_checkbox = false;
2037 // Show a checkbox offering to suppress further messages if this message is
2038 // being displayed within kJavascriptMessageExpectedDelay of the last one.
2039 if (time_since_last_message <
2040 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
2041 show_suppress_checkbox = true;
2042
2043 RunJavascriptMessageBox(AsWC(this), frame_url, flags, message, default_prompt,
2044 show_suppress_checkbox, reply_msg);
2045 } else {
2046 // If we are suppressing messages, just reply as is if the user immediately
2047 // pressed "Cancel".
2048 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
2049 }
2050}
2051
2052void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
2053 IPC::Message* reply_msg) {
2054 RunBeforeUnloadDialog(AsWC(this), message, reply_msg);
2055}
2056
2057void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
2058 const std::string& json_arguments,
2059 IPC::Message* reply_msg) {
2060 if (delegate()) {
2061 HtmlDialogUIDelegate* dialog_delegate =
2062 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
2063 reply_msg, AsWC(this));
2064 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
2065 }
2066}
2067
2068void TabContents::PasswordFormsSeen(
2069 const std::vector<PasswordForm>& forms) {
2070 GetPasswordManager()->PasswordFormsSeen(forms);
2071}
2072
2073void TabContents::AutofillFormSubmitted(
2074 const AutofillForm& form) {
2075 GetAutofillManager()->AutofillFormSubmitted(form);
2076}
2077
2078void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
2079 const std::wstring& user_text, int64 node_id, int request_id) {
2080 GetAutofillManager()->FetchValuesForName(field_name, user_text,
2081 kMaxAutofillMenuItems, node_id, request_id);
2082}
2083
2084void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
2085 const std::wstring& value) {
2086 GetAutofillManager()->RemoveValueForName(field_name, value);
2087}
2088
2089// Checks to see if we should generate a keyword based on the OSDD, and if
2090// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2091void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2092 int32 page_id, const GURL& url,
2093 bool autodetected) {
2094 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2095 DCHECK(url.is_valid());
2096 if (!IsActiveEntry(page_id))
2097 return;
2098 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2099 if (!url_model)
2100 return;
2101 if (!url_model->loaded()) {
2102 url_model->Load();
2103 return;
2104 }
2105 if (!profile()->GetTemplateURLFetcher())
2106 return;
2107
2108 if (profile()->IsOffTheRecord())
2109 return;
2110
2111 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2112 DCHECK(entry);
2113
2114 const NavigationEntry* base_entry = entry;
2115 if (IsFormSubmit(base_entry)) {
2116 // If the current page is a form submit, find the last page that was not
2117 // a form submit and use its url to generate the keyword from.
2118 int index = controller_.last_committed_entry_index() - 1;
2119 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2120 index--;
2121 if (index >= 0)
2122 base_entry = controller_.GetEntryAtIndex(index);
2123 else
2124 base_entry = NULL;
2125 }
2126
2127 // We want to use the user typed URL if available since that represents what
2128 // the user typed to get here, and fall back on the regular URL if not.
2129 if (!base_entry)
2130 return;
2131 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2132 base_entry->user_typed_url() : base_entry->url();
2133 if (!keyword_url.is_valid())
2134 return;
2135 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2136 autodetected);
2137 if (keyword.empty())
2138 return;
2139 const TemplateURL* template_url =
2140 url_model->GetTemplateURLForKeyword(keyword);
2141 if (template_url && (!template_url->safe_for_autoreplace() ||
2142 template_url->originating_url() == url)) {
2143 // Either there is a user created TemplateURL for this keyword, or the
2144 // keyword has the same OSDD url and we've parsed it.
2145 return;
2146 }
2147
2148 // Download the OpenSearch description document. If this is successful a
2149 // new keyword will be created when done.
2150#if defined(OS_WIN)
2151 gfx::NativeView ancestor = GetAncestor(view_->GetNativeView(), GA_ROOT);
2152#else
2153 gfx::NativeView ancestor = NULL;
2154#endif
2155 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2156 keyword,
2157 url,
2158 base_entry->favicon().url(),
2159 ancestor,
2160 autodetected);
2161}
2162
2163void TabContents::InspectElementReply(int num_resources) {
2164 // We have received reply from inspect element request. Notify the
2165 // automation provider in case we need to notify automation client.
2166 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:342167 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:322168 Details<int>(&num_resources));
2169}
2170
2171void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2172 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2173}
2174
2175void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2176 printing_.DidPrintPage(params);
2177}
2178
2179GURL TabContents::GetAlternateErrorPageURL() const {
2180 GURL url;
2181 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2182 if (profile()->IsOffTheRecord())
2183 return url;
2184
2185 PrefService* prefs = profile()->GetPrefs();
2186 DCHECK(prefs);
2187 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2188 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2189 url = google_util::AppendGoogleTLDParam(url);
2190 }
2191 return url;
2192}
2193
2194WebPreferences TabContents::GetWebkitPrefs() {
2195 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2196 bool isDomUI = false;
2197 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2198}
2199
2200void TabContents::OnMissingPluginStatus(int status) {
2201#if defined(OS_WIN)
2202// TODO(PORT): pull in when plug-ins work
2203 GetPluginInstaller()->OnMissingPluginStatus(status);
2204#endif
2205}
2206
2207void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2208#if defined(OS_WIN)
2209// TODO(PORT): pull in when plug-ins work
2210 DCHECK(!plugin_path.value().empty());
2211
2212 std::wstring plugin_name = plugin_path.ToWStringHack();
2213 scoped_ptr<FileVersionInfo> version_info(
2214 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2215 if (version_info.get()) {
2216 const std::wstring& product_name = version_info->product_name();
2217 if (!product_name.empty())
2218 plugin_name = product_name;
2219 }
2220 AddInfoBar(new SimpleAlertInfoBarDelegate(
2221 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2222 NULL));
2223#endif
2224}
2225
2226void TabContents::OnCrashedWorker() {
2227 AddInfoBar(new SimpleAlertInfoBarDelegate(
2228 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2229 NULL));
2230}
2231
2232void TabContents::OnJSOutOfMemory() {
2233 AddInfoBar(new SimpleAlertInfoBarDelegate(
2234 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2235}
2236
2237void TabContents::ShouldClosePage(bool proceed) {
2238 render_manager_.ShouldClosePage(proceed);
2239}
2240
2241void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2242 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342243 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322244 // delivered to a pending RenderViewHost. We must first run the onunload
2245 // handler of the old RenderViewHost before we can allow it to proceed.
2246 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2247 new_request_id);
2248}
2249
2250bool TabContents::CanBlur() const {
2251 return delegate() ? delegate()->CanBlur() : true;
2252}
2253
2254gfx::Rect TabContents::GetRootWindowResizerRect() const {
2255 if (delegate())
2256 return delegate()->GetRootWindowResizerRect();
2257 return gfx::Rect();
2258}
2259
2260void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2261 bool is_during_unload) {
2262 if (is_during_unload) {
2263 // Hang occurred while firing the beforeunload/unload handler.
2264 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112265 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322266
2267 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2268 return;
2269
2270 // If the tab hangs in the beforeunload/unload handler there's really
2271 // nothing we can do to recover. Pretend the unload listeners have
2272 // all fired and close the tab. If the hang is in the beforeunload handler
2273 // then the user will not have the option of cancelling the close.
2274 Close(rvh);
2275 return;
2276 }
2277
2278 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]8897c382009-05-06 17:53:262279 HungRendererDialog::ShowForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322280}
2281
2282void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]8897c382009-05-06 17:53:262283 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322284}
2285
2286void TabContents::LoadStateChanged(const GURL& url,
2287 net::LoadState load_state) {
2288 load_state_ = load_state;
2289 load_state_host_ = UTF8ToWide(url.host());
2290 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2291 SetNotWaitingForResponse();
2292 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502293 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322294}
2295
2296void TabContents::OnDidGetApplicationInfo(
2297 int32 page_id,
2298 const webkit_glue::WebApplicationInfo& info) {
2299 if (pending_install_.page_id != page_id)
2300 return; // The user clicked create on a separate page. Ignore this.
2301
2302 pending_install_.callback_functor =
2303 new GearsCreateShortcutCallbackFunctor(this);
2304 GearsCreateShortcut(
2305 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2306 NewCallback(pending_install_.callback_functor,
2307 &GearsCreateShortcutCallbackFunctor::Run));
2308}
2309
[email protected]14ce83f2009-05-28 18:35:242310void TabContents::OnUserGesture() {
2311 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
2312#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]420ae012009-04-24 05:16:322313 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2314 if (drm)
2315 drm->OnUserGesture(this);
2316#endif
2317}
2318
2319void TabContents::OnFindReply(int request_id,
2320 int number_of_matches,
2321 const gfx::Rect& selection_rect,
2322 int active_match_ordinal,
2323 bool final_update) {
2324 // Ignore responses for requests other than the one we have most recently
2325 // issued. That way we won't act on stale results when the user has
2326 // already typed in another query.
2327 if (request_id != current_find_request_id_)
2328 return;
2329
2330 if (number_of_matches == -1)
[email protected]e491f1c2009-05-22 20:28:122331 number_of_matches = last_search_result_.number_of_matches();
[email protected]420ae012009-04-24 05:16:322332 if (active_match_ordinal == -1)
[email protected]e491f1c2009-05-22 20:28:122333 active_match_ordinal = last_search_result_.active_match_ordinal();
[email protected]420ae012009-04-24 05:16:322334
[email protected]2c355c282009-05-21 23:24:432335 gfx::Rect selection = selection_rect;
2336 if (selection.IsEmpty())
[email protected]e491f1c2009-05-22 20:28:122337 selection = last_search_result_.selection_rect();
[email protected]2c355c282009-05-21 23:24:432338
[email protected]420ae012009-04-24 05:16:322339 // Notify the UI, automation and any other observers that a find result was
2340 // found.
[email protected]e491f1c2009-05-22 20:28:122341 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
2342 selection, active_match_ordinal,
2343 final_update);
[email protected]420ae012009-04-24 05:16:322344 NotificationService::current()->Notify(
2345 NotificationType::FIND_RESULT_AVAILABLE,
2346 Source<TabContents>(this),
[email protected]e491f1c2009-05-22 20:28:122347 Details<FindNotificationDetails>(&last_search_result_));
[email protected]420ae012009-04-24 05:16:322348}
2349
[email protected]829e7612009-04-25 01:15:112350bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322351 if (!delegate())
[email protected]829e7612009-04-25 01:15:112352 return false;
[email protected]420ae012009-04-24 05:16:322353
[email protected]829e7612009-04-25 01:15:112354 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322355}
2356
2357void TabContents::FileSelected(const FilePath& path,
2358 int index, void* params) {
2359 render_view_host()->FileSelected(path);
2360}
2361
2362void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2363 void* params) {
2364 render_view_host()->MultiFilesSelected(files);
2365}
2366
2367void TabContents::FileSelectionCanceled(void* params) {
2368 // If the user cancels choosing a file to upload we pass back an
2369 // empty vector.
2370 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2371}
2372
2373void TabContents::BeforeUnloadFiredFromRenderManager(
2374 bool proceed,
2375 bool* proceed_to_fire_unload) {
2376 if (delegate())
2377 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2378}
2379
2380void TabContents::UpdateRenderViewSizeForRenderManager() {
2381 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2382 view_->SizeContents(view_->GetContainerSize());
2383}
2384
2385DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
2386 return DOMUIFactory::CreateDOMUIForURL(AsWC(this), url);
2387}
2388
2389NavigationEntry*
2390TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2391 return controller_.GetLastCommittedEntry();
2392}
2393
2394bool TabContents::CreateRenderViewForRenderManager(
2395 RenderViewHost* render_view_host) {
2396 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2397 // mode before CreateRenderView is called. When we're asked to create a
2398 // RenderView, that means it's for the pending entry, so we have to use the
2399 // pending DOM UI.
2400 if (render_manager_.pending_dom_ui())
2401 render_view_host->AllowDOMUIBindings();
2402
[email protected]1adff062009-06-02 18:39:552403 // Ditto for extension bindings.
2404 if (controller().pending_entry()->url().SchemeIs(chrome::kExtensionScheme))
2405 render_view_host->AllowExtensionBindings();
2406
[email protected]420ae012009-04-24 05:16:322407 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2408 if (!render_view_host->CreateRenderView())
2409 return false;
2410
2411 // Now that the RenderView has been created, we need to tell it its size.
2412 rwh_view->SetSize(view_->GetContainerSize());
2413
2414 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2415 render_view_host);
2416 return true;
2417}
2418
2419void TabContents::Observe(NotificationType type,
2420 const NotificationSource& source,
2421 const NotificationDetails& details) {
2422 switch (type.value) {
2423 case NotificationType::BOOKMARK_MODEL_LOADED:
2424 // BookmarkModel finished loading, fall through to update starred state.
2425 case NotificationType::URLS_STARRED: {
2426 // Somewhere, a URL has been starred.
2427 // Ignore notifications for profiles other than our current one.
2428 Profile* source_profile = Source<Profile>(source).ptr();
2429 if (!source_profile || !source_profile->IsSameProfile(profile()))
2430 return;
2431
2432 UpdateStarredStateForCurrentURL();
2433 break;
2434 }
2435 case NotificationType::PREF_CHANGED: {
2436 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2437 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2438 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2439 UpdateAlternateErrorPageURL();
2440 } else if (*pref_name_in == prefs::kDefaultCharset ||
2441 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2442 ) {
2443 UpdateWebPreferences();
2444 } else {
2445 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2446 }
2447 break;
2448 }
2449 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2450 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2451 break;
2452
2453 case NotificationType::NAV_ENTRY_COMMITTED: {
2454 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2455
2456 NavigationController::LoadCommittedDetails& committed_details =
2457 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2458 ExpireInfoBars(committed_details);
2459 break;
2460 }
2461
2462 default:
2463 NOTREACHED();
2464 }
2465}