blob: 451d5b5efe5ce0ec6ea99d8e42aa085e28de6223 [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]420ae012009-04-24 05:16:3225#include "chrome/browser/gears_integration.h"
26#include "chrome/browser/google_util.h"
[email protected]8897c382009-05-06 17:53:2627#include "chrome/browser/hung_renderer_dialog.h"
[email protected]420ae012009-04-24 05:16:3228#include "chrome/browser/jsmessage_box_handler.h"
29#include "chrome/browser/load_from_memory_cache_details.h"
30#include "chrome/browser/load_notification_details.h"
[email protected]fdd61c62009-04-22 19:22:5731#include "chrome/browser/password_manager/password_manager.h"
32#include "chrome/browser/plugin_installer.h"
[email protected]96d185d2009-04-24 03:28:5433#include "chrome/browser/renderer_host/render_widget_host_view.h"
34#include "chrome/browser/renderer_host/web_cache_manager.h"
[email protected]f3ec7742009-01-15 00:59:1635#include "chrome/browser/tab_contents/navigation_entry.h"
[email protected]f3ec7742009-01-15 00:59:1636#include "chrome/browser/tab_contents/tab_contents_delegate.h"
[email protected]fdd61c62009-04-22 19:22:5737#include "chrome/browser/tab_contents/tab_contents_view.h"
[email protected]420ae012009-04-24 05:16:3238#include "chrome/browser/search_engines/template_url_fetcher.h"
39#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2740#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5641#include "chrome/common/notification_service.h"
[email protected]ce5c4502009-05-06 16:46:1142#include "chrome/common/page_action.h"
initial.commit09911bf2008-07-26 23:55:2943#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0344#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3245#include "chrome/common/render_messages.h"
[email protected]96d185d2009-04-24 03:28:5446#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2647#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3248#include "grit/locale_settings.h"
49#include "net/base/mime_util.h"
50#include "net/base/net_errors.h"
51#include "net/base/registry_controlled_domain.h"
[email protected]3e45ba92009-02-20 21:09:0052
53#if defined(OS_WIN)
54// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3255#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]3e45ba92009-02-20 21:09:0056#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]3e45ba92009-02-20 21:09:0057#include "chrome/browser/views/blocked_popup_container.h"
[email protected]420ae012009-04-24 05:16:3258#include "chrome/browser/views/download_started_animation.h"
[email protected]2362e4f2009-05-08 00:34:0559#include "views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0060#endif
initial.commit09911bf2008-07-26 23:55:2961
[email protected]420ae012009-04-24 05:16:3262// Cross-Site Navigations
63//
64// If a TabContents is told to navigate to a different web site (as determined
65// by SiteInstance), it will replace its current RenderViewHost with a new
66// RenderViewHost dedicated to the new SiteInstance. This works as follows:
67//
68// - Navigate determines whether the destination is cross-site, and if so,
69// it creates a pending_render_view_host_ and moves into the PENDING
70// RendererState.
71// - The pending RVH is "suspended," so that no navigation messages are sent to
72// its renderer until the onbeforeunload JavaScript handler has a chance to
73// run in the current RVH.
74// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
75// that it has a pending cross-site request. ResourceDispatcherHost will
76// check for this when the response arrives.
77// - The current RVH runs its onbeforeunload handler. If it returns false, we
78// cancel all the pending logic and go back to NORMAL. Otherwise we allow
79// the pending RVH to send the navigation request to its renderer.
80// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
81// checks CrossSiteRequestManager to see that the RVH responsible has a
82// pending cross-site request, and then installs a CrossSiteEventHandler.
83// - When RDH receives a response, the BufferedEventHandler determines whether
84// it is a download. If so, it sends a message to the new renderer causing
85// it to cancel the request, and the download proceeds in the download
86// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:3487// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:3288// doesn't affect any functionality.
89// - After RDH receives a response and determines that it is safe and not a
90// download, it pauses the response to first run the old page's onunload
91// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:3492// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:3293// to the current RVH.
94// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
95// the ResourceDispatcherHost, who unpauses the response. Data is then sent
96// to the pending RVH.
97// - The pending renderer sends a FrameNavigate message that invokes the
98// DidNavigate method. This replaces the current RVH with the
99// pending RVH and goes back to the NORMAL RendererState.
100
101namespace {
102
103// Amount of time we wait between when a key event is received and the renderer
104// is queried for its state and pushed to the NavigationEntry.
105const int kQueryStateDelay = 5000;
106
107const int kSyncWaitDelay = 40;
108
109// If another javascript message box is displayed within
110// kJavascriptMessageExpectedDelay of a previous javascript message box being
111// dismissed, display an option to suppress future message boxes from this
112// contents.
113const int kJavascriptMessageExpectedDelay = 1000;
114
115// Minimum amount of time in ms that has to elapse since the download shelf was
116// shown for us to hide it when navigating away from the current page.
117const int kDownloadShelfHideDelay = 5000;
118
119const char kLinkDoctorBaseURL[] =
120 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
121
122// The printer icon in shell32.dll. That's a standard icon user will quickly
123// recognize.
124const int kShell32PrinterIcon = 17;
125
126// The list of prefs we want to observe.
127const wchar_t* kPrefsToObserve[] = {
128 prefs::kAlternateErrorPagesEnabled,
129 prefs::kWebKitJavaEnabled,
130 prefs::kWebKitJavascriptEnabled,
131 prefs::kWebKitLoadsImagesAutomatically,
132 prefs::kWebKitPluginsEnabled,
133 prefs::kWebKitUsesUniversalDetector,
134 prefs::kWebKitSerifFontFamily,
135 prefs::kWebKitSansSerifFontFamily,
136 prefs::kWebKitFixedFontFamily,
137 prefs::kWebKitDefaultFontSize,
138 prefs::kWebKitDefaultFixedFontSize,
139 prefs::kDefaultCharset
140 // kWebKitStandardFontIsSerif needs to be added
141 // if we let users pick which font to use, serif or sans-serif when
142 // no font is specified or a CSS generic family (serif or sans-serif)
143 // is not specified.
144};
145
146const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
147
148// Limit on the number of suggestions to appear in the pop-up menu under an
149// text input element in a form.
150const int kMaxAutofillMenuItems = 6;
151
152// Returns true if the entry's transition type is FORM_SUBMIT.
153bool IsFormSubmit(const NavigationEntry* entry) {
154 return (PageTransition::StripQualifier(entry->transition_type()) ==
155 PageTransition::FORM_SUBMIT);
156}
157
158#if defined(OS_WIN)
159
160BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
161 // Note: erase is required to properly paint some widgets borders. This can
162 // be seen with textfields.
163 InvalidateRect(hwnd, NULL, TRUE);
164 return TRUE;
165}
166#endif
167
[email protected]57c6a652009-05-04 07:58:34168// TODO(brettw) TabContents should be removed, then this hack is unnecessary.
169TabContents* AsWC(TabContents* tc) {
170 return static_cast<TabContents*>(tc);
[email protected]420ae012009-04-24 05:16:32171}
172
173} // namespace
174
175// -----------------------------------------------------------------------------
176
[email protected]fdd61c62009-04-22 19:22:57177// static
178int TabContents::find_request_id_counter_ = -1;
179
[email protected]420ae012009-04-24 05:16:32180class TabContents::GearsCreateShortcutCallbackFunctor {
181 public:
182 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
183 : contents_(contents) {}
184
185 void Run(const GearsShortcutData2& shortcut_data, bool success) {
186 if (contents_)
187 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
188 delete this;
189 }
190 void Cancel() {
191 contents_ = NULL;
192 }
193
194 private:
195 TabContents* contents_;
196};
197
[email protected]57c6a652009-05-04 07:58:34198// TODO(brettw) many of the data members here have casts to TabContents.
199// This object is the same as TabContents and is currently being merged.
[email protected]fdd61c62009-04-22 19:22:57200// When this merge is done, the casts can be removed.
[email protected]420ae012009-04-24 05:16:32201TabContents::TabContents(Profile* profile,
202 SiteInstance* site_instance,
203 int routing_id,
204 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42205 : delegate_(NULL),
[email protected]ce3fa3c2009-04-20 19:55:57206 controller_(this, profile),
[email protected]57c6a652009-05-04 07:58:34207 view_(TabContentsView::Create(static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57208 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(
[email protected]57c6a652009-05-04 07:58:34209 static_cast<TabContents*>(this),
210 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57211 property_bag_(),
212 registrar_(),
[email protected]57c6a652009-05-04 07:58:34213 printing_(*static_cast<TabContents*>(this)),
[email protected]fdd61c62009-04-22 19:22:57214 save_package_(),
215 cancelable_consumer_(),
216 autofill_manager_(),
217 password_manager_(),
218 plugin_installer_(),
219 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(
[email protected]57c6a652009-05-04 07:58:34220 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57221 select_file_dialog_(),
222 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34223 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29224 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34225 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34226 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57227 current_load_start_(),
228 load_state_(net::LOAD_STATE_IDLE),
229 load_state_host_(),
230 received_page_title_(false),
231 is_starred_(false),
232 contents_mime_type_(),
233 encoding_(),
234 download_shelf_(),
235 shelf_visible_(false),
[email protected]332af7732009-03-11 13:21:35236 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57237 infobar_delegates_(),
238 last_download_shelf_show_(),
239 find_ui_active_(false),
240 find_op_aborted_(false),
241 current_find_request_id_(find_request_id_counter_++),
242 find_text_(),
243 find_prepopulate_text_(NULL),
244 find_result_(),
245 capturing_contents_(false),
246 is_being_destroyed_(false),
247 notify_disconnection_(false),
248 history_requests_(),
249#if defined(OS_WIN)
250 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
251#endif
252 last_javascript_message_dismissal_(),
253 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32254 pending_install_.page_id = 0;
255 pending_install_.callback_functor = NULL;
256
257 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
258
259 view_->CreateView();
260
261 // Register for notifications about all interested prefs change.
262 PrefService* prefs = profile->GetPrefs();
263 if (prefs) {
264 for (int i = 0; i < kPrefsToObserveLength; ++i)
265 prefs->AddPrefObserver(kPrefsToObserve[i], this);
266 }
267
268 // Register for notifications about URL starredness changing on any profile.
269 registrar_.Add(this, NotificationType::URLS_STARRED,
270 NotificationService::AllSources());
271 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
272 NotificationService::AllSources());
273 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
274 NotificationService::AllSources());
275
276 // Keep a global copy of the previous search string (if any).
277 static string16 global_last_search = string16();
278 find_prepopulate_text_ = &global_last_search;
[email protected]332af7732009-03-11 13:21:35279}
initial.commit09911bf2008-07-26 23:55:29280
281TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32282 is_being_destroyed_ = true;
283
284 // We don't want any notifications while we're runnign our destructor.
285 registrar_.RemoveAll();
286
287 // Unregister the notifications of all observed prefs change.
288 PrefService* prefs = profile()->GetPrefs();
289 if (prefs) {
290 for (int i = 0; i < kPrefsToObserveLength; ++i)
291 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
292 }
293
294 // Clean up subwindows like plugins and the find in page bar.
295 view_->OnContentsDestroy();
296
297 NotifyDisconnected();
[email protected]8897c382009-05-06 17:53:26298 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:32299
300 if (pending_install_.callback_functor)
301 pending_install_.callback_functor->Cancel();
302
303 // First cleanly close all child windows.
304 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
305 // some of these to close. CloseWindows is async, so it might get called
306 // twice before it runs.
307 int size = static_cast<int>(child_windows_.size());
308 for (int i = size - 1; i >= 0; --i) {
309 ConstrainedWindow* window = child_windows_[i];
310 if (window)
311 window->CloseConstrainedWindow();
312 }
313
314 // Notify any lasting InfobarDelegates that have not yet been removed that
315 // whatever infobar they were handling in this TabContents has closed,
316 // because the TabContents is going away entirely.
317 for (int i = 0; i < infobar_delegate_count(); ++i) {
318 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
319 delegate->InfoBarClosed();
320 }
321 infobar_delegates_.clear();
322
323 // Notify any observer that have a reference on this tab contents.
324 NotificationService::current()->Notify(
325 NotificationType::TAB_CONTENTS_DESTROYED,
326 Source<TabContents>(this),
327 NotificationService::NoDetails());
328
329 // TODO(brettw) this should be moved to the view.
330#if defined(OS_WIN)
331 // If we still have a window handle, destroy it. GetNativeView can return
332 // NULL if this contents was part of a window that closed.
333 if (GetNativeView())
334 ::DestroyWindow(GetNativeView());
335#endif
initial.commit09911bf2008-07-26 23:55:29336}
337
[email protected]d5f942ba2008-09-26 19:30:34338// static
339void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32340 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
341
342 WebPreferences pref_defaults;
343 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
344 pref_defaults.javascript_enabled);
345 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
346 pref_defaults.web_security_enabled);
347 prefs->RegisterBooleanPref(
348 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
349 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
350 pref_defaults.loads_images_automatically);
351 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
352 pref_defaults.plugins_enabled);
353 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
354 pref_defaults.dom_paste_enabled);
355 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
356 pref_defaults.shrinks_standalone_images_to_fit);
357 prefs->RegisterBooleanPref(prefs::kWebKitDeveloperExtrasEnabled,
358 true);
359 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
360 pref_defaults.text_areas_are_resizable);
361 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
362 pref_defaults.java_enabled);
363
364 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
365 IDS_ACCEPT_LANGUAGES);
366 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
367 IDS_DEFAULT_ENCODING);
368 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
369 IDS_STANDARD_FONT_IS_SERIF);
370 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
371 IDS_FIXED_FONT_FAMILY);
372 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
373 IDS_SERIF_FONT_FAMILY);
374 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
375 IDS_SANS_SERIF_FONT_FAMILY);
376 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
377 IDS_CURSIVE_FONT_FAMILY);
378 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
379 IDS_FANTASY_FONT_FAMILY);
380 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
381 IDS_DEFAULT_FONT_SIZE);
382 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
383 IDS_DEFAULT_FIXED_FONT_SIZE);
384 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
385 IDS_MINIMUM_FONT_SIZE);
386 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
387 IDS_MINIMUM_LOGICAL_FONT_SIZE);
388 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
389 IDS_USES_UNIVERSAL_DETECTOR);
390 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
391 IDS_STATIC_ENCODING_LIST);
392
[email protected]d5f942ba2008-09-26 19:30:34393 prefs->RegisterBooleanPref(prefs::kBlockPopups, false);
initial.commit09911bf2008-07-26 23:55:29394}
395
[email protected]d5f942ba2008-09-26 19:30:34396bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01397 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55398 return true;
[email protected]d5f942ba2008-09-26 19:30:34399}
400
[email protected]6e95706d2009-04-23 22:55:01401AutofillManager* TabContents::GetAutofillManager() {
402 if (autofill_manager_.get() == NULL)
403 autofill_manager_.reset(new AutofillManager(this));
404 return autofill_manager_.get();
405}
406
407PasswordManager* TabContents::GetPasswordManager() {
408 if (password_manager_.get() == NULL)
409 password_manager_.reset(new PasswordManager(this));
410 return password_manager_.get();
411}
412
413PluginInstaller* TabContents::GetPluginInstaller() {
414 if (plugin_installer_.get() == NULL)
415 plugin_installer_.reset(new PluginInstaller(this));
416 return plugin_installer_.get();
417}
418
[email protected]d5f942ba2008-09-26 19:30:34419const GURL& TabContents::GetURL() const {
420 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57421 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34422 return entry ? entry->display_url() : GURL::EmptyGURL();
423}
424
[email protected]96d185d2009-04-24 03:28:54425const string16& TabContents::GetTitle() const {
426 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
427 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
428 if (our_dom_ui) {
429 // Don't override the title in view source mode.
430 NavigationEntry* entry = controller_.GetActiveEntry();
431 if (!(entry && entry->IsViewSourceMode())) {
432 // Give the DOM UI the chance to override our title.
433 const string16& title = our_dom_ui->overridden_title();
434 if (!title.empty())
435 return title;
436 }
437 }
438
439 // We use the title for the last committed entry rather than a pending
440 // navigation entry. For example, when the user types in a URL, we want to
441 // keep the old page's title until the new load has committed and we get a new
442 // title.
443 // The exception is with transient pages, for which we really want to use
444 // their title, as they are not committed.
445 NavigationEntry* entry = controller_.GetTransientEntry();
446 if (entry)
447 return entry->GetTitleForDisplay(&controller_);
448
449 entry = controller_.GetLastCommittedEntry();
450 if (entry)
451 return entry->GetTitleForDisplay(&controller_);
452 else if (controller_.LoadingURLLazily())
453 return controller_.GetLazyTitle();
454 return EmptyString16();
455}
456
[email protected]d5f942ba2008-09-26 19:30:34457int32 TabContents::GetMaxPageID() {
458 if (GetSiteInstance())
459 return GetSiteInstance()->max_page_id();
460 else
461 return max_page_id_;
462}
463
464void TabContents::UpdateMaxPageID(int32 page_id) {
465 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34466 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34467 // testing.
468 if (GetSiteInstance())
469 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34470 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34471}
472
[email protected]96d185d2009-04-24 03:28:54473SiteInstance* TabContents::GetSiteInstance() const {
474 return render_manager_.current_host()->site_instance();
475}
476
[email protected]d5f942ba2008-09-26 19:30:34477const std::wstring TabContents::GetDefaultTitle() const {
478 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
479}
480
[email protected]96d185d2009-04-24 03:28:54481bool TabContents::ShouldDisplayURL() {
482 // Don't hide the url in view source mode.
483 NavigationEntry* entry = controller_.GetActiveEntry();
484 if (entry && entry->IsViewSourceMode())
485 return true;
486 DOMUI* dom_ui = GetDOMUIForCurrentState();
487 if (dom_ui)
488 return !dom_ui->should_hide_url();
489 return true;
490}
491
[email protected]d5f942ba2008-09-26 19:30:34492SkBitmap TabContents::GetFavIcon() const {
493 // Like GetTitle(), we also want to use the favicon for the last committed
494 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57495 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47496 if (entry)
497 return entry->favicon().bitmap();
498
[email protected]ce3fa3c2009-04-20 19:55:57499 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34500 if (entry)
501 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57502 else if (controller_.LoadingURLLazily())
503 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34504 return SkBitmap();
505}
506
[email protected]96d185d2009-04-24 03:28:54507bool TabContents::ShouldDisplayFavIcon() {
508 // Always display a throbber during pending loads.
509 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
510 return true;
511
512 DOMUI* dom_ui = GetDOMUIForCurrentState();
513 if (dom_ui)
514 return !dom_ui->hide_favicon();
515 return true;
516}
517
[email protected]3e45ba92009-02-20 21:09:00518#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34519SecurityStyle TabContents::GetSecurityStyle() const {
520 // We may not have a navigation entry yet.
[email protected]ce3fa3c2009-04-20 19:55:57521 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34522 return entry ? entry->ssl().security_style() : SECURITY_STYLE_UNKNOWN;
523}
524
525bool TabContents::GetSSLEVText(std::wstring* ev_text,
526 std::wstring* ev_tooltip_text) const {
527 DCHECK(ev_text && ev_tooltip_text);
528 ev_text->clear();
529 ev_tooltip_text->clear();
530
[email protected]ce3fa3c2009-04-20 19:55:57531 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34532 if (!entry ||
533 net::IsCertStatusError(entry->ssl().cert_status()) ||
534 ((entry->ssl().cert_status() & net::CERT_STATUS_IS_EV) == 0))
535 return false;
536
537 scoped_refptr<net::X509Certificate> cert;
538 CertStore::GetSharedInstance()->RetrieveCert(entry->ssl().cert_id(), &cert);
539 if (!cert.get()) {
540 NOTREACHED();
541 return false;
542 }
543
544 return SSLManager::GetEVCertNames(*cert, ev_text, ev_tooltip_text);
545}
[email protected]76f68dc2009-03-10 20:31:32546#endif
[email protected]d5f942ba2008-09-26 19:30:34547
[email protected]96d185d2009-04-24 03:28:54548std::wstring TabContents::GetStatusText() const {
549 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
550 return std::wstring();
551
552 switch (load_state_) {
553 case net::LOAD_STATE_WAITING_FOR_CACHE:
554 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
555 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
556 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
557 case net::LOAD_STATE_RESOLVING_HOST:
558 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
559 case net::LOAD_STATE_CONNECTING:
560 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
561 case net::LOAD_STATE_SENDING_REQUEST:
562 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
563 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
564 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
565 load_state_host_);
566 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
567 case net::LOAD_STATE_IDLE:
568 case net::LOAD_STATE_READING_RESPONSE:
569 break;
570 }
571
572 return std::wstring();
573}
574
[email protected]d5f942ba2008-09-26 19:30:34575void TabContents::SetIsCrashed(bool state) {
576 if (state == is_crashed_)
577 return;
578
579 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50580 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34581}
582
[email protected]ce5c4502009-05-06 16:46:11583void TabContents::EnablePageAction(const PageAction* page_action) {
584 DCHECK(page_action);
585
586 if (IsPageActionEnabled(page_action))
587 return; // Already enabled.
588
589 enabled_page_actions_.insert(page_action);
590}
591
592bool TabContents::IsPageActionEnabled(const PageAction* page_action) {
593 DCHECK(page_action);
594 return enabled_page_actions_.end() != enabled_page_actions_.find(page_action);
595}
596
597
[email protected]d5f942ba2008-09-26 19:30:34598void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
599 if (delegate_)
600 delegate_->NavigationStateChanged(this, changed_flags);
601}
602
[email protected]96d185d2009-04-24 03:28:54603void TabContents::DidBecomeSelected() {
604 controller_.SetActive(true);
605
606 if (render_widget_host_view())
607 render_widget_host_view()->DidBecomeSelected();
608
609 // If pid() is -1, that means the RenderProcessHost still hasn't been
610 // initialized. It'll register with CacheManagerHost when it is.
611 if (process()->pid() != -1)
612 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
613}
614
615void TabContents::WasHidden() {
616 if (!capturing_contents()) {
617 // |render_view_host()| can be NULL if the user middle clicks a link to open
618 // a tab in then background, then closes the tab before selecting it. This
619 // is because closing the tab calls TabContents::Destroy(), which removes
620 // the |render_view_host()|; then when we actually destroy the window,
621 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
622 if (render_widget_host_view())
623 render_widget_host_view()->WasHidden();
624
625 // Loop through children and send WasHidden to them, too.
626 int count = static_cast<int>(child_windows_.size());
627 for (int i = count - 1; i >= 0; --i) {
628 ConstrainedWindow* window = child_windows_.at(i);
629 window->WasHidden();
630 }
631 }
632
633 NotificationService::current()->Notify(
634 NotificationType::TAB_CONTENTS_HIDDEN,
635 Source<TabContents>(this),
636 NotificationService::NoDetails());
637}
638
[email protected]d5f942ba2008-09-26 19:30:34639void TabContents::Activate() {
640 if (delegate_)
641 delegate_->ActivateContents(this);
642}
643
[email protected]96d185d2009-04-24 03:28:54644void TabContents::ShowContents() {
645 if (render_widget_host_view())
646 render_widget_host_view()->DidBecomeSelected();
647
648 // Loop through children and send DidBecomeSelected to them, too.
649 int count = static_cast<int>(child_windows_.size());
650 for (int i = count - 1; i >= 0; --i) {
651 ConstrainedWindow* window = child_windows_.at(i);
652 window->DidBecomeSelected();
653 }
654}
655
656void TabContents::HideContents() {
657 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
658 // our superclass HideContents(), because some callers want to be very picky
659 // about the order in which these get called. In addition to making the code
660 // here practically impossible to understand, this also means we end up
661 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34662 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54663 WasHidden();
664}
665
[email protected]c0588052008-10-27 23:01:50666void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34667 WindowOpenDisposition disposition,
668 PageTransition::Type transition) {
669 if (delegate_)
[email protected]c0588052008-10-27 23:01:50670 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34671}
672
673bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54674 const NavigationEntry& entry = *controller_.pending_entry();
675
676 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
677 if (!dest_render_view_host)
678 return false; // Unable to create the desired render view host.
679
680 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]684b4ba22009-05-07 06:27:41681 DevToolsManager* devtools_manager = g_browser_process->devtools_manager();
682 if (devtools_manager) // NULL in unit tests.
683 devtools_manager->OnNavigatingToPendingEntry(
684 render_view_host(),
685 dest_render_view_host,
686 controller_.pending_entry()->url());
[email protected]96d185d2009-04-24 03:28:54687
688 // Used for page load time metrics.
689 current_load_start_ = base::TimeTicks::Now();
690
691 // Navigate in the desired RenderViewHost.
692 dest_render_view_host->NavigateToEntry(entry, reload);
693
694 if (entry.page_id() == -1) {
695 // HACK!! This code suppresses javascript: URLs from being added to
696 // session history, which is what we want to do for javascript: URLs that
697 // do not generate content. What we really need is a message from the
698 // renderer telling us that a new page was not created. The same message
699 // could be used for mailto: URLs and the like.
700 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
701 return false;
702 }
703
704 // Clear any provisional password saves - this stops password infobars
705 // showing up on pages the user navigates to while the right page is
706 // loading.
707 GetPasswordManager()->ClearProvisionalSave();
708
709 if (reload && !profile()->IsOffTheRecord()) {
710 HistoryService* history =
711 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
712 if (history)
713 history->SetFavIconOutOfDateForPage(entry.url());
714 }
715
[email protected]d5f942ba2008-09-26 19:30:34716 return true;
717}
718
[email protected]96d185d2009-04-24 03:28:54719void TabContents::Stop() {
720 render_manager_.Stop();
721 printing_.Stop();
722}
723
724void TabContents::Cut() {
725 render_view_host()->Cut();
726}
727
728void TabContents::Copy() {
729 render_view_host()->Copy();
730}
731
732void TabContents::Paste() {
733 render_view_host()->Paste();
734}
735
736void TabContents::DisassociateFromPopupCount() {
737 render_view_host()->DisassociateFromPopupCount();
738}
739
740TabContents* TabContents::Clone() {
741 // We create a new SiteInstance so that the new tab won't share processes
742 // with the old one. This can be changed in the future if we need it to share
743 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32744 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54745 SiteInstance::CreateSiteInstance(profile()),
746 MSG_ROUTING_NONE, NULL);
747 tc->controller().CopyStateFrom(controller_);
748 return tc;
749}
750
[email protected]420ae012009-04-24 05:16:32751void TabContents::CreateShortcut() {
752 NavigationEntry* entry = controller_.GetLastCommittedEntry();
753 if (!entry)
754 return;
755
756 // We only allow one pending install request. By resetting the page id we
757 // effectively cancel the pending install request.
758 pending_install_.page_id = entry->page_id();
759 pending_install_.icon = GetFavIcon();
760 pending_install_.title = UTF16ToWideHack(GetTitle());
761 pending_install_.url = GetURL();
762 if (pending_install_.callback_functor) {
763 pending_install_.callback_functor->Cancel();
764 pending_install_.callback_functor = NULL;
765 }
766 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
767 if (pending_install_.title.empty())
768 pending_install_.title = UTF8ToWide(GetURL().spec());
769
770 // Request the application info. When done OnDidGetApplicationInfo is invoked
771 // and we'll create the shortcut.
772 render_view_host()->GetApplicationInfo(pending_install_.page_id);
773}
774
[email protected]76f68dc2009-03-10 20:31:32775#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29776ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]c2dacc92008-10-16 23:51:38777 views::WindowDelegate* window_delegate,
778 views::View* contents_view) {
initial.commit09911bf2008-07-26 23:55:29779 ConstrainedWindow* window =
780 ConstrainedWindow::CreateConstrainedDialog(
781 this, gfx::Rect(), contents_view, window_delegate);
782 child_windows_.push_back(window);
783 return window;
784}
[email protected]f3332e12009-03-23 15:28:57785#endif
initial.commit09911bf2008-07-26 23:55:29786
787void TabContents::AddNewContents(TabContents* new_contents,
788 WindowOpenDisposition disposition,
789 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22790 bool user_gesture,
791 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29792 if (!delegate_)
793 return;
794
[email protected]f3332e12009-03-23 15:28:57795#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:22796 bool constrain_popup = false;
[email protected]35f7d212009-04-29 21:19:27797 if ((disposition == NEW_POPUP) && !user_gesture &&
798 !CommandLine::ForCurrentProcess()->HasSwitch(
799 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22800 // Unrequested popups from normal pages are constrained unless they're in
801 // the whitelist.
802 std::string host;
803 if (creator_url.is_valid())
804 host = creator_url.host();
805 constrain_popup = true; // TODO(pkasting): Add whitelist
806
[email protected]3b0a45e82008-10-13 21:01:03807 TabContents* our_owner = delegate_->GetConstrainingContents(this);
[email protected]2c4410d2009-05-06 23:46:22808 TabContents* popup_owner = our_owner ? our_owner : this;
809 if (constrain_popup)
810 popup_owner->AddConstrainedPopup(new_contents, initial_pos, host);
811 else
812 popup_owner->OnPopupOpenedFromWhitelistedHost(host);
813 }
814 if (!constrain_popup) {
[email protected]0aa55312008-10-17 21:53:08815 new_contents->DisassociateFromPopupCount();
816
initial.commit09911bf2008-07-26 23:55:29817 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
818 user_gesture);
[email protected]634a6f92008-12-01 21:39:31819
820 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
initial.commit09911bf2008-07-26 23:55:29821 }
[email protected]f3332e12009-03-23 15:28:57822#else
823 // TODO(port): implement the popup blocker stuff
824 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
825 user_gesture);
826#endif
initial.commit09911bf2008-07-26 23:55:29827}
828
[email protected]f3332e12009-03-23 15:28:57829#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29830void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25831 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22832 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29833}
[email protected]332af7732009-03-11 13:21:35834#endif
initial.commit09911bf2008-07-26 23:55:29835
[email protected]96d185d2009-04-24 03:28:54836void TabContents::PopupNotificationVisibilityChanged(bool visible) {
837 render_view_host()->PopupNotificationVisibilityChanged(visible);
838}
839
840gfx::NativeView TabContents::GetContentNativeView() {
841 return view_->GetContentNativeView();
842}
843
844gfx::NativeView TabContents::GetNativeView() const {
845 return view_->GetNativeView();
846}
847
848void TabContents::GetContainerBounds(gfx::Rect *out) const {
849 view_->GetContainerBounds(out);
850}
851
852void TabContents::Focus() {
853 view_->Focus();
854}
855
856void TabContents::SetInitialFocus(bool reverse) {
857 render_view_host()->SetInitialFocus(reverse);
858}
859
860bool TabContents::FocusLocationBarByDefault() {
861 DOMUI* dom_ui = GetDOMUIForCurrentState();
862 if (dom_ui)
863 return dom_ui->focus_location_bar_by_default();
864 return false;
865}
866
[email protected]616ed5a2008-11-21 22:27:24867void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
868 // Look through the existing InfoBarDelegates we have for a match. If we've
869 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05870 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24871 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
872 return;
873 }
874
875 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56876 NotificationService::current()->Notify(
877 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
878 Source<TabContents>(this),
879 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24880
881 // Add ourselves as an observer for navigations the first time a delegate is
882 // added. We use this notification to expire InfoBars that need to expire on
883 // page transitions.
884 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56885 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57886 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24887 }
888}
889
890void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
891 std::vector<InfoBarDelegate*>::iterator it =
892 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
893 if (it != infobar_delegates_.end()) {
894 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56895 NotificationService::current()->Notify(
896 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
897 Source<TabContents>(this),
898 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05899 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24900
[email protected]6a02963e2009-01-06 16:58:03901 // Remove ourselves as an observer if we are tracking no more InfoBars.
902 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56903 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57904 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03905 }
[email protected]616ed5a2008-11-21 22:27:24906 }
907}
[email protected]3edd9522009-03-04 22:19:41908
[email protected]96d185d2009-04-24 03:28:54909bool TabContents::IsBookmarkBarAlwaysVisible() {
910 // See GetDOMUIForCurrentState() comment for more info. This case is very
911 // similar, but for non-first loads, we want to use the committed entry. This
912 // is so the bookmarks bar disappears at the same time the page does.
913 if (controller_.GetLastCommittedEntry()) {
914 // Not the first load, always use the committed DOM UI.
915 if (render_manager_.dom_ui())
916 return render_manager_.dom_ui()->force_bookmark_bar_visible();
917 return false; // Default.
918 }
919
920 // When it's the first load, we know either the pending one or the committed
921 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
922 // of them will be valid, so we can just check both.
923 if (render_manager_.pending_dom_ui())
924 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
925 if (render_manager_.dom_ui())
926 return render_manager_.dom_ui()->force_bookmark_bar_visible();
927 return false; // Default.
928}
929
930void TabContents::SetDownloadShelfVisible(bool visible) {
931 if (shelf_visible_ != visible) {
932 if (visible) {
933 // Invoke GetDownloadShelf to force the shelf to be created.
934 GetDownloadShelf();
935 }
936 shelf_visible_ = visible;
937
[email protected]c9cd2222009-05-06 05:16:50938 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]96d185d2009-04-24 03:28:54939 }
940
941 // SetShelfVisible can force-close the shelf, so make sure we lay out
942 // everything correctly, as if the animation had finished. This doesn't
943 // matter for showing the shelf, as the show animation will do it.
944 ToolbarSizeChanged(false);
945
946 if (visible) {
947 // Always set this value as it reflects the last time the download shelf
948 // was made visible (even if it was already visible).
949 last_download_shelf_show_ = base::TimeTicks::Now();
950 }
951}
952
[email protected]3edd9522009-03-04 22:19:41953void TabContents::ToolbarSizeChanged(bool is_animating) {
954 TabContentsDelegate* d = delegate();
955 if (d)
956 d->ToolbarSizeChanged(this, is_animating);
957}
[email protected]616ed5a2008-11-21 22:27:24958
[email protected]d5f942ba2008-09-26 19:30:34959void TabContents::OnStartDownload(DownloadItem* download) {
960 DCHECK(download);
961 TabContents* tab_contents = this;
962
[email protected]3edd9522009-03-04 22:19:41963// TODO(port): port contraining contents.
964#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34965 // Download in a constrained popup is shown in the tab that opened it.
966 TabContents* constraining_tab = delegate()->GetConstrainingContents(this);
967 if (constraining_tab)
968 tab_contents = constraining_tab;
[email protected]3edd9522009-03-04 22:19:41969#endif
[email protected]d5f942ba2008-09-26 19:30:34970
[email protected]bcef0dc02009-02-28 00:35:02971 // GetDownloadShelf creates the download shelf if it was not yet created.
972 tab_contents->GetDownloadShelf()->AddDownload(
973 new DownloadItemModel(download));
[email protected]d5f942ba2008-09-26 19:30:34974 tab_contents->SetDownloadShelfVisible(true);
975
[email protected]3edd9522009-03-04 22:19:41976// TODO(port): port animatinos.
977#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34978 // This animation will delete itself when it finishes, or if we become hidden
979 // or destroyed.
[email protected]92edc472009-02-10 20:32:06980 if (IsWindowVisible(GetNativeView())) { // For minimized windows, unit
981 // tests, etc.
[email protected]d5f942ba2008-09-26 19:30:34982 new DownloadStartedAnimation(tab_contents);
983 }
[email protected]3edd9522009-03-04 22:19:41984#endif
[email protected]d5f942ba2008-09-26 19:30:34985}
986
[email protected]bcef0dc02009-02-28 00:35:02987DownloadShelf* TabContents::GetDownloadShelf() {
988 if (!download_shelf_.get())
989 download_shelf_.reset(DownloadShelf::Create(this));
990 return download_shelf_.get();
initial.commit09911bf2008-07-26 23:55:29991}
992
[email protected]bcef0dc02009-02-28 00:35:02993void TabContents::MigrateShelfFrom(TabContents* tab_contents) {
994 download_shelf_.reset(tab_contents->GetDownloadShelf());
995 download_shelf_->ChangeTabContents(tab_contents, this);
996 tab_contents->ReleaseDownloadShelf();
initial.commit09911bf2008-07-26 23:55:29997}
998
[email protected]3edd9522009-03-04 22:19:41999void TabContents::ReleaseDownloadShelf() {
1000 download_shelf_.release();
1001}
1002
1003// static
1004void TabContents::MigrateShelf(TabContents* from, TabContents* to) {
1005 bool was_shelf_visible = from->IsDownloadShelfVisible();
1006 if (was_shelf_visible)
1007 to->MigrateShelfFrom(from);
1008 to->SetDownloadShelfVisible(was_shelf_visible);
1009}
[email protected]3edd9522009-03-04 22:19:411010
[email protected]d5f942ba2008-09-26 19:30:341011void TabContents::WillClose(ConstrainedWindow* window) {
1012 ConstrainedWindowList::iterator it =
1013 find(child_windows_.begin(), child_windows_.end(), window);
1014 if (it != child_windows_.end())
1015 child_windows_.erase(it);
1016
[email protected]332af7732009-03-11 13:21:351017#if defined(OS_WIN)
[email protected]d6598c052008-11-05 19:03:251018 if (window == blocked_popups_)
1019 blocked_popups_ = NULL;
1020
[email protected]92edc472009-02-10 20:32:061021 if (::IsWindow(GetNativeView())) {
[email protected]d5f942ba2008-09-26 19:30:341022 CRect client_rect;
[email protected]92edc472009-02-10 20:32:061023 GetClientRect(GetNativeView(), &client_rect);
[email protected]d5f942ba2008-09-26 19:30:341024 RepositionSupressedPopupsToFit(
1025 gfx::Size(client_rect.Width(), client_rect.Height()));
1026 }
[email protected]332af7732009-03-11 13:21:351027#endif
[email protected]d5f942ba2008-09-26 19:30:341028}
1029
[email protected]d5f942ba2008-09-26 19:30:341030void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:351031#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:061032 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:351033#endif
[email protected]d5f942ba2008-09-26 19:30:341034}
1035
[email protected]6e95706d2009-04-23 22:55:011036void TabContents::StartFinding(const string16& find_text,
1037 bool forward_direction) {
1038 // If find_text is empty, it means FindNext was pressed with a keyboard
1039 // shortcut so unless we have something to search for we return early.
1040 if (find_text.empty() && find_text_.empty())
1041 return;
1042
1043 // This is a FindNext operation if we are searching for the same text again,
1044 // or if the passed in search text is empty (FindNext keyboard shortcut). The
1045 // exception to this is if the Find was aborted (then we don't want FindNext
1046 // because the highlighting has been cleared and we need it to reappear). We
1047 // therefore treat FindNext after an aborted Find operation as a full fledged
1048 // Find.
1049 bool find_next = (find_text_ == find_text || find_text.empty()) &&
1050 !find_op_aborted_;
1051 if (!find_next)
1052 current_find_request_id_ = find_request_id_counter_++;
1053
1054 if (!find_text.empty())
1055 find_text_ = find_text;
1056
1057 find_op_aborted_ = false;
1058
1059 // Keep track of what the last search was across the tabs.
1060 *find_prepopulate_text_ = find_text;
1061
1062 render_view_host()->StartFinding(current_find_request_id_,
1063 find_text_,
1064 forward_direction,
1065 false, // case sensitive
1066 find_next);
1067}
1068
1069void TabContents::StopFinding(bool clear_selection) {
1070 find_ui_active_ = false;
1071 find_op_aborted_ = true;
1072 find_result_ = FindNotificationDetails();
1073 render_view_host()->StopFinding(clear_selection);
1074}
1075
[email protected]420ae012009-04-24 05:16:321076void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
1077 bool success,
1078 const std::wstring& prompt) {
1079 last_javascript_message_dismissal_ = base::TimeTicks::Now();
1080 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
1081}
1082
1083void TabContents::OnSavePage() {
1084 // If we can not save the page, try to download it.
1085 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1086 DownloadManager* dlm = profile()->GetDownloadManager();
1087 const GURL& current_page_url = GetURL();
1088 if (dlm && current_page_url.is_valid())
[email protected]c9825a42009-05-01 22:51:501089 dlm->DownloadUrl(current_page_url, GURL(), "", AsWC(this));
[email protected]420ae012009-04-24 05:16:321090 return;
1091 }
1092
1093 Stop();
1094
1095 // Create the save package and possibly prompt the user for the name to save
1096 // the page as. The user prompt is an asynchronous operation that runs on
1097 // another thread.
1098 save_package_ = new SavePackage(AsWC(this));
1099 save_package_->GetSaveInfo();
1100}
1101
1102// Used in automated testing to bypass prompting the user for file names.
1103// Instead, the names and paths are hard coded rather than running them through
1104// file name sanitation and extension / mime checking.
1105void TabContents::SavePage(const std::wstring& main_file,
1106 const std::wstring& dir_path,
1107 SavePackage::SavePackageType save_type) {
1108 // Stop the page from navigating.
1109 Stop();
1110
1111 save_package_ = new SavePackage(AsWC(this), save_type,
1112 FilePath::FromWStringHack(main_file),
1113 FilePath::FromWStringHack(dir_path));
1114 save_package_->Init();
1115}
1116
1117void TabContents::PrintPreview() {
1118 // We don't show the print preview yet, only the print dialog.
1119 PrintNow();
1120}
1121
1122bool TabContents::PrintNow() {
1123 // We can't print interstitial page for now.
1124 if (showing_interstitial_page())
1125 return false;
1126
1127 return render_view_host()->PrintPages();
1128}
1129
1130bool TabContents::IsActiveEntry(int32 page_id) {
1131 NavigationEntry* active_entry = controller_.GetActiveEntry();
1132 return (active_entry != NULL &&
1133 active_entry->site_instance() == GetSiteInstance() &&
1134 active_entry->page_id() == page_id);
1135}
1136
[email protected]2c4410d2009-05-06 23:46:221137#if defined(OS_WIN)
1138void TabContents::SetWhitelistForHost(const std::string& host, bool whitelist) {
1139 // TODO(pkasting): Add whitelist
1140}
1141#endif
1142
[email protected]96d185d2009-04-24 03:28:541143// Notifies the RenderWidgetHost instance about the fact that the page is
1144// loading, or done loading and calls the base implementation.
1145void TabContents::SetIsLoading(bool is_loading,
1146 LoadNotificationDetails* details) {
1147 if (is_loading == is_loading_)
1148 return;
1149
1150 if (!is_loading) {
1151 load_state_ = net::LOAD_STATE_IDLE;
1152 load_state_host_.clear();
1153 }
1154
1155 render_manager_.SetIsLoading(is_loading);
1156
1157 is_loading_ = is_loading;
1158 waiting_for_response_ = is_loading;
1159
1160 if (delegate_)
1161 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351162 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541163
1164 NotificationType type = is_loading ? NotificationType::LOAD_START :
1165 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111166 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541167 if (details)
1168 det = Details<LoadNotificationDetails>(details);
1169 NotificationService::current()->Notify(type,
1170 Source<NavigationController>(&controller_),
1171 det);
1172}
1173
[email protected]76f68dc2009-03-10 20:31:321174#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:221175void TabContents::CreateBlockedPopupContainerIfNecessary() {
1176 if (blocked_popups_)
1177 return;
1178
1179 CRect client_rect;
1180 GetClientRect(GetNativeView(), &client_rect);
1181 gfx::Point anchor_position(
1182 client_rect.Width() - views::NativeScrollBar::GetVerticalScrollBarWidth(),
1183 client_rect.Height());
1184 blocked_popups_ = BlockedPopupContainer::Create(this, profile(),
1185 anchor_position);
1186 child_windows_.push_back(blocked_popups_);
1187}
1188
1189void TabContents::AddConstrainedPopup(TabContents* new_contents,
1190 const gfx::Rect& initial_pos,
1191 const std::string& host) {
1192 CreateBlockedPopupContainerIfNecessary();
1193 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
1194 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
1195}
1196
1197void TabContents::OnPopupOpenedFromWhitelistedHost(const std::string& host) {
1198 CreateBlockedPopupContainerIfNecessary();
1199 blocked_popups_->OnPopupOpenedFromWhitelistedHost(host);
1200}
1201
[email protected]e69bce3dd2009-04-20 22:05:121202// TODO(brettw) This should be on the TabContentsView.
[email protected]d5f942ba2008-09-26 19:30:341203void TabContents::RepositionSupressedPopupsToFit(const gfx::Size& new_size) {
1204 // TODO(erg): There's no way to detect whether scroll bars are
1205 // visible, so for beta, we're just going to assume that the
1206 // vertical scroll bar is visible, and not care about covering up
1207 // the horizontal scroll bar. Fixing this is half of
1208 // http://b/1118139.
1209 gfx::Point anchor_position(
1210 new_size.width() -
[email protected]c2dacc92008-10-16 23:51:381211 views::NativeScrollBar::GetVerticalScrollBarWidth(),
[email protected]d5f942ba2008-09-26 19:30:341212 new_size.height());
[email protected]d6598c052008-11-05 19:03:251213
1214 if (blocked_popups_)
1215 blocked_popups_->RepositionConstrainedWindowTo(anchor_position);
[email protected]d5f942ba2008-09-26 19:30:341216}
1217
[email protected]b9681312008-11-07 00:08:261218bool TabContents::ShowingBlockedPopupNotification() const {
1219 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221220 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261221}
[email protected]332af7732009-03-11 13:21:351222#endif // defined(OS_WIN)
[email protected]616ed5a2008-11-21 22:27:241223
1224namespace {
1225bool TransitionIsReload(PageTransition::Type transition) {
1226 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1227}
1228}
1229
1230void TabContents::ExpireInfoBars(
1231 const NavigationController::LoadCommittedDetails& details) {
1232 // Only hide InfoBars when the user has done something that makes the main
1233 // frame load. We don't want various automatic or subframe navigations making
1234 // it disappear.
1235 if (!details.is_user_initiated_main_frame_load())
1236 return;
1237
[email protected]f86a07022008-11-25 01:06:051238 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241239 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051240 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241241 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241242 }
1243}
[email protected]fdd61c62009-04-22 19:22:571244
1245void TabContents::OnGearsCreateShortcutDone(
1246 const GearsShortcutData2& shortcut_data, bool success) {
1247 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1248 bool same_page =
1249 current_entry && pending_install_.page_id == current_entry->page_id();
1250
1251 if (success && same_page) {
1252 // Only switch to app mode if the user chose to create a shortcut and
1253 // we're still on the same page that it corresponded to.
1254 if (delegate())
1255 delegate()->ConvertContentsToApplication(this);
1256 }
1257
1258 // Reset the page id to indicate no requests are pending.
1259 pending_install_.page_id = 0;
1260 pending_install_.callback_functor = NULL;
1261}
[email protected]96d185d2009-04-24 03:28:541262
1263DOMUI* TabContents::GetDOMUIForCurrentState() {
1264 // When there is a pending navigation entry, we want to use the pending DOMUI
1265 // that goes along with it to control the basic flags. For example, we want to
1266 // show the pending URL in the URL bar, so we want the display_url flag to
1267 // be from the pending entry.
1268 //
1269 // The confusion comes because there are multiple possibilities for the
1270 // initial load in a tab as a side effect of the way the RenderViewHostManager
1271 // works.
1272 //
1273 // - For the very first tab the load looks "normal". The new tab DOM UI is
1274 // the pending one, and we want it to apply here.
1275 //
1276 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1277 // get switched to the one previously associated with the new tab pages.
1278 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1279 // have a committed DOM UI in this case.
1280 //
1281 // This condition handles all of these cases:
1282 //
1283 // - First load in first tab: no committed nav entry + pending nav entry +
1284 // pending dom ui:
1285 // -> Use pending DOM UI if any.
1286 //
1287 // - First load in second tab: no committed nav entry + pending nav entry +
1288 // no pending DOM UI:
1289 // -> Use the committed DOM UI if any.
1290 //
1291 // - Second navigation in any tab: committed nav entry + pending nav entry:
1292 // -> Use pending DOM UI if any.
1293 //
1294 // - Normal state with no load: committed nav entry + no pending nav entry:
1295 // -> Use committed DOM UI.
1296 if (controller_.pending_entry() &&
1297 (controller_.GetLastCommittedEntry() ||
1298 render_manager_.pending_dom_ui()))
1299 return render_manager_.pending_dom_ui();
1300 return render_manager_.dom_ui();
1301}
[email protected]420ae012009-04-24 05:16:321302
1303void TabContents::DidNavigateMainFramePostCommit(
1304 const NavigationController::LoadCommittedDetails& details,
1305 const ViewHostMsg_FrameNavigate_Params& params) {
1306 // Hide the download shelf if all the following conditions are true:
1307 // - there are no active downloads.
1308 // - this is a navigation to a different TLD.
1309 // - at least 5 seconds have elapsed since the download shelf was shown.
1310 // TODO(jcampan): bug 1156075 when user gestures are reliable, they should
1311 // be used to ensure we are hiding only on user initiated
1312 // navigations.
1313 DownloadManager* download_manager = profile()->GetDownloadManager();
1314 // download_manager can be NULL in unit test context.
1315 if (download_manager && download_manager->in_progress_count() == 0 &&
1316 !details.previous_url.is_empty() &&
1317 !net::RegistryControlledDomainService::SameDomainOrHost(
1318 details.previous_url, details.entry->url())) {
1319 base::TimeDelta time_delta(
1320 base::TimeTicks::Now() - last_download_shelf_show_);
1321 if (time_delta >
1322 base::TimeDelta::FromMilliseconds(kDownloadShelfHideDelay)) {
1323 SetDownloadShelfVisible(false);
1324 }
1325 }
1326
1327 if (details.is_user_initiated_main_frame_load()) {
1328 // Clear the status bubble. This is a workaround for a bug where WebKit
1329 // doesn't let us know that the cursor left an element during a
1330 // transition (this is also why the mouse cursor remains as a hand after
1331 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1332 // clear the bubble when a user navigates to a named anchor in the same
1333 // page.
1334 UpdateTargetURL(details.entry->page_id(), GURL());
1335
1336 // UpdateHelpersForDidNavigate will handle the case where the password_form
1337 // origin is valid.
1338 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1339 // cleaned up and covered by tests.
1340 if (!params.password_form.origin.is_valid())
1341 GetPasswordManager()->DidNavigate();
1342 }
1343
1344 // The keyword generator uses the navigation entries, so must be called after
1345 // the commit.
1346 GenerateKeywordIfNecessary(params);
1347
1348 // Allow the new page to set the title again.
1349 received_page_title_ = false;
1350
1351 // Get the favicon, either from history or request it from the net.
1352 fav_icon_helper_.FetchFavIcon(details.entry->url());
1353
[email protected]ce5c4502009-05-06 16:46:111354 // Disable all page actions.
1355 enabled_page_actions_.clear();
1356
[email protected]420ae012009-04-24 05:16:321357 // Close constrained popups if necessary.
1358 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1359
1360 // Update the starred state.
1361 UpdateStarredStateForCurrentURL();
1362}
1363
1364void TabContents::DidNavigateAnyFramePostCommit(
1365 RenderViewHost* render_view_host,
1366 const NavigationController::LoadCommittedDetails& details,
1367 const ViewHostMsg_FrameNavigate_Params& params) {
1368 // If we navigate, start showing messages again. This does nothing to prevent
1369 // a malicious script from spamming messages, since the script could just
1370 // reload the page to stop blocking.
1371 suppress_javascript_messages_ = false;
1372
1373 // Update history. Note that this needs to happen after the entry is complete,
1374 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1375 if (params.should_update_history) {
1376 // Most of the time, the displayURL matches the loaded URL, but for about:
1377 // URLs, we use a data: URL as the real value. We actually want to save
1378 // the about: URL to the history db and keep the data: URL hidden. This is
1379 // what the TabContents' URL getter does.
1380 UpdateHistoryForNavigation(GetURL(), params);
1381 }
1382
1383 // Notify the password manager of the navigation or form submit.
1384 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1385 // cleaned up and covered by tests.
1386 if (params.password_form.origin.is_valid())
1387 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1388}
1389
1390void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1391 const GURL& current_url) {
1392 if (net::RegistryControlledDomainService::SameDomainOrHost(
1393 previous_url, current_url))
1394 return;
1395
1396 // Clear out any child windows since we are leaving this page entirely.
1397 // We use indices instead of iterators in case CloseWindow does something
1398 // that may invalidate an iterator.
1399 int size = static_cast<int>(child_windows_.size());
1400 for (int i = size - 1; i >= 0; --i) {
1401 ConstrainedWindow* window = child_windows_[i];
1402 if (window)
1403 window->CloseConstrainedWindow();
1404 }
1405}
1406
1407void TabContents::UpdateStarredStateForCurrentURL() {
1408 BookmarkModel* model = profile()->GetBookmarkModel();
1409 const bool old_state = is_starred_;
1410 is_starred_ = (model && model->IsBookmarked(GetURL()));
1411
1412 if (is_starred_ != old_state && delegate())
1413 delegate()->URLStarredChanged(this, is_starred_);
1414}
1415
1416void TabContents::UpdateAlternateErrorPageURL() {
1417 GURL url = GetAlternateErrorPageURL();
1418 render_view_host()->SetAlternateErrorPageURL(url);
1419}
1420
1421void TabContents::UpdateWebPreferences() {
1422 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1423}
1424
1425void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1426 RenderViewHost* rvh) {
1427 // If we are creating a RVH for a restored controller, then we might
1428 // have more page IDs than the SiteInstance's current max page ID. We must
1429 // make sure that the max page ID is larger than any restored page ID.
1430 // Note that it is ok for conflicting page IDs to exist in another tab
1431 // (i.e., NavigationController), but if any page ID is larger than the max,
1432 // the back/forward list will get confused.
1433 int max_restored_page_id = controller_.max_restored_page_id();
1434 if (max_restored_page_id > 0) {
1435 int curr_max_page_id = site_instance->max_page_id();
1436 if (max_restored_page_id > curr_max_page_id) {
1437 // Need to update the site instance immediately.
1438 site_instance->UpdateMaxPageID(max_restored_page_id);
1439
1440 // Also tell the renderer to update its internal representation. We
1441 // need to reserve enough IDs to make all restored page IDs less than
1442 // the max.
1443 if (curr_max_page_id < 0)
1444 curr_max_page_id = 0;
1445 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1446 }
1447 }
1448}
1449
1450void TabContents::UpdateHistoryForNavigation(
1451 const GURL& display_url,
1452 const ViewHostMsg_FrameNavigate_Params& params) {
1453 if (profile()->IsOffTheRecord())
1454 return;
1455
1456 // Add to history service.
1457 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1458 if (hs) {
1459 if (PageTransition::IsMainFrame(params.transition) &&
1460 display_url != params.url) {
1461 // Hack on the "display" URL so that it will appear in history. For some
1462 // types of URLs, we will display a magic URL that is different from where
1463 // the page is actually navigated. We want the user to see in history
1464 // what they saw in the URL bar, so we add the display URL as a redirect.
1465 // This only applies to the main frame, as the display URL doesn't apply
1466 // to sub-frames.
1467 std::vector<GURL> redirects = params.redirects;
1468 if (!redirects.empty())
1469 redirects.back() = display_url;
1470 hs->AddPage(display_url, this, params.page_id, params.referrer,
1471 params.transition, redirects);
1472 } else {
1473 hs->AddPage(params.url, this, params.page_id, params.referrer,
1474 params.transition, params.redirects);
1475 }
1476 }
1477}
1478
1479bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1480 const std::wstring& title) {
1481 // For file URLs without a title, use the pathname instead. In the case of a
1482 // synthesized title, we don't want the update to count toward the "one set
1483 // per page of the title to history."
1484 std::wstring final_title;
1485 bool explicit_set;
1486 if (entry->url().SchemeIsFile() && title.empty()) {
1487 final_title = UTF8ToWide(entry->url().ExtractFileName());
1488 explicit_set = false; // Don't count synthetic titles toward the set limit.
1489 } else {
1490 TrimWhitespace(title, TRIM_ALL, &final_title);
1491 explicit_set = true;
1492 }
1493
1494 if (final_title == UTF16ToWideHack(entry->title()))
1495 return false; // Nothing changed, don't bother.
1496
1497 entry->set_title(WideToUTF16Hack(final_title));
1498
1499 // Update the history system for this page.
1500 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1501 HistoryService* hs =
1502 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1503 if (hs)
1504 hs->SetPageTitle(entry->display_url(), final_title);
1505
1506 // Don't allow the title to be saved again for explicitly set ones.
1507 received_page_title_ = explicit_set;
1508 }
1509
1510 // Lastly, set the title for the view.
1511 view_->SetPageTitle(final_title);
1512
1513 return true;
1514}
1515
1516void TabContents::NotifySwapped() {
1517 // After sending out a swap notification, we need to send a disconnect
1518 // notification so that clients that pick up a pointer to |this| can NULL the
1519 // pointer. See Bug 1230284.
1520 notify_disconnection_ = true;
1521 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341522 NotificationType::TAB_CONTENTS_SWAPPED,
1523 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321524 NotificationService::NoDetails());
1525}
1526
1527void TabContents::NotifyConnected() {
1528 notify_disconnection_ = true;
1529 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341530 NotificationType::TAB_CONTENTS_CONNECTED,
1531 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321532 NotificationService::NoDetails());
1533}
1534
1535void TabContents::NotifyDisconnected() {
1536 if (!notify_disconnection_)
1537 return;
1538
1539 notify_disconnection_ = false;
1540 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341541 NotificationType::TAB_CONTENTS_DISCONNECTED,
1542 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321543 NotificationService::NoDetails());
1544}
1545
1546void TabContents::GenerateKeywordIfNecessary(
1547 const ViewHostMsg_FrameNavigate_Params& params) {
1548 if (!params.searchable_form_url.is_valid())
1549 return;
1550
1551 if (profile()->IsOffTheRecord())
1552 return;
1553
1554 int last_index = controller_.last_committed_entry_index();
1555 // When there was no previous page, the last index will be 0. This is
1556 // normally due to a form submit that opened in a new tab.
1557 // TODO(brettw) bug 916126: we should support keywords when form submits
1558 // happen in new tabs.
1559 if (last_index <= 0)
1560 return;
1561 const NavigationEntry* previous_entry =
1562 controller_.GetEntryAtIndex(last_index - 1);
1563 if (IsFormSubmit(previous_entry)) {
1564 // Only generate a keyword if the previous page wasn't itself a form
1565 // submit.
1566 return;
1567 }
1568
1569 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1570 previous_entry->user_typed_url() : previous_entry->url();
1571 std::wstring keyword =
1572 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1573 if (keyword.empty())
1574 return;
1575
1576 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1577 if (!url_model)
1578 return;
1579
1580 if (!url_model->loaded()) {
1581 url_model->Load();
1582 return;
1583 }
1584
1585 const TemplateURL* current_url;
1586 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1587 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1588 return;
1589
1590 if (current_url) {
1591 if (current_url->originating_url().is_valid()) {
1592 // The existing keyword was generated from an OpenSearch description
1593 // document, don't regenerate.
1594 return;
1595 }
1596 url_model->Remove(current_url);
1597 }
1598 TemplateURL* new_url = new TemplateURL();
1599 new_url->set_keyword(keyword);
1600 new_url->set_short_name(keyword);
1601 new_url->SetURL(url, 0, 0);
1602 new_url->add_input_encoding(params.searchable_form_encoding);
1603 DCHECK(controller_.GetLastCommittedEntry());
1604 const GURL& favicon_url =
1605 controller_.GetLastCommittedEntry()->favicon().url();
1606 if (favicon_url.is_valid()) {
1607 new_url->SetFavIconURL(favicon_url);
1608 } else {
1609 // The favicon url isn't valid. This means there really isn't a favicon,
1610 // or the favicon url wasn't obtained before the load started. This assumes
1611 // the later.
1612 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1613 // its url.
1614 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1615 }
1616 new_url->set_safe_for_autoreplace(true);
1617 url_model->Add(new_url);
1618}
1619
1620RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1621 return view_.get();
1622}
1623
1624RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1625 return save_package_.get(); // May be NULL, but we can return NULL.
1626}
1627
1628Profile* TabContents::GetProfile() const {
1629 return profile();
1630}
1631
[email protected]6dfed102009-04-28 03:09:531632ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1633 RenderViewHost* render_view_host,
1634 const std::string& extension_id) {
1635 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1636 extension_id);
1637}
1638
[email protected]57c6a652009-05-04 07:58:341639TabContents* TabContents::GetAsTabContents() {
1640 return this;
1641}
1642
[email protected]420ae012009-04-24 05:16:321643void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1644 NavigationEntry* entry = controller_.GetActiveEntry();
1645 if (!entry)
1646 return;
1647
1648 // When we're creating views, we're still doing initial setup, so we always
1649 // use the pending DOM UI rather than any possibly existing committed one.
1650 if (render_manager_.pending_dom_ui()) {
1651 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1652 }
1653
1654 if (entry->IsViewSourceMode()) {
1655 // Put the renderer in view source mode.
1656 render_view_host->Send(
1657 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1658 }
1659}
1660
1661void TabContents::RenderViewReady(RenderViewHost* rvh) {
1662 if (rvh != render_view_host()) {
1663 // Don't notify the world, since this came from a renderer in the
1664 // background.
1665 return;
1666 }
1667
1668 NotifyConnected();
1669 SetIsCrashed(false);
1670}
1671
1672void TabContents::RenderViewGone(RenderViewHost* rvh) {
1673 // Ask the print preview if this renderer was valuable.
1674 if (!printing_.OnRenderViewGone(rvh))
1675 return;
1676 if (rvh != render_view_host()) {
1677 // The pending page's RenderViewHost is gone.
1678 return;
1679 }
1680
1681 SetIsLoading(false, NULL);
1682 NotifyDisconnected();
1683 SetIsCrashed(true);
1684
1685 // Force an invalidation to render sad tab. The view will notice we crashed
1686 // when it paints.
1687 view_->Invalidate();
1688
1689 // Hide any visible hung renderer warning for this web contents' process.
[email protected]8897c382009-05-06 17:53:261690 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:321691}
1692
1693void TabContents::DidNavigate(RenderViewHost* rvh,
1694 const ViewHostMsg_FrameNavigate_Params& params) {
1695 if (PageTransition::IsMainFrame(params.transition))
1696 render_manager_.DidNavigateMainFrame(rvh);
1697
1698 // Update the site of the SiteInstance if it doesn't have one yet.
1699 if (!GetSiteInstance()->has_site())
1700 GetSiteInstance()->SetSite(params.url);
1701
1702 // Need to update MIME type here because it's referred to in
1703 // UpdateNavigationCommands() called by RendererDidNavigate() to
1704 // determine whether or not to enable the encoding menu.
1705 // It's updated only for the main frame. For a subframe,
1706 // RenderView::UpdateURL does not set params.contents_mime_type.
1707 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1708 // TODO(jungshik): Add a test for the encoding menu to avoid
1709 // regressing it again.
1710 if (PageTransition::IsMainFrame(params.transition))
1711 contents_mime_type_ = params.contents_mime_type;
1712
1713 NavigationController::LoadCommittedDetails details;
1714 if (!controller_.RendererDidNavigate(params, &details))
1715 return; // No navigation happened.
1716
1717 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1718 // for the appropriate notification (best) or you can add it to
1719 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1720 // necessary, please).
1721
1722 // Run post-commit tasks.
1723 if (details.is_main_frame)
1724 DidNavigateMainFramePostCommit(details, params);
1725 DidNavigateAnyFramePostCommit(rvh, details, params);
1726}
1727
1728void TabContents::UpdateState(RenderViewHost* rvh,
1729 int32 page_id,
1730 const std::string& state) {
1731 DCHECK(rvh == render_view_host());
1732
1733 // We must be prepared to handle state updates for any page, these occur
1734 // when the user is scrolling and entering form data, as well as when we're
1735 // leaving a page, in which case our state may have already been moved to
1736 // the next page. The navigation controller will look up the appropriate
1737 // NavigationEntry and update it when it is notified via the delegate.
1738
1739 int entry_index = controller_.GetEntryIndexWithPageID(
1740 GetSiteInstance(), page_id);
1741 if (entry_index < 0)
1742 return;
1743 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1744
1745 if (state == entry->content_state())
1746 return; // Nothing to update.
1747 entry->set_content_state(state);
1748 controller_.NotifyEntryChanged(entry, entry_index);
1749}
1750
1751void TabContents::UpdateTitle(RenderViewHost* rvh,
1752 int32 page_id, const std::wstring& title) {
1753 // If we have a title, that's a pretty good indication that we've started
1754 // getting useful data.
1755 SetNotWaitingForResponse();
1756
1757 DCHECK(rvh == render_view_host());
1758 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1759 page_id);
1760 if (!entry || !UpdateTitleForEntry(entry, title))
1761 return;
1762
1763 // Broadcast notifications when the UI should be updated.
1764 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501765 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321766}
1767
[email protected]420ae012009-04-24 05:16:321768void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1769 const std::wstring& encoding) {
1770 set_encoding(encoding);
1771}
1772
1773void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1774 if (delegate())
1775 delegate()->UpdateTargetURL(this, url);
1776}
1777
1778void TabContents::UpdateThumbnail(const GURL& url,
1779 const SkBitmap& bitmap,
1780 const ThumbnailScore& score) {
1781 // Tell History about this thumbnail
1782 HistoryService* hs;
1783 if (!profile()->IsOffTheRecord() &&
1784 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1785 hs->SetPageThumbnail(url, bitmap, score);
1786 }
1787}
1788
1789void TabContents::Close(RenderViewHost* rvh) {
1790 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1791 if (delegate() && rvh == render_view_host())
1792 delegate()->CloseContents(this);
1793}
1794
1795void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1796 if (delegate() && delegate()->IsPopup(this))
1797 delegate()->MoveContents(this, new_bounds);
1798}
1799
[email protected]329581b2009-04-28 06:52:351800void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321801 SetIsLoading(true, NULL);
1802}
1803
[email protected]329581b2009-04-28 06:52:351804void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321805 scoped_ptr<LoadNotificationDetails> details;
1806
1807 NavigationEntry* entry = controller_.GetActiveEntry();
1808 // An entry may not exist for a stop when loading an initial blank page or
1809 // if an iframe injected by script into a blank page finishes loading.
1810 if (entry) {
1811 scoped_ptr<base::ProcessMetrics> metrics(
1812 base::ProcessMetrics::CreateProcessMetrics(
1813 process()->process().handle()));
1814
1815 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1816
1817 details.reset(new LoadNotificationDetails(
1818 entry->display_url(),
1819 entry->transition_type(),
1820 elapsed,
1821 &controller_,
1822 controller_.GetCurrentEntryIndex()));
1823 }
1824
1825 // Tell PasswordManager we've finished a page load, which serves as a
1826 // green light to save pending passwords and reset itself.
1827 GetPasswordManager()->DidStopLoading();
1828
1829 SetIsLoading(false, details.get());
1830}
1831
1832void TabContents::DidStartProvisionalLoadForFrame(
1833 RenderViewHost* render_view_host,
1834 bool is_main_frame,
1835 const GURL& url) {
1836 ProvisionalLoadDetails details(is_main_frame,
1837 controller_.IsURLInPageNavigation(url),
1838 url, std::string(), false);
1839 NotificationService::current()->Notify(
1840 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1841 Source<NavigationController>(&controller_),
1842 Details<ProvisionalLoadDetails>(&details));
1843}
1844
1845void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1846 const GURL& source_url,
1847 const GURL& target_url) {
1848 NavigationEntry* entry;
1849 if (page_id == -1)
1850 entry = controller_.pending_entry();
1851 else
1852 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1853 if (!entry || entry->url() != source_url)
1854 return;
1855 entry->set_url(target_url);
1856}
1857
1858void TabContents::DidLoadResourceFromMemoryCache(
1859 const GURL& url,
1860 const std::string& frame_origin,
1861 const std::string& main_frame_origin,
1862 const std::string& security_info) {
1863 // Send out a notification that we loaded a resource from our memory cache.
1864 int cert_id = 0, cert_status = 0, security_bits = 0;
1865 SSLManager::DeserializeSecurityInfo(security_info,
1866 &cert_id, &cert_status,
1867 &security_bits);
1868 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
1869 cert_id, cert_status);
1870
1871 NotificationService::current()->Notify(
1872 NotificationType::LOAD_FROM_MEMORY_CACHE,
1873 Source<NavigationController>(&controller_),
1874 Details<LoadFromMemoryCacheDetails>(&details));
1875}
1876
1877void TabContents::DidFailProvisionalLoadWithError(
1878 RenderViewHost* render_view_host,
1879 bool is_main_frame,
1880 int error_code,
1881 const GURL& url,
1882 bool showing_repost_interstitial) {
1883 if (net::ERR_ABORTED == error_code) {
1884 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1885 // This means that the interstitial won't be torn down properly, which is
1886 // bad. But if we have an interstitial, go back to another tab type, and
1887 // then load the same interstitial again, we could end up getting the first
1888 // interstitial's "failed" message (as a result of the cancel) when we're on
1889 // the second one.
1890 //
1891 // We can't tell this apart, so we think we're tearing down the current page
1892 // which will cause a crash later one. There is also some code in
1893 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1894 // out because of this problem.
1895 //
1896 // http://code.google.com/p/chromium/issues/detail?id=2855
1897 // Because this will not tear down the interstitial properly, if "back" is
1898 // back to another tab type, the interstitial will still be somewhat alive
1899 // in the previous tab type. If you navigate somewhere that activates the
1900 // tab with the interstitial again, you'll see a flash before the new load
1901 // commits of the interstitial page.
1902 if (showing_interstitial_page()) {
1903 LOG(WARNING) << "Discarding message during interstitial.";
1904 return;
1905 }
1906
1907 // This will discard our pending entry if we cancelled the load (e.g., if we
1908 // decided to download the file instead of load it). Only discard the
1909 // pending entry if the URLs match, otherwise the user initiated a navigate
1910 // before the page loaded so that the discard would discard the wrong entry.
1911 NavigationEntry* pending_entry = controller_.pending_entry();
1912 if (pending_entry && pending_entry->url() == url)
1913 controller_.DiscardNonCommittedEntries();
1914
1915 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1916 }
1917
1918 // Send out a notification that we failed a provisional load with an error.
1919 ProvisionalLoadDetails details(is_main_frame,
1920 controller_.IsURLInPageNavigation(url),
1921 url, std::string(), false);
1922 details.set_error_code(error_code);
1923
1924 NotificationService::current()->Notify(
1925 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1926 Source<NavigationController>(&controller_),
1927 Details<ProvisionalLoadDetails>(&details));
1928}
1929
1930void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1931 int32 page_id,
1932 const GURL& icon_url) {
1933 fav_icon_helper_.SetFavIconURL(icon_url);
1934}
1935
1936void TabContents::DidDownloadImage(
1937 RenderViewHost* render_view_host,
1938 int id,
1939 const GURL& image_url,
1940 bool errored,
1941 const SkBitmap& image) {
1942 // A notification for downloading would be more flexible, but for now I'm
1943 // forwarding to the two places that could possibly have initiated the
1944 // request. If we end up with another place invoking DownloadImage, probably
1945 // best to refactor out into notification service, or something similar.
1946 if (errored)
1947 fav_icon_helper_.FavIconDownloadFailed(id);
1948 else
1949 fav_icon_helper_.SetFavIcon(id, image_url, image);
1950}
1951
1952void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1953 WindowOpenDisposition disposition) {
1954 if (render_manager_.dom_ui()) {
1955 // When we're a DOM UI, it will provide a page transition type for us (this
1956 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1957 // generated suggestions).
1958 //
1959 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161960 // want web sites to see a referrer of "chrome://blah" (and some
1961 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321962 // send to the site), so we send no referrer.
1963 OpenURL(url, GURL(), disposition,
1964 render_manager_.dom_ui()->link_transition_type());
1965 } else {
1966 OpenURL(url, referrer, disposition, PageTransition::LINK);
1967 }
1968}
1969
1970void TabContents::DomOperationResponse(const std::string& json_string,
1971 int automation_id) {
1972 DomOperationNotificationDetails details(json_string, automation_id);
1973 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341974 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321975 Details<DomOperationNotificationDetails>(&details));
1976}
1977
1978void TabContents::ProcessDOMUIMessage(const std::string& message,
1979 const std::string& content) {
1980 if (!render_manager_.dom_ui()) {
1981 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1982 // Because the renderer might be owned and sending random messages, we need
1983 // to ignore these inproper ones.
1984 NOTREACHED();
1985 return;
1986 }
1987 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1988}
1989
1990void TabContents::ProcessExternalHostMessage(const std::string& message,
1991 const std::string& origin,
1992 const std::string& target) {
1993 if (delegate())
1994 delegate()->ForwardMessageToExternalHost(message, origin, target);
1995}
1996
1997void TabContents::GoToEntryAtOffset(int offset) {
1998 controller_.GoToOffset(offset);
1999}
2000
2001void TabContents::GetHistoryListCount(int* back_list_count,
2002 int* forward_list_count) {
2003 int current_index = controller_.last_committed_entry_index();
2004 *back_list_count = current_index;
2005 *forward_list_count = controller_.entry_count() - current_index - 1;
2006}
2007
2008void TabContents::RunFileChooser(bool multiple_files,
2009 const string16& title,
2010 const FilePath& default_file) {
2011 if (!select_file_dialog_.get())
2012 select_file_dialog_ = SelectFileDialog::Create(this);
2013 SelectFileDialog::Type dialog_type =
2014 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
2015 SelectFileDialog::SELECT_OPEN_FILE;
2016 select_file_dialog_->SelectFile(dialog_type, title, default_file,
2017 NULL, 0, FILE_PATH_LITERAL(""),
2018 view_->GetTopLevelNativeWindow(), NULL);
2019}
2020
2021void TabContents::RunJavaScriptMessage(
2022 const std::wstring& message,
2023 const std::wstring& default_prompt,
2024 const GURL& frame_url,
2025 const int flags,
2026 IPC::Message* reply_msg,
2027 bool* did_suppress_message) {
2028 // Suppress javascript messages when requested and when inside a constrained
2029 // popup window (because that activates them and breaks them out of the
2030 // constrained window jail).
2031 bool suppress_this_message = suppress_javascript_messages_;
2032 if (delegate())
2033 suppress_this_message |=
2034 (delegate()->GetConstrainingContents(this) != NULL);
2035
2036 *did_suppress_message = suppress_this_message;
2037
2038 if (!suppress_this_message) {
2039 base::TimeDelta time_since_last_message(
2040 base::TimeTicks::Now() - last_javascript_message_dismissal_);
2041 bool show_suppress_checkbox = false;
2042 // Show a checkbox offering to suppress further messages if this message is
2043 // being displayed within kJavascriptMessageExpectedDelay of the last one.
2044 if (time_since_last_message <
2045 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
2046 show_suppress_checkbox = true;
2047
2048 RunJavascriptMessageBox(AsWC(this), frame_url, flags, message, default_prompt,
2049 show_suppress_checkbox, reply_msg);
2050 } else {
2051 // If we are suppressing messages, just reply as is if the user immediately
2052 // pressed "Cancel".
2053 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
2054 }
2055}
2056
2057void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
2058 IPC::Message* reply_msg) {
2059 RunBeforeUnloadDialog(AsWC(this), message, reply_msg);
2060}
2061
2062void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
2063 const std::string& json_arguments,
2064 IPC::Message* reply_msg) {
2065 if (delegate()) {
2066 HtmlDialogUIDelegate* dialog_delegate =
2067 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
2068 reply_msg, AsWC(this));
2069 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
2070 }
2071}
2072
2073void TabContents::PasswordFormsSeen(
2074 const std::vector<PasswordForm>& forms) {
2075 GetPasswordManager()->PasswordFormsSeen(forms);
2076}
2077
2078void TabContents::AutofillFormSubmitted(
2079 const AutofillForm& form) {
2080 GetAutofillManager()->AutofillFormSubmitted(form);
2081}
2082
2083void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
2084 const std::wstring& user_text, int64 node_id, int request_id) {
2085 GetAutofillManager()->FetchValuesForName(field_name, user_text,
2086 kMaxAutofillMenuItems, node_id, request_id);
2087}
2088
2089void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
2090 const std::wstring& value) {
2091 GetAutofillManager()->RemoveValueForName(field_name, value);
2092}
2093
2094// Checks to see if we should generate a keyword based on the OSDD, and if
2095// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2096void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2097 int32 page_id, const GURL& url,
2098 bool autodetected) {
2099 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2100 DCHECK(url.is_valid());
2101 if (!IsActiveEntry(page_id))
2102 return;
2103 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2104 if (!url_model)
2105 return;
2106 if (!url_model->loaded()) {
2107 url_model->Load();
2108 return;
2109 }
2110 if (!profile()->GetTemplateURLFetcher())
2111 return;
2112
2113 if (profile()->IsOffTheRecord())
2114 return;
2115
2116 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2117 DCHECK(entry);
2118
2119 const NavigationEntry* base_entry = entry;
2120 if (IsFormSubmit(base_entry)) {
2121 // If the current page is a form submit, find the last page that was not
2122 // a form submit and use its url to generate the keyword from.
2123 int index = controller_.last_committed_entry_index() - 1;
2124 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2125 index--;
2126 if (index >= 0)
2127 base_entry = controller_.GetEntryAtIndex(index);
2128 else
2129 base_entry = NULL;
2130 }
2131
2132 // We want to use the user typed URL if available since that represents what
2133 // the user typed to get here, and fall back on the regular URL if not.
2134 if (!base_entry)
2135 return;
2136 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2137 base_entry->user_typed_url() : base_entry->url();
2138 if (!keyword_url.is_valid())
2139 return;
2140 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2141 autodetected);
2142 if (keyword.empty())
2143 return;
2144 const TemplateURL* template_url =
2145 url_model->GetTemplateURLForKeyword(keyword);
2146 if (template_url && (!template_url->safe_for_autoreplace() ||
2147 template_url->originating_url() == url)) {
2148 // Either there is a user created TemplateURL for this keyword, or the
2149 // keyword has the same OSDD url and we've parsed it.
2150 return;
2151 }
2152
2153 // Download the OpenSearch description document. If this is successful a
2154 // new keyword will be created when done.
2155#if defined(OS_WIN)
2156 gfx::NativeView ancestor = GetAncestor(view_->GetNativeView(), GA_ROOT);
2157#else
2158 gfx::NativeView ancestor = NULL;
2159#endif
2160 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2161 keyword,
2162 url,
2163 base_entry->favicon().url(),
2164 ancestor,
2165 autodetected);
2166}
2167
2168void TabContents::InspectElementReply(int num_resources) {
2169 // We have received reply from inspect element request. Notify the
2170 // automation provider in case we need to notify automation client.
2171 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:342172 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:322173 Details<int>(&num_resources));
2174}
2175
2176void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2177 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2178}
2179
2180void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2181 printing_.DidPrintPage(params);
2182}
2183
2184GURL TabContents::GetAlternateErrorPageURL() const {
2185 GURL url;
2186 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2187 if (profile()->IsOffTheRecord())
2188 return url;
2189
2190 PrefService* prefs = profile()->GetPrefs();
2191 DCHECK(prefs);
2192 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2193 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2194 url = google_util::AppendGoogleTLDParam(url);
2195 }
2196 return url;
2197}
2198
2199WebPreferences TabContents::GetWebkitPrefs() {
2200 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2201 bool isDomUI = false;
2202 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2203}
2204
2205void TabContents::OnMissingPluginStatus(int status) {
2206#if defined(OS_WIN)
2207// TODO(PORT): pull in when plug-ins work
2208 GetPluginInstaller()->OnMissingPluginStatus(status);
2209#endif
2210}
2211
2212void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2213#if defined(OS_WIN)
2214// TODO(PORT): pull in when plug-ins work
2215 DCHECK(!plugin_path.value().empty());
2216
2217 std::wstring plugin_name = plugin_path.ToWStringHack();
2218 scoped_ptr<FileVersionInfo> version_info(
2219 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2220 if (version_info.get()) {
2221 const std::wstring& product_name = version_info->product_name();
2222 if (!product_name.empty())
2223 plugin_name = product_name;
2224 }
2225 AddInfoBar(new SimpleAlertInfoBarDelegate(
2226 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2227 NULL));
2228#endif
2229}
2230
2231void TabContents::OnCrashedWorker() {
2232 AddInfoBar(new SimpleAlertInfoBarDelegate(
2233 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2234 NULL));
2235}
2236
2237void TabContents::OnJSOutOfMemory() {
2238 AddInfoBar(new SimpleAlertInfoBarDelegate(
2239 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2240}
2241
2242void TabContents::ShouldClosePage(bool proceed) {
2243 render_manager_.ShouldClosePage(proceed);
2244}
2245
2246void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2247 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342248 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322249 // delivered to a pending RenderViewHost. We must first run the onunload
2250 // handler of the old RenderViewHost before we can allow it to proceed.
2251 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2252 new_request_id);
2253}
2254
2255bool TabContents::CanBlur() const {
2256 return delegate() ? delegate()->CanBlur() : true;
2257}
2258
2259gfx::Rect TabContents::GetRootWindowResizerRect() const {
2260 if (delegate())
2261 return delegate()->GetRootWindowResizerRect();
2262 return gfx::Rect();
2263}
2264
2265void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2266 bool is_during_unload) {
2267 if (is_during_unload) {
2268 // Hang occurred while firing the beforeunload/unload handler.
2269 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112270 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322271
2272 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2273 return;
2274
2275 // If the tab hangs in the beforeunload/unload handler there's really
2276 // nothing we can do to recover. Pretend the unload listeners have
2277 // all fired and close the tab. If the hang is in the beforeunload handler
2278 // then the user will not have the option of cancelling the close.
2279 Close(rvh);
2280 return;
2281 }
2282
2283 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]8897c382009-05-06 17:53:262284 HungRendererDialog::ShowForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322285}
2286
2287void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]8897c382009-05-06 17:53:262288 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322289}
2290
2291void TabContents::LoadStateChanged(const GURL& url,
2292 net::LoadState load_state) {
2293 load_state_ = load_state;
2294 load_state_host_ = UTF8ToWide(url.host());
2295 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2296 SetNotWaitingForResponse();
2297 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502298 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322299}
2300
2301void TabContents::OnDidGetApplicationInfo(
2302 int32 page_id,
2303 const webkit_glue::WebApplicationInfo& info) {
2304 if (pending_install_.page_id != page_id)
2305 return; // The user clicked create on a separate page. Ignore this.
2306
2307 pending_install_.callback_functor =
2308 new GearsCreateShortcutCallbackFunctor(this);
2309 GearsCreateShortcut(
2310 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2311 NewCallback(pending_install_.callback_functor,
2312 &GearsCreateShortcutCallbackFunctor::Run));
2313}
2314
2315void TabContents::OnEnterOrSpace() {
2316 // See comment in RenderViewHostDelegate::OnEnterOrSpace as to why we do this.
2317#if defined(OS_WIN)
2318 // TODO(port): this is stubbed in BrowserProcess
2319 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2320 if (drm)
2321 drm->OnUserGesture(this);
2322#endif
2323}
2324
2325void TabContents::OnFindReply(int request_id,
2326 int number_of_matches,
2327 const gfx::Rect& selection_rect,
2328 int active_match_ordinal,
2329 bool final_update) {
2330 // Ignore responses for requests other than the one we have most recently
2331 // issued. That way we won't act on stale results when the user has
2332 // already typed in another query.
2333 if (request_id != current_find_request_id_)
2334 return;
2335
2336 if (number_of_matches == -1)
2337 number_of_matches = find_result_.number_of_matches();
2338 if (active_match_ordinal == -1)
2339 active_match_ordinal = find_result_.active_match_ordinal();
2340
2341 // Notify the UI, automation and any other observers that a find result was
2342 // found.
2343 find_result_ = FindNotificationDetails(request_id, number_of_matches,
2344 selection_rect, active_match_ordinal,
2345 final_update);
2346 NotificationService::current()->Notify(
2347 NotificationType::FIND_RESULT_AVAILABLE,
2348 Source<TabContents>(this),
2349 Details<FindNotificationDetails>(&find_result_));
2350}
2351
[email protected]829e7612009-04-25 01:15:112352bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322353 if (!delegate())
[email protected]829e7612009-04-25 01:15:112354 return false;
[email protected]420ae012009-04-24 05:16:322355
[email protected]829e7612009-04-25 01:15:112356 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322357}
2358
2359void TabContents::FileSelected(const FilePath& path,
2360 int index, void* params) {
2361 render_view_host()->FileSelected(path);
2362}
2363
2364void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2365 void* params) {
2366 render_view_host()->MultiFilesSelected(files);
2367}
2368
2369void TabContents::FileSelectionCanceled(void* params) {
2370 // If the user cancels choosing a file to upload we pass back an
2371 // empty vector.
2372 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2373}
2374
2375void TabContents::BeforeUnloadFiredFromRenderManager(
2376 bool proceed,
2377 bool* proceed_to_fire_unload) {
2378 if (delegate())
2379 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2380}
2381
2382void TabContents::UpdateRenderViewSizeForRenderManager() {
2383 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2384 view_->SizeContents(view_->GetContainerSize());
2385}
2386
2387DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
2388 return DOMUIFactory::CreateDOMUIForURL(AsWC(this), url);
2389}
2390
2391NavigationEntry*
2392TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2393 return controller_.GetLastCommittedEntry();
2394}
2395
2396bool TabContents::CreateRenderViewForRenderManager(
2397 RenderViewHost* render_view_host) {
2398 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2399 // mode before CreateRenderView is called. When we're asked to create a
2400 // RenderView, that means it's for the pending entry, so we have to use the
2401 // pending DOM UI.
2402 if (render_manager_.pending_dom_ui())
2403 render_view_host->AllowDOMUIBindings();
2404
2405 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2406 if (!render_view_host->CreateRenderView())
2407 return false;
2408
2409 // Now that the RenderView has been created, we need to tell it its size.
2410 rwh_view->SetSize(view_->GetContainerSize());
2411
2412 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2413 render_view_host);
2414 return true;
2415}
2416
2417void TabContents::Observe(NotificationType type,
2418 const NotificationSource& source,
2419 const NotificationDetails& details) {
2420 switch (type.value) {
2421 case NotificationType::BOOKMARK_MODEL_LOADED:
2422 // BookmarkModel finished loading, fall through to update starred state.
2423 case NotificationType::URLS_STARRED: {
2424 // Somewhere, a URL has been starred.
2425 // Ignore notifications for profiles other than our current one.
2426 Profile* source_profile = Source<Profile>(source).ptr();
2427 if (!source_profile || !source_profile->IsSameProfile(profile()))
2428 return;
2429
2430 UpdateStarredStateForCurrentURL();
2431 break;
2432 }
2433 case NotificationType::PREF_CHANGED: {
2434 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2435 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2436 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2437 UpdateAlternateErrorPageURL();
2438 } else if (*pref_name_in == prefs::kDefaultCharset ||
2439 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2440 ) {
2441 UpdateWebPreferences();
2442 } else {
2443 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2444 }
2445 break;
2446 }
2447 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2448 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2449 break;
2450
2451 case NotificationType::NAV_ENTRY_COMMITTED: {
2452 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2453
2454 NavigationController::LoadCommittedDetails& committed_details =
2455 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2456 ExpireInfoBars(committed_details);
2457 break;
2458 }
2459
2460 default:
2461 NOTREACHED();
2462 }
2463}