blob: af83bfd9c77763709dda2157539642d1d1ee0951 [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.
[email protected]0a2aeb82009-05-15 21:52:48922 GetDownloadShelf(true);
[email protected]96d185d2009-04-24 03:28:54923 }
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.
[email protected]0a2aeb82009-05-15 21:52:48954 tab_contents->GetDownloadShelf(true)->AddDownload(
[email protected]bcef0dc02009-02-28 00:35:02955 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]0a2aeb82009-05-15 21:52:48969DownloadShelf* TabContents::GetDownloadShelf(bool create) {
970 if (!download_shelf_.get() && create)
[email protected]bcef0dc02009-02-28 00:35:02971 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) {
[email protected]0a2aeb82009-05-15 21:52:48976 download_shelf_.reset(tab_contents->GetDownloadShelf(true));
[email protected]bcef0dc02009-02-28 00:35:02977 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
[email protected]571e31152009-05-15 19:34:021065void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
1066 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
1067}
1068
[email protected]420ae012009-04-24 05:16:321069void TabContents::OnSavePage() {
1070 // If we can not save the page, try to download it.
1071 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1072 DownloadManager* dlm = profile()->GetDownloadManager();
1073 const GURL& current_page_url = GetURL();
1074 if (dlm && current_page_url.is_valid())
[email protected]c9825a42009-05-01 22:51:501075 dlm->DownloadUrl(current_page_url, GURL(), "", AsWC(this));
[email protected]420ae012009-04-24 05:16:321076 return;
1077 }
1078
1079 Stop();
1080
1081 // Create the save package and possibly prompt the user for the name to save
1082 // the page as. The user prompt is an asynchronous operation that runs on
1083 // another thread.
1084 save_package_ = new SavePackage(AsWC(this));
1085 save_package_->GetSaveInfo();
1086}
1087
1088// Used in automated testing to bypass prompting the user for file names.
1089// Instead, the names and paths are hard coded rather than running them through
1090// file name sanitation and extension / mime checking.
1091void TabContents::SavePage(const std::wstring& main_file,
1092 const std::wstring& dir_path,
1093 SavePackage::SavePackageType save_type) {
1094 // Stop the page from navigating.
1095 Stop();
1096
1097 save_package_ = new SavePackage(AsWC(this), save_type,
1098 FilePath::FromWStringHack(main_file),
1099 FilePath::FromWStringHack(dir_path));
1100 save_package_->Init();
1101}
1102
1103void TabContents::PrintPreview() {
1104 // We don't show the print preview yet, only the print dialog.
1105 PrintNow();
1106}
1107
1108bool TabContents::PrintNow() {
1109 // We can't print interstitial page for now.
1110 if (showing_interstitial_page())
1111 return false;
1112
1113 return render_view_host()->PrintPages();
1114}
1115
1116bool TabContents::IsActiveEntry(int32 page_id) {
1117 NavigationEntry* active_entry = controller_.GetActiveEntry();
1118 return (active_entry != NULL &&
1119 active_entry->site_instance() == GetSiteInstance() &&
1120 active_entry->page_id() == page_id);
1121}
1122
[email protected]96d185d2009-04-24 03:28:541123// Notifies the RenderWidgetHost instance about the fact that the page is
1124// loading, or done loading and calls the base implementation.
1125void TabContents::SetIsLoading(bool is_loading,
1126 LoadNotificationDetails* details) {
1127 if (is_loading == is_loading_)
1128 return;
1129
1130 if (!is_loading) {
1131 load_state_ = net::LOAD_STATE_IDLE;
1132 load_state_host_.clear();
1133 }
1134
1135 render_manager_.SetIsLoading(is_loading);
1136
1137 is_loading_ = is_loading;
1138 waiting_for_response_ = is_loading;
1139
1140 if (delegate_)
1141 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351142 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541143
1144 NotificationType type = is_loading ? NotificationType::LOAD_START :
1145 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111146 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541147 if (details)
1148 det = Details<LoadNotificationDetails>(details);
1149 NotificationService::current()->Notify(type,
1150 Source<NavigationController>(&controller_),
1151 det);
1152}
1153
[email protected]76f68dc2009-03-10 20:31:321154#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:221155void TabContents::CreateBlockedPopupContainerIfNecessary() {
1156 if (blocked_popups_)
1157 return;
1158
1159 CRect client_rect;
1160 GetClientRect(GetNativeView(), &client_rect);
1161 gfx::Point anchor_position(
1162 client_rect.Width() - views::NativeScrollBar::GetVerticalScrollBarWidth(),
1163 client_rect.Height());
1164 blocked_popups_ = BlockedPopupContainer::Create(this, profile(),
1165 anchor_position);
1166 child_windows_.push_back(blocked_popups_);
1167}
1168
[email protected]b6c874582009-05-08 19:38:311169void TabContents::AddPopup(TabContents* new_contents,
1170 const gfx::Rect& initial_pos,
1171 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221172 CreateBlockedPopupContainerIfNecessary();
1173 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221174}
1175
[email protected]e69bce3dd2009-04-20 22:05:121176// TODO(brettw) This should be on the TabContentsView.
[email protected]d5f942ba2008-09-26 19:30:341177void TabContents::RepositionSupressedPopupsToFit(const gfx::Size& new_size) {
1178 // TODO(erg): There's no way to detect whether scroll bars are
1179 // visible, so for beta, we're just going to assume that the
1180 // vertical scroll bar is visible, and not care about covering up
1181 // the horizontal scroll bar. Fixing this is half of
1182 // http://b/1118139.
1183 gfx::Point anchor_position(
1184 new_size.width() -
[email protected]c2dacc92008-10-16 23:51:381185 views::NativeScrollBar::GetVerticalScrollBarWidth(),
[email protected]d5f942ba2008-09-26 19:30:341186 new_size.height());
[email protected]d6598c052008-11-05 19:03:251187
1188 if (blocked_popups_)
1189 blocked_popups_->RepositionConstrainedWindowTo(anchor_position);
[email protected]d5f942ba2008-09-26 19:30:341190}
1191
[email protected]b9681312008-11-07 00:08:261192bool TabContents::ShowingBlockedPopupNotification() const {
1193 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221194 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261195}
[email protected]332af7732009-03-11 13:21:351196#endif // defined(OS_WIN)
[email protected]616ed5a2008-11-21 22:27:241197
1198namespace {
1199bool TransitionIsReload(PageTransition::Type transition) {
1200 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1201}
1202}
1203
1204void TabContents::ExpireInfoBars(
1205 const NavigationController::LoadCommittedDetails& details) {
1206 // Only hide InfoBars when the user has done something that makes the main
1207 // frame load. We don't want various automatic or subframe navigations making
1208 // it disappear.
1209 if (!details.is_user_initiated_main_frame_load())
1210 return;
1211
[email protected]f86a07022008-11-25 01:06:051212 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241213 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051214 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241215 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241216 }
1217}
[email protected]fdd61c62009-04-22 19:22:571218
1219void TabContents::OnGearsCreateShortcutDone(
1220 const GearsShortcutData2& shortcut_data, bool success) {
1221 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1222 bool same_page =
1223 current_entry && pending_install_.page_id == current_entry->page_id();
1224
1225 if (success && same_page) {
1226 // Only switch to app mode if the user chose to create a shortcut and
1227 // we're still on the same page that it corresponded to.
1228 if (delegate())
1229 delegate()->ConvertContentsToApplication(this);
1230 }
1231
1232 // Reset the page id to indicate no requests are pending.
1233 pending_install_.page_id = 0;
1234 pending_install_.callback_functor = NULL;
1235}
[email protected]96d185d2009-04-24 03:28:541236
1237DOMUI* TabContents::GetDOMUIForCurrentState() {
1238 // When there is a pending navigation entry, we want to use the pending DOMUI
1239 // that goes along with it to control the basic flags. For example, we want to
1240 // show the pending URL in the URL bar, so we want the display_url flag to
1241 // be from the pending entry.
1242 //
1243 // The confusion comes because there are multiple possibilities for the
1244 // initial load in a tab as a side effect of the way the RenderViewHostManager
1245 // works.
1246 //
1247 // - For the very first tab the load looks "normal". The new tab DOM UI is
1248 // the pending one, and we want it to apply here.
1249 //
1250 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1251 // get switched to the one previously associated with the new tab pages.
1252 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1253 // have a committed DOM UI in this case.
1254 //
1255 // This condition handles all of these cases:
1256 //
1257 // - First load in first tab: no committed nav entry + pending nav entry +
1258 // pending dom ui:
1259 // -> Use pending DOM UI if any.
1260 //
1261 // - First load in second tab: no committed nav entry + pending nav entry +
1262 // no pending DOM UI:
1263 // -> Use the committed DOM UI if any.
1264 //
1265 // - Second navigation in any tab: committed nav entry + pending nav entry:
1266 // -> Use pending DOM UI if any.
1267 //
1268 // - Normal state with no load: committed nav entry + no pending nav entry:
1269 // -> Use committed DOM UI.
1270 if (controller_.pending_entry() &&
1271 (controller_.GetLastCommittedEntry() ||
1272 render_manager_.pending_dom_ui()))
1273 return render_manager_.pending_dom_ui();
1274 return render_manager_.dom_ui();
1275}
[email protected]420ae012009-04-24 05:16:321276
1277void TabContents::DidNavigateMainFramePostCommit(
1278 const NavigationController::LoadCommittedDetails& details,
1279 const ViewHostMsg_FrameNavigate_Params& params) {
1280 // Hide the download shelf if all the following conditions are true:
1281 // - there are no active downloads.
1282 // - this is a navigation to a different TLD.
1283 // - at least 5 seconds have elapsed since the download shelf was shown.
1284 // TODO(jcampan): bug 1156075 when user gestures are reliable, they should
1285 // be used to ensure we are hiding only on user initiated
1286 // navigations.
1287 DownloadManager* download_manager = profile()->GetDownloadManager();
1288 // download_manager can be NULL in unit test context.
1289 if (download_manager && download_manager->in_progress_count() == 0 &&
1290 !details.previous_url.is_empty() &&
1291 !net::RegistryControlledDomainService::SameDomainOrHost(
1292 details.previous_url, details.entry->url())) {
1293 base::TimeDelta time_delta(
1294 base::TimeTicks::Now() - last_download_shelf_show_);
1295 if (time_delta >
1296 base::TimeDelta::FromMilliseconds(kDownloadShelfHideDelay)) {
1297 SetDownloadShelfVisible(false);
1298 }
1299 }
1300
1301 if (details.is_user_initiated_main_frame_load()) {
1302 // Clear the status bubble. This is a workaround for a bug where WebKit
1303 // doesn't let us know that the cursor left an element during a
1304 // transition (this is also why the mouse cursor remains as a hand after
1305 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1306 // clear the bubble when a user navigates to a named anchor in the same
1307 // page.
1308 UpdateTargetURL(details.entry->page_id(), GURL());
1309
1310 // UpdateHelpersForDidNavigate will handle the case where the password_form
1311 // origin is valid.
1312 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1313 // cleaned up and covered by tests.
1314 if (!params.password_form.origin.is_valid())
1315 GetPasswordManager()->DidNavigate();
1316 }
1317
1318 // The keyword generator uses the navigation entries, so must be called after
1319 // the commit.
1320 GenerateKeywordIfNecessary(params);
1321
1322 // Allow the new page to set the title again.
1323 received_page_title_ = false;
1324
1325 // Get the favicon, either from history or request it from the net.
1326 fav_icon_helper_.FetchFavIcon(details.entry->url());
1327
[email protected]ce5c4502009-05-06 16:46:111328 // Disable all page actions.
1329 enabled_page_actions_.clear();
1330
[email protected]420ae012009-04-24 05:16:321331 // Close constrained popups if necessary.
1332 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1333
1334 // Update the starred state.
1335 UpdateStarredStateForCurrentURL();
1336}
1337
1338void TabContents::DidNavigateAnyFramePostCommit(
1339 RenderViewHost* render_view_host,
1340 const NavigationController::LoadCommittedDetails& details,
1341 const ViewHostMsg_FrameNavigate_Params& params) {
1342 // If we navigate, start showing messages again. This does nothing to prevent
1343 // a malicious script from spamming messages, since the script could just
1344 // reload the page to stop blocking.
1345 suppress_javascript_messages_ = false;
1346
1347 // Update history. Note that this needs to happen after the entry is complete,
1348 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1349 if (params.should_update_history) {
1350 // Most of the time, the displayURL matches the loaded URL, but for about:
1351 // URLs, we use a data: URL as the real value. We actually want to save
1352 // the about: URL to the history db and keep the data: URL hidden. This is
1353 // what the TabContents' URL getter does.
1354 UpdateHistoryForNavigation(GetURL(), params);
1355 }
1356
1357 // Notify the password manager of the navigation or form submit.
1358 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1359 // cleaned up and covered by tests.
1360 if (params.password_form.origin.is_valid())
1361 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1362}
1363
1364void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1365 const GURL& current_url) {
1366 if (net::RegistryControlledDomainService::SameDomainOrHost(
1367 previous_url, current_url))
1368 return;
1369
1370 // Clear out any child windows since we are leaving this page entirely.
1371 // We use indices instead of iterators in case CloseWindow does something
1372 // that may invalidate an iterator.
1373 int size = static_cast<int>(child_windows_.size());
1374 for (int i = size - 1; i >= 0; --i) {
1375 ConstrainedWindow* window = child_windows_[i];
1376 if (window)
1377 window->CloseConstrainedWindow();
1378 }
1379}
1380
1381void TabContents::UpdateStarredStateForCurrentURL() {
1382 BookmarkModel* model = profile()->GetBookmarkModel();
1383 const bool old_state = is_starred_;
1384 is_starred_ = (model && model->IsBookmarked(GetURL()));
1385
1386 if (is_starred_ != old_state && delegate())
1387 delegate()->URLStarredChanged(this, is_starred_);
1388}
1389
1390void TabContents::UpdateAlternateErrorPageURL() {
1391 GURL url = GetAlternateErrorPageURL();
1392 render_view_host()->SetAlternateErrorPageURL(url);
1393}
1394
1395void TabContents::UpdateWebPreferences() {
1396 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1397}
1398
1399void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1400 RenderViewHost* rvh) {
1401 // If we are creating a RVH for a restored controller, then we might
1402 // have more page IDs than the SiteInstance's current max page ID. We must
1403 // make sure that the max page ID is larger than any restored page ID.
1404 // Note that it is ok for conflicting page IDs to exist in another tab
1405 // (i.e., NavigationController), but if any page ID is larger than the max,
1406 // the back/forward list will get confused.
1407 int max_restored_page_id = controller_.max_restored_page_id();
1408 if (max_restored_page_id > 0) {
1409 int curr_max_page_id = site_instance->max_page_id();
1410 if (max_restored_page_id > curr_max_page_id) {
1411 // Need to update the site instance immediately.
1412 site_instance->UpdateMaxPageID(max_restored_page_id);
1413
1414 // Also tell the renderer to update its internal representation. We
1415 // need to reserve enough IDs to make all restored page IDs less than
1416 // the max.
1417 if (curr_max_page_id < 0)
1418 curr_max_page_id = 0;
1419 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1420 }
1421 }
1422}
1423
1424void TabContents::UpdateHistoryForNavigation(
1425 const GURL& display_url,
1426 const ViewHostMsg_FrameNavigate_Params& params) {
1427 if (profile()->IsOffTheRecord())
1428 return;
1429
1430 // Add to history service.
1431 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1432 if (hs) {
1433 if (PageTransition::IsMainFrame(params.transition) &&
1434 display_url != params.url) {
1435 // Hack on the "display" URL so that it will appear in history. For some
1436 // types of URLs, we will display a magic URL that is different from where
1437 // the page is actually navigated. We want the user to see in history
1438 // what they saw in the URL bar, so we add the display URL as a redirect.
1439 // This only applies to the main frame, as the display URL doesn't apply
1440 // to sub-frames.
1441 std::vector<GURL> redirects = params.redirects;
1442 if (!redirects.empty())
1443 redirects.back() = display_url;
1444 hs->AddPage(display_url, this, params.page_id, params.referrer,
1445 params.transition, redirects);
1446 } else {
1447 hs->AddPage(params.url, this, params.page_id, params.referrer,
1448 params.transition, params.redirects);
1449 }
1450 }
1451}
1452
1453bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1454 const std::wstring& title) {
1455 // For file URLs without a title, use the pathname instead. In the case of a
1456 // synthesized title, we don't want the update to count toward the "one set
1457 // per page of the title to history."
1458 std::wstring final_title;
1459 bool explicit_set;
1460 if (entry->url().SchemeIsFile() && title.empty()) {
1461 final_title = UTF8ToWide(entry->url().ExtractFileName());
1462 explicit_set = false; // Don't count synthetic titles toward the set limit.
1463 } else {
1464 TrimWhitespace(title, TRIM_ALL, &final_title);
1465 explicit_set = true;
1466 }
1467
1468 if (final_title == UTF16ToWideHack(entry->title()))
1469 return false; // Nothing changed, don't bother.
1470
1471 entry->set_title(WideToUTF16Hack(final_title));
1472
1473 // Update the history system for this page.
1474 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1475 HistoryService* hs =
1476 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1477 if (hs)
1478 hs->SetPageTitle(entry->display_url(), final_title);
1479
1480 // Don't allow the title to be saved again for explicitly set ones.
1481 received_page_title_ = explicit_set;
1482 }
1483
1484 // Lastly, set the title for the view.
1485 view_->SetPageTitle(final_title);
1486
1487 return true;
1488}
1489
1490void TabContents::NotifySwapped() {
1491 // After sending out a swap notification, we need to send a disconnect
1492 // notification so that clients that pick up a pointer to |this| can NULL the
1493 // pointer. See Bug 1230284.
1494 notify_disconnection_ = true;
1495 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341496 NotificationType::TAB_CONTENTS_SWAPPED,
1497 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321498 NotificationService::NoDetails());
1499}
1500
1501void TabContents::NotifyConnected() {
1502 notify_disconnection_ = true;
1503 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341504 NotificationType::TAB_CONTENTS_CONNECTED,
1505 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321506 NotificationService::NoDetails());
1507}
1508
1509void TabContents::NotifyDisconnected() {
1510 if (!notify_disconnection_)
1511 return;
1512
1513 notify_disconnection_ = false;
1514 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341515 NotificationType::TAB_CONTENTS_DISCONNECTED,
1516 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321517 NotificationService::NoDetails());
1518}
1519
1520void TabContents::GenerateKeywordIfNecessary(
1521 const ViewHostMsg_FrameNavigate_Params& params) {
1522 if (!params.searchable_form_url.is_valid())
1523 return;
1524
1525 if (profile()->IsOffTheRecord())
1526 return;
1527
1528 int last_index = controller_.last_committed_entry_index();
1529 // When there was no previous page, the last index will be 0. This is
1530 // normally due to a form submit that opened in a new tab.
1531 // TODO(brettw) bug 916126: we should support keywords when form submits
1532 // happen in new tabs.
1533 if (last_index <= 0)
1534 return;
1535 const NavigationEntry* previous_entry =
1536 controller_.GetEntryAtIndex(last_index - 1);
1537 if (IsFormSubmit(previous_entry)) {
1538 // Only generate a keyword if the previous page wasn't itself a form
1539 // submit.
1540 return;
1541 }
1542
1543 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1544 previous_entry->user_typed_url() : previous_entry->url();
1545 std::wstring keyword =
1546 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1547 if (keyword.empty())
1548 return;
1549
1550 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1551 if (!url_model)
1552 return;
1553
1554 if (!url_model->loaded()) {
1555 url_model->Load();
1556 return;
1557 }
1558
1559 const TemplateURL* current_url;
1560 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1561 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1562 return;
1563
1564 if (current_url) {
1565 if (current_url->originating_url().is_valid()) {
1566 // The existing keyword was generated from an OpenSearch description
1567 // document, don't regenerate.
1568 return;
1569 }
1570 url_model->Remove(current_url);
1571 }
1572 TemplateURL* new_url = new TemplateURL();
1573 new_url->set_keyword(keyword);
1574 new_url->set_short_name(keyword);
1575 new_url->SetURL(url, 0, 0);
1576 new_url->add_input_encoding(params.searchable_form_encoding);
1577 DCHECK(controller_.GetLastCommittedEntry());
1578 const GURL& favicon_url =
1579 controller_.GetLastCommittedEntry()->favicon().url();
1580 if (favicon_url.is_valid()) {
1581 new_url->SetFavIconURL(favicon_url);
1582 } else {
1583 // The favicon url isn't valid. This means there really isn't a favicon,
1584 // or the favicon url wasn't obtained before the load started. This assumes
1585 // the later.
1586 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1587 // its url.
1588 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1589 }
1590 new_url->set_safe_for_autoreplace(true);
1591 url_model->Add(new_url);
1592}
1593
1594RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1595 return view_.get();
1596}
1597
1598RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1599 return save_package_.get(); // May be NULL, but we can return NULL.
1600}
1601
1602Profile* TabContents::GetProfile() const {
1603 return profile();
1604}
1605
[email protected]6dfed102009-04-28 03:09:531606ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1607 RenderViewHost* render_view_host,
1608 const std::string& extension_id) {
1609 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1610 extension_id);
1611}
1612
[email protected]57c6a652009-05-04 07:58:341613TabContents* TabContents::GetAsTabContents() {
1614 return this;
1615}
1616
[email protected]420ae012009-04-24 05:16:321617void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1618 NavigationEntry* entry = controller_.GetActiveEntry();
1619 if (!entry)
1620 return;
1621
1622 // When we're creating views, we're still doing initial setup, so we always
1623 // use the pending DOM UI rather than any possibly existing committed one.
1624 if (render_manager_.pending_dom_ui()) {
1625 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1626 }
1627
1628 if (entry->IsViewSourceMode()) {
1629 // Put the renderer in view source mode.
1630 render_view_host->Send(
1631 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1632 }
[email protected]0666aef2009-05-13 19:48:081633
1634 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321635}
1636
1637void TabContents::RenderViewReady(RenderViewHost* rvh) {
1638 if (rvh != render_view_host()) {
1639 // Don't notify the world, since this came from a renderer in the
1640 // background.
1641 return;
1642 }
1643
1644 NotifyConnected();
1645 SetIsCrashed(false);
1646}
1647
1648void TabContents::RenderViewGone(RenderViewHost* rvh) {
1649 // Ask the print preview if this renderer was valuable.
1650 if (!printing_.OnRenderViewGone(rvh))
1651 return;
1652 if (rvh != render_view_host()) {
1653 // The pending page's RenderViewHost is gone.
1654 return;
1655 }
1656
1657 SetIsLoading(false, NULL);
1658 NotifyDisconnected();
1659 SetIsCrashed(true);
1660
1661 // Force an invalidation to render sad tab. The view will notice we crashed
1662 // when it paints.
1663 view_->Invalidate();
1664
1665 // Hide any visible hung renderer warning for this web contents' process.
[email protected]8897c382009-05-06 17:53:261666 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:321667}
1668
1669void TabContents::DidNavigate(RenderViewHost* rvh,
1670 const ViewHostMsg_FrameNavigate_Params& params) {
1671 if (PageTransition::IsMainFrame(params.transition))
1672 render_manager_.DidNavigateMainFrame(rvh);
1673
1674 // Update the site of the SiteInstance if it doesn't have one yet.
1675 if (!GetSiteInstance()->has_site())
1676 GetSiteInstance()->SetSite(params.url);
1677
1678 // Need to update MIME type here because it's referred to in
1679 // UpdateNavigationCommands() called by RendererDidNavigate() to
1680 // determine whether or not to enable the encoding menu.
1681 // It's updated only for the main frame. For a subframe,
1682 // RenderView::UpdateURL does not set params.contents_mime_type.
1683 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1684 // TODO(jungshik): Add a test for the encoding menu to avoid
1685 // regressing it again.
1686 if (PageTransition::IsMainFrame(params.transition))
1687 contents_mime_type_ = params.contents_mime_type;
1688
1689 NavigationController::LoadCommittedDetails details;
1690 if (!controller_.RendererDidNavigate(params, &details))
1691 return; // No navigation happened.
1692
1693 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1694 // for the appropriate notification (best) or you can add it to
1695 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1696 // necessary, please).
1697
1698 // Run post-commit tasks.
1699 if (details.is_main_frame)
1700 DidNavigateMainFramePostCommit(details, params);
1701 DidNavigateAnyFramePostCommit(rvh, details, params);
1702}
1703
1704void TabContents::UpdateState(RenderViewHost* rvh,
1705 int32 page_id,
1706 const std::string& state) {
1707 DCHECK(rvh == render_view_host());
1708
1709 // We must be prepared to handle state updates for any page, these occur
1710 // when the user is scrolling and entering form data, as well as when we're
1711 // leaving a page, in which case our state may have already been moved to
1712 // the next page. The navigation controller will look up the appropriate
1713 // NavigationEntry and update it when it is notified via the delegate.
1714
1715 int entry_index = controller_.GetEntryIndexWithPageID(
1716 GetSiteInstance(), page_id);
1717 if (entry_index < 0)
1718 return;
1719 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1720
1721 if (state == entry->content_state())
1722 return; // Nothing to update.
1723 entry->set_content_state(state);
1724 controller_.NotifyEntryChanged(entry, entry_index);
1725}
1726
1727void TabContents::UpdateTitle(RenderViewHost* rvh,
1728 int32 page_id, const std::wstring& title) {
1729 // If we have a title, that's a pretty good indication that we've started
1730 // getting useful data.
1731 SetNotWaitingForResponse();
1732
1733 DCHECK(rvh == render_view_host());
1734 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1735 page_id);
1736 if (!entry || !UpdateTitleForEntry(entry, title))
1737 return;
1738
1739 // Broadcast notifications when the UI should be updated.
1740 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501741 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321742}
1743
[email protected]420ae012009-04-24 05:16:321744void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1745 const std::wstring& encoding) {
1746 set_encoding(encoding);
1747}
1748
1749void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1750 if (delegate())
1751 delegate()->UpdateTargetURL(this, url);
1752}
1753
1754void TabContents::UpdateThumbnail(const GURL& url,
1755 const SkBitmap& bitmap,
1756 const ThumbnailScore& score) {
1757 // Tell History about this thumbnail
1758 HistoryService* hs;
1759 if (!profile()->IsOffTheRecord() &&
1760 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1761 hs->SetPageThumbnail(url, bitmap, score);
1762 }
1763}
1764
1765void TabContents::Close(RenderViewHost* rvh) {
1766 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1767 if (delegate() && rvh == render_view_host())
1768 delegate()->CloseContents(this);
1769}
1770
1771void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1772 if (delegate() && delegate()->IsPopup(this))
1773 delegate()->MoveContents(this, new_bounds);
1774}
1775
[email protected]329581b2009-04-28 06:52:351776void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321777 SetIsLoading(true, NULL);
1778}
1779
[email protected]329581b2009-04-28 06:52:351780void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321781 scoped_ptr<LoadNotificationDetails> details;
1782
1783 NavigationEntry* entry = controller_.GetActiveEntry();
1784 // An entry may not exist for a stop when loading an initial blank page or
1785 // if an iframe injected by script into a blank page finishes loading.
1786 if (entry) {
1787 scoped_ptr<base::ProcessMetrics> metrics(
1788 base::ProcessMetrics::CreateProcessMetrics(
1789 process()->process().handle()));
1790
1791 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1792
1793 details.reset(new LoadNotificationDetails(
1794 entry->display_url(),
1795 entry->transition_type(),
1796 elapsed,
1797 &controller_,
1798 controller_.GetCurrentEntryIndex()));
1799 }
1800
1801 // Tell PasswordManager we've finished a page load, which serves as a
1802 // green light to save pending passwords and reset itself.
1803 GetPasswordManager()->DidStopLoading();
1804
1805 SetIsLoading(false, details.get());
1806}
1807
1808void TabContents::DidStartProvisionalLoadForFrame(
1809 RenderViewHost* render_view_host,
1810 bool is_main_frame,
1811 const GURL& url) {
1812 ProvisionalLoadDetails details(is_main_frame,
1813 controller_.IsURLInPageNavigation(url),
1814 url, std::string(), false);
1815 NotificationService::current()->Notify(
1816 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1817 Source<NavigationController>(&controller_),
1818 Details<ProvisionalLoadDetails>(&details));
1819}
1820
1821void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1822 const GURL& source_url,
1823 const GURL& target_url) {
1824 NavigationEntry* entry;
1825 if (page_id == -1)
1826 entry = controller_.pending_entry();
1827 else
1828 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1829 if (!entry || entry->url() != source_url)
1830 return;
1831 entry->set_url(target_url);
1832}
1833
1834void TabContents::DidLoadResourceFromMemoryCache(
1835 const GURL& url,
1836 const std::string& frame_origin,
1837 const std::string& main_frame_origin,
1838 const std::string& security_info) {
1839 // Send out a notification that we loaded a resource from our memory cache.
1840 int cert_id = 0, cert_status = 0, security_bits = 0;
1841 SSLManager::DeserializeSecurityInfo(security_info,
1842 &cert_id, &cert_status,
1843 &security_bits);
1844 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]9ae66cbf2009-05-12 16:21:031845 process()->pid(), cert_id, cert_status);
[email protected]420ae012009-04-24 05:16:321846
1847 NotificationService::current()->Notify(
1848 NotificationType::LOAD_FROM_MEMORY_CACHE,
1849 Source<NavigationController>(&controller_),
1850 Details<LoadFromMemoryCacheDetails>(&details));
1851}
1852
1853void TabContents::DidFailProvisionalLoadWithError(
1854 RenderViewHost* render_view_host,
1855 bool is_main_frame,
1856 int error_code,
1857 const GURL& url,
1858 bool showing_repost_interstitial) {
1859 if (net::ERR_ABORTED == error_code) {
1860 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1861 // This means that the interstitial won't be torn down properly, which is
1862 // bad. But if we have an interstitial, go back to another tab type, and
1863 // then load the same interstitial again, we could end up getting the first
1864 // interstitial's "failed" message (as a result of the cancel) when we're on
1865 // the second one.
1866 //
1867 // We can't tell this apart, so we think we're tearing down the current page
1868 // which will cause a crash later one. There is also some code in
1869 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1870 // out because of this problem.
1871 //
1872 // http://code.google.com/p/chromium/issues/detail?id=2855
1873 // Because this will not tear down the interstitial properly, if "back" is
1874 // back to another tab type, the interstitial will still be somewhat alive
1875 // in the previous tab type. If you navigate somewhere that activates the
1876 // tab with the interstitial again, you'll see a flash before the new load
1877 // commits of the interstitial page.
1878 if (showing_interstitial_page()) {
1879 LOG(WARNING) << "Discarding message during interstitial.";
1880 return;
1881 }
1882
1883 // This will discard our pending entry if we cancelled the load (e.g., if we
1884 // decided to download the file instead of load it). Only discard the
1885 // pending entry if the URLs match, otherwise the user initiated a navigate
1886 // before the page loaded so that the discard would discard the wrong entry.
1887 NavigationEntry* pending_entry = controller_.pending_entry();
1888 if (pending_entry && pending_entry->url() == url)
1889 controller_.DiscardNonCommittedEntries();
1890
1891 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1892 }
1893
1894 // Send out a notification that we failed a provisional load with an error.
1895 ProvisionalLoadDetails details(is_main_frame,
1896 controller_.IsURLInPageNavigation(url),
1897 url, std::string(), false);
1898 details.set_error_code(error_code);
1899
1900 NotificationService::current()->Notify(
1901 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1902 Source<NavigationController>(&controller_),
1903 Details<ProvisionalLoadDetails>(&details));
1904}
1905
1906void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1907 int32 page_id,
1908 const GURL& icon_url) {
1909 fav_icon_helper_.SetFavIconURL(icon_url);
1910}
1911
1912void TabContents::DidDownloadImage(
1913 RenderViewHost* render_view_host,
1914 int id,
1915 const GURL& image_url,
1916 bool errored,
1917 const SkBitmap& image) {
1918 // A notification for downloading would be more flexible, but for now I'm
1919 // forwarding to the two places that could possibly have initiated the
1920 // request. If we end up with another place invoking DownloadImage, probably
1921 // best to refactor out into notification service, or something similar.
1922 if (errored)
1923 fav_icon_helper_.FavIconDownloadFailed(id);
1924 else
1925 fav_icon_helper_.SetFavIcon(id, image_url, image);
1926}
1927
1928void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1929 WindowOpenDisposition disposition) {
1930 if (render_manager_.dom_ui()) {
1931 // When we're a DOM UI, it will provide a page transition type for us (this
1932 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1933 // generated suggestions).
1934 //
1935 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161936 // want web sites to see a referrer of "chrome://blah" (and some
1937 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321938 // send to the site), so we send no referrer.
1939 OpenURL(url, GURL(), disposition,
1940 render_manager_.dom_ui()->link_transition_type());
1941 } else {
1942 OpenURL(url, referrer, disposition, PageTransition::LINK);
1943 }
1944}
1945
1946void TabContents::DomOperationResponse(const std::string& json_string,
1947 int automation_id) {
1948 DomOperationNotificationDetails details(json_string, automation_id);
1949 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341950 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321951 Details<DomOperationNotificationDetails>(&details));
1952}
1953
1954void TabContents::ProcessDOMUIMessage(const std::string& message,
1955 const std::string& content) {
1956 if (!render_manager_.dom_ui()) {
1957 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1958 // Because the renderer might be owned and sending random messages, we need
1959 // to ignore these inproper ones.
1960 NOTREACHED();
1961 return;
1962 }
1963 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1964}
1965
1966void TabContents::ProcessExternalHostMessage(const std::string& message,
1967 const std::string& origin,
1968 const std::string& target) {
1969 if (delegate())
1970 delegate()->ForwardMessageToExternalHost(message, origin, target);
1971}
1972
1973void TabContents::GoToEntryAtOffset(int offset) {
1974 controller_.GoToOffset(offset);
1975}
1976
1977void TabContents::GetHistoryListCount(int* back_list_count,
1978 int* forward_list_count) {
1979 int current_index = controller_.last_committed_entry_index();
1980 *back_list_count = current_index;
1981 *forward_list_count = controller_.entry_count() - current_index - 1;
1982}
1983
1984void TabContents::RunFileChooser(bool multiple_files,
1985 const string16& title,
1986 const FilePath& default_file) {
1987 if (!select_file_dialog_.get())
1988 select_file_dialog_ = SelectFileDialog::Create(this);
1989 SelectFileDialog::Type dialog_type =
1990 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
1991 SelectFileDialog::SELECT_OPEN_FILE;
1992 select_file_dialog_->SelectFile(dialog_type, title, default_file,
1993 NULL, 0, FILE_PATH_LITERAL(""),
1994 view_->GetTopLevelNativeWindow(), NULL);
1995}
1996
1997void TabContents::RunJavaScriptMessage(
1998 const std::wstring& message,
1999 const std::wstring& default_prompt,
2000 const GURL& frame_url,
2001 const int flags,
2002 IPC::Message* reply_msg,
2003 bool* did_suppress_message) {
2004 // Suppress javascript messages when requested and when inside a constrained
2005 // popup window (because that activates them and breaks them out of the
2006 // constrained window jail).
2007 bool suppress_this_message = suppress_javascript_messages_;
2008 if (delegate())
2009 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:312010 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:322011
2012 *did_suppress_message = suppress_this_message;
2013
2014 if (!suppress_this_message) {
2015 base::TimeDelta time_since_last_message(
2016 base::TimeTicks::Now() - last_javascript_message_dismissal_);
2017 bool show_suppress_checkbox = false;
2018 // Show a checkbox offering to suppress further messages if this message is
2019 // being displayed within kJavascriptMessageExpectedDelay of the last one.
2020 if (time_since_last_message <
2021 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
2022 show_suppress_checkbox = true;
2023
2024 RunJavascriptMessageBox(AsWC(this), frame_url, flags, message, default_prompt,
2025 show_suppress_checkbox, reply_msg);
2026 } else {
2027 // If we are suppressing messages, just reply as is if the user immediately
2028 // pressed "Cancel".
2029 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
2030 }
2031}
2032
2033void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
2034 IPC::Message* reply_msg) {
2035 RunBeforeUnloadDialog(AsWC(this), message, reply_msg);
2036}
2037
2038void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
2039 const std::string& json_arguments,
2040 IPC::Message* reply_msg) {
2041 if (delegate()) {
2042 HtmlDialogUIDelegate* dialog_delegate =
2043 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
2044 reply_msg, AsWC(this));
2045 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
2046 }
2047}
2048
2049void TabContents::PasswordFormsSeen(
2050 const std::vector<PasswordForm>& forms) {
2051 GetPasswordManager()->PasswordFormsSeen(forms);
2052}
2053
2054void TabContents::AutofillFormSubmitted(
2055 const AutofillForm& form) {
2056 GetAutofillManager()->AutofillFormSubmitted(form);
2057}
2058
2059void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
2060 const std::wstring& user_text, int64 node_id, int request_id) {
2061 GetAutofillManager()->FetchValuesForName(field_name, user_text,
2062 kMaxAutofillMenuItems, node_id, request_id);
2063}
2064
2065void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
2066 const std::wstring& value) {
2067 GetAutofillManager()->RemoveValueForName(field_name, value);
2068}
2069
2070// Checks to see if we should generate a keyword based on the OSDD, and if
2071// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2072void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2073 int32 page_id, const GURL& url,
2074 bool autodetected) {
2075 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2076 DCHECK(url.is_valid());
2077 if (!IsActiveEntry(page_id))
2078 return;
2079 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2080 if (!url_model)
2081 return;
2082 if (!url_model->loaded()) {
2083 url_model->Load();
2084 return;
2085 }
2086 if (!profile()->GetTemplateURLFetcher())
2087 return;
2088
2089 if (profile()->IsOffTheRecord())
2090 return;
2091
2092 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2093 DCHECK(entry);
2094
2095 const NavigationEntry* base_entry = entry;
2096 if (IsFormSubmit(base_entry)) {
2097 // If the current page is a form submit, find the last page that was not
2098 // a form submit and use its url to generate the keyword from.
2099 int index = controller_.last_committed_entry_index() - 1;
2100 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2101 index--;
2102 if (index >= 0)
2103 base_entry = controller_.GetEntryAtIndex(index);
2104 else
2105 base_entry = NULL;
2106 }
2107
2108 // We want to use the user typed URL if available since that represents what
2109 // the user typed to get here, and fall back on the regular URL if not.
2110 if (!base_entry)
2111 return;
2112 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2113 base_entry->user_typed_url() : base_entry->url();
2114 if (!keyword_url.is_valid())
2115 return;
2116 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2117 autodetected);
2118 if (keyword.empty())
2119 return;
2120 const TemplateURL* template_url =
2121 url_model->GetTemplateURLForKeyword(keyword);
2122 if (template_url && (!template_url->safe_for_autoreplace() ||
2123 template_url->originating_url() == url)) {
2124 // Either there is a user created TemplateURL for this keyword, or the
2125 // keyword has the same OSDD url and we've parsed it.
2126 return;
2127 }
2128
2129 // Download the OpenSearch description document. If this is successful a
2130 // new keyword will be created when done.
2131#if defined(OS_WIN)
2132 gfx::NativeView ancestor = GetAncestor(view_->GetNativeView(), GA_ROOT);
2133#else
2134 gfx::NativeView ancestor = NULL;
2135#endif
2136 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2137 keyword,
2138 url,
2139 base_entry->favicon().url(),
2140 ancestor,
2141 autodetected);
2142}
2143
2144void TabContents::InspectElementReply(int num_resources) {
2145 // We have received reply from inspect element request. Notify the
2146 // automation provider in case we need to notify automation client.
2147 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:342148 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:322149 Details<int>(&num_resources));
2150}
2151
2152void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2153 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2154}
2155
2156void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2157 printing_.DidPrintPage(params);
2158}
2159
2160GURL TabContents::GetAlternateErrorPageURL() const {
2161 GURL url;
2162 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2163 if (profile()->IsOffTheRecord())
2164 return url;
2165
2166 PrefService* prefs = profile()->GetPrefs();
2167 DCHECK(prefs);
2168 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2169 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2170 url = google_util::AppendGoogleTLDParam(url);
2171 }
2172 return url;
2173}
2174
2175WebPreferences TabContents::GetWebkitPrefs() {
2176 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2177 bool isDomUI = false;
2178 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2179}
2180
2181void TabContents::OnMissingPluginStatus(int status) {
2182#if defined(OS_WIN)
2183// TODO(PORT): pull in when plug-ins work
2184 GetPluginInstaller()->OnMissingPluginStatus(status);
2185#endif
2186}
2187
2188void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2189#if defined(OS_WIN)
2190// TODO(PORT): pull in when plug-ins work
2191 DCHECK(!plugin_path.value().empty());
2192
2193 std::wstring plugin_name = plugin_path.ToWStringHack();
2194 scoped_ptr<FileVersionInfo> version_info(
2195 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2196 if (version_info.get()) {
2197 const std::wstring& product_name = version_info->product_name();
2198 if (!product_name.empty())
2199 plugin_name = product_name;
2200 }
2201 AddInfoBar(new SimpleAlertInfoBarDelegate(
2202 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2203 NULL));
2204#endif
2205}
2206
2207void TabContents::OnCrashedWorker() {
2208 AddInfoBar(new SimpleAlertInfoBarDelegate(
2209 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2210 NULL));
2211}
2212
2213void TabContents::OnJSOutOfMemory() {
2214 AddInfoBar(new SimpleAlertInfoBarDelegate(
2215 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2216}
2217
2218void TabContents::ShouldClosePage(bool proceed) {
2219 render_manager_.ShouldClosePage(proceed);
2220}
2221
2222void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2223 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342224 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322225 // delivered to a pending RenderViewHost. We must first run the onunload
2226 // handler of the old RenderViewHost before we can allow it to proceed.
2227 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2228 new_request_id);
2229}
2230
2231bool TabContents::CanBlur() const {
2232 return delegate() ? delegate()->CanBlur() : true;
2233}
2234
2235gfx::Rect TabContents::GetRootWindowResizerRect() const {
2236 if (delegate())
2237 return delegate()->GetRootWindowResizerRect();
2238 return gfx::Rect();
2239}
2240
2241void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2242 bool is_during_unload) {
2243 if (is_during_unload) {
2244 // Hang occurred while firing the beforeunload/unload handler.
2245 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112246 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322247
2248 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2249 return;
2250
2251 // If the tab hangs in the beforeunload/unload handler there's really
2252 // nothing we can do to recover. Pretend the unload listeners have
2253 // all fired and close the tab. If the hang is in the beforeunload handler
2254 // then the user will not have the option of cancelling the close.
2255 Close(rvh);
2256 return;
2257 }
2258
2259 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]8897c382009-05-06 17:53:262260 HungRendererDialog::ShowForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322261}
2262
2263void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]8897c382009-05-06 17:53:262264 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322265}
2266
2267void TabContents::LoadStateChanged(const GURL& url,
2268 net::LoadState load_state) {
2269 load_state_ = load_state;
2270 load_state_host_ = UTF8ToWide(url.host());
2271 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2272 SetNotWaitingForResponse();
2273 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502274 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322275}
2276
2277void TabContents::OnDidGetApplicationInfo(
2278 int32 page_id,
2279 const webkit_glue::WebApplicationInfo& info) {
2280 if (pending_install_.page_id != page_id)
2281 return; // The user clicked create on a separate page. Ignore this.
2282
2283 pending_install_.callback_functor =
2284 new GearsCreateShortcutCallbackFunctor(this);
2285 GearsCreateShortcut(
2286 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2287 NewCallback(pending_install_.callback_functor,
2288 &GearsCreateShortcutCallbackFunctor::Run));
2289}
2290
2291void TabContents::OnEnterOrSpace() {
2292 // See comment in RenderViewHostDelegate::OnEnterOrSpace as to why we do this.
2293#if defined(OS_WIN)
2294 // TODO(port): this is stubbed in BrowserProcess
2295 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2296 if (drm)
2297 drm->OnUserGesture(this);
2298#endif
2299}
2300
2301void TabContents::OnFindReply(int request_id,
2302 int number_of_matches,
2303 const gfx::Rect& selection_rect,
2304 int active_match_ordinal,
2305 bool final_update) {
2306 // Ignore responses for requests other than the one we have most recently
2307 // issued. That way we won't act on stale results when the user has
2308 // already typed in another query.
2309 if (request_id != current_find_request_id_)
2310 return;
2311
2312 if (number_of_matches == -1)
2313 number_of_matches = find_result_.number_of_matches();
2314 if (active_match_ordinal == -1)
2315 active_match_ordinal = find_result_.active_match_ordinal();
2316
2317 // Notify the UI, automation and any other observers that a find result was
2318 // found.
2319 find_result_ = FindNotificationDetails(request_id, number_of_matches,
2320 selection_rect, active_match_ordinal,
2321 final_update);
2322 NotificationService::current()->Notify(
2323 NotificationType::FIND_RESULT_AVAILABLE,
2324 Source<TabContents>(this),
2325 Details<FindNotificationDetails>(&find_result_));
2326}
2327
[email protected]829e7612009-04-25 01:15:112328bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322329 if (!delegate())
[email protected]829e7612009-04-25 01:15:112330 return false;
[email protected]420ae012009-04-24 05:16:322331
[email protected]829e7612009-04-25 01:15:112332 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322333}
2334
2335void TabContents::FileSelected(const FilePath& path,
2336 int index, void* params) {
2337 render_view_host()->FileSelected(path);
2338}
2339
2340void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2341 void* params) {
2342 render_view_host()->MultiFilesSelected(files);
2343}
2344
2345void TabContents::FileSelectionCanceled(void* params) {
2346 // If the user cancels choosing a file to upload we pass back an
2347 // empty vector.
2348 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2349}
2350
2351void TabContents::BeforeUnloadFiredFromRenderManager(
2352 bool proceed,
2353 bool* proceed_to_fire_unload) {
2354 if (delegate())
2355 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2356}
2357
2358void TabContents::UpdateRenderViewSizeForRenderManager() {
2359 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2360 view_->SizeContents(view_->GetContainerSize());
2361}
2362
2363DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
2364 return DOMUIFactory::CreateDOMUIForURL(AsWC(this), url);
2365}
2366
2367NavigationEntry*
2368TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2369 return controller_.GetLastCommittedEntry();
2370}
2371
2372bool TabContents::CreateRenderViewForRenderManager(
2373 RenderViewHost* render_view_host) {
2374 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2375 // mode before CreateRenderView is called. When we're asked to create a
2376 // RenderView, that means it's for the pending entry, so we have to use the
2377 // pending DOM UI.
2378 if (render_manager_.pending_dom_ui())
2379 render_view_host->AllowDOMUIBindings();
2380
2381 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2382 if (!render_view_host->CreateRenderView())
2383 return false;
2384
2385 // Now that the RenderView has been created, we need to tell it its size.
2386 rwh_view->SetSize(view_->GetContainerSize());
2387
2388 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2389 render_view_host);
2390 return true;
2391}
2392
2393void TabContents::Observe(NotificationType type,
2394 const NotificationSource& source,
2395 const NotificationDetails& details) {
2396 switch (type.value) {
2397 case NotificationType::BOOKMARK_MODEL_LOADED:
2398 // BookmarkModel finished loading, fall through to update starred state.
2399 case NotificationType::URLS_STARRED: {
2400 // Somewhere, a URL has been starred.
2401 // Ignore notifications for profiles other than our current one.
2402 Profile* source_profile = Source<Profile>(source).ptr();
2403 if (!source_profile || !source_profile->IsSameProfile(profile()))
2404 return;
2405
2406 UpdateStarredStateForCurrentURL();
2407 break;
2408 }
2409 case NotificationType::PREF_CHANGED: {
2410 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2411 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2412 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2413 UpdateAlternateErrorPageURL();
2414 } else if (*pref_name_in == prefs::kDefaultCharset ||
2415 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2416 ) {
2417 UpdateWebPreferences();
2418 } else {
2419 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2420 }
2421 break;
2422 }
2423 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2424 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2425 break;
2426
2427 case NotificationType::NAV_ENTRY_COMMITTED: {
2428 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2429
2430 NavigationController::LoadCommittedDetails& committed_details =
2431 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2432 ExpireInfoBars(committed_details);
2433 break;
2434 }
2435
2436 default:
2437 NOTREACHED();
2438 }
2439}