blob: e3a0bb6741fa115eae1a4385aa2ada26a4c06d80 [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]96d185d2009-04-24 03:28:5434#include "chrome/browser/renderer_host/render_widget_host_view.h"
35#include "chrome/browser/renderer_host/web_cache_manager.h"
[email protected]bd1ad682009-05-15 22:19:1736#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]f3ec7742009-01-15 00:59:1637#include "chrome/browser/tab_contents/navigation_entry.h"
38#include "chrome/browser/tab_contents/tab_contents_delegate.h"
[email protected]fdd61c62009-04-22 19:22:5739#include "chrome/browser/tab_contents/tab_contents_view.h"
[email protected]420ae012009-04-24 05:16:3240#include "chrome/browser/search_engines/template_url_fetcher.h"
41#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2742#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5643#include "chrome/common/notification_service.h"
[email protected]ce5c4502009-05-06 16:46:1144#include "chrome/common/page_action.h"
[email protected]bd1ad682009-05-15 22:19:1745#include "chrome/common/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2946#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0347#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3248#include "chrome/common/render_messages.h"
[email protected]96d185d2009-04-24 03:28:5449#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2650#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3251#include "grit/locale_settings.h"
52#include "net/base/mime_util.h"
53#include "net/base/net_errors.h"
54#include "net/base/registry_controlled_domain.h"
[email protected]3e45ba92009-02-20 21:09:0055
56#if defined(OS_WIN)
57// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3258#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]3e45ba92009-02-20 21:09:0059#include "chrome/browser/views/blocked_popup_container.h"
[email protected]2362e4f2009-05-08 00:34:0560#include "views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0061#endif
initial.commit09911bf2008-07-26 23:55:2962
[email protected]420ae012009-04-24 05:16:3263// Cross-Site Navigations
64//
65// If a TabContents is told to navigate to a different web site (as determined
66// by SiteInstance), it will replace its current RenderViewHost with a new
67// RenderViewHost dedicated to the new SiteInstance. This works as follows:
68//
69// - Navigate determines whether the destination is cross-site, and if so,
70// it creates a pending_render_view_host_ and moves into the PENDING
71// RendererState.
72// - The pending RVH is "suspended," so that no navigation messages are sent to
73// its renderer until the onbeforeunload JavaScript handler has a chance to
74// run in the current RVH.
75// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
76// that it has a pending cross-site request. ResourceDispatcherHost will
77// check for this when the response arrives.
78// - The current RVH runs its onbeforeunload handler. If it returns false, we
79// cancel all the pending logic and go back to NORMAL. Otherwise we allow
80// the pending RVH to send the navigation request to its renderer.
81// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
82// checks CrossSiteRequestManager to see that the RVH responsible has a
83// pending cross-site request, and then installs a CrossSiteEventHandler.
84// - When RDH receives a response, the BufferedEventHandler determines whether
85// it is a download. If so, it sends a message to the new renderer causing
86// it to cancel the request, and the download proceeds in the download
87// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:3488// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:3289// doesn't affect any functionality.
90// - After RDH receives a response and determines that it is safe and not a
91// download, it pauses the response to first run the old page's onunload
92// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:3493// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:3294// to the current RVH.
95// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
96// the ResourceDispatcherHost, who unpauses the response. Data is then sent
97// to the pending RVH.
98// - The pending renderer sends a FrameNavigate message that invokes the
99// DidNavigate method. This replaces the current RVH with the
100// pending RVH and goes back to the NORMAL RendererState.
101
102namespace {
103
104// Amount of time we wait between when a key event is received and the renderer
105// is queried for its state and pushed to the NavigationEntry.
106const int kQueryStateDelay = 5000;
107
108const int kSyncWaitDelay = 40;
109
110// If another javascript message box is displayed within
111// kJavascriptMessageExpectedDelay of a previous javascript message box being
112// dismissed, display an option to suppress future message boxes from this
113// contents.
114const int kJavascriptMessageExpectedDelay = 1000;
115
116// Minimum amount of time in ms that has to elapse since the download shelf was
117// shown for us to hide it when navigating away from the current page.
118const int kDownloadShelfHideDelay = 5000;
119
120const char kLinkDoctorBaseURL[] =
121 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
122
123// The printer icon in shell32.dll. That's a standard icon user will quickly
124// recognize.
125const int kShell32PrinterIcon = 17;
126
127// The list of prefs we want to observe.
128const wchar_t* kPrefsToObserve[] = {
129 prefs::kAlternateErrorPagesEnabled,
130 prefs::kWebKitJavaEnabled,
131 prefs::kWebKitJavascriptEnabled,
132 prefs::kWebKitLoadsImagesAutomatically,
133 prefs::kWebKitPluginsEnabled,
134 prefs::kWebKitUsesUniversalDetector,
[email protected]96d3fb52009-05-27 14:51:21135 prefs::kWebKitDeveloperExtrasEnabled,
[email protected]420ae012009-04-24 05:16:32136 prefs::kWebKitSerifFontFamily,
137 prefs::kWebKitSansSerifFontFamily,
138 prefs::kWebKitFixedFontFamily,
139 prefs::kWebKitDefaultFontSize,
140 prefs::kWebKitDefaultFixedFontSize,
141 prefs::kDefaultCharset
142 // kWebKitStandardFontIsSerif needs to be added
143 // if we let users pick which font to use, serif or sans-serif when
144 // no font is specified or a CSS generic family (serif or sans-serif)
145 // is not specified.
146};
147
148const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
149
150// Limit on the number of suggestions to appear in the pop-up menu under an
151// text input element in a form.
152const int kMaxAutofillMenuItems = 6;
153
154// Returns true if the entry's transition type is FORM_SUBMIT.
155bool IsFormSubmit(const NavigationEntry* entry) {
156 return (PageTransition::StripQualifier(entry->transition_type()) ==
157 PageTransition::FORM_SUBMIT);
158}
159
160#if defined(OS_WIN)
161
162BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
163 // Note: erase is required to properly paint some widgets borders. This can
164 // be seen with textfields.
165 InvalidateRect(hwnd, NULL, TRUE);
166 return TRUE;
167}
168#endif
169
[email protected]57c6a652009-05-04 07:58:34170// TODO(brettw) TabContents should be removed, then this hack is unnecessary.
171TabContents* AsWC(TabContents* tc) {
172 return static_cast<TabContents*>(tc);
[email protected]420ae012009-04-24 05:16:32173}
174
175} // namespace
176
177// -----------------------------------------------------------------------------
178
[email protected]fdd61c62009-04-22 19:22:57179// static
180int TabContents::find_request_id_counter_ = -1;
181
[email protected]420ae012009-04-24 05:16:32182class TabContents::GearsCreateShortcutCallbackFunctor {
183 public:
184 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
185 : contents_(contents) {}
186
187 void Run(const GearsShortcutData2& shortcut_data, bool success) {
188 if (contents_)
189 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
190 delete this;
191 }
192 void Cancel() {
193 contents_ = NULL;
194 }
195
196 private:
197 TabContents* contents_;
198};
199
[email protected]57c6a652009-05-04 07:58:34200// TODO(brettw) many of the data members here have casts to TabContents.
201// This object is the same as TabContents and is currently being merged.
[email protected]fdd61c62009-04-22 19:22:57202// When this merge is done, the casts can be removed.
[email protected]420ae012009-04-24 05:16:32203TabContents::TabContents(Profile* profile,
204 SiteInstance* site_instance,
205 int routing_id,
206 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42207 : delegate_(NULL),
[email protected]ce3fa3c2009-04-20 19:55:57208 controller_(this, profile),
[email protected]57c6a652009-05-04 07:58:34209 view_(TabContentsView::Create(static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57210 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(
[email protected]57c6a652009-05-04 07:58:34211 static_cast<TabContents*>(this),
212 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57213 property_bag_(),
214 registrar_(),
[email protected]57c6a652009-05-04 07:58:34215 printing_(*static_cast<TabContents*>(this)),
[email protected]fdd61c62009-04-22 19:22:57216 save_package_(),
217 cancelable_consumer_(),
218 autofill_manager_(),
219 password_manager_(),
220 plugin_installer_(),
221 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(
[email protected]57c6a652009-05-04 07:58:34222 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57223 select_file_dialog_(),
224 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34225 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29226 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34227 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34228 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57229 current_load_start_(),
230 load_state_(net::LOAD_STATE_IDLE),
231 load_state_host_(),
232 received_page_title_(false),
233 is_starred_(false),
234 contents_mime_type_(),
235 encoding_(),
236 download_shelf_(),
237 shelf_visible_(false),
[email protected]332af7732009-03-11 13:21:35238 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57239 infobar_delegates_(),
240 last_download_shelf_show_(),
241 find_ui_active_(false),
242 find_op_aborted_(false),
243 current_find_request_id_(find_request_id_counter_++),
244 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12245 last_search_case_sensitive_(false),
246 last_search_prepopulate_text_(NULL),
247 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57248 capturing_contents_(false),
249 is_being_destroyed_(false),
250 notify_disconnection_(false),
251 history_requests_(),
252#if defined(OS_WIN)
253 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
254#endif
255 last_javascript_message_dismissal_(),
256 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32257 pending_install_.page_id = 0;
258 pending_install_.callback_functor = NULL;
259
260 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
261
262 view_->CreateView();
263
264 // Register for notifications about all interested prefs change.
265 PrefService* prefs = profile->GetPrefs();
266 if (prefs) {
267 for (int i = 0; i < kPrefsToObserveLength; ++i)
268 prefs->AddPrefObserver(kPrefsToObserve[i], this);
269 }
270
271 // Register for notifications about URL starredness changing on any profile.
272 registrar_.Add(this, NotificationType::URLS_STARRED,
273 NotificationService::AllSources());
274 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
275 NotificationService::AllSources());
276 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
277 NotificationService::AllSources());
278
279 // Keep a global copy of the previous search string (if any).
280 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12281 last_search_prepopulate_text_ = &global_last_search;
[email protected]332af7732009-03-11 13:21:35282}
initial.commit09911bf2008-07-26 23:55:29283
284TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32285 is_being_destroyed_ = true;
286
287 // We don't want any notifications while we're runnign our destructor.
288 registrar_.RemoveAll();
289
290 // Unregister the notifications of all observed prefs change.
291 PrefService* prefs = profile()->GetPrefs();
292 if (prefs) {
293 for (int i = 0; i < kPrefsToObserveLength; ++i)
294 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
295 }
296
297 // Clean up subwindows like plugins and the find in page bar.
298 view_->OnContentsDestroy();
299
300 NotifyDisconnected();
[email protected]8897c382009-05-06 17:53:26301 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:32302
303 if (pending_install_.callback_functor)
304 pending_install_.callback_functor->Cancel();
305
306 // First cleanly close all child windows.
307 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
308 // some of these to close. CloseWindows is async, so it might get called
309 // twice before it runs.
310 int size = static_cast<int>(child_windows_.size());
311 for (int i = size - 1; i >= 0; --i) {
312 ConstrainedWindow* window = child_windows_[i];
313 if (window)
314 window->CloseConstrainedWindow();
315 }
316
[email protected]420ae012009-04-24 05:16:32317 // Notify any observer that have a reference on this tab contents.
318 NotificationService::current()->Notify(
319 NotificationType::TAB_CONTENTS_DESTROYED,
320 Source<TabContents>(this),
321 NotificationService::NoDetails());
322
[email protected]1e5e74f2009-05-27 20:55:12323 // Notify any lasting InfobarDelegates that have not yet been removed that
324 // whatever infobar they were handling in this TabContents has closed,
325 // because the TabContents is going away entirely.
326 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
327 // notification may trigger infobars calls that access their delegate. (and
328 // some implementations of InfoBarDelegate do delete themselves on
329 // InfoBarClosed()).
330 for (int i = 0; i < infobar_delegate_count(); ++i) {
331 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
332 delegate->InfoBarClosed();
333 }
334 infobar_delegates_.clear();
335
[email protected]420ae012009-04-24 05:16:32336 // TODO(brettw) this should be moved to the view.
337#if defined(OS_WIN)
338 // If we still have a window handle, destroy it. GetNativeView can return
339 // NULL if this contents was part of a window that closed.
340 if (GetNativeView())
341 ::DestroyWindow(GetNativeView());
342#endif
initial.commit09911bf2008-07-26 23:55:29343}
344
[email protected]d5f942ba2008-09-26 19:30:34345// static
346void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32347 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
348
349 WebPreferences pref_defaults;
350 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
351 pref_defaults.javascript_enabled);
352 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
353 pref_defaults.web_security_enabled);
354 prefs->RegisterBooleanPref(
355 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
356 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
357 pref_defaults.loads_images_automatically);
358 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
359 pref_defaults.plugins_enabled);
360 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
361 pref_defaults.dom_paste_enabled);
362 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
363 pref_defaults.shrinks_standalone_images_to_fit);
364 prefs->RegisterBooleanPref(prefs::kWebKitDeveloperExtrasEnabled,
[email protected]96d3fb52009-05-27 14:51:21365 pref_defaults.developer_extras_enabled);
[email protected]420ae012009-04-24 05:16:32366 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
367 pref_defaults.text_areas_are_resizable);
368 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
369 pref_defaults.java_enabled);
370
371 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
372 IDS_ACCEPT_LANGUAGES);
373 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
374 IDS_DEFAULT_ENCODING);
375 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
376 IDS_STANDARD_FONT_IS_SERIF);
377 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
378 IDS_FIXED_FONT_FAMILY);
379 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
380 IDS_SERIF_FONT_FAMILY);
381 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
382 IDS_SANS_SERIF_FONT_FAMILY);
383 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
384 IDS_CURSIVE_FONT_FAMILY);
385 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
386 IDS_FANTASY_FONT_FAMILY);
387 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
388 IDS_DEFAULT_FONT_SIZE);
389 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
390 IDS_DEFAULT_FIXED_FONT_SIZE);
391 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
392 IDS_MINIMUM_FONT_SIZE);
393 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
394 IDS_MINIMUM_LOGICAL_FONT_SIZE);
395 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
396 IDS_USES_UNIVERSAL_DETECTOR);
397 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
398 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29399}
400
[email protected]d5f942ba2008-09-26 19:30:34401bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01402 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55403 return true;
[email protected]d5f942ba2008-09-26 19:30:34404}
405
[email protected]6e95706d2009-04-23 22:55:01406AutofillManager* TabContents::GetAutofillManager() {
407 if (autofill_manager_.get() == NULL)
408 autofill_manager_.reset(new AutofillManager(this));
409 return autofill_manager_.get();
410}
411
412PasswordManager* TabContents::GetPasswordManager() {
413 if (password_manager_.get() == NULL)
414 password_manager_.reset(new PasswordManager(this));
415 return password_manager_.get();
416}
417
418PluginInstaller* TabContents::GetPluginInstaller() {
419 if (plugin_installer_.get() == NULL)
420 plugin_installer_.reset(new PluginInstaller(this));
421 return plugin_installer_.get();
422}
423
[email protected]d5f942ba2008-09-26 19:30:34424const GURL& TabContents::GetURL() const {
425 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57426 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34427 return entry ? entry->display_url() : GURL::EmptyGURL();
428}
429
[email protected]96d185d2009-04-24 03:28:54430const string16& TabContents::GetTitle() const {
431 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
432 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
433 if (our_dom_ui) {
434 // Don't override the title in view source mode.
435 NavigationEntry* entry = controller_.GetActiveEntry();
436 if (!(entry && entry->IsViewSourceMode())) {
437 // Give the DOM UI the chance to override our title.
438 const string16& title = our_dom_ui->overridden_title();
439 if (!title.empty())
440 return title;
441 }
442 }
443
444 // We use the title for the last committed entry rather than a pending
445 // navigation entry. For example, when the user types in a URL, we want to
446 // keep the old page's title until the new load has committed and we get a new
447 // title.
448 // The exception is with transient pages, for which we really want to use
449 // their title, as they are not committed.
450 NavigationEntry* entry = controller_.GetTransientEntry();
451 if (entry)
452 return entry->GetTitleForDisplay(&controller_);
453
454 entry = controller_.GetLastCommittedEntry();
455 if (entry)
456 return entry->GetTitleForDisplay(&controller_);
457 else if (controller_.LoadingURLLazily())
458 return controller_.GetLazyTitle();
459 return EmptyString16();
460}
461
[email protected]d5f942ba2008-09-26 19:30:34462int32 TabContents::GetMaxPageID() {
463 if (GetSiteInstance())
464 return GetSiteInstance()->max_page_id();
465 else
466 return max_page_id_;
467}
468
469void TabContents::UpdateMaxPageID(int32 page_id) {
470 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34471 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34472 // testing.
473 if (GetSiteInstance())
474 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34475 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34476}
477
[email protected]96d185d2009-04-24 03:28:54478SiteInstance* TabContents::GetSiteInstance() const {
479 return render_manager_.current_host()->site_instance();
480}
481
[email protected]d5f942ba2008-09-26 19:30:34482const std::wstring TabContents::GetDefaultTitle() const {
483 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
484}
485
[email protected]96d185d2009-04-24 03:28:54486bool TabContents::ShouldDisplayURL() {
487 // Don't hide the url in view source mode.
488 NavigationEntry* entry = controller_.GetActiveEntry();
489 if (entry && entry->IsViewSourceMode())
490 return true;
491 DOMUI* dom_ui = GetDOMUIForCurrentState();
492 if (dom_ui)
493 return !dom_ui->should_hide_url();
494 return true;
495}
496
[email protected]d5f942ba2008-09-26 19:30:34497SkBitmap TabContents::GetFavIcon() const {
498 // Like GetTitle(), we also want to use the favicon for the last committed
499 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57500 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47501 if (entry)
502 return entry->favicon().bitmap();
503
[email protected]ce3fa3c2009-04-20 19:55:57504 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34505 if (entry)
506 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57507 else if (controller_.LoadingURLLazily())
508 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34509 return SkBitmap();
510}
511
[email protected]96d185d2009-04-24 03:28:54512bool TabContents::ShouldDisplayFavIcon() {
513 // Always display a throbber during pending loads.
514 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
515 return true;
516
517 DOMUI* dom_ui = GetDOMUIForCurrentState();
518 if (dom_ui)
519 return !dom_ui->hide_favicon();
520 return true;
521}
522
[email protected]3e45ba92009-02-20 21:09:00523#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34524SecurityStyle TabContents::GetSecurityStyle() const {
525 // We may not have a navigation entry yet.
[email protected]ce3fa3c2009-04-20 19:55:57526 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34527 return entry ? entry->ssl().security_style() : SECURITY_STYLE_UNKNOWN;
528}
529
530bool TabContents::GetSSLEVText(std::wstring* ev_text,
531 std::wstring* ev_tooltip_text) const {
532 DCHECK(ev_text && ev_tooltip_text);
533 ev_text->clear();
534 ev_tooltip_text->clear();
535
[email protected]ce3fa3c2009-04-20 19:55:57536 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34537 if (!entry ||
538 net::IsCertStatusError(entry->ssl().cert_status()) ||
539 ((entry->ssl().cert_status() & net::CERT_STATUS_IS_EV) == 0))
540 return false;
541
542 scoped_refptr<net::X509Certificate> cert;
543 CertStore::GetSharedInstance()->RetrieveCert(entry->ssl().cert_id(), &cert);
544 if (!cert.get()) {
545 NOTREACHED();
546 return false;
547 }
548
549 return SSLManager::GetEVCertNames(*cert, ev_text, ev_tooltip_text);
550}
[email protected]76f68dc2009-03-10 20:31:32551#endif
[email protected]d5f942ba2008-09-26 19:30:34552
[email protected]96d185d2009-04-24 03:28:54553std::wstring TabContents::GetStatusText() const {
554 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
555 return std::wstring();
556
557 switch (load_state_) {
558 case net::LOAD_STATE_WAITING_FOR_CACHE:
559 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
560 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
561 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
562 case net::LOAD_STATE_RESOLVING_HOST:
563 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
564 case net::LOAD_STATE_CONNECTING:
565 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
566 case net::LOAD_STATE_SENDING_REQUEST:
567 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
568 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
569 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
570 load_state_host_);
571 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
572 case net::LOAD_STATE_IDLE:
573 case net::LOAD_STATE_READING_RESPONSE:
574 break;
575 }
576
577 return std::wstring();
578}
579
[email protected]d5f942ba2008-09-26 19:30:34580void TabContents::SetIsCrashed(bool state) {
581 if (state == is_crashed_)
582 return;
583
584 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50585 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34586}
587
[email protected]ce5c4502009-05-06 16:46:11588void TabContents::EnablePageAction(const PageAction* page_action) {
589 DCHECK(page_action);
590
591 if (IsPageActionEnabled(page_action))
592 return; // Already enabled.
593
594 enabled_page_actions_.insert(page_action);
595}
596
597bool TabContents::IsPageActionEnabled(const PageAction* page_action) {
598 DCHECK(page_action);
599 return enabled_page_actions_.end() != enabled_page_actions_.find(page_action);
600}
601
602
[email protected]d5f942ba2008-09-26 19:30:34603void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
604 if (delegate_)
605 delegate_->NavigationStateChanged(this, changed_flags);
606}
607
[email protected]96d185d2009-04-24 03:28:54608void TabContents::DidBecomeSelected() {
609 controller_.SetActive(true);
610
611 if (render_widget_host_view())
612 render_widget_host_view()->DidBecomeSelected();
613
614 // If pid() is -1, that means the RenderProcessHost still hasn't been
615 // initialized. It'll register with CacheManagerHost when it is.
616 if (process()->pid() != -1)
617 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
618}
619
620void TabContents::WasHidden() {
621 if (!capturing_contents()) {
622 // |render_view_host()| can be NULL if the user middle clicks a link to open
623 // a tab in then background, then closes the tab before selecting it. This
624 // is because closing the tab calls TabContents::Destroy(), which removes
625 // the |render_view_host()|; then when we actually destroy the window,
626 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
627 if (render_widget_host_view())
628 render_widget_host_view()->WasHidden();
629
630 // Loop through children and send WasHidden to them, too.
631 int count = static_cast<int>(child_windows_.size());
632 for (int i = count - 1; i >= 0; --i) {
633 ConstrainedWindow* window = child_windows_.at(i);
634 window->WasHidden();
635 }
636 }
637
638 NotificationService::current()->Notify(
639 NotificationType::TAB_CONTENTS_HIDDEN,
640 Source<TabContents>(this),
641 NotificationService::NoDetails());
642}
643
[email protected]d5f942ba2008-09-26 19:30:34644void TabContents::Activate() {
645 if (delegate_)
646 delegate_->ActivateContents(this);
647}
648
[email protected]96d185d2009-04-24 03:28:54649void TabContents::ShowContents() {
650 if (render_widget_host_view())
651 render_widget_host_view()->DidBecomeSelected();
652
653 // Loop through children and send DidBecomeSelected to them, too.
654 int count = static_cast<int>(child_windows_.size());
655 for (int i = count - 1; i >= 0; --i) {
656 ConstrainedWindow* window = child_windows_.at(i);
657 window->DidBecomeSelected();
658 }
659}
660
661void TabContents::HideContents() {
662 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
663 // our superclass HideContents(), because some callers want to be very picky
664 // about the order in which these get called. In addition to making the code
665 // here practically impossible to understand, this also means we end up
666 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34667 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54668 WasHidden();
669}
670
[email protected]c0588052008-10-27 23:01:50671void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34672 WindowOpenDisposition disposition,
673 PageTransition::Type transition) {
674 if (delegate_)
[email protected]c0588052008-10-27 23:01:50675 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34676}
677
678bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54679 const NavigationEntry& entry = *controller_.pending_entry();
680
681 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
682 if (!dest_render_view_host)
683 return false; // Unable to create the desired render view host.
684
685 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]684b4ba22009-05-07 06:27:41686 DevToolsManager* devtools_manager = g_browser_process->devtools_manager();
[email protected]7e8e6b62009-05-08 11:28:32687 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41688 devtools_manager->OnNavigatingToPendingEntry(
689 render_view_host(),
690 dest_render_view_host,
691 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32692 }
[email protected]96d185d2009-04-24 03:28:54693
694 // Used for page load time metrics.
695 current_load_start_ = base::TimeTicks::Now();
696
697 // Navigate in the desired RenderViewHost.
698 dest_render_view_host->NavigateToEntry(entry, reload);
699
700 if (entry.page_id() == -1) {
701 // HACK!! This code suppresses javascript: URLs from being added to
702 // session history, which is what we want to do for javascript: URLs that
703 // do not generate content. What we really need is a message from the
704 // renderer telling us that a new page was not created. The same message
705 // could be used for mailto: URLs and the like.
706 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
707 return false;
708 }
709
710 // Clear any provisional password saves - this stops password infobars
711 // showing up on pages the user navigates to while the right page is
712 // loading.
713 GetPasswordManager()->ClearProvisionalSave();
714
715 if (reload && !profile()->IsOffTheRecord()) {
716 HistoryService* history =
717 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
718 if (history)
719 history->SetFavIconOutOfDateForPage(entry.url());
720 }
721
[email protected]d5f942ba2008-09-26 19:30:34722 return true;
723}
724
[email protected]96d185d2009-04-24 03:28:54725void TabContents::Stop() {
726 render_manager_.Stop();
727 printing_.Stop();
728}
729
730void TabContents::Cut() {
731 render_view_host()->Cut();
732}
733
734void TabContents::Copy() {
735 render_view_host()->Copy();
736}
737
738void TabContents::Paste() {
739 render_view_host()->Paste();
740}
741
742void TabContents::DisassociateFromPopupCount() {
743 render_view_host()->DisassociateFromPopupCount();
744}
745
746TabContents* TabContents::Clone() {
747 // We create a new SiteInstance so that the new tab won't share processes
748 // with the old one. This can be changed in the future if we need it to share
749 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32750 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54751 SiteInstance::CreateSiteInstance(profile()),
752 MSG_ROUTING_NONE, NULL);
753 tc->controller().CopyStateFrom(controller_);
754 return tc;
755}
756
[email protected]420ae012009-04-24 05:16:32757void TabContents::CreateShortcut() {
758 NavigationEntry* entry = controller_.GetLastCommittedEntry();
759 if (!entry)
760 return;
761
762 // We only allow one pending install request. By resetting the page id we
763 // effectively cancel the pending install request.
764 pending_install_.page_id = entry->page_id();
765 pending_install_.icon = GetFavIcon();
766 pending_install_.title = UTF16ToWideHack(GetTitle());
767 pending_install_.url = GetURL();
768 if (pending_install_.callback_functor) {
769 pending_install_.callback_functor->Cancel();
770 pending_install_.callback_functor = NULL;
771 }
772 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
773 if (pending_install_.title.empty())
774 pending_install_.title = UTF8ToWide(GetURL().spec());
775
776 // Request the application info. When done OnDidGetApplicationInfo is invoked
777 // and we'll create the shortcut.
778 render_view_host()->GetApplicationInfo(pending_install_.page_id);
779}
780
[email protected]76f68dc2009-03-10 20:31:32781#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29782ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]c2dacc92008-10-16 23:51:38783 views::WindowDelegate* window_delegate,
784 views::View* contents_view) {
initial.commit09911bf2008-07-26 23:55:29785 ConstrainedWindow* window =
786 ConstrainedWindow::CreateConstrainedDialog(
787 this, gfx::Rect(), contents_view, window_delegate);
788 child_windows_.push_back(window);
789 return window;
790}
[email protected]f3332e12009-03-23 15:28:57791#endif
initial.commit09911bf2008-07-26 23:55:29792
793void TabContents::AddNewContents(TabContents* new_contents,
794 WindowOpenDisposition disposition,
795 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22796 bool user_gesture,
797 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29798 if (!delegate_)
799 return;
800
[email protected]f3332e12009-03-23 15:28:57801#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:22802 bool constrain_popup = false;
[email protected]35f7d212009-04-29 21:19:27803 if ((disposition == NEW_POPUP) && !user_gesture &&
804 !CommandLine::ForCurrentProcess()->HasSwitch(
805 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22806 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31807 // the whitelist. The popup owner will handle checking this.
808 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
809 initial_pos,
810 creator_url.is_valid() ? creator_url.host() : std::string());
811 } else {
[email protected]0aa55312008-10-17 21:53:08812 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29813 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
814 user_gesture);
815 }
[email protected]b6c874582009-05-08 19:38:31816 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
[email protected]f3332e12009-03-23 15:28:57817#else
818 // TODO(port): implement the popup blocker stuff
819 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
820 user_gesture);
821#endif
initial.commit09911bf2008-07-26 23:55:29822}
823
[email protected]f3332e12009-03-23 15:28:57824#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29825void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25826 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22827 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29828}
[email protected]332af7732009-03-11 13:21:35829#endif
initial.commit09911bf2008-07-26 23:55:29830
[email protected]96d185d2009-04-24 03:28:54831void TabContents::PopupNotificationVisibilityChanged(bool visible) {
832 render_view_host()->PopupNotificationVisibilityChanged(visible);
833}
834
835gfx::NativeView TabContents::GetContentNativeView() {
836 return view_->GetContentNativeView();
837}
838
839gfx::NativeView TabContents::GetNativeView() const {
840 return view_->GetNativeView();
841}
842
843void TabContents::GetContainerBounds(gfx::Rect *out) const {
844 view_->GetContainerBounds(out);
845}
846
847void TabContents::Focus() {
848 view_->Focus();
849}
850
851void TabContents::SetInitialFocus(bool reverse) {
852 render_view_host()->SetInitialFocus(reverse);
853}
854
855bool TabContents::FocusLocationBarByDefault() {
856 DOMUI* dom_ui = GetDOMUIForCurrentState();
857 if (dom_ui)
858 return dom_ui->focus_location_bar_by_default();
859 return false;
860}
861
[email protected]616ed5a2008-11-21 22:27:24862void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
863 // Look through the existing InfoBarDelegates we have for a match. If we've
864 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05865 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24866 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
867 return;
868 }
869
870 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56871 NotificationService::current()->Notify(
872 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
873 Source<TabContents>(this),
874 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24875
876 // Add ourselves as an observer for navigations the first time a delegate is
877 // added. We use this notification to expire InfoBars that need to expire on
878 // page transitions.
879 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56880 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57881 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24882 }
883}
884
885void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
886 std::vector<InfoBarDelegate*>::iterator it =
887 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
888 if (it != infobar_delegates_.end()) {
889 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56890 NotificationService::current()->Notify(
891 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
892 Source<TabContents>(this),
893 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05894 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24895
[email protected]6a02963e2009-01-06 16:58:03896 // Remove ourselves as an observer if we are tracking no more InfoBars.
897 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56898 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57899 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03900 }
[email protected]616ed5a2008-11-21 22:27:24901 }
902}
[email protected]3edd9522009-03-04 22:19:41903
[email protected]96d185d2009-04-24 03:28:54904bool TabContents::IsBookmarkBarAlwaysVisible() {
905 // See GetDOMUIForCurrentState() comment for more info. This case is very
906 // similar, but for non-first loads, we want to use the committed entry. This
907 // is so the bookmarks bar disappears at the same time the page does.
908 if (controller_.GetLastCommittedEntry()) {
909 // Not the first load, always use the committed DOM UI.
910 if (render_manager_.dom_ui())
911 return render_manager_.dom_ui()->force_bookmark_bar_visible();
912 return false; // Default.
913 }
914
915 // When it's the first load, we know either the pending one or the committed
916 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
917 // of them will be valid, so we can just check both.
918 if (render_manager_.pending_dom_ui())
919 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
920 if (render_manager_.dom_ui())
921 return render_manager_.dom_ui()->force_bookmark_bar_visible();
922 return false; // Default.
923}
924
925void TabContents::SetDownloadShelfVisible(bool visible) {
926 if (shelf_visible_ != visible) {
927 if (visible) {
928 // Invoke GetDownloadShelf to force the shelf to be created.
[email protected]0a2aeb82009-05-15 21:52:48929 GetDownloadShelf(true);
[email protected]96d185d2009-04-24 03:28:54930 }
931 shelf_visible_ = visible;
932
[email protected]c9cd2222009-05-06 05:16:50933 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]3a6a3b62009-05-27 21:36:20934
935 if (delegate())
936 delegate()->UpdateDownloadShelfVisibility(visible);
[email protected]96d185d2009-04-24 03:28:54937 }
938
939 // SetShelfVisible can force-close the shelf, so make sure we lay out
940 // everything correctly, as if the animation had finished. This doesn't
941 // matter for showing the shelf, as the show animation will do it.
942 ToolbarSizeChanged(false);
943
944 if (visible) {
945 // Always set this value as it reflects the last time the download shelf
946 // was made visible (even if it was already visible).
947 last_download_shelf_show_ = base::TimeTicks::Now();
948 }
949}
950
[email protected]3edd9522009-03-04 22:19:41951void TabContents::ToolbarSizeChanged(bool is_animating) {
952 TabContentsDelegate* d = delegate();
953 if (d)
954 d->ToolbarSizeChanged(this, is_animating);
955}
[email protected]616ed5a2008-11-21 22:27:24956
[email protected]d5f942ba2008-09-26 19:30:34957void TabContents::OnStartDownload(DownloadItem* download) {
958 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34959
960 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31961 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34962
[email protected]bcef0dc02009-02-28 00:35:02963 // GetDownloadShelf creates the download shelf if it was not yet created.
[email protected]0a2aeb82009-05-15 21:52:48964 tab_contents->GetDownloadShelf(true)->AddDownload(
[email protected]bcef0dc02009-02-28 00:35:02965 new DownloadItemModel(download));
[email protected]d5f942ba2008-09-26 19:30:34966 tab_contents->SetDownloadShelfVisible(true);
967
[email protected]bd1ad682009-05-15 22:19:17968// TODO(port): port for mac.
969#if defined(OS_WIN) || defined(OS_LINUX)
970 // We make this check for the case of minimized windows, unit tests, etc.
971 if (platform_util::IsVisible(GetNativeView())) {
972 DownloadStartedAnimation::Show(tab_contents);
[email protected]d5f942ba2008-09-26 19:30:34973 }
[email protected]3edd9522009-03-04 22:19:41974#endif
[email protected]d5f942ba2008-09-26 19:30:34975}
976
[email protected]0a2aeb82009-05-15 21:52:48977DownloadShelf* TabContents::GetDownloadShelf(bool create) {
978 if (!download_shelf_.get() && create)
[email protected]bcef0dc02009-02-28 00:35:02979 download_shelf_.reset(DownloadShelf::Create(this));
980 return download_shelf_.get();
initial.commit09911bf2008-07-26 23:55:29981}
982
[email protected]bcef0dc02009-02-28 00:35:02983void TabContents::MigrateShelfFrom(TabContents* tab_contents) {
[email protected]0a2aeb82009-05-15 21:52:48984 download_shelf_.reset(tab_contents->GetDownloadShelf(true));
[email protected]bcef0dc02009-02-28 00:35:02985 download_shelf_->ChangeTabContents(tab_contents, this);
986 tab_contents->ReleaseDownloadShelf();
initial.commit09911bf2008-07-26 23:55:29987}
988
[email protected]3edd9522009-03-04 22:19:41989void TabContents::ReleaseDownloadShelf() {
990 download_shelf_.release();
991}
992
993// static
994void TabContents::MigrateShelf(TabContents* from, TabContents* to) {
995 bool was_shelf_visible = from->IsDownloadShelfVisible();
996 if (was_shelf_visible)
997 to->MigrateShelfFrom(from);
998 to->SetDownloadShelfVisible(was_shelf_visible);
999}
[email protected]3edd9522009-03-04 22:19:411000
[email protected]d5f942ba2008-09-26 19:30:341001void TabContents::WillClose(ConstrainedWindow* window) {
1002 ConstrainedWindowList::iterator it =
1003 find(child_windows_.begin(), child_windows_.end(), window);
1004 if (it != child_windows_.end())
1005 child_windows_.erase(it);
1006
[email protected]332af7732009-03-11 13:21:351007#if defined(OS_WIN)
[email protected]d6598c052008-11-05 19:03:251008 if (window == blocked_popups_)
1009 blocked_popups_ = NULL;
1010
[email protected]92edc472009-02-10 20:32:061011 if (::IsWindow(GetNativeView())) {
[email protected]d5f942ba2008-09-26 19:30:341012 CRect client_rect;
[email protected]92edc472009-02-10 20:32:061013 GetClientRect(GetNativeView(), &client_rect);
[email protected]d5f942ba2008-09-26 19:30:341014 RepositionSupressedPopupsToFit(
1015 gfx::Size(client_rect.Width(), client_rect.Height()));
1016 }
[email protected]332af7732009-03-11 13:21:351017#endif
[email protected]d5f942ba2008-09-26 19:30:341018}
1019
[email protected]d5f942ba2008-09-26 19:30:341020void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:351021#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:061022 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:351023#endif
[email protected]d5f942ba2008-09-26 19:30:341024}
1025
[email protected]e491f1c2009-05-22 20:28:121026void TabContents::StartFinding(string16 find_text,
1027 bool forward_direction,
1028 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:011029 // If find_text is empty, it means FindNext was pressed with a keyboard
1030 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:121031 if (find_text.empty() && find_text_.empty()) {
1032 if (last_search_prepopulate_text_->empty())
1033 return;
1034 // Try whatever we searched for last in any tab.
1035 find_text = *last_search_prepopulate_text_;
1036 }
[email protected]6e95706d2009-04-23 22:55:011037
1038 // This is a FindNext operation if we are searching for the same text again,
1039 // or if the passed in search text is empty (FindNext keyboard shortcut). The
1040 // exception to this is if the Find was aborted (then we don't want FindNext
1041 // because the highlighting has been cleared and we need it to reappear). We
1042 // therefore treat FindNext after an aborted Find operation as a full fledged
1043 // Find.
1044 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:121045 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:011046 !find_op_aborted_;
1047 if (!find_next)
1048 current_find_request_id_ = find_request_id_counter_++;
1049
1050 if (!find_text.empty())
1051 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:121052 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:011053
1054 find_op_aborted_ = false;
1055
1056 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:121057 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:011058
1059 render_view_host()->StartFinding(current_find_request_id_,
1060 find_text_,
1061 forward_direction,
[email protected]e491f1c2009-05-22 20:28:121062 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:011063 find_next);
1064}
1065
1066void TabContents::StopFinding(bool clear_selection) {
1067 find_ui_active_ = false;
1068 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:121069 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:011070 render_view_host()->StopFinding(clear_selection);
1071}
1072
[email protected]420ae012009-04-24 05:16:321073void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
1074 bool success,
1075 const std::wstring& prompt) {
1076 last_javascript_message_dismissal_ = base::TimeTicks::Now();
1077 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
1078}
1079
[email protected]571e31152009-05-15 19:34:021080void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
1081 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
1082}
1083
[email protected]420ae012009-04-24 05:16:321084void TabContents::OnSavePage() {
1085 // If we can not save the page, try to download it.
1086 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1087 DownloadManager* dlm = profile()->GetDownloadManager();
1088 const GURL& current_page_url = GetURL();
1089 if (dlm && current_page_url.is_valid())
[email protected]c9825a42009-05-01 22:51:501090 dlm->DownloadUrl(current_page_url, GURL(), "", AsWC(this));
[email protected]420ae012009-04-24 05:16:321091 return;
1092 }
1093
1094 Stop();
1095
1096 // Create the save package and possibly prompt the user for the name to save
1097 // the page as. The user prompt is an asynchronous operation that runs on
1098 // another thread.
1099 save_package_ = new SavePackage(AsWC(this));
1100 save_package_->GetSaveInfo();
1101}
1102
1103// Used in automated testing to bypass prompting the user for file names.
1104// Instead, the names and paths are hard coded rather than running them through
1105// file name sanitation and extension / mime checking.
1106void TabContents::SavePage(const std::wstring& main_file,
1107 const std::wstring& dir_path,
1108 SavePackage::SavePackageType save_type) {
1109 // Stop the page from navigating.
1110 Stop();
1111
1112 save_package_ = new SavePackage(AsWC(this), save_type,
1113 FilePath::FromWStringHack(main_file),
1114 FilePath::FromWStringHack(dir_path));
1115 save_package_->Init();
1116}
1117
1118void TabContents::PrintPreview() {
1119 // We don't show the print preview yet, only the print dialog.
1120 PrintNow();
1121}
1122
1123bool TabContents::PrintNow() {
1124 // We can't print interstitial page for now.
1125 if (showing_interstitial_page())
1126 return false;
1127
1128 return render_view_host()->PrintPages();
1129}
1130
1131bool TabContents::IsActiveEntry(int32 page_id) {
1132 NavigationEntry* active_entry = controller_.GetActiveEntry();
1133 return (active_entry != NULL &&
1134 active_entry->site_instance() == GetSiteInstance() &&
1135 active_entry->page_id() == page_id);
1136}
1137
[email protected]96d185d2009-04-24 03:28:541138// Notifies the RenderWidgetHost instance about the fact that the page is
1139// loading, or done loading and calls the base implementation.
1140void TabContents::SetIsLoading(bool is_loading,
1141 LoadNotificationDetails* details) {
1142 if (is_loading == is_loading_)
1143 return;
1144
1145 if (!is_loading) {
1146 load_state_ = net::LOAD_STATE_IDLE;
1147 load_state_host_.clear();
1148 }
1149
1150 render_manager_.SetIsLoading(is_loading);
1151
1152 is_loading_ = is_loading;
1153 waiting_for_response_ = is_loading;
1154
1155 if (delegate_)
1156 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351157 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541158
1159 NotificationType type = is_loading ? NotificationType::LOAD_START :
1160 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111161 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541162 if (details)
1163 det = Details<LoadNotificationDetails>(details);
1164 NotificationService::current()->Notify(type,
1165 Source<NavigationController>(&controller_),
1166 det);
1167}
1168
[email protected]76f68dc2009-03-10 20:31:321169#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:221170void TabContents::CreateBlockedPopupContainerIfNecessary() {
1171 if (blocked_popups_)
1172 return;
1173
1174 CRect client_rect;
1175 GetClientRect(GetNativeView(), &client_rect);
1176 gfx::Point anchor_position(
1177 client_rect.Width() - views::NativeScrollBar::GetVerticalScrollBarWidth(),
1178 client_rect.Height());
1179 blocked_popups_ = BlockedPopupContainer::Create(this, profile(),
1180 anchor_position);
1181 child_windows_.push_back(blocked_popups_);
1182}
1183
[email protected]b6c874582009-05-08 19:38:311184void TabContents::AddPopup(TabContents* new_contents,
1185 const gfx::Rect& initial_pos,
1186 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221187 CreateBlockedPopupContainerIfNecessary();
1188 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221189}
1190
[email protected]e69bce3dd2009-04-20 22:05:121191// TODO(brettw) This should be on the TabContentsView.
[email protected]d5f942ba2008-09-26 19:30:341192void TabContents::RepositionSupressedPopupsToFit(const gfx::Size& new_size) {
1193 // TODO(erg): There's no way to detect whether scroll bars are
1194 // visible, so for beta, we're just going to assume that the
1195 // vertical scroll bar is visible, and not care about covering up
1196 // the horizontal scroll bar. Fixing this is half of
1197 // http://b/1118139.
1198 gfx::Point anchor_position(
1199 new_size.width() -
[email protected]c2dacc92008-10-16 23:51:381200 views::NativeScrollBar::GetVerticalScrollBarWidth(),
[email protected]d5f942ba2008-09-26 19:30:341201 new_size.height());
[email protected]d6598c052008-11-05 19:03:251202
1203 if (blocked_popups_)
1204 blocked_popups_->RepositionConstrainedWindowTo(anchor_position);
[email protected]d5f942ba2008-09-26 19:30:341205}
1206
[email protected]b9681312008-11-07 00:08:261207bool TabContents::ShowingBlockedPopupNotification() const {
1208 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221209 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261210}
[email protected]332af7732009-03-11 13:21:351211#endif // defined(OS_WIN)
[email protected]616ed5a2008-11-21 22:27:241212
1213namespace {
1214bool TransitionIsReload(PageTransition::Type transition) {
1215 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1216}
1217}
1218
1219void TabContents::ExpireInfoBars(
1220 const NavigationController::LoadCommittedDetails& details) {
1221 // Only hide InfoBars when the user has done something that makes the main
1222 // frame load. We don't want various automatic or subframe navigations making
1223 // it disappear.
1224 if (!details.is_user_initiated_main_frame_load())
1225 return;
1226
[email protected]f86a07022008-11-25 01:06:051227 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241228 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051229 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241230 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241231 }
1232}
[email protected]fdd61c62009-04-22 19:22:571233
1234void TabContents::OnGearsCreateShortcutDone(
1235 const GearsShortcutData2& shortcut_data, bool success) {
1236 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1237 bool same_page =
1238 current_entry && pending_install_.page_id == current_entry->page_id();
1239
1240 if (success && same_page) {
1241 // Only switch to app mode if the user chose to create a shortcut and
1242 // we're still on the same page that it corresponded to.
1243 if (delegate())
1244 delegate()->ConvertContentsToApplication(this);
1245 }
1246
1247 // Reset the page id to indicate no requests are pending.
1248 pending_install_.page_id = 0;
1249 pending_install_.callback_functor = NULL;
1250}
[email protected]96d185d2009-04-24 03:28:541251
1252DOMUI* TabContents::GetDOMUIForCurrentState() {
1253 // When there is a pending navigation entry, we want to use the pending DOMUI
1254 // that goes along with it to control the basic flags. For example, we want to
1255 // show the pending URL in the URL bar, so we want the display_url flag to
1256 // be from the pending entry.
1257 //
1258 // The confusion comes because there are multiple possibilities for the
1259 // initial load in a tab as a side effect of the way the RenderViewHostManager
1260 // works.
1261 //
1262 // - For the very first tab the load looks "normal". The new tab DOM UI is
1263 // the pending one, and we want it to apply here.
1264 //
1265 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1266 // get switched to the one previously associated with the new tab pages.
1267 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1268 // have a committed DOM UI in this case.
1269 //
1270 // This condition handles all of these cases:
1271 //
1272 // - First load in first tab: no committed nav entry + pending nav entry +
1273 // pending dom ui:
1274 // -> Use pending DOM UI if any.
1275 //
1276 // - First load in second tab: no committed nav entry + pending nav entry +
1277 // no pending DOM UI:
1278 // -> Use the committed DOM UI if any.
1279 //
1280 // - Second navigation in any tab: committed nav entry + pending nav entry:
1281 // -> Use pending DOM UI if any.
1282 //
1283 // - Normal state with no load: committed nav entry + no pending nav entry:
1284 // -> Use committed DOM UI.
1285 if (controller_.pending_entry() &&
1286 (controller_.GetLastCommittedEntry() ||
1287 render_manager_.pending_dom_ui()))
1288 return render_manager_.pending_dom_ui();
1289 return render_manager_.dom_ui();
1290}
[email protected]420ae012009-04-24 05:16:321291
1292void TabContents::DidNavigateMainFramePostCommit(
1293 const NavigationController::LoadCommittedDetails& details,
1294 const ViewHostMsg_FrameNavigate_Params& params) {
1295 // Hide the download shelf if all the following conditions are true:
1296 // - there are no active downloads.
1297 // - this is a navigation to a different TLD.
1298 // - at least 5 seconds have elapsed since the download shelf was shown.
1299 // TODO(jcampan): bug 1156075 when user gestures are reliable, they should
1300 // be used to ensure we are hiding only on user initiated
1301 // navigations.
1302 DownloadManager* download_manager = profile()->GetDownloadManager();
1303 // download_manager can be NULL in unit test context.
1304 if (download_manager && download_manager->in_progress_count() == 0 &&
1305 !details.previous_url.is_empty() &&
1306 !net::RegistryControlledDomainService::SameDomainOrHost(
1307 details.previous_url, details.entry->url())) {
1308 base::TimeDelta time_delta(
1309 base::TimeTicks::Now() - last_download_shelf_show_);
1310 if (time_delta >
1311 base::TimeDelta::FromMilliseconds(kDownloadShelfHideDelay)) {
1312 SetDownloadShelfVisible(false);
1313 }
1314 }
1315
1316 if (details.is_user_initiated_main_frame_load()) {
1317 // Clear the status bubble. This is a workaround for a bug where WebKit
1318 // doesn't let us know that the cursor left an element during a
1319 // transition (this is also why the mouse cursor remains as a hand after
1320 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1321 // clear the bubble when a user navigates to a named anchor in the same
1322 // page.
1323 UpdateTargetURL(details.entry->page_id(), GURL());
1324
1325 // UpdateHelpersForDidNavigate will handle the case where the password_form
1326 // origin is valid.
1327 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1328 // cleaned up and covered by tests.
1329 if (!params.password_form.origin.is_valid())
1330 GetPasswordManager()->DidNavigate();
1331 }
1332
1333 // The keyword generator uses the navigation entries, so must be called after
1334 // the commit.
1335 GenerateKeywordIfNecessary(params);
1336
1337 // Allow the new page to set the title again.
1338 received_page_title_ = false;
1339
1340 // Get the favicon, either from history or request it from the net.
1341 fav_icon_helper_.FetchFavIcon(details.entry->url());
1342
[email protected]ce5c4502009-05-06 16:46:111343 // Disable all page actions.
1344 enabled_page_actions_.clear();
1345
[email protected]420ae012009-04-24 05:16:321346 // Close constrained popups if necessary.
1347 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1348
1349 // Update the starred state.
1350 UpdateStarredStateForCurrentURL();
1351}
1352
1353void TabContents::DidNavigateAnyFramePostCommit(
1354 RenderViewHost* render_view_host,
1355 const NavigationController::LoadCommittedDetails& details,
1356 const ViewHostMsg_FrameNavigate_Params& params) {
1357 // If we navigate, start showing messages again. This does nothing to prevent
1358 // a malicious script from spamming messages, since the script could just
1359 // reload the page to stop blocking.
1360 suppress_javascript_messages_ = false;
1361
1362 // Update history. Note that this needs to happen after the entry is complete,
1363 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1364 if (params.should_update_history) {
1365 // Most of the time, the displayURL matches the loaded URL, but for about:
1366 // URLs, we use a data: URL as the real value. We actually want to save
1367 // the about: URL to the history db and keep the data: URL hidden. This is
1368 // what the TabContents' URL getter does.
1369 UpdateHistoryForNavigation(GetURL(), params);
1370 }
1371
1372 // Notify the password manager of the navigation or form submit.
1373 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1374 // cleaned up and covered by tests.
1375 if (params.password_form.origin.is_valid())
1376 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1377}
1378
1379void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1380 const GURL& current_url) {
1381 if (net::RegistryControlledDomainService::SameDomainOrHost(
1382 previous_url, current_url))
1383 return;
1384
1385 // Clear out any child windows since we are leaving this page entirely.
1386 // We use indices instead of iterators in case CloseWindow does something
1387 // that may invalidate an iterator.
1388 int size = static_cast<int>(child_windows_.size());
1389 for (int i = size - 1; i >= 0; --i) {
1390 ConstrainedWindow* window = child_windows_[i];
1391 if (window)
1392 window->CloseConstrainedWindow();
1393 }
1394}
1395
1396void TabContents::UpdateStarredStateForCurrentURL() {
1397 BookmarkModel* model = profile()->GetBookmarkModel();
1398 const bool old_state = is_starred_;
1399 is_starred_ = (model && model->IsBookmarked(GetURL()));
1400
1401 if (is_starred_ != old_state && delegate())
1402 delegate()->URLStarredChanged(this, is_starred_);
1403}
1404
1405void TabContents::UpdateAlternateErrorPageURL() {
1406 GURL url = GetAlternateErrorPageURL();
1407 render_view_host()->SetAlternateErrorPageURL(url);
1408}
1409
1410void TabContents::UpdateWebPreferences() {
1411 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1412}
1413
1414void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1415 RenderViewHost* rvh) {
1416 // If we are creating a RVH for a restored controller, then we might
1417 // have more page IDs than the SiteInstance's current max page ID. We must
1418 // make sure that the max page ID is larger than any restored page ID.
1419 // Note that it is ok for conflicting page IDs to exist in another tab
1420 // (i.e., NavigationController), but if any page ID is larger than the max,
1421 // the back/forward list will get confused.
1422 int max_restored_page_id = controller_.max_restored_page_id();
1423 if (max_restored_page_id > 0) {
1424 int curr_max_page_id = site_instance->max_page_id();
1425 if (max_restored_page_id > curr_max_page_id) {
1426 // Need to update the site instance immediately.
1427 site_instance->UpdateMaxPageID(max_restored_page_id);
1428
1429 // Also tell the renderer to update its internal representation. We
1430 // need to reserve enough IDs to make all restored page IDs less than
1431 // the max.
1432 if (curr_max_page_id < 0)
1433 curr_max_page_id = 0;
1434 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1435 }
1436 }
1437}
1438
1439void TabContents::UpdateHistoryForNavigation(
1440 const GURL& display_url,
1441 const ViewHostMsg_FrameNavigate_Params& params) {
1442 if (profile()->IsOffTheRecord())
1443 return;
1444
1445 // Add to history service.
1446 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1447 if (hs) {
1448 if (PageTransition::IsMainFrame(params.transition) &&
1449 display_url != params.url) {
1450 // Hack on the "display" URL so that it will appear in history. For some
1451 // types of URLs, we will display a magic URL that is different from where
1452 // the page is actually navigated. We want the user to see in history
1453 // what they saw in the URL bar, so we add the display URL as a redirect.
1454 // This only applies to the main frame, as the display URL doesn't apply
1455 // to sub-frames.
1456 std::vector<GURL> redirects = params.redirects;
1457 if (!redirects.empty())
1458 redirects.back() = display_url;
1459 hs->AddPage(display_url, this, params.page_id, params.referrer,
1460 params.transition, redirects);
1461 } else {
1462 hs->AddPage(params.url, this, params.page_id, params.referrer,
1463 params.transition, params.redirects);
1464 }
1465 }
1466}
1467
1468bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1469 const std::wstring& title) {
1470 // For file URLs without a title, use the pathname instead. In the case of a
1471 // synthesized title, we don't want the update to count toward the "one set
1472 // per page of the title to history."
1473 std::wstring final_title;
1474 bool explicit_set;
1475 if (entry->url().SchemeIsFile() && title.empty()) {
1476 final_title = UTF8ToWide(entry->url().ExtractFileName());
1477 explicit_set = false; // Don't count synthetic titles toward the set limit.
1478 } else {
1479 TrimWhitespace(title, TRIM_ALL, &final_title);
1480 explicit_set = true;
1481 }
1482
1483 if (final_title == UTF16ToWideHack(entry->title()))
1484 return false; // Nothing changed, don't bother.
1485
1486 entry->set_title(WideToUTF16Hack(final_title));
1487
1488 // Update the history system for this page.
1489 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1490 HistoryService* hs =
1491 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1492 if (hs)
1493 hs->SetPageTitle(entry->display_url(), final_title);
1494
1495 // Don't allow the title to be saved again for explicitly set ones.
1496 received_page_title_ = explicit_set;
1497 }
1498
1499 // Lastly, set the title for the view.
1500 view_->SetPageTitle(final_title);
1501
1502 return true;
1503}
1504
1505void TabContents::NotifySwapped() {
1506 // After sending out a swap notification, we need to send a disconnect
1507 // notification so that clients that pick up a pointer to |this| can NULL the
1508 // pointer. See Bug 1230284.
1509 notify_disconnection_ = true;
1510 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341511 NotificationType::TAB_CONTENTS_SWAPPED,
1512 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321513 NotificationService::NoDetails());
1514}
1515
1516void TabContents::NotifyConnected() {
1517 notify_disconnection_ = true;
1518 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341519 NotificationType::TAB_CONTENTS_CONNECTED,
1520 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321521 NotificationService::NoDetails());
1522}
1523
1524void TabContents::NotifyDisconnected() {
1525 if (!notify_disconnection_)
1526 return;
1527
1528 notify_disconnection_ = false;
1529 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341530 NotificationType::TAB_CONTENTS_DISCONNECTED,
1531 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321532 NotificationService::NoDetails());
1533}
1534
1535void TabContents::GenerateKeywordIfNecessary(
1536 const ViewHostMsg_FrameNavigate_Params& params) {
1537 if (!params.searchable_form_url.is_valid())
1538 return;
1539
1540 if (profile()->IsOffTheRecord())
1541 return;
1542
1543 int last_index = controller_.last_committed_entry_index();
1544 // When there was no previous page, the last index will be 0. This is
1545 // normally due to a form submit that opened in a new tab.
1546 // TODO(brettw) bug 916126: we should support keywords when form submits
1547 // happen in new tabs.
1548 if (last_index <= 0)
1549 return;
1550 const NavigationEntry* previous_entry =
1551 controller_.GetEntryAtIndex(last_index - 1);
1552 if (IsFormSubmit(previous_entry)) {
1553 // Only generate a keyword if the previous page wasn't itself a form
1554 // submit.
1555 return;
1556 }
1557
1558 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1559 previous_entry->user_typed_url() : previous_entry->url();
1560 std::wstring keyword =
1561 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1562 if (keyword.empty())
1563 return;
1564
1565 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1566 if (!url_model)
1567 return;
1568
1569 if (!url_model->loaded()) {
1570 url_model->Load();
1571 return;
1572 }
1573
1574 const TemplateURL* current_url;
1575 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1576 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1577 return;
1578
1579 if (current_url) {
1580 if (current_url->originating_url().is_valid()) {
1581 // The existing keyword was generated from an OpenSearch description
1582 // document, don't regenerate.
1583 return;
1584 }
1585 url_model->Remove(current_url);
1586 }
1587 TemplateURL* new_url = new TemplateURL();
1588 new_url->set_keyword(keyword);
1589 new_url->set_short_name(keyword);
1590 new_url->SetURL(url, 0, 0);
1591 new_url->add_input_encoding(params.searchable_form_encoding);
1592 DCHECK(controller_.GetLastCommittedEntry());
1593 const GURL& favicon_url =
1594 controller_.GetLastCommittedEntry()->favicon().url();
1595 if (favicon_url.is_valid()) {
1596 new_url->SetFavIconURL(favicon_url);
1597 } else {
1598 // The favicon url isn't valid. This means there really isn't a favicon,
1599 // or the favicon url wasn't obtained before the load started. This assumes
1600 // the later.
1601 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1602 // its url.
1603 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1604 }
1605 new_url->set_safe_for_autoreplace(true);
1606 url_model->Add(new_url);
1607}
1608
1609RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1610 return view_.get();
1611}
1612
1613RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1614 return save_package_.get(); // May be NULL, but we can return NULL.
1615}
1616
[email protected]6dfed102009-04-28 03:09:531617ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1618 RenderViewHost* render_view_host,
1619 const std::string& extension_id) {
1620 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1621 extension_id);
1622}
1623
[email protected]57c6a652009-05-04 07:58:341624TabContents* TabContents::GetAsTabContents() {
1625 return this;
1626}
1627
[email protected]420ae012009-04-24 05:16:321628void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1629 NavigationEntry* entry = controller_.GetActiveEntry();
1630 if (!entry)
1631 return;
1632
1633 // When we're creating views, we're still doing initial setup, so we always
1634 // use the pending DOM UI rather than any possibly existing committed one.
1635 if (render_manager_.pending_dom_ui()) {
1636 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1637 }
1638
1639 if (entry->IsViewSourceMode()) {
1640 // Put the renderer in view source mode.
1641 render_view_host->Send(
1642 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1643 }
[email protected]0666aef2009-05-13 19:48:081644
1645 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321646}
1647
1648void TabContents::RenderViewReady(RenderViewHost* rvh) {
1649 if (rvh != render_view_host()) {
1650 // Don't notify the world, since this came from a renderer in the
1651 // background.
1652 return;
1653 }
1654
1655 NotifyConnected();
1656 SetIsCrashed(false);
1657}
1658
1659void TabContents::RenderViewGone(RenderViewHost* rvh) {
1660 // Ask the print preview if this renderer was valuable.
1661 if (!printing_.OnRenderViewGone(rvh))
1662 return;
1663 if (rvh != render_view_host()) {
1664 // The pending page's RenderViewHost is gone.
1665 return;
1666 }
1667
1668 SetIsLoading(false, NULL);
1669 NotifyDisconnected();
1670 SetIsCrashed(true);
1671
1672 // Force an invalidation to render sad tab. The view will notice we crashed
1673 // when it paints.
1674 view_->Invalidate();
1675
1676 // Hide any visible hung renderer warning for this web contents' process.
[email protected]8897c382009-05-06 17:53:261677 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:321678}
1679
1680void TabContents::DidNavigate(RenderViewHost* rvh,
1681 const ViewHostMsg_FrameNavigate_Params& params) {
1682 if (PageTransition::IsMainFrame(params.transition))
1683 render_manager_.DidNavigateMainFrame(rvh);
1684
1685 // Update the site of the SiteInstance if it doesn't have one yet.
1686 if (!GetSiteInstance()->has_site())
1687 GetSiteInstance()->SetSite(params.url);
1688
1689 // Need to update MIME type here because it's referred to in
1690 // UpdateNavigationCommands() called by RendererDidNavigate() to
1691 // determine whether or not to enable the encoding menu.
1692 // It's updated only for the main frame. For a subframe,
1693 // RenderView::UpdateURL does not set params.contents_mime_type.
1694 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1695 // TODO(jungshik): Add a test for the encoding menu to avoid
1696 // regressing it again.
1697 if (PageTransition::IsMainFrame(params.transition))
1698 contents_mime_type_ = params.contents_mime_type;
1699
1700 NavigationController::LoadCommittedDetails details;
1701 if (!controller_.RendererDidNavigate(params, &details))
1702 return; // No navigation happened.
1703
1704 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1705 // for the appropriate notification (best) or you can add it to
1706 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1707 // necessary, please).
1708
1709 // Run post-commit tasks.
1710 if (details.is_main_frame)
1711 DidNavigateMainFramePostCommit(details, params);
1712 DidNavigateAnyFramePostCommit(rvh, details, params);
1713}
1714
1715void TabContents::UpdateState(RenderViewHost* rvh,
1716 int32 page_id,
1717 const std::string& state) {
1718 DCHECK(rvh == render_view_host());
1719
1720 // We must be prepared to handle state updates for any page, these occur
1721 // when the user is scrolling and entering form data, as well as when we're
1722 // leaving a page, in which case our state may have already been moved to
1723 // the next page. The navigation controller will look up the appropriate
1724 // NavigationEntry and update it when it is notified via the delegate.
1725
1726 int entry_index = controller_.GetEntryIndexWithPageID(
1727 GetSiteInstance(), page_id);
1728 if (entry_index < 0)
1729 return;
1730 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1731
1732 if (state == entry->content_state())
1733 return; // Nothing to update.
1734 entry->set_content_state(state);
1735 controller_.NotifyEntryChanged(entry, entry_index);
1736}
1737
1738void TabContents::UpdateTitle(RenderViewHost* rvh,
1739 int32 page_id, const std::wstring& title) {
1740 // If we have a title, that's a pretty good indication that we've started
1741 // getting useful data.
1742 SetNotWaitingForResponse();
1743
1744 DCHECK(rvh == render_view_host());
1745 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1746 page_id);
1747 if (!entry || !UpdateTitleForEntry(entry, title))
1748 return;
1749
1750 // Broadcast notifications when the UI should be updated.
1751 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501752 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321753}
1754
[email protected]420ae012009-04-24 05:16:321755void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1756 const std::wstring& encoding) {
1757 set_encoding(encoding);
1758}
1759
1760void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1761 if (delegate())
1762 delegate()->UpdateTargetURL(this, url);
1763}
1764
1765void TabContents::UpdateThumbnail(const GURL& url,
1766 const SkBitmap& bitmap,
1767 const ThumbnailScore& score) {
1768 // Tell History about this thumbnail
1769 HistoryService* hs;
1770 if (!profile()->IsOffTheRecord() &&
1771 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1772 hs->SetPageThumbnail(url, bitmap, score);
1773 }
1774}
1775
1776void TabContents::Close(RenderViewHost* rvh) {
1777 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1778 if (delegate() && rvh == render_view_host())
1779 delegate()->CloseContents(this);
1780}
1781
1782void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1783 if (delegate() && delegate()->IsPopup(this))
1784 delegate()->MoveContents(this, new_bounds);
1785}
1786
[email protected]329581b2009-04-28 06:52:351787void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321788 SetIsLoading(true, NULL);
1789}
1790
[email protected]329581b2009-04-28 06:52:351791void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321792 scoped_ptr<LoadNotificationDetails> details;
1793
1794 NavigationEntry* entry = controller_.GetActiveEntry();
1795 // An entry may not exist for a stop when loading an initial blank page or
1796 // if an iframe injected by script into a blank page finishes loading.
1797 if (entry) {
1798 scoped_ptr<base::ProcessMetrics> metrics(
1799 base::ProcessMetrics::CreateProcessMetrics(
1800 process()->process().handle()));
1801
1802 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1803
1804 details.reset(new LoadNotificationDetails(
1805 entry->display_url(),
1806 entry->transition_type(),
1807 elapsed,
1808 &controller_,
1809 controller_.GetCurrentEntryIndex()));
1810 }
1811
1812 // Tell PasswordManager we've finished a page load, which serves as a
1813 // green light to save pending passwords and reset itself.
1814 GetPasswordManager()->DidStopLoading();
1815
1816 SetIsLoading(false, details.get());
1817}
1818
1819void TabContents::DidStartProvisionalLoadForFrame(
1820 RenderViewHost* render_view_host,
1821 bool is_main_frame,
1822 const GURL& url) {
1823 ProvisionalLoadDetails details(is_main_frame,
1824 controller_.IsURLInPageNavigation(url),
1825 url, std::string(), false);
1826 NotificationService::current()->Notify(
1827 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1828 Source<NavigationController>(&controller_),
1829 Details<ProvisionalLoadDetails>(&details));
1830}
1831
1832void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1833 const GURL& source_url,
1834 const GURL& target_url) {
1835 NavigationEntry* entry;
1836 if (page_id == -1)
1837 entry = controller_.pending_entry();
1838 else
1839 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1840 if (!entry || entry->url() != source_url)
1841 return;
1842 entry->set_url(target_url);
1843}
1844
1845void TabContents::DidLoadResourceFromMemoryCache(
1846 const GURL& url,
1847 const std::string& frame_origin,
1848 const std::string& main_frame_origin,
1849 const std::string& security_info) {
1850 // Send out a notification that we loaded a resource from our memory cache.
1851 int cert_id = 0, cert_status = 0, security_bits = 0;
1852 SSLManager::DeserializeSecurityInfo(security_info,
1853 &cert_id, &cert_status,
1854 &security_bits);
1855 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]9ae66cbf2009-05-12 16:21:031856 process()->pid(), cert_id, cert_status);
[email protected]420ae012009-04-24 05:16:321857
1858 NotificationService::current()->Notify(
1859 NotificationType::LOAD_FROM_MEMORY_CACHE,
1860 Source<NavigationController>(&controller_),
1861 Details<LoadFromMemoryCacheDetails>(&details));
1862}
1863
1864void TabContents::DidFailProvisionalLoadWithError(
1865 RenderViewHost* render_view_host,
1866 bool is_main_frame,
1867 int error_code,
1868 const GURL& url,
1869 bool showing_repost_interstitial) {
1870 if (net::ERR_ABORTED == error_code) {
1871 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1872 // This means that the interstitial won't be torn down properly, which is
1873 // bad. But if we have an interstitial, go back to another tab type, and
1874 // then load the same interstitial again, we could end up getting the first
1875 // interstitial's "failed" message (as a result of the cancel) when we're on
1876 // the second one.
1877 //
1878 // We can't tell this apart, so we think we're tearing down the current page
1879 // which will cause a crash later one. There is also some code in
1880 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1881 // out because of this problem.
1882 //
1883 // http://code.google.com/p/chromium/issues/detail?id=2855
1884 // Because this will not tear down the interstitial properly, if "back" is
1885 // back to another tab type, the interstitial will still be somewhat alive
1886 // in the previous tab type. If you navigate somewhere that activates the
1887 // tab with the interstitial again, you'll see a flash before the new load
1888 // commits of the interstitial page.
1889 if (showing_interstitial_page()) {
1890 LOG(WARNING) << "Discarding message during interstitial.";
1891 return;
1892 }
1893
1894 // This will discard our pending entry if we cancelled the load (e.g., if we
1895 // decided to download the file instead of load it). Only discard the
1896 // pending entry if the URLs match, otherwise the user initiated a navigate
1897 // before the page loaded so that the discard would discard the wrong entry.
1898 NavigationEntry* pending_entry = controller_.pending_entry();
1899 if (pending_entry && pending_entry->url() == url)
1900 controller_.DiscardNonCommittedEntries();
1901
1902 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1903 }
1904
1905 // Send out a notification that we failed a provisional load with an error.
1906 ProvisionalLoadDetails details(is_main_frame,
1907 controller_.IsURLInPageNavigation(url),
1908 url, std::string(), false);
1909 details.set_error_code(error_code);
1910
1911 NotificationService::current()->Notify(
1912 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1913 Source<NavigationController>(&controller_),
1914 Details<ProvisionalLoadDetails>(&details));
1915}
1916
1917void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1918 int32 page_id,
1919 const GURL& icon_url) {
1920 fav_icon_helper_.SetFavIconURL(icon_url);
1921}
1922
1923void TabContents::DidDownloadImage(
1924 RenderViewHost* render_view_host,
1925 int id,
1926 const GURL& image_url,
1927 bool errored,
1928 const SkBitmap& image) {
1929 // A notification for downloading would be more flexible, but for now I'm
1930 // forwarding to the two places that could possibly have initiated the
1931 // request. If we end up with another place invoking DownloadImage, probably
1932 // best to refactor out into notification service, or something similar.
1933 if (errored)
1934 fav_icon_helper_.FavIconDownloadFailed(id);
1935 else
1936 fav_icon_helper_.SetFavIcon(id, image_url, image);
1937}
1938
1939void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1940 WindowOpenDisposition disposition) {
1941 if (render_manager_.dom_ui()) {
1942 // When we're a DOM UI, it will provide a page transition type for us (this
1943 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1944 // generated suggestions).
1945 //
1946 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161947 // want web sites to see a referrer of "chrome://blah" (and some
1948 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321949 // send to the site), so we send no referrer.
1950 OpenURL(url, GURL(), disposition,
1951 render_manager_.dom_ui()->link_transition_type());
1952 } else {
1953 OpenURL(url, referrer, disposition, PageTransition::LINK);
1954 }
1955}
1956
1957void TabContents::DomOperationResponse(const std::string& json_string,
1958 int automation_id) {
1959 DomOperationNotificationDetails details(json_string, automation_id);
1960 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341961 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321962 Details<DomOperationNotificationDetails>(&details));
1963}
1964
1965void TabContents::ProcessDOMUIMessage(const std::string& message,
1966 const std::string& content) {
1967 if (!render_manager_.dom_ui()) {
1968 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1969 // Because the renderer might be owned and sending random messages, we need
1970 // to ignore these inproper ones.
1971 NOTREACHED();
1972 return;
1973 }
1974 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1975}
1976
1977void TabContents::ProcessExternalHostMessage(const std::string& message,
1978 const std::string& origin,
1979 const std::string& target) {
1980 if (delegate())
1981 delegate()->ForwardMessageToExternalHost(message, origin, target);
1982}
1983
1984void TabContents::GoToEntryAtOffset(int offset) {
1985 controller_.GoToOffset(offset);
1986}
1987
1988void TabContents::GetHistoryListCount(int* back_list_count,
1989 int* forward_list_count) {
1990 int current_index = controller_.last_committed_entry_index();
1991 *back_list_count = current_index;
1992 *forward_list_count = controller_.entry_count() - current_index - 1;
1993}
1994
1995void TabContents::RunFileChooser(bool multiple_files,
1996 const string16& title,
1997 const FilePath& default_file) {
1998 if (!select_file_dialog_.get())
1999 select_file_dialog_ = SelectFileDialog::Create(this);
2000 SelectFileDialog::Type dialog_type =
2001 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
2002 SelectFileDialog::SELECT_OPEN_FILE;
2003 select_file_dialog_->SelectFile(dialog_type, title, default_file,
2004 NULL, 0, FILE_PATH_LITERAL(""),
2005 view_->GetTopLevelNativeWindow(), NULL);
2006}
2007
2008void TabContents::RunJavaScriptMessage(
2009 const std::wstring& message,
2010 const std::wstring& default_prompt,
2011 const GURL& frame_url,
2012 const int flags,
2013 IPC::Message* reply_msg,
2014 bool* did_suppress_message) {
2015 // Suppress javascript messages when requested and when inside a constrained
2016 // popup window (because that activates them and breaks them out of the
2017 // constrained window jail).
2018 bool suppress_this_message = suppress_javascript_messages_;
2019 if (delegate())
2020 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:312021 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:322022
2023 *did_suppress_message = suppress_this_message;
2024
2025 if (!suppress_this_message) {
2026 base::TimeDelta time_since_last_message(
2027 base::TimeTicks::Now() - last_javascript_message_dismissal_);
2028 bool show_suppress_checkbox = false;
2029 // Show a checkbox offering to suppress further messages if this message is
2030 // being displayed within kJavascriptMessageExpectedDelay of the last one.
2031 if (time_since_last_message <
2032 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
2033 show_suppress_checkbox = true;
2034
2035 RunJavascriptMessageBox(AsWC(this), frame_url, flags, message, default_prompt,
2036 show_suppress_checkbox, reply_msg);
2037 } else {
2038 // If we are suppressing messages, just reply as is if the user immediately
2039 // pressed "Cancel".
2040 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
2041 }
2042}
2043
2044void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
2045 IPC::Message* reply_msg) {
2046 RunBeforeUnloadDialog(AsWC(this), message, reply_msg);
2047}
2048
2049void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
2050 const std::string& json_arguments,
2051 IPC::Message* reply_msg) {
2052 if (delegate()) {
2053 HtmlDialogUIDelegate* dialog_delegate =
2054 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
2055 reply_msg, AsWC(this));
2056 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
2057 }
2058}
2059
2060void TabContents::PasswordFormsSeen(
2061 const std::vector<PasswordForm>& forms) {
2062 GetPasswordManager()->PasswordFormsSeen(forms);
2063}
2064
2065void TabContents::AutofillFormSubmitted(
2066 const AutofillForm& form) {
2067 GetAutofillManager()->AutofillFormSubmitted(form);
2068}
2069
2070void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
2071 const std::wstring& user_text, int64 node_id, int request_id) {
2072 GetAutofillManager()->FetchValuesForName(field_name, user_text,
2073 kMaxAutofillMenuItems, node_id, request_id);
2074}
2075
2076void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
2077 const std::wstring& value) {
2078 GetAutofillManager()->RemoveValueForName(field_name, value);
2079}
2080
2081// Checks to see if we should generate a keyword based on the OSDD, and if
2082// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2083void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2084 int32 page_id, const GURL& url,
2085 bool autodetected) {
2086 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2087 DCHECK(url.is_valid());
2088 if (!IsActiveEntry(page_id))
2089 return;
2090 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2091 if (!url_model)
2092 return;
2093 if (!url_model->loaded()) {
2094 url_model->Load();
2095 return;
2096 }
2097 if (!profile()->GetTemplateURLFetcher())
2098 return;
2099
2100 if (profile()->IsOffTheRecord())
2101 return;
2102
2103 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2104 DCHECK(entry);
2105
2106 const NavigationEntry* base_entry = entry;
2107 if (IsFormSubmit(base_entry)) {
2108 // If the current page is a form submit, find the last page that was not
2109 // a form submit and use its url to generate the keyword from.
2110 int index = controller_.last_committed_entry_index() - 1;
2111 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2112 index--;
2113 if (index >= 0)
2114 base_entry = controller_.GetEntryAtIndex(index);
2115 else
2116 base_entry = NULL;
2117 }
2118
2119 // We want to use the user typed URL if available since that represents what
2120 // the user typed to get here, and fall back on the regular URL if not.
2121 if (!base_entry)
2122 return;
2123 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2124 base_entry->user_typed_url() : base_entry->url();
2125 if (!keyword_url.is_valid())
2126 return;
2127 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2128 autodetected);
2129 if (keyword.empty())
2130 return;
2131 const TemplateURL* template_url =
2132 url_model->GetTemplateURLForKeyword(keyword);
2133 if (template_url && (!template_url->safe_for_autoreplace() ||
2134 template_url->originating_url() == url)) {
2135 // Either there is a user created TemplateURL for this keyword, or the
2136 // keyword has the same OSDD url and we've parsed it.
2137 return;
2138 }
2139
2140 // Download the OpenSearch description document. If this is successful a
2141 // new keyword will be created when done.
2142#if defined(OS_WIN)
2143 gfx::NativeView ancestor = GetAncestor(view_->GetNativeView(), GA_ROOT);
2144#else
2145 gfx::NativeView ancestor = NULL;
2146#endif
2147 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2148 keyword,
2149 url,
2150 base_entry->favicon().url(),
2151 ancestor,
2152 autodetected);
2153}
2154
2155void TabContents::InspectElementReply(int num_resources) {
2156 // We have received reply from inspect element request. Notify the
2157 // automation provider in case we need to notify automation client.
2158 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:342159 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:322160 Details<int>(&num_resources));
2161}
2162
2163void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2164 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2165}
2166
2167void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2168 printing_.DidPrintPage(params);
2169}
2170
2171GURL TabContents::GetAlternateErrorPageURL() const {
2172 GURL url;
2173 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2174 if (profile()->IsOffTheRecord())
2175 return url;
2176
2177 PrefService* prefs = profile()->GetPrefs();
2178 DCHECK(prefs);
2179 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2180 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2181 url = google_util::AppendGoogleTLDParam(url);
2182 }
2183 return url;
2184}
2185
2186WebPreferences TabContents::GetWebkitPrefs() {
2187 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2188 bool isDomUI = false;
2189 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2190}
2191
2192void TabContents::OnMissingPluginStatus(int status) {
2193#if defined(OS_WIN)
2194// TODO(PORT): pull in when plug-ins work
2195 GetPluginInstaller()->OnMissingPluginStatus(status);
2196#endif
2197}
2198
2199void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2200#if defined(OS_WIN)
2201// TODO(PORT): pull in when plug-ins work
2202 DCHECK(!plugin_path.value().empty());
2203
2204 std::wstring plugin_name = plugin_path.ToWStringHack();
2205 scoped_ptr<FileVersionInfo> version_info(
2206 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2207 if (version_info.get()) {
2208 const std::wstring& product_name = version_info->product_name();
2209 if (!product_name.empty())
2210 plugin_name = product_name;
2211 }
2212 AddInfoBar(new SimpleAlertInfoBarDelegate(
2213 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2214 NULL));
2215#endif
2216}
2217
2218void TabContents::OnCrashedWorker() {
2219 AddInfoBar(new SimpleAlertInfoBarDelegate(
2220 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2221 NULL));
2222}
2223
2224void TabContents::OnJSOutOfMemory() {
2225 AddInfoBar(new SimpleAlertInfoBarDelegate(
2226 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2227}
2228
2229void TabContents::ShouldClosePage(bool proceed) {
2230 render_manager_.ShouldClosePage(proceed);
2231}
2232
2233void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2234 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342235 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322236 // delivered to a pending RenderViewHost. We must first run the onunload
2237 // handler of the old RenderViewHost before we can allow it to proceed.
2238 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2239 new_request_id);
2240}
2241
2242bool TabContents::CanBlur() const {
2243 return delegate() ? delegate()->CanBlur() : true;
2244}
2245
2246gfx::Rect TabContents::GetRootWindowResizerRect() const {
2247 if (delegate())
2248 return delegate()->GetRootWindowResizerRect();
2249 return gfx::Rect();
2250}
2251
2252void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2253 bool is_during_unload) {
2254 if (is_during_unload) {
2255 // Hang occurred while firing the beforeunload/unload handler.
2256 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112257 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322258
2259 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2260 return;
2261
2262 // If the tab hangs in the beforeunload/unload handler there's really
2263 // nothing we can do to recover. Pretend the unload listeners have
2264 // all fired and close the tab. If the hang is in the beforeunload handler
2265 // then the user will not have the option of cancelling the close.
2266 Close(rvh);
2267 return;
2268 }
2269
2270 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]8897c382009-05-06 17:53:262271 HungRendererDialog::ShowForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322272}
2273
2274void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]8897c382009-05-06 17:53:262275 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322276}
2277
2278void TabContents::LoadStateChanged(const GURL& url,
2279 net::LoadState load_state) {
2280 load_state_ = load_state;
2281 load_state_host_ = UTF8ToWide(url.host());
2282 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2283 SetNotWaitingForResponse();
2284 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502285 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322286}
2287
2288void TabContents::OnDidGetApplicationInfo(
2289 int32 page_id,
2290 const webkit_glue::WebApplicationInfo& info) {
2291 if (pending_install_.page_id != page_id)
2292 return; // The user clicked create on a separate page. Ignore this.
2293
2294 pending_install_.callback_functor =
2295 new GearsCreateShortcutCallbackFunctor(this);
2296 GearsCreateShortcut(
2297 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2298 NewCallback(pending_install_.callback_functor,
2299 &GearsCreateShortcutCallbackFunctor::Run));
2300}
2301
[email protected]14ce83f2009-05-28 18:35:242302void TabContents::OnUserGesture() {
2303 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
2304#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]420ae012009-04-24 05:16:322305 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2306 if (drm)
2307 drm->OnUserGesture(this);
2308#endif
2309}
2310
2311void TabContents::OnFindReply(int request_id,
2312 int number_of_matches,
2313 const gfx::Rect& selection_rect,
2314 int active_match_ordinal,
2315 bool final_update) {
2316 // Ignore responses for requests other than the one we have most recently
2317 // issued. That way we won't act on stale results when the user has
2318 // already typed in another query.
2319 if (request_id != current_find_request_id_)
2320 return;
2321
2322 if (number_of_matches == -1)
[email protected]e491f1c2009-05-22 20:28:122323 number_of_matches = last_search_result_.number_of_matches();
[email protected]420ae012009-04-24 05:16:322324 if (active_match_ordinal == -1)
[email protected]e491f1c2009-05-22 20:28:122325 active_match_ordinal = last_search_result_.active_match_ordinal();
[email protected]420ae012009-04-24 05:16:322326
[email protected]2c355c282009-05-21 23:24:432327 gfx::Rect selection = selection_rect;
2328 if (selection.IsEmpty())
[email protected]e491f1c2009-05-22 20:28:122329 selection = last_search_result_.selection_rect();
[email protected]2c355c282009-05-21 23:24:432330
[email protected]420ae012009-04-24 05:16:322331 // Notify the UI, automation and any other observers that a find result was
2332 // found.
[email protected]e491f1c2009-05-22 20:28:122333 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
2334 selection, active_match_ordinal,
2335 final_update);
[email protected]420ae012009-04-24 05:16:322336 NotificationService::current()->Notify(
2337 NotificationType::FIND_RESULT_AVAILABLE,
2338 Source<TabContents>(this),
[email protected]e491f1c2009-05-22 20:28:122339 Details<FindNotificationDetails>(&last_search_result_));
[email protected]420ae012009-04-24 05:16:322340}
2341
[email protected]829e7612009-04-25 01:15:112342bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322343 if (!delegate())
[email protected]829e7612009-04-25 01:15:112344 return false;
[email protected]420ae012009-04-24 05:16:322345
[email protected]829e7612009-04-25 01:15:112346 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322347}
2348
2349void TabContents::FileSelected(const FilePath& path,
2350 int index, void* params) {
2351 render_view_host()->FileSelected(path);
2352}
2353
2354void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2355 void* params) {
2356 render_view_host()->MultiFilesSelected(files);
2357}
2358
2359void TabContents::FileSelectionCanceled(void* params) {
2360 // If the user cancels choosing a file to upload we pass back an
2361 // empty vector.
2362 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2363}
2364
2365void TabContents::BeforeUnloadFiredFromRenderManager(
2366 bool proceed,
2367 bool* proceed_to_fire_unload) {
2368 if (delegate())
2369 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2370}
2371
2372void TabContents::UpdateRenderViewSizeForRenderManager() {
2373 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2374 view_->SizeContents(view_->GetContainerSize());
2375}
2376
2377DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
2378 return DOMUIFactory::CreateDOMUIForURL(AsWC(this), url);
2379}
2380
2381NavigationEntry*
2382TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2383 return controller_.GetLastCommittedEntry();
2384}
2385
2386bool TabContents::CreateRenderViewForRenderManager(
2387 RenderViewHost* render_view_host) {
2388 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2389 // mode before CreateRenderView is called. When we're asked to create a
2390 // RenderView, that means it's for the pending entry, so we have to use the
2391 // pending DOM UI.
2392 if (render_manager_.pending_dom_ui())
2393 render_view_host->AllowDOMUIBindings();
2394
2395 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2396 if (!render_view_host->CreateRenderView())
2397 return false;
2398
2399 // Now that the RenderView has been created, we need to tell it its size.
2400 rwh_view->SetSize(view_->GetContainerSize());
2401
2402 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2403 render_view_host);
2404 return true;
2405}
2406
2407void TabContents::Observe(NotificationType type,
2408 const NotificationSource& source,
2409 const NotificationDetails& details) {
2410 switch (type.value) {
2411 case NotificationType::BOOKMARK_MODEL_LOADED:
2412 // BookmarkModel finished loading, fall through to update starred state.
2413 case NotificationType::URLS_STARRED: {
2414 // Somewhere, a URL has been starred.
2415 // Ignore notifications for profiles other than our current one.
2416 Profile* source_profile = Source<Profile>(source).ptr();
2417 if (!source_profile || !source_profile->IsSameProfile(profile()))
2418 return;
2419
2420 UpdateStarredStateForCurrentURL();
2421 break;
2422 }
2423 case NotificationType::PREF_CHANGED: {
2424 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2425 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2426 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2427 UpdateAlternateErrorPageURL();
2428 } else if (*pref_name_in == prefs::kDefaultCharset ||
2429 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2430 ) {
2431 UpdateWebPreferences();
2432 } else {
2433 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2434 }
2435 break;
2436 }
2437 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2438 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2439 break;
2440
2441 case NotificationType::NAV_ENTRY_COMMITTED: {
2442 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2443
2444 NavigationController::LoadCommittedDetails& committed_details =
2445 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2446 ExpireInfoBars(committed_details);
2447 break;
2448 }
2449
2450 default:
2451 NOTREACHED();
2452 }
2453}