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