blob: 5bc2cacd25e52ca9e35b285b84ad53f92656d90f [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"
36#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);
initial.commit09911bf2008-07-26 23:55:29392}
393
[email protected]d5f942ba2008-09-26 19:30:34394bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01395 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55396 return true;
[email protected]d5f942ba2008-09-26 19:30:34397}
398
[email protected]6e95706d2009-04-23 22:55:01399AutofillManager* TabContents::GetAutofillManager() {
400 if (autofill_manager_.get() == NULL)
401 autofill_manager_.reset(new AutofillManager(this));
402 return autofill_manager_.get();
403}
404
405PasswordManager* TabContents::GetPasswordManager() {
406 if (password_manager_.get() == NULL)
407 password_manager_.reset(new PasswordManager(this));
408 return password_manager_.get();
409}
410
411PluginInstaller* TabContents::GetPluginInstaller() {
412 if (plugin_installer_.get() == NULL)
413 plugin_installer_.reset(new PluginInstaller(this));
414 return plugin_installer_.get();
415}
416
[email protected]d5f942ba2008-09-26 19:30:34417const GURL& TabContents::GetURL() const {
418 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57419 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34420 return entry ? entry->display_url() : GURL::EmptyGURL();
421}
422
[email protected]96d185d2009-04-24 03:28:54423const string16& TabContents::GetTitle() const {
424 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
425 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
426 if (our_dom_ui) {
427 // Don't override the title in view source mode.
428 NavigationEntry* entry = controller_.GetActiveEntry();
429 if (!(entry && entry->IsViewSourceMode())) {
430 // Give the DOM UI the chance to override our title.
431 const string16& title = our_dom_ui->overridden_title();
432 if (!title.empty())
433 return title;
434 }
435 }
436
437 // We use the title for the last committed entry rather than a pending
438 // navigation entry. For example, when the user types in a URL, we want to
439 // keep the old page's title until the new load has committed and we get a new
440 // title.
441 // The exception is with transient pages, for which we really want to use
442 // their title, as they are not committed.
443 NavigationEntry* entry = controller_.GetTransientEntry();
444 if (entry)
445 return entry->GetTitleForDisplay(&controller_);
446
447 entry = controller_.GetLastCommittedEntry();
448 if (entry)
449 return entry->GetTitleForDisplay(&controller_);
450 else if (controller_.LoadingURLLazily())
451 return controller_.GetLazyTitle();
452 return EmptyString16();
453}
454
[email protected]d5f942ba2008-09-26 19:30:34455int32 TabContents::GetMaxPageID() {
456 if (GetSiteInstance())
457 return GetSiteInstance()->max_page_id();
458 else
459 return max_page_id_;
460}
461
462void TabContents::UpdateMaxPageID(int32 page_id) {
463 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34464 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34465 // testing.
466 if (GetSiteInstance())
467 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34468 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34469}
470
[email protected]96d185d2009-04-24 03:28:54471SiteInstance* TabContents::GetSiteInstance() const {
472 return render_manager_.current_host()->site_instance();
473}
474
[email protected]d5f942ba2008-09-26 19:30:34475const std::wstring TabContents::GetDefaultTitle() const {
476 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
477}
478
[email protected]96d185d2009-04-24 03:28:54479bool TabContents::ShouldDisplayURL() {
480 // Don't hide the url in view source mode.
481 NavigationEntry* entry = controller_.GetActiveEntry();
482 if (entry && entry->IsViewSourceMode())
483 return true;
484 DOMUI* dom_ui = GetDOMUIForCurrentState();
485 if (dom_ui)
486 return !dom_ui->should_hide_url();
487 return true;
488}
489
[email protected]d5f942ba2008-09-26 19:30:34490SkBitmap TabContents::GetFavIcon() const {
491 // Like GetTitle(), we also want to use the favicon for the last committed
492 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57493 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47494 if (entry)
495 return entry->favicon().bitmap();
496
[email protected]ce3fa3c2009-04-20 19:55:57497 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34498 if (entry)
499 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57500 else if (controller_.LoadingURLLazily())
501 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34502 return SkBitmap();
503}
504
[email protected]96d185d2009-04-24 03:28:54505bool TabContents::ShouldDisplayFavIcon() {
506 // Always display a throbber during pending loads.
507 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
508 return true;
509
510 DOMUI* dom_ui = GetDOMUIForCurrentState();
511 if (dom_ui)
512 return !dom_ui->hide_favicon();
513 return true;
514}
515
[email protected]3e45ba92009-02-20 21:09:00516#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34517SecurityStyle TabContents::GetSecurityStyle() const {
518 // We may not have a navigation entry yet.
[email protected]ce3fa3c2009-04-20 19:55:57519 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34520 return entry ? entry->ssl().security_style() : SECURITY_STYLE_UNKNOWN;
521}
522
523bool TabContents::GetSSLEVText(std::wstring* ev_text,
524 std::wstring* ev_tooltip_text) const {
525 DCHECK(ev_text && ev_tooltip_text);
526 ev_text->clear();
527 ev_tooltip_text->clear();
528
[email protected]ce3fa3c2009-04-20 19:55:57529 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34530 if (!entry ||
531 net::IsCertStatusError(entry->ssl().cert_status()) ||
532 ((entry->ssl().cert_status() & net::CERT_STATUS_IS_EV) == 0))
533 return false;
534
535 scoped_refptr<net::X509Certificate> cert;
536 CertStore::GetSharedInstance()->RetrieveCert(entry->ssl().cert_id(), &cert);
537 if (!cert.get()) {
538 NOTREACHED();
539 return false;
540 }
541
542 return SSLManager::GetEVCertNames(*cert, ev_text, ev_tooltip_text);
543}
[email protected]76f68dc2009-03-10 20:31:32544#endif
[email protected]d5f942ba2008-09-26 19:30:34545
[email protected]96d185d2009-04-24 03:28:54546std::wstring TabContents::GetStatusText() const {
547 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
548 return std::wstring();
549
550 switch (load_state_) {
551 case net::LOAD_STATE_WAITING_FOR_CACHE:
552 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
553 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
554 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
555 case net::LOAD_STATE_RESOLVING_HOST:
556 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
557 case net::LOAD_STATE_CONNECTING:
558 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
559 case net::LOAD_STATE_SENDING_REQUEST:
560 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
561 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
562 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
563 load_state_host_);
564 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
565 case net::LOAD_STATE_IDLE:
566 case net::LOAD_STATE_READING_RESPONSE:
567 break;
568 }
569
570 return std::wstring();
571}
572
[email protected]d5f942ba2008-09-26 19:30:34573void TabContents::SetIsCrashed(bool state) {
574 if (state == is_crashed_)
575 return;
576
577 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50578 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34579}
580
[email protected]ce5c4502009-05-06 16:46:11581void TabContents::EnablePageAction(const PageAction* page_action) {
582 DCHECK(page_action);
583
584 if (IsPageActionEnabled(page_action))
585 return; // Already enabled.
586
587 enabled_page_actions_.insert(page_action);
588}
589
590bool TabContents::IsPageActionEnabled(const PageAction* page_action) {
591 DCHECK(page_action);
592 return enabled_page_actions_.end() != enabled_page_actions_.find(page_action);
593}
594
595
[email protected]d5f942ba2008-09-26 19:30:34596void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
597 if (delegate_)
598 delegate_->NavigationStateChanged(this, changed_flags);
599}
600
[email protected]96d185d2009-04-24 03:28:54601void TabContents::DidBecomeSelected() {
602 controller_.SetActive(true);
603
604 if (render_widget_host_view())
605 render_widget_host_view()->DidBecomeSelected();
606
607 // If pid() is -1, that means the RenderProcessHost still hasn't been
608 // initialized. It'll register with CacheManagerHost when it is.
609 if (process()->pid() != -1)
610 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
611}
612
613void TabContents::WasHidden() {
614 if (!capturing_contents()) {
615 // |render_view_host()| can be NULL if the user middle clicks a link to open
616 // a tab in then background, then closes the tab before selecting it. This
617 // is because closing the tab calls TabContents::Destroy(), which removes
618 // the |render_view_host()|; then when we actually destroy the window,
619 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
620 if (render_widget_host_view())
621 render_widget_host_view()->WasHidden();
622
623 // Loop through children and send WasHidden to them, too.
624 int count = static_cast<int>(child_windows_.size());
625 for (int i = count - 1; i >= 0; --i) {
626 ConstrainedWindow* window = child_windows_.at(i);
627 window->WasHidden();
628 }
629 }
630
631 NotificationService::current()->Notify(
632 NotificationType::TAB_CONTENTS_HIDDEN,
633 Source<TabContents>(this),
634 NotificationService::NoDetails());
635}
636
[email protected]d5f942ba2008-09-26 19:30:34637void TabContents::Activate() {
638 if (delegate_)
639 delegate_->ActivateContents(this);
640}
641
[email protected]96d185d2009-04-24 03:28:54642void TabContents::ShowContents() {
643 if (render_widget_host_view())
644 render_widget_host_view()->DidBecomeSelected();
645
646 // Loop through children and send DidBecomeSelected to them, too.
647 int count = static_cast<int>(child_windows_.size());
648 for (int i = count - 1; i >= 0; --i) {
649 ConstrainedWindow* window = child_windows_.at(i);
650 window->DidBecomeSelected();
651 }
652}
653
654void TabContents::HideContents() {
655 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
656 // our superclass HideContents(), because some callers want to be very picky
657 // about the order in which these get called. In addition to making the code
658 // here practically impossible to understand, this also means we end up
659 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34660 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54661 WasHidden();
662}
663
[email protected]c0588052008-10-27 23:01:50664void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34665 WindowOpenDisposition disposition,
666 PageTransition::Type transition) {
667 if (delegate_)
[email protected]c0588052008-10-27 23:01:50668 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34669}
670
671bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54672 const NavigationEntry& entry = *controller_.pending_entry();
673
674 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
675 if (!dest_render_view_host)
676 return false; // Unable to create the desired render view host.
677
678 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]684b4ba22009-05-07 06:27:41679 DevToolsManager* devtools_manager = g_browser_process->devtools_manager();
[email protected]7e8e6b62009-05-08 11:28:32680 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41681 devtools_manager->OnNavigatingToPendingEntry(
682 render_view_host(),
683 dest_render_view_host,
684 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32685 }
[email protected]96d185d2009-04-24 03:28:54686
687 // Used for page load time metrics.
688 current_load_start_ = base::TimeTicks::Now();
689
690 // Navigate in the desired RenderViewHost.
691 dest_render_view_host->NavigateToEntry(entry, reload);
692
693 if (entry.page_id() == -1) {
694 // HACK!! This code suppresses javascript: URLs from being added to
695 // session history, which is what we want to do for javascript: URLs that
696 // do not generate content. What we really need is a message from the
697 // renderer telling us that a new page was not created. The same message
698 // could be used for mailto: URLs and the like.
699 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
700 return false;
701 }
702
703 // Clear any provisional password saves - this stops password infobars
704 // showing up on pages the user navigates to while the right page is
705 // loading.
706 GetPasswordManager()->ClearProvisionalSave();
707
708 if (reload && !profile()->IsOffTheRecord()) {
709 HistoryService* history =
710 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
711 if (history)
712 history->SetFavIconOutOfDateForPage(entry.url());
713 }
714
[email protected]d5f942ba2008-09-26 19:30:34715 return true;
716}
717
[email protected]96d185d2009-04-24 03:28:54718void TabContents::Stop() {
719 render_manager_.Stop();
720 printing_.Stop();
721}
722
723void TabContents::Cut() {
724 render_view_host()->Cut();
725}
726
727void TabContents::Copy() {
728 render_view_host()->Copy();
729}
730
731void TabContents::Paste() {
732 render_view_host()->Paste();
733}
734
735void TabContents::DisassociateFromPopupCount() {
736 render_view_host()->DisassociateFromPopupCount();
737}
738
739TabContents* TabContents::Clone() {
740 // We create a new SiteInstance so that the new tab won't share processes
741 // with the old one. This can be changed in the future if we need it to share
742 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32743 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54744 SiteInstance::CreateSiteInstance(profile()),
745 MSG_ROUTING_NONE, NULL);
746 tc->controller().CopyStateFrom(controller_);
747 return tc;
748}
749
[email protected]420ae012009-04-24 05:16:32750void TabContents::CreateShortcut() {
751 NavigationEntry* entry = controller_.GetLastCommittedEntry();
752 if (!entry)
753 return;
754
755 // We only allow one pending install request. By resetting the page id we
756 // effectively cancel the pending install request.
757 pending_install_.page_id = entry->page_id();
758 pending_install_.icon = GetFavIcon();
759 pending_install_.title = UTF16ToWideHack(GetTitle());
760 pending_install_.url = GetURL();
761 if (pending_install_.callback_functor) {
762 pending_install_.callback_functor->Cancel();
763 pending_install_.callback_functor = NULL;
764 }
765 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
766 if (pending_install_.title.empty())
767 pending_install_.title = UTF8ToWide(GetURL().spec());
768
769 // Request the application info. When done OnDidGetApplicationInfo is invoked
770 // and we'll create the shortcut.
771 render_view_host()->GetApplicationInfo(pending_install_.page_id);
772}
773
[email protected]76f68dc2009-03-10 20:31:32774#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29775ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]c2dacc92008-10-16 23:51:38776 views::WindowDelegate* window_delegate,
777 views::View* contents_view) {
initial.commit09911bf2008-07-26 23:55:29778 ConstrainedWindow* window =
779 ConstrainedWindow::CreateConstrainedDialog(
780 this, gfx::Rect(), contents_view, window_delegate);
781 child_windows_.push_back(window);
782 return window;
783}
[email protected]f3332e12009-03-23 15:28:57784#endif
initial.commit09911bf2008-07-26 23:55:29785
786void TabContents::AddNewContents(TabContents* new_contents,
787 WindowOpenDisposition disposition,
788 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22789 bool user_gesture,
790 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29791 if (!delegate_)
792 return;
793
[email protected]f3332e12009-03-23 15:28:57794#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:22795 bool constrain_popup = false;
[email protected]35f7d212009-04-29 21:19:27796 if ((disposition == NEW_POPUP) && !user_gesture &&
797 !CommandLine::ForCurrentProcess()->HasSwitch(
798 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22799 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31800 // the whitelist. The popup owner will handle checking this.
801 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
802 initial_pos,
803 creator_url.is_valid() ? creator_url.host() : std::string());
804 } else {
[email protected]0aa55312008-10-17 21:53:08805 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29806 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
807 user_gesture);
808 }
[email protected]b6c874582009-05-08 19:38:31809 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
[email protected]f3332e12009-03-23 15:28:57810#else
811 // TODO(port): implement the popup blocker stuff
812 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
813 user_gesture);
814#endif
initial.commit09911bf2008-07-26 23:55:29815}
816
[email protected]f3332e12009-03-23 15:28:57817#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29818void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25819 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22820 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29821}
[email protected]332af7732009-03-11 13:21:35822#endif
initial.commit09911bf2008-07-26 23:55:29823
[email protected]96d185d2009-04-24 03:28:54824void TabContents::PopupNotificationVisibilityChanged(bool visible) {
825 render_view_host()->PopupNotificationVisibilityChanged(visible);
826}
827
828gfx::NativeView TabContents::GetContentNativeView() {
829 return view_->GetContentNativeView();
830}
831
832gfx::NativeView TabContents::GetNativeView() const {
833 return view_->GetNativeView();
834}
835
836void TabContents::GetContainerBounds(gfx::Rect *out) const {
837 view_->GetContainerBounds(out);
838}
839
840void TabContents::Focus() {
841 view_->Focus();
842}
843
844void TabContents::SetInitialFocus(bool reverse) {
845 render_view_host()->SetInitialFocus(reverse);
846}
847
848bool TabContents::FocusLocationBarByDefault() {
849 DOMUI* dom_ui = GetDOMUIForCurrentState();
850 if (dom_ui)
851 return dom_ui->focus_location_bar_by_default();
852 return false;
853}
854
[email protected]616ed5a2008-11-21 22:27:24855void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
856 // Look through the existing InfoBarDelegates we have for a match. If we've
857 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05858 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24859 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
860 return;
861 }
862
863 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56864 NotificationService::current()->Notify(
865 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
866 Source<TabContents>(this),
867 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24868
869 // Add ourselves as an observer for navigations the first time a delegate is
870 // added. We use this notification to expire InfoBars that need to expire on
871 // page transitions.
872 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56873 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57874 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24875 }
876}
877
878void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
879 std::vector<InfoBarDelegate*>::iterator it =
880 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
881 if (it != infobar_delegates_.end()) {
882 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56883 NotificationService::current()->Notify(
884 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
885 Source<TabContents>(this),
886 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05887 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24888
[email protected]6a02963e2009-01-06 16:58:03889 // Remove ourselves as an observer if we are tracking no more InfoBars.
890 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56891 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57892 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03893 }
[email protected]616ed5a2008-11-21 22:27:24894 }
895}
[email protected]3edd9522009-03-04 22:19:41896
[email protected]96d185d2009-04-24 03:28:54897bool TabContents::IsBookmarkBarAlwaysVisible() {
898 // See GetDOMUIForCurrentState() comment for more info. This case is very
899 // similar, but for non-first loads, we want to use the committed entry. This
900 // is so the bookmarks bar disappears at the same time the page does.
901 if (controller_.GetLastCommittedEntry()) {
902 // Not the first load, always use the committed DOM UI.
903 if (render_manager_.dom_ui())
904 return render_manager_.dom_ui()->force_bookmark_bar_visible();
905 return false; // Default.
906 }
907
908 // When it's the first load, we know either the pending one or the committed
909 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
910 // of them will be valid, so we can just check both.
911 if (render_manager_.pending_dom_ui())
912 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
913 if (render_manager_.dom_ui())
914 return render_manager_.dom_ui()->force_bookmark_bar_visible();
915 return false; // Default.
916}
917
918void TabContents::SetDownloadShelfVisible(bool visible) {
919 if (shelf_visible_ != visible) {
920 if (visible) {
921 // Invoke GetDownloadShelf to force the shelf to be created.
922 GetDownloadShelf();
923 }
924 shelf_visible_ = visible;
925
[email protected]c9cd2222009-05-06 05:16:50926 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]96d185d2009-04-24 03:28:54927 }
928
929 // SetShelfVisible can force-close the shelf, so make sure we lay out
930 // everything correctly, as if the animation had finished. This doesn't
931 // matter for showing the shelf, as the show animation will do it.
932 ToolbarSizeChanged(false);
933
934 if (visible) {
935 // Always set this value as it reflects the last time the download shelf
936 // was made visible (even if it was already visible).
937 last_download_shelf_show_ = base::TimeTicks::Now();
938 }
939}
940
[email protected]3edd9522009-03-04 22:19:41941void TabContents::ToolbarSizeChanged(bool is_animating) {
942 TabContentsDelegate* d = delegate();
943 if (d)
944 d->ToolbarSizeChanged(this, is_animating);
945}
[email protected]616ed5a2008-11-21 22:27:24946
[email protected]d5f942ba2008-09-26 19:30:34947void TabContents::OnStartDownload(DownloadItem* download) {
948 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34949
950 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31951 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34952
[email protected]bcef0dc02009-02-28 00:35:02953 // GetDownloadShelf creates the download shelf if it was not yet created.
954 tab_contents->GetDownloadShelf()->AddDownload(
955 new DownloadItemModel(download));
[email protected]d5f942ba2008-09-26 19:30:34956 tab_contents->SetDownloadShelfVisible(true);
957
[email protected]3edd9522009-03-04 22:19:41958// TODO(port): port animatinos.
959#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34960 // This animation will delete itself when it finishes, or if we become hidden
961 // or destroyed.
[email protected]92edc472009-02-10 20:32:06962 if (IsWindowVisible(GetNativeView())) { // For minimized windows, unit
963 // tests, etc.
[email protected]d5f942ba2008-09-26 19:30:34964 new DownloadStartedAnimation(tab_contents);
965 }
[email protected]3edd9522009-03-04 22:19:41966#endif
[email protected]d5f942ba2008-09-26 19:30:34967}
968
[email protected]bcef0dc02009-02-28 00:35:02969DownloadShelf* TabContents::GetDownloadShelf() {
970 if (!download_shelf_.get())
971 download_shelf_.reset(DownloadShelf::Create(this));
972 return download_shelf_.get();
initial.commit09911bf2008-07-26 23:55:29973}
974
[email protected]bcef0dc02009-02-28 00:35:02975void TabContents::MigrateShelfFrom(TabContents* tab_contents) {
976 download_shelf_.reset(tab_contents->GetDownloadShelf());
977 download_shelf_->ChangeTabContents(tab_contents, this);
978 tab_contents->ReleaseDownloadShelf();
initial.commit09911bf2008-07-26 23:55:29979}
980
[email protected]3edd9522009-03-04 22:19:41981void TabContents::ReleaseDownloadShelf() {
982 download_shelf_.release();
983}
984
985// static
986void TabContents::MigrateShelf(TabContents* from, TabContents* to) {
987 bool was_shelf_visible = from->IsDownloadShelfVisible();
988 if (was_shelf_visible)
989 to->MigrateShelfFrom(from);
990 to->SetDownloadShelfVisible(was_shelf_visible);
991}
[email protected]3edd9522009-03-04 22:19:41992
[email protected]d5f942ba2008-09-26 19:30:34993void TabContents::WillClose(ConstrainedWindow* window) {
994 ConstrainedWindowList::iterator it =
995 find(child_windows_.begin(), child_windows_.end(), window);
996 if (it != child_windows_.end())
997 child_windows_.erase(it);
998
[email protected]332af7732009-03-11 13:21:35999#if defined(OS_WIN)
[email protected]d6598c052008-11-05 19:03:251000 if (window == blocked_popups_)
1001 blocked_popups_ = NULL;
1002
[email protected]92edc472009-02-10 20:32:061003 if (::IsWindow(GetNativeView())) {
[email protected]d5f942ba2008-09-26 19:30:341004 CRect client_rect;
[email protected]92edc472009-02-10 20:32:061005 GetClientRect(GetNativeView(), &client_rect);
[email protected]d5f942ba2008-09-26 19:30:341006 RepositionSupressedPopupsToFit(
1007 gfx::Size(client_rect.Width(), client_rect.Height()));
1008 }
[email protected]332af7732009-03-11 13:21:351009#endif
[email protected]d5f942ba2008-09-26 19:30:341010}
1011
[email protected]d5f942ba2008-09-26 19:30:341012void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:351013#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:061014 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:351015#endif
[email protected]d5f942ba2008-09-26 19:30:341016}
1017
[email protected]6e95706d2009-04-23 22:55:011018void TabContents::StartFinding(const string16& find_text,
1019 bool forward_direction) {
1020 // If find_text is empty, it means FindNext was pressed with a keyboard
1021 // shortcut so unless we have something to search for we return early.
1022 if (find_text.empty() && find_text_.empty())
1023 return;
1024
1025 // This is a FindNext operation if we are searching for the same text again,
1026 // or if the passed in search text is empty (FindNext keyboard shortcut). The
1027 // exception to this is if the Find was aborted (then we don't want FindNext
1028 // because the highlighting has been cleared and we need it to reappear). We
1029 // therefore treat FindNext after an aborted Find operation as a full fledged
1030 // Find.
1031 bool find_next = (find_text_ == find_text || find_text.empty()) &&
1032 !find_op_aborted_;
1033 if (!find_next)
1034 current_find_request_id_ = find_request_id_counter_++;
1035
1036 if (!find_text.empty())
1037 find_text_ = find_text;
1038
1039 find_op_aborted_ = false;
1040
1041 // Keep track of what the last search was across the tabs.
1042 *find_prepopulate_text_ = find_text;
1043
1044 render_view_host()->StartFinding(current_find_request_id_,
1045 find_text_,
1046 forward_direction,
1047 false, // case sensitive
1048 find_next);
1049}
1050
1051void TabContents::StopFinding(bool clear_selection) {
1052 find_ui_active_ = false;
1053 find_op_aborted_ = true;
1054 find_result_ = FindNotificationDetails();
1055 render_view_host()->StopFinding(clear_selection);
1056}
1057
[email protected]420ae012009-04-24 05:16:321058void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
1059 bool success,
1060 const std::wstring& prompt) {
1061 last_javascript_message_dismissal_ = base::TimeTicks::Now();
1062 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
1063}
1064
1065void TabContents::OnSavePage() {
1066 // If we can not save the page, try to download it.
1067 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1068 DownloadManager* dlm = profile()->GetDownloadManager();
1069 const GURL& current_page_url = GetURL();
1070 if (dlm && current_page_url.is_valid())
[email protected]c9825a42009-05-01 22:51:501071 dlm->DownloadUrl(current_page_url, GURL(), "", AsWC(this));
[email protected]420ae012009-04-24 05:16:321072 return;
1073 }
1074
1075 Stop();
1076
1077 // Create the save package and possibly prompt the user for the name to save
1078 // the page as. The user prompt is an asynchronous operation that runs on
1079 // another thread.
1080 save_package_ = new SavePackage(AsWC(this));
1081 save_package_->GetSaveInfo();
1082}
1083
1084// Used in automated testing to bypass prompting the user for file names.
1085// Instead, the names and paths are hard coded rather than running them through
1086// file name sanitation and extension / mime checking.
1087void TabContents::SavePage(const std::wstring& main_file,
1088 const std::wstring& dir_path,
1089 SavePackage::SavePackageType save_type) {
1090 // Stop the page from navigating.
1091 Stop();
1092
1093 save_package_ = new SavePackage(AsWC(this), save_type,
1094 FilePath::FromWStringHack(main_file),
1095 FilePath::FromWStringHack(dir_path));
1096 save_package_->Init();
1097}
1098
1099void TabContents::PrintPreview() {
1100 // We don't show the print preview yet, only the print dialog.
1101 PrintNow();
1102}
1103
1104bool TabContents::PrintNow() {
1105 // We can't print interstitial page for now.
1106 if (showing_interstitial_page())
1107 return false;
1108
1109 return render_view_host()->PrintPages();
1110}
1111
1112bool TabContents::IsActiveEntry(int32 page_id) {
1113 NavigationEntry* active_entry = controller_.GetActiveEntry();
1114 return (active_entry != NULL &&
1115 active_entry->site_instance() == GetSiteInstance() &&
1116 active_entry->page_id() == page_id);
1117}
1118
[email protected]96d185d2009-04-24 03:28:541119// Notifies the RenderWidgetHost instance about the fact that the page is
1120// loading, or done loading and calls the base implementation.
1121void TabContents::SetIsLoading(bool is_loading,
1122 LoadNotificationDetails* details) {
1123 if (is_loading == is_loading_)
1124 return;
1125
1126 if (!is_loading) {
1127 load_state_ = net::LOAD_STATE_IDLE;
1128 load_state_host_.clear();
1129 }
1130
1131 render_manager_.SetIsLoading(is_loading);
1132
1133 is_loading_ = is_loading;
1134 waiting_for_response_ = is_loading;
1135
1136 if (delegate_)
1137 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351138 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541139
1140 NotificationType type = is_loading ? NotificationType::LOAD_START :
1141 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111142 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541143 if (details)
1144 det = Details<LoadNotificationDetails>(details);
1145 NotificationService::current()->Notify(type,
1146 Source<NavigationController>(&controller_),
1147 det);
1148}
1149
[email protected]76f68dc2009-03-10 20:31:321150#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:221151void TabContents::CreateBlockedPopupContainerIfNecessary() {
1152 if (blocked_popups_)
1153 return;
1154
1155 CRect client_rect;
1156 GetClientRect(GetNativeView(), &client_rect);
1157 gfx::Point anchor_position(
1158 client_rect.Width() - views::NativeScrollBar::GetVerticalScrollBarWidth(),
1159 client_rect.Height());
1160 blocked_popups_ = BlockedPopupContainer::Create(this, profile(),
1161 anchor_position);
1162 child_windows_.push_back(blocked_popups_);
1163}
1164
[email protected]b6c874582009-05-08 19:38:311165void TabContents::AddPopup(TabContents* new_contents,
1166 const gfx::Rect& initial_pos,
1167 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221168 CreateBlockedPopupContainerIfNecessary();
1169 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221170}
1171
[email protected]e69bce3dd2009-04-20 22:05:121172// TODO(brettw) This should be on the TabContentsView.
[email protected]d5f942ba2008-09-26 19:30:341173void TabContents::RepositionSupressedPopupsToFit(const gfx::Size& new_size) {
1174 // TODO(erg): There's no way to detect whether scroll bars are
1175 // visible, so for beta, we're just going to assume that the
1176 // vertical scroll bar is visible, and not care about covering up
1177 // the horizontal scroll bar. Fixing this is half of
1178 // http://b/1118139.
1179 gfx::Point anchor_position(
1180 new_size.width() -
[email protected]c2dacc92008-10-16 23:51:381181 views::NativeScrollBar::GetVerticalScrollBarWidth(),
[email protected]d5f942ba2008-09-26 19:30:341182 new_size.height());
[email protected]d6598c052008-11-05 19:03:251183
1184 if (blocked_popups_)
1185 blocked_popups_->RepositionConstrainedWindowTo(anchor_position);
[email protected]d5f942ba2008-09-26 19:30:341186}
1187
[email protected]b9681312008-11-07 00:08:261188bool TabContents::ShowingBlockedPopupNotification() const {
1189 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221190 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261191}
[email protected]332af7732009-03-11 13:21:351192#endif // defined(OS_WIN)
[email protected]616ed5a2008-11-21 22:27:241193
1194namespace {
1195bool TransitionIsReload(PageTransition::Type transition) {
1196 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1197}
1198}
1199
1200void TabContents::ExpireInfoBars(
1201 const NavigationController::LoadCommittedDetails& details) {
1202 // Only hide InfoBars when the user has done something that makes the main
1203 // frame load. We don't want various automatic or subframe navigations making
1204 // it disappear.
1205 if (!details.is_user_initiated_main_frame_load())
1206 return;
1207
[email protected]f86a07022008-11-25 01:06:051208 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241209 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051210 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241211 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241212 }
1213}
[email protected]fdd61c62009-04-22 19:22:571214
1215void TabContents::OnGearsCreateShortcutDone(
1216 const GearsShortcutData2& shortcut_data, bool success) {
1217 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1218 bool same_page =
1219 current_entry && pending_install_.page_id == current_entry->page_id();
1220
1221 if (success && same_page) {
1222 // Only switch to app mode if the user chose to create a shortcut and
1223 // we're still on the same page that it corresponded to.
1224 if (delegate())
1225 delegate()->ConvertContentsToApplication(this);
1226 }
1227
1228 // Reset the page id to indicate no requests are pending.
1229 pending_install_.page_id = 0;
1230 pending_install_.callback_functor = NULL;
1231}
[email protected]96d185d2009-04-24 03:28:541232
1233DOMUI* TabContents::GetDOMUIForCurrentState() {
1234 // When there is a pending navigation entry, we want to use the pending DOMUI
1235 // that goes along with it to control the basic flags. For example, we want to
1236 // show the pending URL in the URL bar, so we want the display_url flag to
1237 // be from the pending entry.
1238 //
1239 // The confusion comes because there are multiple possibilities for the
1240 // initial load in a tab as a side effect of the way the RenderViewHostManager
1241 // works.
1242 //
1243 // - For the very first tab the load looks "normal". The new tab DOM UI is
1244 // the pending one, and we want it to apply here.
1245 //
1246 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1247 // get switched to the one previously associated with the new tab pages.
1248 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1249 // have a committed DOM UI in this case.
1250 //
1251 // This condition handles all of these cases:
1252 //
1253 // - First load in first tab: no committed nav entry + pending nav entry +
1254 // pending dom ui:
1255 // -> Use pending DOM UI if any.
1256 //
1257 // - First load in second tab: no committed nav entry + pending nav entry +
1258 // no pending DOM UI:
1259 // -> Use the committed DOM UI if any.
1260 //
1261 // - Second navigation in any tab: committed nav entry + pending nav entry:
1262 // -> Use pending DOM UI if any.
1263 //
1264 // - Normal state with no load: committed nav entry + no pending nav entry:
1265 // -> Use committed DOM UI.
1266 if (controller_.pending_entry() &&
1267 (controller_.GetLastCommittedEntry() ||
1268 render_manager_.pending_dom_ui()))
1269 return render_manager_.pending_dom_ui();
1270 return render_manager_.dom_ui();
1271}
[email protected]420ae012009-04-24 05:16:321272
1273void TabContents::DidNavigateMainFramePostCommit(
1274 const NavigationController::LoadCommittedDetails& details,
1275 const ViewHostMsg_FrameNavigate_Params& params) {
1276 // Hide the download shelf if all the following conditions are true:
1277 // - there are no active downloads.
1278 // - this is a navigation to a different TLD.
1279 // - at least 5 seconds have elapsed since the download shelf was shown.
1280 // TODO(jcampan): bug 1156075 when user gestures are reliable, they should
1281 // be used to ensure we are hiding only on user initiated
1282 // navigations.
1283 DownloadManager* download_manager = profile()->GetDownloadManager();
1284 // download_manager can be NULL in unit test context.
1285 if (download_manager && download_manager->in_progress_count() == 0 &&
1286 !details.previous_url.is_empty() &&
1287 !net::RegistryControlledDomainService::SameDomainOrHost(
1288 details.previous_url, details.entry->url())) {
1289 base::TimeDelta time_delta(
1290 base::TimeTicks::Now() - last_download_shelf_show_);
1291 if (time_delta >
1292 base::TimeDelta::FromMilliseconds(kDownloadShelfHideDelay)) {
1293 SetDownloadShelfVisible(false);
1294 }
1295 }
1296
1297 if (details.is_user_initiated_main_frame_load()) {
1298 // Clear the status bubble. This is a workaround for a bug where WebKit
1299 // doesn't let us know that the cursor left an element during a
1300 // transition (this is also why the mouse cursor remains as a hand after
1301 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1302 // clear the bubble when a user navigates to a named anchor in the same
1303 // page.
1304 UpdateTargetURL(details.entry->page_id(), GURL());
1305
1306 // UpdateHelpersForDidNavigate will handle the case where the password_form
1307 // origin is valid.
1308 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1309 // cleaned up and covered by tests.
1310 if (!params.password_form.origin.is_valid())
1311 GetPasswordManager()->DidNavigate();
1312 }
1313
1314 // The keyword generator uses the navigation entries, so must be called after
1315 // the commit.
1316 GenerateKeywordIfNecessary(params);
1317
1318 // Allow the new page to set the title again.
1319 received_page_title_ = false;
1320
1321 // Get the favicon, either from history or request it from the net.
1322 fav_icon_helper_.FetchFavIcon(details.entry->url());
1323
[email protected]ce5c4502009-05-06 16:46:111324 // Disable all page actions.
1325 enabled_page_actions_.clear();
1326
[email protected]420ae012009-04-24 05:16:321327 // Close constrained popups if necessary.
1328 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1329
1330 // Update the starred state.
1331 UpdateStarredStateForCurrentURL();
1332}
1333
1334void TabContents::DidNavigateAnyFramePostCommit(
1335 RenderViewHost* render_view_host,
1336 const NavigationController::LoadCommittedDetails& details,
1337 const ViewHostMsg_FrameNavigate_Params& params) {
1338 // If we navigate, start showing messages again. This does nothing to prevent
1339 // a malicious script from spamming messages, since the script could just
1340 // reload the page to stop blocking.
1341 suppress_javascript_messages_ = false;
1342
1343 // Update history. Note that this needs to happen after the entry is complete,
1344 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1345 if (params.should_update_history) {
1346 // Most of the time, the displayURL matches the loaded URL, but for about:
1347 // URLs, we use a data: URL as the real value. We actually want to save
1348 // the about: URL to the history db and keep the data: URL hidden. This is
1349 // what the TabContents' URL getter does.
1350 UpdateHistoryForNavigation(GetURL(), params);
1351 }
1352
1353 // Notify the password manager of the navigation or form submit.
1354 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1355 // cleaned up and covered by tests.
1356 if (params.password_form.origin.is_valid())
1357 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1358}
1359
1360void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1361 const GURL& current_url) {
1362 if (net::RegistryControlledDomainService::SameDomainOrHost(
1363 previous_url, current_url))
1364 return;
1365
1366 // Clear out any child windows since we are leaving this page entirely.
1367 // We use indices instead of iterators in case CloseWindow does something
1368 // that may invalidate an iterator.
1369 int size = static_cast<int>(child_windows_.size());
1370 for (int i = size - 1; i >= 0; --i) {
1371 ConstrainedWindow* window = child_windows_[i];
1372 if (window)
1373 window->CloseConstrainedWindow();
1374 }
1375}
1376
1377void TabContents::UpdateStarredStateForCurrentURL() {
1378 BookmarkModel* model = profile()->GetBookmarkModel();
1379 const bool old_state = is_starred_;
1380 is_starred_ = (model && model->IsBookmarked(GetURL()));
1381
1382 if (is_starred_ != old_state && delegate())
1383 delegate()->URLStarredChanged(this, is_starred_);
1384}
1385
1386void TabContents::UpdateAlternateErrorPageURL() {
1387 GURL url = GetAlternateErrorPageURL();
1388 render_view_host()->SetAlternateErrorPageURL(url);
1389}
1390
1391void TabContents::UpdateWebPreferences() {
1392 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1393}
1394
1395void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1396 RenderViewHost* rvh) {
1397 // If we are creating a RVH for a restored controller, then we might
1398 // have more page IDs than the SiteInstance's current max page ID. We must
1399 // make sure that the max page ID is larger than any restored page ID.
1400 // Note that it is ok for conflicting page IDs to exist in another tab
1401 // (i.e., NavigationController), but if any page ID is larger than the max,
1402 // the back/forward list will get confused.
1403 int max_restored_page_id = controller_.max_restored_page_id();
1404 if (max_restored_page_id > 0) {
1405 int curr_max_page_id = site_instance->max_page_id();
1406 if (max_restored_page_id > curr_max_page_id) {
1407 // Need to update the site instance immediately.
1408 site_instance->UpdateMaxPageID(max_restored_page_id);
1409
1410 // Also tell the renderer to update its internal representation. We
1411 // need to reserve enough IDs to make all restored page IDs less than
1412 // the max.
1413 if (curr_max_page_id < 0)
1414 curr_max_page_id = 0;
1415 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1416 }
1417 }
1418}
1419
1420void TabContents::UpdateHistoryForNavigation(
1421 const GURL& display_url,
1422 const ViewHostMsg_FrameNavigate_Params& params) {
1423 if (profile()->IsOffTheRecord())
1424 return;
1425
1426 // Add to history service.
1427 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1428 if (hs) {
1429 if (PageTransition::IsMainFrame(params.transition) &&
1430 display_url != params.url) {
1431 // Hack on the "display" URL so that it will appear in history. For some
1432 // types of URLs, we will display a magic URL that is different from where
1433 // the page is actually navigated. We want the user to see in history
1434 // what they saw in the URL bar, so we add the display URL as a redirect.
1435 // This only applies to the main frame, as the display URL doesn't apply
1436 // to sub-frames.
1437 std::vector<GURL> redirects = params.redirects;
1438 if (!redirects.empty())
1439 redirects.back() = display_url;
1440 hs->AddPage(display_url, this, params.page_id, params.referrer,
1441 params.transition, redirects);
1442 } else {
1443 hs->AddPage(params.url, this, params.page_id, params.referrer,
1444 params.transition, params.redirects);
1445 }
1446 }
1447}
1448
1449bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1450 const std::wstring& title) {
1451 // For file URLs without a title, use the pathname instead. In the case of a
1452 // synthesized title, we don't want the update to count toward the "one set
1453 // per page of the title to history."
1454 std::wstring final_title;
1455 bool explicit_set;
1456 if (entry->url().SchemeIsFile() && title.empty()) {
1457 final_title = UTF8ToWide(entry->url().ExtractFileName());
1458 explicit_set = false; // Don't count synthetic titles toward the set limit.
1459 } else {
1460 TrimWhitespace(title, TRIM_ALL, &final_title);
1461 explicit_set = true;
1462 }
1463
1464 if (final_title == UTF16ToWideHack(entry->title()))
1465 return false; // Nothing changed, don't bother.
1466
1467 entry->set_title(WideToUTF16Hack(final_title));
1468
1469 // Update the history system for this page.
1470 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1471 HistoryService* hs =
1472 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1473 if (hs)
1474 hs->SetPageTitle(entry->display_url(), final_title);
1475
1476 // Don't allow the title to be saved again for explicitly set ones.
1477 received_page_title_ = explicit_set;
1478 }
1479
1480 // Lastly, set the title for the view.
1481 view_->SetPageTitle(final_title);
1482
1483 return true;
1484}
1485
1486void TabContents::NotifySwapped() {
1487 // After sending out a swap notification, we need to send a disconnect
1488 // notification so that clients that pick up a pointer to |this| can NULL the
1489 // pointer. See Bug 1230284.
1490 notify_disconnection_ = true;
1491 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341492 NotificationType::TAB_CONTENTS_SWAPPED,
1493 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321494 NotificationService::NoDetails());
1495}
1496
1497void TabContents::NotifyConnected() {
1498 notify_disconnection_ = true;
1499 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341500 NotificationType::TAB_CONTENTS_CONNECTED,
1501 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321502 NotificationService::NoDetails());
1503}
1504
1505void TabContents::NotifyDisconnected() {
1506 if (!notify_disconnection_)
1507 return;
1508
1509 notify_disconnection_ = false;
1510 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341511 NotificationType::TAB_CONTENTS_DISCONNECTED,
1512 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321513 NotificationService::NoDetails());
1514}
1515
1516void TabContents::GenerateKeywordIfNecessary(
1517 const ViewHostMsg_FrameNavigate_Params& params) {
1518 if (!params.searchable_form_url.is_valid())
1519 return;
1520
1521 if (profile()->IsOffTheRecord())
1522 return;
1523
1524 int last_index = controller_.last_committed_entry_index();
1525 // When there was no previous page, the last index will be 0. This is
1526 // normally due to a form submit that opened in a new tab.
1527 // TODO(brettw) bug 916126: we should support keywords when form submits
1528 // happen in new tabs.
1529 if (last_index <= 0)
1530 return;
1531 const NavigationEntry* previous_entry =
1532 controller_.GetEntryAtIndex(last_index - 1);
1533 if (IsFormSubmit(previous_entry)) {
1534 // Only generate a keyword if the previous page wasn't itself a form
1535 // submit.
1536 return;
1537 }
1538
1539 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1540 previous_entry->user_typed_url() : previous_entry->url();
1541 std::wstring keyword =
1542 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1543 if (keyword.empty())
1544 return;
1545
1546 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1547 if (!url_model)
1548 return;
1549
1550 if (!url_model->loaded()) {
1551 url_model->Load();
1552 return;
1553 }
1554
1555 const TemplateURL* current_url;
1556 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1557 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1558 return;
1559
1560 if (current_url) {
1561 if (current_url->originating_url().is_valid()) {
1562 // The existing keyword was generated from an OpenSearch description
1563 // document, don't regenerate.
1564 return;
1565 }
1566 url_model->Remove(current_url);
1567 }
1568 TemplateURL* new_url = new TemplateURL();
1569 new_url->set_keyword(keyword);
1570 new_url->set_short_name(keyword);
1571 new_url->SetURL(url, 0, 0);
1572 new_url->add_input_encoding(params.searchable_form_encoding);
1573 DCHECK(controller_.GetLastCommittedEntry());
1574 const GURL& favicon_url =
1575 controller_.GetLastCommittedEntry()->favicon().url();
1576 if (favicon_url.is_valid()) {
1577 new_url->SetFavIconURL(favicon_url);
1578 } else {
1579 // The favicon url isn't valid. This means there really isn't a favicon,
1580 // or the favicon url wasn't obtained before the load started. This assumes
1581 // the later.
1582 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1583 // its url.
1584 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1585 }
1586 new_url->set_safe_for_autoreplace(true);
1587 url_model->Add(new_url);
1588}
1589
1590RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1591 return view_.get();
1592}
1593
1594RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1595 return save_package_.get(); // May be NULL, but we can return NULL.
1596}
1597
1598Profile* TabContents::GetProfile() const {
1599 return profile();
1600}
1601
[email protected]6dfed102009-04-28 03:09:531602ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1603 RenderViewHost* render_view_host,
1604 const std::string& extension_id) {
1605 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1606 extension_id);
1607}
1608
[email protected]57c6a652009-05-04 07:58:341609TabContents* TabContents::GetAsTabContents() {
1610 return this;
1611}
1612
[email protected]420ae012009-04-24 05:16:321613void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1614 NavigationEntry* entry = controller_.GetActiveEntry();
1615 if (!entry)
1616 return;
1617
1618 // When we're creating views, we're still doing initial setup, so we always
1619 // use the pending DOM UI rather than any possibly existing committed one.
1620 if (render_manager_.pending_dom_ui()) {
1621 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1622 }
1623
1624 if (entry->IsViewSourceMode()) {
1625 // Put the renderer in view source mode.
1626 render_view_host->Send(
1627 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1628 }
1629}
1630
1631void TabContents::RenderViewReady(RenderViewHost* rvh) {
1632 if (rvh != render_view_host()) {
1633 // Don't notify the world, since this came from a renderer in the
1634 // background.
1635 return;
1636 }
1637
1638 NotifyConnected();
1639 SetIsCrashed(false);
1640}
1641
1642void TabContents::RenderViewGone(RenderViewHost* rvh) {
1643 // Ask the print preview if this renderer was valuable.
1644 if (!printing_.OnRenderViewGone(rvh))
1645 return;
1646 if (rvh != render_view_host()) {
1647 // The pending page's RenderViewHost is gone.
1648 return;
1649 }
1650
1651 SetIsLoading(false, NULL);
1652 NotifyDisconnected();
1653 SetIsCrashed(true);
1654
1655 // Force an invalidation to render sad tab. The view will notice we crashed
1656 // when it paints.
1657 view_->Invalidate();
1658
1659 // Hide any visible hung renderer warning for this web contents' process.
[email protected]8897c382009-05-06 17:53:261660 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:321661}
1662
1663void TabContents::DidNavigate(RenderViewHost* rvh,
1664 const ViewHostMsg_FrameNavigate_Params& params) {
1665 if (PageTransition::IsMainFrame(params.transition))
1666 render_manager_.DidNavigateMainFrame(rvh);
1667
1668 // Update the site of the SiteInstance if it doesn't have one yet.
1669 if (!GetSiteInstance()->has_site())
1670 GetSiteInstance()->SetSite(params.url);
1671
1672 // Need to update MIME type here because it's referred to in
1673 // UpdateNavigationCommands() called by RendererDidNavigate() to
1674 // determine whether or not to enable the encoding menu.
1675 // It's updated only for the main frame. For a subframe,
1676 // RenderView::UpdateURL does not set params.contents_mime_type.
1677 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1678 // TODO(jungshik): Add a test for the encoding menu to avoid
1679 // regressing it again.
1680 if (PageTransition::IsMainFrame(params.transition))
1681 contents_mime_type_ = params.contents_mime_type;
1682
1683 NavigationController::LoadCommittedDetails details;
1684 if (!controller_.RendererDidNavigate(params, &details))
1685 return; // No navigation happened.
1686
1687 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1688 // for the appropriate notification (best) or you can add it to
1689 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1690 // necessary, please).
1691
1692 // Run post-commit tasks.
1693 if (details.is_main_frame)
1694 DidNavigateMainFramePostCommit(details, params);
1695 DidNavigateAnyFramePostCommit(rvh, details, params);
1696}
1697
1698void TabContents::UpdateState(RenderViewHost* rvh,
1699 int32 page_id,
1700 const std::string& state) {
1701 DCHECK(rvh == render_view_host());
1702
1703 // We must be prepared to handle state updates for any page, these occur
1704 // when the user is scrolling and entering form data, as well as when we're
1705 // leaving a page, in which case our state may have already been moved to
1706 // the next page. The navigation controller will look up the appropriate
1707 // NavigationEntry and update it when it is notified via the delegate.
1708
1709 int entry_index = controller_.GetEntryIndexWithPageID(
1710 GetSiteInstance(), page_id);
1711 if (entry_index < 0)
1712 return;
1713 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1714
1715 if (state == entry->content_state())
1716 return; // Nothing to update.
1717 entry->set_content_state(state);
1718 controller_.NotifyEntryChanged(entry, entry_index);
1719}
1720
1721void TabContents::UpdateTitle(RenderViewHost* rvh,
1722 int32 page_id, const std::wstring& title) {
1723 // If we have a title, that's a pretty good indication that we've started
1724 // getting useful data.
1725 SetNotWaitingForResponse();
1726
1727 DCHECK(rvh == render_view_host());
1728 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1729 page_id);
1730 if (!entry || !UpdateTitleForEntry(entry, title))
1731 return;
1732
1733 // Broadcast notifications when the UI should be updated.
1734 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501735 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321736}
1737
[email protected]420ae012009-04-24 05:16:321738void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1739 const std::wstring& encoding) {
1740 set_encoding(encoding);
1741}
1742
1743void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1744 if (delegate())
1745 delegate()->UpdateTargetURL(this, url);
1746}
1747
1748void TabContents::UpdateThumbnail(const GURL& url,
1749 const SkBitmap& bitmap,
1750 const ThumbnailScore& score) {
1751 // Tell History about this thumbnail
1752 HistoryService* hs;
1753 if (!profile()->IsOffTheRecord() &&
1754 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1755 hs->SetPageThumbnail(url, bitmap, score);
1756 }
1757}
1758
1759void TabContents::Close(RenderViewHost* rvh) {
1760 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1761 if (delegate() && rvh == render_view_host())
1762 delegate()->CloseContents(this);
1763}
1764
1765void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1766 if (delegate() && delegate()->IsPopup(this))
1767 delegate()->MoveContents(this, new_bounds);
1768}
1769
[email protected]329581b2009-04-28 06:52:351770void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321771 SetIsLoading(true, NULL);
1772}
1773
[email protected]329581b2009-04-28 06:52:351774void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321775 scoped_ptr<LoadNotificationDetails> details;
1776
1777 NavigationEntry* entry = controller_.GetActiveEntry();
1778 // An entry may not exist for a stop when loading an initial blank page or
1779 // if an iframe injected by script into a blank page finishes loading.
1780 if (entry) {
1781 scoped_ptr<base::ProcessMetrics> metrics(
1782 base::ProcessMetrics::CreateProcessMetrics(
1783 process()->process().handle()));
1784
1785 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1786
1787 details.reset(new LoadNotificationDetails(
1788 entry->display_url(),
1789 entry->transition_type(),
1790 elapsed,
1791 &controller_,
1792 controller_.GetCurrentEntryIndex()));
1793 }
1794
1795 // Tell PasswordManager we've finished a page load, which serves as a
1796 // green light to save pending passwords and reset itself.
1797 GetPasswordManager()->DidStopLoading();
1798
1799 SetIsLoading(false, details.get());
1800}
1801
1802void TabContents::DidStartProvisionalLoadForFrame(
1803 RenderViewHost* render_view_host,
1804 bool is_main_frame,
1805 const GURL& url) {
1806 ProvisionalLoadDetails details(is_main_frame,
1807 controller_.IsURLInPageNavigation(url),
1808 url, std::string(), false);
1809 NotificationService::current()->Notify(
1810 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1811 Source<NavigationController>(&controller_),
1812 Details<ProvisionalLoadDetails>(&details));
1813}
1814
1815void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1816 const GURL& source_url,
1817 const GURL& target_url) {
1818 NavigationEntry* entry;
1819 if (page_id == -1)
1820 entry = controller_.pending_entry();
1821 else
1822 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1823 if (!entry || entry->url() != source_url)
1824 return;
1825 entry->set_url(target_url);
1826}
1827
1828void TabContents::DidLoadResourceFromMemoryCache(
1829 const GURL& url,
1830 const std::string& frame_origin,
1831 const std::string& main_frame_origin,
1832 const std::string& security_info) {
1833 // Send out a notification that we loaded a resource from our memory cache.
1834 int cert_id = 0, cert_status = 0, security_bits = 0;
1835 SSLManager::DeserializeSecurityInfo(security_info,
1836 &cert_id, &cert_status,
1837 &security_bits);
1838 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]9ae66cbf2009-05-12 16:21:031839 process()->pid(), cert_id, cert_status);
[email protected]420ae012009-04-24 05:16:321840
1841 NotificationService::current()->Notify(
1842 NotificationType::LOAD_FROM_MEMORY_CACHE,
1843 Source<NavigationController>(&controller_),
1844 Details<LoadFromMemoryCacheDetails>(&details));
1845}
1846
1847void TabContents::DidFailProvisionalLoadWithError(
1848 RenderViewHost* render_view_host,
1849 bool is_main_frame,
1850 int error_code,
1851 const GURL& url,
1852 bool showing_repost_interstitial) {
1853 if (net::ERR_ABORTED == error_code) {
1854 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1855 // This means that the interstitial won't be torn down properly, which is
1856 // bad. But if we have an interstitial, go back to another tab type, and
1857 // then load the same interstitial again, we could end up getting the first
1858 // interstitial's "failed" message (as a result of the cancel) when we're on
1859 // the second one.
1860 //
1861 // We can't tell this apart, so we think we're tearing down the current page
1862 // which will cause a crash later one. There is also some code in
1863 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1864 // out because of this problem.
1865 //
1866 // http://code.google.com/p/chromium/issues/detail?id=2855
1867 // Because this will not tear down the interstitial properly, if "back" is
1868 // back to another tab type, the interstitial will still be somewhat alive
1869 // in the previous tab type. If you navigate somewhere that activates the
1870 // tab with the interstitial again, you'll see a flash before the new load
1871 // commits of the interstitial page.
1872 if (showing_interstitial_page()) {
1873 LOG(WARNING) << "Discarding message during interstitial.";
1874 return;
1875 }
1876
1877 // This will discard our pending entry if we cancelled the load (e.g., if we
1878 // decided to download the file instead of load it). Only discard the
1879 // pending entry if the URLs match, otherwise the user initiated a navigate
1880 // before the page loaded so that the discard would discard the wrong entry.
1881 NavigationEntry* pending_entry = controller_.pending_entry();
1882 if (pending_entry && pending_entry->url() == url)
1883 controller_.DiscardNonCommittedEntries();
1884
1885 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1886 }
1887
1888 // Send out a notification that we failed a provisional load with an error.
1889 ProvisionalLoadDetails details(is_main_frame,
1890 controller_.IsURLInPageNavigation(url),
1891 url, std::string(), false);
1892 details.set_error_code(error_code);
1893
1894 NotificationService::current()->Notify(
1895 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1896 Source<NavigationController>(&controller_),
1897 Details<ProvisionalLoadDetails>(&details));
1898}
1899
1900void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1901 int32 page_id,
1902 const GURL& icon_url) {
1903 fav_icon_helper_.SetFavIconURL(icon_url);
1904}
1905
1906void TabContents::DidDownloadImage(
1907 RenderViewHost* render_view_host,
1908 int id,
1909 const GURL& image_url,
1910 bool errored,
1911 const SkBitmap& image) {
1912 // A notification for downloading would be more flexible, but for now I'm
1913 // forwarding to the two places that could possibly have initiated the
1914 // request. If we end up with another place invoking DownloadImage, probably
1915 // best to refactor out into notification service, or something similar.
1916 if (errored)
1917 fav_icon_helper_.FavIconDownloadFailed(id);
1918 else
1919 fav_icon_helper_.SetFavIcon(id, image_url, image);
1920}
1921
1922void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1923 WindowOpenDisposition disposition) {
1924 if (render_manager_.dom_ui()) {
1925 // When we're a DOM UI, it will provide a page transition type for us (this
1926 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1927 // generated suggestions).
1928 //
1929 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161930 // want web sites to see a referrer of "chrome://blah" (and some
1931 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321932 // send to the site), so we send no referrer.
1933 OpenURL(url, GURL(), disposition,
1934 render_manager_.dom_ui()->link_transition_type());
1935 } else {
1936 OpenURL(url, referrer, disposition, PageTransition::LINK);
1937 }
1938}
1939
1940void TabContents::DomOperationResponse(const std::string& json_string,
1941 int automation_id) {
1942 DomOperationNotificationDetails details(json_string, automation_id);
1943 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341944 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321945 Details<DomOperationNotificationDetails>(&details));
1946}
1947
1948void TabContents::ProcessDOMUIMessage(const std::string& message,
1949 const std::string& content) {
1950 if (!render_manager_.dom_ui()) {
1951 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1952 // Because the renderer might be owned and sending random messages, we need
1953 // to ignore these inproper ones.
1954 NOTREACHED();
1955 return;
1956 }
1957 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1958}
1959
1960void TabContents::ProcessExternalHostMessage(const std::string& message,
1961 const std::string& origin,
1962 const std::string& target) {
1963 if (delegate())
1964 delegate()->ForwardMessageToExternalHost(message, origin, target);
1965}
1966
1967void TabContents::GoToEntryAtOffset(int offset) {
1968 controller_.GoToOffset(offset);
1969}
1970
1971void TabContents::GetHistoryListCount(int* back_list_count,
1972 int* forward_list_count) {
1973 int current_index = controller_.last_committed_entry_index();
1974 *back_list_count = current_index;
1975 *forward_list_count = controller_.entry_count() - current_index - 1;
1976}
1977
1978void TabContents::RunFileChooser(bool multiple_files,
1979 const string16& title,
1980 const FilePath& default_file) {
1981 if (!select_file_dialog_.get())
1982 select_file_dialog_ = SelectFileDialog::Create(this);
1983 SelectFileDialog::Type dialog_type =
1984 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
1985 SelectFileDialog::SELECT_OPEN_FILE;
1986 select_file_dialog_->SelectFile(dialog_type, title, default_file,
1987 NULL, 0, FILE_PATH_LITERAL(""),
1988 view_->GetTopLevelNativeWindow(), NULL);
1989}
1990
1991void TabContents::RunJavaScriptMessage(
1992 const std::wstring& message,
1993 const std::wstring& default_prompt,
1994 const GURL& frame_url,
1995 const int flags,
1996 IPC::Message* reply_msg,
1997 bool* did_suppress_message) {
1998 // Suppress javascript messages when requested and when inside a constrained
1999 // popup window (because that activates them and breaks them out of the
2000 // constrained window jail).
2001 bool suppress_this_message = suppress_javascript_messages_;
2002 if (delegate())
2003 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:312004 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:322005
2006 *did_suppress_message = suppress_this_message;
2007
2008 if (!suppress_this_message) {
2009 base::TimeDelta time_since_last_message(
2010 base::TimeTicks::Now() - last_javascript_message_dismissal_);
2011 bool show_suppress_checkbox = false;
2012 // Show a checkbox offering to suppress further messages if this message is
2013 // being displayed within kJavascriptMessageExpectedDelay of the last one.
2014 if (time_since_last_message <
2015 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
2016 show_suppress_checkbox = true;
2017
2018 RunJavascriptMessageBox(AsWC(this), frame_url, flags, message, default_prompt,
2019 show_suppress_checkbox, reply_msg);
2020 } else {
2021 // If we are suppressing messages, just reply as is if the user immediately
2022 // pressed "Cancel".
2023 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
2024 }
2025}
2026
2027void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
2028 IPC::Message* reply_msg) {
2029 RunBeforeUnloadDialog(AsWC(this), message, reply_msg);
2030}
2031
2032void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
2033 const std::string& json_arguments,
2034 IPC::Message* reply_msg) {
2035 if (delegate()) {
2036 HtmlDialogUIDelegate* dialog_delegate =
2037 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
2038 reply_msg, AsWC(this));
2039 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
2040 }
2041}
2042
2043void TabContents::PasswordFormsSeen(
2044 const std::vector<PasswordForm>& forms) {
2045 GetPasswordManager()->PasswordFormsSeen(forms);
2046}
2047
2048void TabContents::AutofillFormSubmitted(
2049 const AutofillForm& form) {
2050 GetAutofillManager()->AutofillFormSubmitted(form);
2051}
2052
2053void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
2054 const std::wstring& user_text, int64 node_id, int request_id) {
2055 GetAutofillManager()->FetchValuesForName(field_name, user_text,
2056 kMaxAutofillMenuItems, node_id, request_id);
2057}
2058
2059void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
2060 const std::wstring& value) {
2061 GetAutofillManager()->RemoveValueForName(field_name, value);
2062}
2063
2064// Checks to see if we should generate a keyword based on the OSDD, and if
2065// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2066void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2067 int32 page_id, const GURL& url,
2068 bool autodetected) {
2069 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2070 DCHECK(url.is_valid());
2071 if (!IsActiveEntry(page_id))
2072 return;
2073 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2074 if (!url_model)
2075 return;
2076 if (!url_model->loaded()) {
2077 url_model->Load();
2078 return;
2079 }
2080 if (!profile()->GetTemplateURLFetcher())
2081 return;
2082
2083 if (profile()->IsOffTheRecord())
2084 return;
2085
2086 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2087 DCHECK(entry);
2088
2089 const NavigationEntry* base_entry = entry;
2090 if (IsFormSubmit(base_entry)) {
2091 // If the current page is a form submit, find the last page that was not
2092 // a form submit and use its url to generate the keyword from.
2093 int index = controller_.last_committed_entry_index() - 1;
2094 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2095 index--;
2096 if (index >= 0)
2097 base_entry = controller_.GetEntryAtIndex(index);
2098 else
2099 base_entry = NULL;
2100 }
2101
2102 // We want to use the user typed URL if available since that represents what
2103 // the user typed to get here, and fall back on the regular URL if not.
2104 if (!base_entry)
2105 return;
2106 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2107 base_entry->user_typed_url() : base_entry->url();
2108 if (!keyword_url.is_valid())
2109 return;
2110 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2111 autodetected);
2112 if (keyword.empty())
2113 return;
2114 const TemplateURL* template_url =
2115 url_model->GetTemplateURLForKeyword(keyword);
2116 if (template_url && (!template_url->safe_for_autoreplace() ||
2117 template_url->originating_url() == url)) {
2118 // Either there is a user created TemplateURL for this keyword, or the
2119 // keyword has the same OSDD url and we've parsed it.
2120 return;
2121 }
2122
2123 // Download the OpenSearch description document. If this is successful a
2124 // new keyword will be created when done.
2125#if defined(OS_WIN)
2126 gfx::NativeView ancestor = GetAncestor(view_->GetNativeView(), GA_ROOT);
2127#else
2128 gfx::NativeView ancestor = NULL;
2129#endif
2130 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2131 keyword,
2132 url,
2133 base_entry->favicon().url(),
2134 ancestor,
2135 autodetected);
2136}
2137
2138void TabContents::InspectElementReply(int num_resources) {
2139 // We have received reply from inspect element request. Notify the
2140 // automation provider in case we need to notify automation client.
2141 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:342142 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:322143 Details<int>(&num_resources));
2144}
2145
2146void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2147 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2148}
2149
2150void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2151 printing_.DidPrintPage(params);
2152}
2153
2154GURL TabContents::GetAlternateErrorPageURL() const {
2155 GURL url;
2156 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2157 if (profile()->IsOffTheRecord())
2158 return url;
2159
2160 PrefService* prefs = profile()->GetPrefs();
2161 DCHECK(prefs);
2162 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2163 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2164 url = google_util::AppendGoogleTLDParam(url);
2165 }
2166 return url;
2167}
2168
2169WebPreferences TabContents::GetWebkitPrefs() {
2170 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2171 bool isDomUI = false;
2172 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2173}
2174
2175void TabContents::OnMissingPluginStatus(int status) {
2176#if defined(OS_WIN)
2177// TODO(PORT): pull in when plug-ins work
2178 GetPluginInstaller()->OnMissingPluginStatus(status);
2179#endif
2180}
2181
2182void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2183#if defined(OS_WIN)
2184// TODO(PORT): pull in when plug-ins work
2185 DCHECK(!plugin_path.value().empty());
2186
2187 std::wstring plugin_name = plugin_path.ToWStringHack();
2188 scoped_ptr<FileVersionInfo> version_info(
2189 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2190 if (version_info.get()) {
2191 const std::wstring& product_name = version_info->product_name();
2192 if (!product_name.empty())
2193 plugin_name = product_name;
2194 }
2195 AddInfoBar(new SimpleAlertInfoBarDelegate(
2196 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2197 NULL));
2198#endif
2199}
2200
2201void TabContents::OnCrashedWorker() {
2202 AddInfoBar(new SimpleAlertInfoBarDelegate(
2203 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2204 NULL));
2205}
2206
2207void TabContents::OnJSOutOfMemory() {
2208 AddInfoBar(new SimpleAlertInfoBarDelegate(
2209 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2210}
2211
2212void TabContents::ShouldClosePage(bool proceed) {
2213 render_manager_.ShouldClosePage(proceed);
2214}
2215
2216void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2217 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342218 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322219 // delivered to a pending RenderViewHost. We must first run the onunload
2220 // handler of the old RenderViewHost before we can allow it to proceed.
2221 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2222 new_request_id);
2223}
2224
2225bool TabContents::CanBlur() const {
2226 return delegate() ? delegate()->CanBlur() : true;
2227}
2228
2229gfx::Rect TabContents::GetRootWindowResizerRect() const {
2230 if (delegate())
2231 return delegate()->GetRootWindowResizerRect();
2232 return gfx::Rect();
2233}
2234
2235void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2236 bool is_during_unload) {
2237 if (is_during_unload) {
2238 // Hang occurred while firing the beforeunload/unload handler.
2239 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112240 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322241
2242 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2243 return;
2244
2245 // If the tab hangs in the beforeunload/unload handler there's really
2246 // nothing we can do to recover. Pretend the unload listeners have
2247 // all fired and close the tab. If the hang is in the beforeunload handler
2248 // then the user will not have the option of cancelling the close.
2249 Close(rvh);
2250 return;
2251 }
2252
2253 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]8897c382009-05-06 17:53:262254 HungRendererDialog::ShowForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322255}
2256
2257void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]8897c382009-05-06 17:53:262258 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322259}
2260
2261void TabContents::LoadStateChanged(const GURL& url,
2262 net::LoadState load_state) {
2263 load_state_ = load_state;
2264 load_state_host_ = UTF8ToWide(url.host());
2265 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2266 SetNotWaitingForResponse();
2267 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502268 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322269}
2270
2271void TabContents::OnDidGetApplicationInfo(
2272 int32 page_id,
2273 const webkit_glue::WebApplicationInfo& info) {
2274 if (pending_install_.page_id != page_id)
2275 return; // The user clicked create on a separate page. Ignore this.
2276
2277 pending_install_.callback_functor =
2278 new GearsCreateShortcutCallbackFunctor(this);
2279 GearsCreateShortcut(
2280 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2281 NewCallback(pending_install_.callback_functor,
2282 &GearsCreateShortcutCallbackFunctor::Run));
2283}
2284
2285void TabContents::OnEnterOrSpace() {
2286 // See comment in RenderViewHostDelegate::OnEnterOrSpace as to why we do this.
2287#if defined(OS_WIN)
2288 // TODO(port): this is stubbed in BrowserProcess
2289 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2290 if (drm)
2291 drm->OnUserGesture(this);
2292#endif
2293}
2294
2295void TabContents::OnFindReply(int request_id,
2296 int number_of_matches,
2297 const gfx::Rect& selection_rect,
2298 int active_match_ordinal,
2299 bool final_update) {
2300 // Ignore responses for requests other than the one we have most recently
2301 // issued. That way we won't act on stale results when the user has
2302 // already typed in another query.
2303 if (request_id != current_find_request_id_)
2304 return;
2305
2306 if (number_of_matches == -1)
2307 number_of_matches = find_result_.number_of_matches();
2308 if (active_match_ordinal == -1)
2309 active_match_ordinal = find_result_.active_match_ordinal();
2310
2311 // Notify the UI, automation and any other observers that a find result was
2312 // found.
2313 find_result_ = FindNotificationDetails(request_id, number_of_matches,
2314 selection_rect, active_match_ordinal,
2315 final_update);
2316 NotificationService::current()->Notify(
2317 NotificationType::FIND_RESULT_AVAILABLE,
2318 Source<TabContents>(this),
2319 Details<FindNotificationDetails>(&find_result_));
2320}
2321
[email protected]829e7612009-04-25 01:15:112322bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322323 if (!delegate())
[email protected]829e7612009-04-25 01:15:112324 return false;
[email protected]420ae012009-04-24 05:16:322325
[email protected]829e7612009-04-25 01:15:112326 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322327}
2328
2329void TabContents::FileSelected(const FilePath& path,
2330 int index, void* params) {
2331 render_view_host()->FileSelected(path);
2332}
2333
2334void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2335 void* params) {
2336 render_view_host()->MultiFilesSelected(files);
2337}
2338
2339void TabContents::FileSelectionCanceled(void* params) {
2340 // If the user cancels choosing a file to upload we pass back an
2341 // empty vector.
2342 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2343}
2344
2345void TabContents::BeforeUnloadFiredFromRenderManager(
2346 bool proceed,
2347 bool* proceed_to_fire_unload) {
2348 if (delegate())
2349 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2350}
2351
2352void TabContents::UpdateRenderViewSizeForRenderManager() {
2353 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2354 view_->SizeContents(view_->GetContainerSize());
2355}
2356
2357DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
2358 return DOMUIFactory::CreateDOMUIForURL(AsWC(this), url);
2359}
2360
2361NavigationEntry*
2362TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2363 return controller_.GetLastCommittedEntry();
2364}
2365
2366bool TabContents::CreateRenderViewForRenderManager(
2367 RenderViewHost* render_view_host) {
2368 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2369 // mode before CreateRenderView is called. When we're asked to create a
2370 // RenderView, that means it's for the pending entry, so we have to use the
2371 // pending DOM UI.
2372 if (render_manager_.pending_dom_ui())
2373 render_view_host->AllowDOMUIBindings();
2374
2375 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2376 if (!render_view_host->CreateRenderView())
2377 return false;
2378
2379 // Now that the RenderView has been created, we need to tell it its size.
2380 rwh_view->SetSize(view_->GetContainerSize());
2381
2382 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2383 render_view_host);
2384 return true;
2385}
2386
2387void TabContents::Observe(NotificationType type,
2388 const NotificationSource& source,
2389 const NotificationDetails& details) {
2390 switch (type.value) {
2391 case NotificationType::BOOKMARK_MODEL_LOADED:
2392 // BookmarkModel finished loading, fall through to update starred state.
2393 case NotificationType::URLS_STARRED: {
2394 // Somewhere, a URL has been starred.
2395 // Ignore notifications for profiles other than our current one.
2396 Profile* source_profile = Source<Profile>(source).ptr();
2397 if (!source_profile || !source_profile->IsSameProfile(profile()))
2398 return;
2399
2400 UpdateStarredStateForCurrentURL();
2401 break;
2402 }
2403 case NotificationType::PREF_CHANGED: {
2404 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2405 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2406 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2407 UpdateAlternateErrorPageURL();
2408 } else if (*pref_name_in == prefs::kDefaultCharset ||
2409 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2410 ) {
2411 UpdateWebPreferences();
2412 } else {
2413 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2414 }
2415 break;
2416 }
2417 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2418 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2419 break;
2420
2421 case NotificationType::NAV_ENTRY_COMMITTED: {
2422 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2423
2424 NavigationController::LoadCommittedDetails& committed_details =
2425 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2426 ExpireInfoBars(committed_details);
2427 break;
2428 }
2429
2430 default:
2431 NOTREACHED();
2432 }
2433}