blob: 3e15f1035e868dd4a1c98b977d4eb99367f9f328 [file] [log] [blame]
[email protected]ce5c4502009-05-06 16:46:111// Copyright (c) 2009 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]f3ec7742009-01-15 00:59:165#include "chrome/browser/tab_contents/tab_contents.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]a92b8642009-05-05 23:38:567#include "app/l10n_util.h"
[email protected]9929da92009-05-05 02:05:118#include "app/resource_bundle.h"
[email protected]420ae012009-04-24 05:16:329#include "base/file_version_info.h"
10#include "base/process_util.h"
[email protected]96d185d2009-04-24 03:28:5411#include "base/string16.h"
12#include "base/time.h"
[email protected]fdd61c62009-04-22 19:22:5713#include "chrome/browser/autofill_manager.h"
[email protected]420ae012009-04-24 05:16:3214#include "chrome/browser/bookmarks/bookmark_model.h"
[email protected]96d185d2009-04-24 03:28:5415#include "chrome/browser/browser_process.h"
initial.commit09911bf2008-07-26 23:55:2916#include "chrome/browser/cert_store.h"
[email protected]96d185d2009-04-24 03:28:5417#include "chrome/browser/debugger/devtools_manager.h"
[email protected]420ae012009-04-24 05:16:3218#include "chrome/browser/dom_operation_notification_details.h"
[email protected]96d185d2009-04-24 03:28:5419#include "chrome/browser/dom_ui/dom_ui.h"
20#include "chrome/browser/dom_ui/dom_ui_factory.h"
[email protected]bcef0dc02009-02-28 00:35:0221#include "chrome/browser/download/download_item_model.h"
[email protected]420ae012009-04-24 05:16:3222#include "chrome/browser/download/download_manager.h"
23#include "chrome/browser/download/download_request_manager.h"
[email protected]bcef0dc02009-02-28 00:35:0224#include "chrome/browser/download/download_shelf.h"
[email protected]bd1ad682009-05-15 22:19:1725#include "chrome/browser/download/download_started_animation.h"
[email protected]420ae012009-04-24 05:16:3226#include "chrome/browser/gears_integration.h"
27#include "chrome/browser/google_util.h"
[email protected]8897c382009-05-06 17:53:2628#include "chrome/browser/hung_renderer_dialog.h"
[email protected]420ae012009-04-24 05:16:3229#include "chrome/browser/jsmessage_box_handler.h"
30#include "chrome/browser/load_from_memory_cache_details.h"
31#include "chrome/browser/load_notification_details.h"
[email protected]fdd61c62009-04-22 19:22:5732#include "chrome/browser/password_manager/password_manager.h"
33#include "chrome/browser/plugin_installer.h"
[email protected]ce560f82009-06-03 09:39:4434#include "chrome/browser/profile.h"
[email protected]96d185d2009-04-24 03:28:5435#include "chrome/browser/renderer_host/render_widget_host_view.h"
36#include "chrome/browser/renderer_host/web_cache_manager.h"
[email protected]bd1ad682009-05-15 22:19:1737#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]f3ec7742009-01-15 00:59:1638#include "chrome/browser/tab_contents/navigation_entry.h"
39#include "chrome/browser/tab_contents/tab_contents_delegate.h"
[email protected]fdd61c62009-04-22 19:22:5740#include "chrome/browser/tab_contents/tab_contents_view.h"
[email protected]420ae012009-04-24 05:16:3241#include "chrome/browser/search_engines/template_url_fetcher.h"
42#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2743#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5644#include "chrome/common/notification_service.h"
[email protected]ce5c4502009-05-06 16:46:1145#include "chrome/common/page_action.h"
[email protected]bd1ad682009-05-15 22:19:1746#include "chrome/common/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2947#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0348#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3249#include "chrome/common/render_messages.h"
[email protected]96d185d2009-04-24 03:28:5450#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2651#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3252#include "grit/locale_settings.h"
53#include "net/base/mime_util.h"
54#include "net/base/net_errors.h"
[email protected]d686e812009-06-03 19:10:2955#include "net/base/net_util.h"
[email protected]420ae012009-04-24 05:16:3256#include "net/base/registry_controlled_domain.h"
[email protected]3e45ba92009-02-20 21:09:0057
58#if defined(OS_WIN)
59// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3260#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]0c9ee992009-06-03 16:56:3861#include "chrome/browser/views/blocked_popup_container.h"
[email protected]2362e4f2009-05-08 00:34:0562#include "views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0063#endif
initial.commit09911bf2008-07-26 23:55:2964
[email protected]420ae012009-04-24 05:16:3265// Cross-Site Navigations
66//
67// If a TabContents is told to navigate to a different web site (as determined
68// by SiteInstance), it will replace its current RenderViewHost with a new
69// RenderViewHost dedicated to the new SiteInstance. This works as follows:
70//
71// - Navigate determines whether the destination is cross-site, and if so,
72// it creates a pending_render_view_host_ and moves into the PENDING
73// RendererState.
74// - The pending RVH is "suspended," so that no navigation messages are sent to
75// its renderer until the onbeforeunload JavaScript handler has a chance to
76// run in the current RVH.
77// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
78// that it has a pending cross-site request. ResourceDispatcherHost will
79// check for this when the response arrives.
80// - The current RVH runs its onbeforeunload handler. If it returns false, we
81// cancel all the pending logic and go back to NORMAL. Otherwise we allow
82// the pending RVH to send the navigation request to its renderer.
83// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
84// checks CrossSiteRequestManager to see that the RVH responsible has a
85// pending cross-site request, and then installs a CrossSiteEventHandler.
86// - When RDH receives a response, the BufferedEventHandler determines whether
87// it is a download. If so, it sends a message to the new renderer causing
88// it to cancel the request, and the download proceeds in the download
89// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:3490// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:3291// doesn't affect any functionality.
92// - After RDH receives a response and determines that it is safe and not a
93// download, it pauses the response to first run the old page's onunload
94// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:3495// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:3296// to the current RVH.
97// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
98// the ResourceDispatcherHost, who unpauses the response. Data is then sent
99// to the pending RVH.
100// - The pending renderer sends a FrameNavigate message that invokes the
101// DidNavigate method. This replaces the current RVH with the
102// pending RVH and goes back to the NORMAL RendererState.
103
104namespace {
105
106// Amount of time we wait between when a key event is received and the renderer
107// is queried for its state and pushed to the NavigationEntry.
108const int kQueryStateDelay = 5000;
109
110const int kSyncWaitDelay = 40;
111
112// If another javascript message box is displayed within
113// kJavascriptMessageExpectedDelay of a previous javascript message box being
114// dismissed, display an option to suppress future message boxes from this
115// contents.
116const int kJavascriptMessageExpectedDelay = 1000;
117
118// Minimum amount of time in ms that has to elapse since the download shelf was
119// shown for us to hide it when navigating away from the current page.
120const int kDownloadShelfHideDelay = 5000;
121
122const char kLinkDoctorBaseURL[] =
123 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
124
125// The printer icon in shell32.dll. That's a standard icon user will quickly
126// recognize.
127const int kShell32PrinterIcon = 17;
128
129// The list of prefs we want to observe.
130const wchar_t* kPrefsToObserve[] = {
131 prefs::kAlternateErrorPagesEnabled,
132 prefs::kWebKitJavaEnabled,
133 prefs::kWebKitJavascriptEnabled,
134 prefs::kWebKitLoadsImagesAutomatically,
135 prefs::kWebKitPluginsEnabled,
136 prefs::kWebKitUsesUniversalDetector,
[email protected]96d3fb52009-05-27 14:51:21137 prefs::kWebKitDeveloperExtrasEnabled,
[email protected]420ae012009-04-24 05:16:32138 prefs::kWebKitSerifFontFamily,
139 prefs::kWebKitSansSerifFontFamily,
140 prefs::kWebKitFixedFontFamily,
141 prefs::kWebKitDefaultFontSize,
142 prefs::kWebKitDefaultFixedFontSize,
143 prefs::kDefaultCharset
144 // kWebKitStandardFontIsSerif needs to be added
145 // if we let users pick which font to use, serif or sans-serif when
146 // no font is specified or a CSS generic family (serif or sans-serif)
147 // is not specified.
148};
149
150const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
151
152// Limit on the number of suggestions to appear in the pop-up menu under an
153// text input element in a form.
154const int kMaxAutofillMenuItems = 6;
155
156// Returns true if the entry's transition type is FORM_SUBMIT.
157bool IsFormSubmit(const NavigationEntry* entry) {
158 return (PageTransition::StripQualifier(entry->transition_type()) ==
159 PageTransition::FORM_SUBMIT);
160}
161
162#if defined(OS_WIN)
163
164BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
165 // Note: erase is required to properly paint some widgets borders. This can
166 // be seen with textfields.
167 InvalidateRect(hwnd, NULL, TRUE);
168 return TRUE;
169}
170#endif
171
[email protected]57c6a652009-05-04 07:58:34172// TODO(brettw) TabContents should be removed, then this hack is unnecessary.
173TabContents* AsWC(TabContents* tc) {
174 return static_cast<TabContents*>(tc);
[email protected]420ae012009-04-24 05:16:32175}
176
177} // namespace
178
179// -----------------------------------------------------------------------------
180
[email protected]fdd61c62009-04-22 19:22:57181// static
182int TabContents::find_request_id_counter_ = -1;
183
[email protected]420ae012009-04-24 05:16:32184class TabContents::GearsCreateShortcutCallbackFunctor {
185 public:
186 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
187 : contents_(contents) {}
188
189 void Run(const GearsShortcutData2& shortcut_data, bool success) {
190 if (contents_)
191 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
192 delete this;
193 }
194 void Cancel() {
195 contents_ = NULL;
196 }
197
198 private:
199 TabContents* contents_;
200};
201
[email protected]57c6a652009-05-04 07:58:34202// TODO(brettw) many of the data members here have casts to TabContents.
203// This object is the same as TabContents and is currently being merged.
[email protected]fdd61c62009-04-22 19:22:57204// When this merge is done, the casts can be removed.
[email protected]420ae012009-04-24 05:16:32205TabContents::TabContents(Profile* profile,
206 SiteInstance* site_instance,
207 int routing_id,
208 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42209 : delegate_(NULL),
[email protected]ce3fa3c2009-04-20 19:55:57210 controller_(this, profile),
[email protected]57c6a652009-05-04 07:58:34211 view_(TabContentsView::Create(static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57212 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(
[email protected]57c6a652009-05-04 07:58:34213 static_cast<TabContents*>(this),
214 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57215 property_bag_(),
216 registrar_(),
[email protected]57c6a652009-05-04 07:58:34217 printing_(*static_cast<TabContents*>(this)),
[email protected]fdd61c62009-04-22 19:22:57218 save_package_(),
219 cancelable_consumer_(),
220 autofill_manager_(),
221 password_manager_(),
222 plugin_installer_(),
223 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(
[email protected]57c6a652009-05-04 07:58:34224 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57225 select_file_dialog_(),
226 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34227 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29228 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34229 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34230 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57231 current_load_start_(),
232 load_state_(net::LOAD_STATE_IDLE),
233 load_state_host_(),
234 received_page_title_(false),
235 is_starred_(false),
236 contents_mime_type_(),
237 encoding_(),
238 download_shelf_(),
239 shelf_visible_(false),
[email protected]332af7732009-03-11 13:21:35240 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57241 infobar_delegates_(),
242 last_download_shelf_show_(),
243 find_ui_active_(false),
244 find_op_aborted_(false),
245 current_find_request_id_(find_request_id_counter_++),
246 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12247 last_search_case_sensitive_(false),
248 last_search_prepopulate_text_(NULL),
249 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57250 capturing_contents_(false),
251 is_being_destroyed_(false),
252 notify_disconnection_(false),
253 history_requests_(),
254#if defined(OS_WIN)
255 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
256#endif
257 last_javascript_message_dismissal_(),
258 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32259 pending_install_.page_id = 0;
260 pending_install_.callback_functor = NULL;
261
262 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
263
264 view_->CreateView();
265
266 // Register for notifications about all interested prefs change.
267 PrefService* prefs = profile->GetPrefs();
268 if (prefs) {
269 for (int i = 0; i < kPrefsToObserveLength; ++i)
270 prefs->AddPrefObserver(kPrefsToObserve[i], this);
271 }
272
273 // Register for notifications about URL starredness changing on any profile.
274 registrar_.Add(this, NotificationType::URLS_STARRED,
275 NotificationService::AllSources());
276 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
277 NotificationService::AllSources());
278 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
279 NotificationService::AllSources());
280
281 // Keep a global copy of the previous search string (if any).
282 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12283 last_search_prepopulate_text_ = &global_last_search;
[email protected]332af7732009-03-11 13:21:35284}
initial.commit09911bf2008-07-26 23:55:29285
286TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32287 is_being_destroyed_ = true;
288
289 // We don't want any notifications while we're runnign our destructor.
290 registrar_.RemoveAll();
291
292 // Unregister the notifications of all observed prefs change.
293 PrefService* prefs = profile()->GetPrefs();
294 if (prefs) {
295 for (int i = 0; i < kPrefsToObserveLength; ++i)
296 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
297 }
298
299 // Clean up subwindows like plugins and the find in page bar.
300 view_->OnContentsDestroy();
301
302 NotifyDisconnected();
[email protected]8897c382009-05-06 17:53:26303 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:32304
305 if (pending_install_.callback_functor)
306 pending_install_.callback_functor->Cancel();
307
308 // First cleanly close all child windows.
309 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
310 // some of these to close. CloseWindows is async, so it might get called
311 // twice before it runs.
312 int size = static_cast<int>(child_windows_.size());
313 for (int i = size - 1; i >= 0; --i) {
314 ConstrainedWindow* window = child_windows_[i];
315 if (window)
316 window->CloseConstrainedWindow();
317 }
318
[email protected]420ae012009-04-24 05:16:32319 // Notify any observer that have a reference on this tab contents.
320 NotificationService::current()->Notify(
321 NotificationType::TAB_CONTENTS_DESTROYED,
322 Source<TabContents>(this),
323 NotificationService::NoDetails());
324
[email protected]1e5e74f2009-05-27 20:55:12325 // Notify any lasting InfobarDelegates that have not yet been removed that
326 // whatever infobar they were handling in this TabContents has closed,
327 // because the TabContents is going away entirely.
328 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
329 // notification may trigger infobars calls that access their delegate. (and
330 // some implementations of InfoBarDelegate do delete themselves on
331 // InfoBarClosed()).
332 for (int i = 0; i < infobar_delegate_count(); ++i) {
333 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
334 delegate->InfoBarClosed();
335 }
336 infobar_delegates_.clear();
337
[email protected]420ae012009-04-24 05:16:32338 // TODO(brettw) this should be moved to the view.
339#if defined(OS_WIN)
340 // If we still have a window handle, destroy it. GetNativeView can return
341 // NULL if this contents was part of a window that closed.
342 if (GetNativeView())
343 ::DestroyWindow(GetNativeView());
344#endif
initial.commit09911bf2008-07-26 23:55:29345}
346
[email protected]d5f942ba2008-09-26 19:30:34347// static
348void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32349 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
350
351 WebPreferences pref_defaults;
352 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
353 pref_defaults.javascript_enabled);
354 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
355 pref_defaults.web_security_enabled);
356 prefs->RegisterBooleanPref(
357 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
358 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
359 pref_defaults.loads_images_automatically);
360 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
361 pref_defaults.plugins_enabled);
362 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
363 pref_defaults.dom_paste_enabled);
364 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
365 pref_defaults.shrinks_standalone_images_to_fit);
366 prefs->RegisterBooleanPref(prefs::kWebKitDeveloperExtrasEnabled,
[email protected]96d3fb52009-05-27 14:51:21367 pref_defaults.developer_extras_enabled);
[email protected]0df30122009-06-03 12:13:08368 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
369 pref_defaults.inspector_settings);
[email protected]420ae012009-04-24 05:16:32370 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
371 pref_defaults.text_areas_are_resizable);
372 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
373 pref_defaults.java_enabled);
374
375 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
376 IDS_ACCEPT_LANGUAGES);
377 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
378 IDS_DEFAULT_ENCODING);
379 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
380 IDS_STANDARD_FONT_IS_SERIF);
381 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
382 IDS_FIXED_FONT_FAMILY);
383 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
384 IDS_SERIF_FONT_FAMILY);
385 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
386 IDS_SANS_SERIF_FONT_FAMILY);
387 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
388 IDS_CURSIVE_FONT_FAMILY);
389 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
390 IDS_FANTASY_FONT_FAMILY);
391 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
392 IDS_DEFAULT_FONT_SIZE);
393 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
394 IDS_DEFAULT_FIXED_FONT_SIZE);
395 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
396 IDS_MINIMUM_FONT_SIZE);
397 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
398 IDS_MINIMUM_LOGICAL_FONT_SIZE);
399 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
400 IDS_USES_UNIVERSAL_DETECTOR);
401 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
402 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29403}
404
[email protected]d5f942ba2008-09-26 19:30:34405bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01406 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55407 return true;
[email protected]d5f942ba2008-09-26 19:30:34408}
409
[email protected]6e95706d2009-04-23 22:55:01410AutofillManager* TabContents::GetAutofillManager() {
411 if (autofill_manager_.get() == NULL)
412 autofill_manager_.reset(new AutofillManager(this));
413 return autofill_manager_.get();
414}
415
416PasswordManager* TabContents::GetPasswordManager() {
417 if (password_manager_.get() == NULL)
418 password_manager_.reset(new PasswordManager(this));
419 return password_manager_.get();
420}
421
422PluginInstaller* TabContents::GetPluginInstaller() {
423 if (plugin_installer_.get() == NULL)
424 plugin_installer_.reset(new PluginInstaller(this));
425 return plugin_installer_.get();
426}
427
[email protected]d5f942ba2008-09-26 19:30:34428const GURL& TabContents::GetURL() const {
429 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57430 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34431 return entry ? entry->display_url() : GURL::EmptyGURL();
432}
433
[email protected]96d185d2009-04-24 03:28:54434const string16& TabContents::GetTitle() const {
435 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
436 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
437 if (our_dom_ui) {
438 // Don't override the title in view source mode.
439 NavigationEntry* entry = controller_.GetActiveEntry();
440 if (!(entry && entry->IsViewSourceMode())) {
441 // Give the DOM UI the chance to override our title.
442 const string16& title = our_dom_ui->overridden_title();
443 if (!title.empty())
444 return title;
445 }
446 }
447
448 // We use the title for the last committed entry rather than a pending
449 // navigation entry. For example, when the user types in a URL, we want to
450 // keep the old page's title until the new load has committed and we get a new
451 // title.
452 // The exception is with transient pages, for which we really want to use
453 // their title, as they are not committed.
454 NavigationEntry* entry = controller_.GetTransientEntry();
455 if (entry)
456 return entry->GetTitleForDisplay(&controller_);
457
458 entry = controller_.GetLastCommittedEntry();
459 if (entry)
460 return entry->GetTitleForDisplay(&controller_);
461 else if (controller_.LoadingURLLazily())
462 return controller_.GetLazyTitle();
463 return EmptyString16();
464}
465
[email protected]d5f942ba2008-09-26 19:30:34466int32 TabContents::GetMaxPageID() {
467 if (GetSiteInstance())
468 return GetSiteInstance()->max_page_id();
469 else
470 return max_page_id_;
471}
472
473void TabContents::UpdateMaxPageID(int32 page_id) {
474 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34475 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34476 // testing.
477 if (GetSiteInstance())
478 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34479 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34480}
481
[email protected]96d185d2009-04-24 03:28:54482SiteInstance* TabContents::GetSiteInstance() const {
483 return render_manager_.current_host()->site_instance();
484}
485
[email protected]d5f942ba2008-09-26 19:30:34486const std::wstring TabContents::GetDefaultTitle() const {
487 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
488}
489
[email protected]96d185d2009-04-24 03:28:54490bool TabContents::ShouldDisplayURL() {
491 // Don't hide the url in view source mode.
492 NavigationEntry* entry = controller_.GetActiveEntry();
493 if (entry && entry->IsViewSourceMode())
494 return true;
495 DOMUI* dom_ui = GetDOMUIForCurrentState();
496 if (dom_ui)
497 return !dom_ui->should_hide_url();
498 return true;
499}
500
[email protected]d5f942ba2008-09-26 19:30:34501SkBitmap TabContents::GetFavIcon() const {
502 // Like GetTitle(), we also want to use the favicon for the last committed
503 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57504 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47505 if (entry)
506 return entry->favicon().bitmap();
507
[email protected]ce3fa3c2009-04-20 19:55:57508 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34509 if (entry)
510 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57511 else if (controller_.LoadingURLLazily())
512 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34513 return SkBitmap();
514}
515
[email protected]96d185d2009-04-24 03:28:54516bool TabContents::ShouldDisplayFavIcon() {
517 // Always display a throbber during pending loads.
518 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
519 return true;
520
521 DOMUI* dom_ui = GetDOMUIForCurrentState();
522 if (dom_ui)
523 return !dom_ui->hide_favicon();
524 return true;
525}
526
[email protected]3e45ba92009-02-20 21:09:00527#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34528SecurityStyle TabContents::GetSecurityStyle() const {
529 // We may not have a navigation entry yet.
[email protected]ce3fa3c2009-04-20 19:55:57530 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34531 return entry ? entry->ssl().security_style() : SECURITY_STYLE_UNKNOWN;
532}
533
534bool TabContents::GetSSLEVText(std::wstring* ev_text,
535 std::wstring* ev_tooltip_text) const {
536 DCHECK(ev_text && ev_tooltip_text);
537 ev_text->clear();
538 ev_tooltip_text->clear();
539
[email protected]ce3fa3c2009-04-20 19:55:57540 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34541 if (!entry ||
542 net::IsCertStatusError(entry->ssl().cert_status()) ||
543 ((entry->ssl().cert_status() & net::CERT_STATUS_IS_EV) == 0))
544 return false;
545
546 scoped_refptr<net::X509Certificate> cert;
547 CertStore::GetSharedInstance()->RetrieveCert(entry->ssl().cert_id(), &cert);
548 if (!cert.get()) {
549 NOTREACHED();
550 return false;
551 }
552
553 return SSLManager::GetEVCertNames(*cert, ev_text, ev_tooltip_text);
554}
[email protected]76f68dc2009-03-10 20:31:32555#endif
[email protected]d5f942ba2008-09-26 19:30:34556
[email protected]96d185d2009-04-24 03:28:54557std::wstring TabContents::GetStatusText() const {
558 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
559 return std::wstring();
560
561 switch (load_state_) {
562 case net::LOAD_STATE_WAITING_FOR_CACHE:
563 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
564 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
565 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
566 case net::LOAD_STATE_RESOLVING_HOST:
567 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
568 case net::LOAD_STATE_CONNECTING:
569 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
570 case net::LOAD_STATE_SENDING_REQUEST:
571 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
572 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
573 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
574 load_state_host_);
575 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
576 case net::LOAD_STATE_IDLE:
577 case net::LOAD_STATE_READING_RESPONSE:
578 break;
579 }
580
581 return std::wstring();
582}
583
[email protected]d5f942ba2008-09-26 19:30:34584void TabContents::SetIsCrashed(bool state) {
585 if (state == is_crashed_)
586 return;
587
588 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50589 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34590}
591
[email protected]ce5c4502009-05-06 16:46:11592void TabContents::EnablePageAction(const PageAction* page_action) {
593 DCHECK(page_action);
594
595 if (IsPageActionEnabled(page_action))
596 return; // Already enabled.
597
598 enabled_page_actions_.insert(page_action);
599}
600
601bool TabContents::IsPageActionEnabled(const PageAction* page_action) {
602 DCHECK(page_action);
603 return enabled_page_actions_.end() != enabled_page_actions_.find(page_action);
604}
605
606
[email protected]d5f942ba2008-09-26 19:30:34607void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
608 if (delegate_)
609 delegate_->NavigationStateChanged(this, changed_flags);
610}
611
[email protected]96d185d2009-04-24 03:28:54612void TabContents::DidBecomeSelected() {
613 controller_.SetActive(true);
614
615 if (render_widget_host_view())
616 render_widget_host_view()->DidBecomeSelected();
617
618 // If pid() is -1, that means the RenderProcessHost still hasn't been
619 // initialized. It'll register with CacheManagerHost when it is.
620 if (process()->pid() != -1)
621 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
622}
623
624void TabContents::WasHidden() {
625 if (!capturing_contents()) {
626 // |render_view_host()| can be NULL if the user middle clicks a link to open
627 // a tab in then background, then closes the tab before selecting it. This
628 // is because closing the tab calls TabContents::Destroy(), which removes
629 // the |render_view_host()|; then when we actually destroy the window,
630 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
631 if (render_widget_host_view())
632 render_widget_host_view()->WasHidden();
633
634 // Loop through children and send WasHidden to them, too.
635 int count = static_cast<int>(child_windows_.size());
636 for (int i = count - 1; i >= 0; --i) {
637 ConstrainedWindow* window = child_windows_.at(i);
638 window->WasHidden();
639 }
640 }
641
642 NotificationService::current()->Notify(
643 NotificationType::TAB_CONTENTS_HIDDEN,
644 Source<TabContents>(this),
645 NotificationService::NoDetails());
646}
647
[email protected]d5f942ba2008-09-26 19:30:34648void TabContents::Activate() {
649 if (delegate_)
650 delegate_->ActivateContents(this);
651}
652
[email protected]96d185d2009-04-24 03:28:54653void TabContents::ShowContents() {
654 if (render_widget_host_view())
655 render_widget_host_view()->DidBecomeSelected();
656
657 // Loop through children and send DidBecomeSelected to them, too.
658 int count = static_cast<int>(child_windows_.size());
659 for (int i = count - 1; i >= 0; --i) {
660 ConstrainedWindow* window = child_windows_.at(i);
661 window->DidBecomeSelected();
662 }
663}
664
665void TabContents::HideContents() {
666 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
667 // our superclass HideContents(), because some callers want to be very picky
668 // about the order in which these get called. In addition to making the code
669 // here practically impossible to understand, this also means we end up
670 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34671 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54672 WasHidden();
673}
674
[email protected]c0588052008-10-27 23:01:50675void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34676 WindowOpenDisposition disposition,
677 PageTransition::Type transition) {
678 if (delegate_)
[email protected]c0588052008-10-27 23:01:50679 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34680}
681
682bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54683 const NavigationEntry& entry = *controller_.pending_entry();
684
685 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
686 if (!dest_render_view_host)
687 return false; // Unable to create the desired render view host.
688
689 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]684b4ba22009-05-07 06:27:41690 DevToolsManager* devtools_manager = g_browser_process->devtools_manager();
[email protected]7e8e6b62009-05-08 11:28:32691 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41692 devtools_manager->OnNavigatingToPendingEntry(
693 render_view_host(),
694 dest_render_view_host,
695 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32696 }
[email protected]96d185d2009-04-24 03:28:54697
698 // Used for page load time metrics.
699 current_load_start_ = base::TimeTicks::Now();
700
701 // Navigate in the desired RenderViewHost.
702 dest_render_view_host->NavigateToEntry(entry, reload);
703
704 if (entry.page_id() == -1) {
705 // HACK!! This code suppresses javascript: URLs from being added to
706 // session history, which is what we want to do for javascript: URLs that
707 // do not generate content. What we really need is a message from the
708 // renderer telling us that a new page was not created. The same message
709 // could be used for mailto: URLs and the like.
710 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
711 return false;
712 }
713
714 // Clear any provisional password saves - this stops password infobars
715 // showing up on pages the user navigates to while the right page is
716 // loading.
717 GetPasswordManager()->ClearProvisionalSave();
718
719 if (reload && !profile()->IsOffTheRecord()) {
720 HistoryService* history =
721 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
722 if (history)
723 history->SetFavIconOutOfDateForPage(entry.url());
724 }
725
[email protected]d5f942ba2008-09-26 19:30:34726 return true;
727}
728
[email protected]96d185d2009-04-24 03:28:54729void TabContents::Stop() {
730 render_manager_.Stop();
731 printing_.Stop();
732}
733
734void TabContents::Cut() {
735 render_view_host()->Cut();
736}
737
738void TabContents::Copy() {
739 render_view_host()->Copy();
740}
741
742void TabContents::Paste() {
743 render_view_host()->Paste();
744}
745
746void TabContents::DisassociateFromPopupCount() {
747 render_view_host()->DisassociateFromPopupCount();
748}
749
750TabContents* TabContents::Clone() {
751 // We create a new SiteInstance so that the new tab won't share processes
752 // with the old one. This can be changed in the future if we need it to share
753 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32754 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54755 SiteInstance::CreateSiteInstance(profile()),
756 MSG_ROUTING_NONE, NULL);
757 tc->controller().CopyStateFrom(controller_);
758 return tc;
759}
760
[email protected]420ae012009-04-24 05:16:32761void TabContents::CreateShortcut() {
762 NavigationEntry* entry = controller_.GetLastCommittedEntry();
763 if (!entry)
764 return;
765
766 // We only allow one pending install request. By resetting the page id we
767 // effectively cancel the pending install request.
768 pending_install_.page_id = entry->page_id();
769 pending_install_.icon = GetFavIcon();
770 pending_install_.title = UTF16ToWideHack(GetTitle());
771 pending_install_.url = GetURL();
772 if (pending_install_.callback_functor) {
773 pending_install_.callback_functor->Cancel();
774 pending_install_.callback_functor = NULL;
775 }
776 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
777 if (pending_install_.title.empty())
778 pending_install_.title = UTF8ToWide(GetURL().spec());
779
780 // Request the application info. When done OnDidGetApplicationInfo is invoked
781 // and we'll create the shortcut.
782 render_view_host()->GetApplicationInfo(pending_install_.page_id);
783}
784
[email protected]76f68dc2009-03-10 20:31:32785#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29786ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]c2dacc92008-10-16 23:51:38787 views::WindowDelegate* window_delegate,
788 views::View* contents_view) {
initial.commit09911bf2008-07-26 23:55:29789 ConstrainedWindow* window =
790 ConstrainedWindow::CreateConstrainedDialog(
791 this, gfx::Rect(), contents_view, window_delegate);
792 child_windows_.push_back(window);
793 return window;
794}
[email protected]f3332e12009-03-23 15:28:57795#endif
initial.commit09911bf2008-07-26 23:55:29796
797void TabContents::AddNewContents(TabContents* new_contents,
798 WindowOpenDisposition disposition,
799 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22800 bool user_gesture,
801 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29802 if (!delegate_)
803 return;
804
[email protected]f3332e12009-03-23 15:28:57805#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:22806 bool constrain_popup = false;
[email protected]35f7d212009-04-29 21:19:27807 if ((disposition == NEW_POPUP) && !user_gesture &&
808 !CommandLine::ForCurrentProcess()->HasSwitch(
809 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22810 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31811 // the whitelist. The popup owner will handle checking this.
812 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
813 initial_pos,
814 creator_url.is_valid() ? creator_url.host() : std::string());
815 } else {
[email protected]0aa55312008-10-17 21:53:08816 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29817 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
818 user_gesture);
819 }
[email protected]b6c874582009-05-08 19:38:31820 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
[email protected]f3332e12009-03-23 15:28:57821#else
822 // TODO(port): implement the popup blocker stuff
823 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
824 user_gesture);
825#endif
initial.commit09911bf2008-07-26 23:55:29826}
827
[email protected]0c9ee992009-06-03 16:56:38828#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29829void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25830 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22831 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29832}
[email protected]0c9ee992009-06-03 16:56:38833#endif
initial.commit09911bf2008-07-26 23:55:29834
[email protected]96d185d2009-04-24 03:28:54835void TabContents::PopupNotificationVisibilityChanged(bool visible) {
836 render_view_host()->PopupNotificationVisibilityChanged(visible);
837}
838
839gfx::NativeView TabContents::GetContentNativeView() {
840 return view_->GetContentNativeView();
841}
842
843gfx::NativeView TabContents::GetNativeView() const {
844 return view_->GetNativeView();
845}
846
847void TabContents::GetContainerBounds(gfx::Rect *out) const {
848 view_->GetContainerBounds(out);
849}
850
851void TabContents::Focus() {
852 view_->Focus();
853}
854
855void TabContents::SetInitialFocus(bool reverse) {
856 render_view_host()->SetInitialFocus(reverse);
857}
858
859bool TabContents::FocusLocationBarByDefault() {
860 DOMUI* dom_ui = GetDOMUIForCurrentState();
861 if (dom_ui)
862 return dom_ui->focus_location_bar_by_default();
863 return false;
864}
865
[email protected]616ed5a2008-11-21 22:27:24866void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
867 // Look through the existing InfoBarDelegates we have for a match. If we've
868 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05869 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24870 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
871 return;
872 }
873
874 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56875 NotificationService::current()->Notify(
876 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
877 Source<TabContents>(this),
878 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24879
880 // Add ourselves as an observer for navigations the first time a delegate is
881 // added. We use this notification to expire InfoBars that need to expire on
882 // page transitions.
883 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56884 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57885 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24886 }
887}
888
889void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
890 std::vector<InfoBarDelegate*>::iterator it =
891 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
892 if (it != infobar_delegates_.end()) {
893 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56894 NotificationService::current()->Notify(
895 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
896 Source<TabContents>(this),
897 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05898 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24899
[email protected]6a02963e2009-01-06 16:58:03900 // Remove ourselves as an observer if we are tracking no more InfoBars.
901 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56902 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57903 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03904 }
[email protected]616ed5a2008-11-21 22:27:24905 }
906}
[email protected]3edd9522009-03-04 22:19:41907
[email protected]96d185d2009-04-24 03:28:54908bool TabContents::IsBookmarkBarAlwaysVisible() {
909 // See GetDOMUIForCurrentState() comment for more info. This case is very
910 // similar, but for non-first loads, we want to use the committed entry. This
911 // is so the bookmarks bar disappears at the same time the page does.
912 if (controller_.GetLastCommittedEntry()) {
913 // Not the first load, always use the committed DOM UI.
914 if (render_manager_.dom_ui())
915 return render_manager_.dom_ui()->force_bookmark_bar_visible();
916 return false; // Default.
917 }
918
919 // When it's the first load, we know either the pending one or the committed
920 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
921 // of them will be valid, so we can just check both.
922 if (render_manager_.pending_dom_ui())
923 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
924 if (render_manager_.dom_ui())
925 return render_manager_.dom_ui()->force_bookmark_bar_visible();
926 return false; // Default.
927}
928
929void TabContents::SetDownloadShelfVisible(bool visible) {
930 if (shelf_visible_ != visible) {
931 if (visible) {
932 // Invoke GetDownloadShelf to force the shelf to be created.
[email protected]0a2aeb82009-05-15 21:52:48933 GetDownloadShelf(true);
[email protected]96d185d2009-04-24 03:28:54934 }
935 shelf_visible_ = visible;
936
[email protected]c9cd2222009-05-06 05:16:50937 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]3a6a3b62009-05-27 21:36:20938
939 if (delegate())
940 delegate()->UpdateDownloadShelfVisibility(visible);
[email protected]96d185d2009-04-24 03:28:54941 }
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);
[email protected]d5f942ba2008-09-26 19:30:34963
964 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31965 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34966
[email protected]bcef0dc02009-02-28 00:35:02967 // GetDownloadShelf creates the download shelf if it was not yet created.
[email protected]0a2aeb82009-05-15 21:52:48968 tab_contents->GetDownloadShelf(true)->AddDownload(
[email protected]bcef0dc02009-02-28 00:35:02969 new DownloadItemModel(download));
[email protected]d5f942ba2008-09-26 19:30:34970 tab_contents->SetDownloadShelfVisible(true);
971
[email protected]bd1ad682009-05-15 22:19:17972// TODO(port): port for mac.
973#if defined(OS_WIN) || defined(OS_LINUX)
974 // We make this check for the case of minimized windows, unit tests, etc.
975 if (platform_util::IsVisible(GetNativeView())) {
976 DownloadStartedAnimation::Show(tab_contents);
[email protected]d5f942ba2008-09-26 19:30:34977 }
[email protected]3edd9522009-03-04 22:19:41978#endif
[email protected]d5f942ba2008-09-26 19:30:34979}
980
[email protected]0a2aeb82009-05-15 21:52:48981DownloadShelf* TabContents::GetDownloadShelf(bool create) {
982 if (!download_shelf_.get() && create)
[email protected]bcef0dc02009-02-28 00:35:02983 download_shelf_.reset(DownloadShelf::Create(this));
984 return download_shelf_.get();
initial.commit09911bf2008-07-26 23:55:29985}
986
[email protected]bcef0dc02009-02-28 00:35:02987void TabContents::MigrateShelfFrom(TabContents* tab_contents) {
[email protected]0a2aeb82009-05-15 21:52:48988 download_shelf_.reset(tab_contents->GetDownloadShelf(true));
[email protected]bcef0dc02009-02-28 00:35:02989 download_shelf_->ChangeTabContents(tab_contents, this);
990 tab_contents->ReleaseDownloadShelf();
initial.commit09911bf2008-07-26 23:55:29991}
992
[email protected]3edd9522009-03-04 22:19:41993void TabContents::ReleaseDownloadShelf() {
994 download_shelf_.release();
995}
996
997// static
998void TabContents::MigrateShelf(TabContents* from, TabContents* to) {
999 bool was_shelf_visible = from->IsDownloadShelfVisible();
1000 if (was_shelf_visible)
1001 to->MigrateShelfFrom(from);
1002 to->SetDownloadShelfVisible(was_shelf_visible);
1003}
[email protected]3edd9522009-03-04 22:19:411004
[email protected]d5f942ba2008-09-26 19:30:341005void TabContents::WillClose(ConstrainedWindow* window) {
1006 ConstrainedWindowList::iterator it =
1007 find(child_windows_.begin(), child_windows_.end(), window);
1008 if (it != child_windows_.end())
1009 child_windows_.erase(it);
1010
[email protected]0c9ee992009-06-03 16:56:381011#if defined(OS_WIN)
1012 if (window == blocked_popups_)
1013 blocked_popups_ = NULL;
1014
1015 if (::IsWindow(GetNativeView())) {
1016 CRect client_rect;
1017 GetClientRect(GetNativeView(), &client_rect);
1018 RepositionSupressedPopupsToFit(
1019 gfx::Size(client_rect.Width(), client_rect.Height()));
1020 }
1021#endif
[email protected]d5f942ba2008-09-26 19:30:341022}
1023
[email protected]d5f942ba2008-09-26 19:30:341024void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:351025#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:061026 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:351027#endif
[email protected]d5f942ba2008-09-26 19:30:341028}
1029
[email protected]e491f1c2009-05-22 20:28:121030void TabContents::StartFinding(string16 find_text,
1031 bool forward_direction,
1032 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:011033 // If find_text is empty, it means FindNext was pressed with a keyboard
1034 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:121035 if (find_text.empty() && find_text_.empty()) {
1036 if (last_search_prepopulate_text_->empty())
1037 return;
1038 // Try whatever we searched for last in any tab.
1039 find_text = *last_search_prepopulate_text_;
1040 }
[email protected]6e95706d2009-04-23 22:55:011041
1042 // This is a FindNext operation if we are searching for the same text again,
1043 // or if the passed in search text is empty (FindNext keyboard shortcut). The
1044 // exception to this is if the Find was aborted (then we don't want FindNext
1045 // because the highlighting has been cleared and we need it to reappear). We
1046 // therefore treat FindNext after an aborted Find operation as a full fledged
1047 // Find.
1048 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:121049 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:011050 !find_op_aborted_;
1051 if (!find_next)
1052 current_find_request_id_ = find_request_id_counter_++;
1053
1054 if (!find_text.empty())
1055 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:121056 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:011057
1058 find_op_aborted_ = false;
1059
1060 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:121061 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:011062
1063 render_view_host()->StartFinding(current_find_request_id_,
1064 find_text_,
1065 forward_direction,
[email protected]e491f1c2009-05-22 20:28:121066 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:011067 find_next);
1068}
1069
1070void TabContents::StopFinding(bool clear_selection) {
1071 find_ui_active_ = false;
1072 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:121073 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:011074 render_view_host()->StopFinding(clear_selection);
1075}
1076
[email protected]420ae012009-04-24 05:16:321077void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
1078 bool success,
1079 const std::wstring& prompt) {
1080 last_javascript_message_dismissal_ = base::TimeTicks::Now();
1081 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
1082}
1083
[email protected]571e31152009-05-15 19:34:021084void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
1085 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
1086}
1087
[email protected]420ae012009-04-24 05:16:321088void TabContents::OnSavePage() {
1089 // If we can not save the page, try to download it.
1090 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1091 DownloadManager* dlm = profile()->GetDownloadManager();
1092 const GURL& current_page_url = GetURL();
1093 if (dlm && current_page_url.is_valid())
[email protected]c9825a42009-05-01 22:51:501094 dlm->DownloadUrl(current_page_url, GURL(), "", AsWC(this));
[email protected]420ae012009-04-24 05:16:321095 return;
1096 }
1097
1098 Stop();
1099
1100 // Create the save package and possibly prompt the user for the name to save
1101 // the page as. The user prompt is an asynchronous operation that runs on
1102 // another thread.
1103 save_package_ = new SavePackage(AsWC(this));
1104 save_package_->GetSaveInfo();
1105}
1106
1107// Used in automated testing to bypass prompting the user for file names.
1108// Instead, the names and paths are hard coded rather than running them through
1109// file name sanitation and extension / mime checking.
1110void TabContents::SavePage(const std::wstring& main_file,
1111 const std::wstring& dir_path,
1112 SavePackage::SavePackageType save_type) {
1113 // Stop the page from navigating.
1114 Stop();
1115
1116 save_package_ = new SavePackage(AsWC(this), save_type,
1117 FilePath::FromWStringHack(main_file),
1118 FilePath::FromWStringHack(dir_path));
1119 save_package_->Init();
1120}
1121
1122void TabContents::PrintPreview() {
1123 // We don't show the print preview yet, only the print dialog.
1124 PrintNow();
1125}
1126
1127bool TabContents::PrintNow() {
1128 // We can't print interstitial page for now.
1129 if (showing_interstitial_page())
1130 return false;
1131
1132 return render_view_host()->PrintPages();
1133}
1134
1135bool TabContents::IsActiveEntry(int32 page_id) {
1136 NavigationEntry* active_entry = controller_.GetActiveEntry();
1137 return (active_entry != NULL &&
1138 active_entry->site_instance() == GetSiteInstance() &&
1139 active_entry->page_id() == page_id);
1140}
1141
[email protected]96d185d2009-04-24 03:28:541142// Notifies the RenderWidgetHost instance about the fact that the page is
1143// loading, or done loading and calls the base implementation.
1144void TabContents::SetIsLoading(bool is_loading,
1145 LoadNotificationDetails* details) {
1146 if (is_loading == is_loading_)
1147 return;
1148
1149 if (!is_loading) {
1150 load_state_ = net::LOAD_STATE_IDLE;
1151 load_state_host_.clear();
1152 }
1153
1154 render_manager_.SetIsLoading(is_loading);
1155
1156 is_loading_ = is_loading;
1157 waiting_for_response_ = is_loading;
1158
1159 if (delegate_)
1160 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351161 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541162
1163 NotificationType type = is_loading ? NotificationType::LOAD_START :
1164 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111165 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541166 if (details)
1167 det = Details<LoadNotificationDetails>(details);
1168 NotificationService::current()->Notify(type,
1169 Source<NavigationController>(&controller_),
1170 det);
1171}
1172
[email protected]76f68dc2009-03-10 20:31:321173#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:221174void TabContents::CreateBlockedPopupContainerIfNecessary() {
1175 if (blocked_popups_)
1176 return;
1177
1178 CRect client_rect;
1179 GetClientRect(GetNativeView(), &client_rect);
1180 gfx::Point anchor_position(
1181 client_rect.Width() - views::NativeScrollBar::GetVerticalScrollBarWidth(),
1182 client_rect.Height());
1183 blocked_popups_ = BlockedPopupContainer::Create(this, profile(),
1184 anchor_position);
[email protected]0c9ee992009-06-03 16:56:381185 child_windows_.push_back(blocked_popups_);
[email protected]2c4410d2009-05-06 23:46:221186}
1187
[email protected]b6c874582009-05-08 19:38:311188void TabContents::AddPopup(TabContents* new_contents,
1189 const gfx::Rect& initial_pos,
1190 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221191 CreateBlockedPopupContainerIfNecessary();
1192 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221193}
1194
[email protected]e69bce3dd2009-04-20 22:05:121195// TODO(brettw) This should be on the TabContentsView.
[email protected]0c9ee992009-06-03 16:56:381196void TabContents::RepositionSupressedPopupsToFit(const gfx::Size& new_size) {
1197 // TODO(erg): There's no way to detect whether scroll bars are
1198 // visible, so for beta, we're just going to assume that the
1199 // vertical scroll bar is visible, and not care about covering up
1200 // the horizontal scroll bar. Fixing this is half of
1201 // http://b/1118139.
1202 gfx::Point anchor_position(
1203 new_size.width() -
1204 views::NativeScrollBar::GetVerticalScrollBarWidth(),
1205 new_size.height());
1206
[email protected]d6598c052008-11-05 19:03:251207 if (blocked_popups_)
[email protected]0c9ee992009-06-03 16:56:381208 blocked_popups_->RepositionConstrainedWindowTo(anchor_position);
[email protected]d5f942ba2008-09-26 19:30:341209}
1210
[email protected]b9681312008-11-07 00:08:261211bool TabContents::ShowingBlockedPopupNotification() const {
1212 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221213 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261214}
[email protected]0c9ee992009-06-03 16:56:381215#endif // defined(OS_WIN)
[email protected]616ed5a2008-11-21 22:27:241216
1217namespace {
1218bool TransitionIsReload(PageTransition::Type transition) {
1219 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1220}
1221}
1222
1223void TabContents::ExpireInfoBars(
1224 const NavigationController::LoadCommittedDetails& details) {
1225 // Only hide InfoBars when the user has done something that makes the main
1226 // frame load. We don't want various automatic or subframe navigations making
1227 // it disappear.
1228 if (!details.is_user_initiated_main_frame_load())
1229 return;
1230
[email protected]f86a07022008-11-25 01:06:051231 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241232 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051233 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241234 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241235 }
1236}
[email protected]fdd61c62009-04-22 19:22:571237
1238void TabContents::OnGearsCreateShortcutDone(
1239 const GearsShortcutData2& shortcut_data, bool success) {
1240 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1241 bool same_page =
1242 current_entry && pending_install_.page_id == current_entry->page_id();
1243
1244 if (success && same_page) {
1245 // Only switch to app mode if the user chose to create a shortcut and
1246 // we're still on the same page that it corresponded to.
1247 if (delegate())
1248 delegate()->ConvertContentsToApplication(this);
1249 }
1250
1251 // Reset the page id to indicate no requests are pending.
1252 pending_install_.page_id = 0;
1253 pending_install_.callback_functor = NULL;
1254}
[email protected]96d185d2009-04-24 03:28:541255
1256DOMUI* TabContents::GetDOMUIForCurrentState() {
1257 // When there is a pending navigation entry, we want to use the pending DOMUI
1258 // that goes along with it to control the basic flags. For example, we want to
1259 // show the pending URL in the URL bar, so we want the display_url flag to
1260 // be from the pending entry.
1261 //
1262 // The confusion comes because there are multiple possibilities for the
1263 // initial load in a tab as a side effect of the way the RenderViewHostManager
1264 // works.
1265 //
1266 // - For the very first tab the load looks "normal". The new tab DOM UI is
1267 // the pending one, and we want it to apply here.
1268 //
1269 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1270 // get switched to the one previously associated with the new tab pages.
1271 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1272 // have a committed DOM UI in this case.
1273 //
1274 // This condition handles all of these cases:
1275 //
1276 // - First load in first tab: no committed nav entry + pending nav entry +
1277 // pending dom ui:
1278 // -> Use pending DOM UI if any.
1279 //
1280 // - First load in second tab: no committed nav entry + pending nav entry +
1281 // no pending DOM UI:
1282 // -> Use the committed DOM UI if any.
1283 //
1284 // - Second navigation in any tab: committed nav entry + pending nav entry:
1285 // -> Use pending DOM UI if any.
1286 //
1287 // - Normal state with no load: committed nav entry + no pending nav entry:
1288 // -> Use committed DOM UI.
1289 if (controller_.pending_entry() &&
1290 (controller_.GetLastCommittedEntry() ||
1291 render_manager_.pending_dom_ui()))
1292 return render_manager_.pending_dom_ui();
1293 return render_manager_.dom_ui();
1294}
[email protected]420ae012009-04-24 05:16:321295
1296void TabContents::DidNavigateMainFramePostCommit(
1297 const NavigationController::LoadCommittedDetails& details,
1298 const ViewHostMsg_FrameNavigate_Params& params) {
1299 // Hide the download shelf if all the following conditions are true:
1300 // - there are no active downloads.
1301 // - this is a navigation to a different TLD.
1302 // - at least 5 seconds have elapsed since the download shelf was shown.
1303 // TODO(jcampan): bug 1156075 when user gestures are reliable, they should
1304 // be used to ensure we are hiding only on user initiated
1305 // navigations.
1306 DownloadManager* download_manager = profile()->GetDownloadManager();
1307 // download_manager can be NULL in unit test context.
1308 if (download_manager && download_manager->in_progress_count() == 0 &&
1309 !details.previous_url.is_empty() &&
1310 !net::RegistryControlledDomainService::SameDomainOrHost(
1311 details.previous_url, details.entry->url())) {
1312 base::TimeDelta time_delta(
1313 base::TimeTicks::Now() - last_download_shelf_show_);
1314 if (time_delta >
1315 base::TimeDelta::FromMilliseconds(kDownloadShelfHideDelay)) {
1316 SetDownloadShelfVisible(false);
1317 }
1318 }
1319
1320 if (details.is_user_initiated_main_frame_load()) {
1321 // Clear the status bubble. This is a workaround for a bug where WebKit
1322 // doesn't let us know that the cursor left an element during a
1323 // transition (this is also why the mouse cursor remains as a hand after
1324 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1325 // clear the bubble when a user navigates to a named anchor in the same
1326 // page.
1327 UpdateTargetURL(details.entry->page_id(), GURL());
1328
1329 // UpdateHelpersForDidNavigate will handle the case where the password_form
1330 // origin is valid.
1331 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1332 // cleaned up and covered by tests.
1333 if (!params.password_form.origin.is_valid())
1334 GetPasswordManager()->DidNavigate();
1335 }
1336
1337 // The keyword generator uses the navigation entries, so must be called after
1338 // the commit.
1339 GenerateKeywordIfNecessary(params);
1340
1341 // Allow the new page to set the title again.
1342 received_page_title_ = false;
1343
1344 // Get the favicon, either from history or request it from the net.
1345 fav_icon_helper_.FetchFavIcon(details.entry->url());
1346
[email protected]ce5c4502009-05-06 16:46:111347 // Disable all page actions.
1348 enabled_page_actions_.clear();
1349
[email protected]420ae012009-04-24 05:16:321350 // Close constrained popups if necessary.
1351 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1352
1353 // Update the starred state.
1354 UpdateStarredStateForCurrentURL();
1355}
1356
1357void TabContents::DidNavigateAnyFramePostCommit(
1358 RenderViewHost* render_view_host,
1359 const NavigationController::LoadCommittedDetails& details,
1360 const ViewHostMsg_FrameNavigate_Params& params) {
1361 // If we navigate, start showing messages again. This does nothing to prevent
1362 // a malicious script from spamming messages, since the script could just
1363 // reload the page to stop blocking.
1364 suppress_javascript_messages_ = false;
1365
1366 // Update history. Note that this needs to happen after the entry is complete,
1367 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1368 if (params.should_update_history) {
1369 // Most of the time, the displayURL matches the loaded URL, but for about:
1370 // URLs, we use a data: URL as the real value. We actually want to save
1371 // the about: URL to the history db and keep the data: URL hidden. This is
1372 // what the TabContents' URL getter does.
1373 UpdateHistoryForNavigation(GetURL(), params);
1374 }
1375
1376 // Notify the password manager of the navigation or form submit.
1377 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1378 // cleaned up and covered by tests.
1379 if (params.password_form.origin.is_valid())
1380 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1381}
1382
1383void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1384 const GURL& current_url) {
1385 if (net::RegistryControlledDomainService::SameDomainOrHost(
1386 previous_url, current_url))
1387 return;
1388
1389 // Clear out any child windows since we are leaving this page entirely.
1390 // We use indices instead of iterators in case CloseWindow does something
1391 // that may invalidate an iterator.
1392 int size = static_cast<int>(child_windows_.size());
1393 for (int i = size - 1; i >= 0; --i) {
1394 ConstrainedWindow* window = child_windows_[i];
1395 if (window)
1396 window->CloseConstrainedWindow();
1397 }
1398}
1399
1400void TabContents::UpdateStarredStateForCurrentURL() {
1401 BookmarkModel* model = profile()->GetBookmarkModel();
1402 const bool old_state = is_starred_;
1403 is_starred_ = (model && model->IsBookmarked(GetURL()));
1404
1405 if (is_starred_ != old_state && delegate())
1406 delegate()->URLStarredChanged(this, is_starred_);
1407}
1408
1409void TabContents::UpdateAlternateErrorPageURL() {
1410 GURL url = GetAlternateErrorPageURL();
1411 render_view_host()->SetAlternateErrorPageURL(url);
1412}
1413
1414void TabContents::UpdateWebPreferences() {
1415 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1416}
1417
1418void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1419 RenderViewHost* rvh) {
1420 // If we are creating a RVH for a restored controller, then we might
1421 // have more page IDs than the SiteInstance's current max page ID. We must
1422 // make sure that the max page ID is larger than any restored page ID.
1423 // Note that it is ok for conflicting page IDs to exist in another tab
1424 // (i.e., NavigationController), but if any page ID is larger than the max,
1425 // the back/forward list will get confused.
1426 int max_restored_page_id = controller_.max_restored_page_id();
1427 if (max_restored_page_id > 0) {
1428 int curr_max_page_id = site_instance->max_page_id();
1429 if (max_restored_page_id > curr_max_page_id) {
1430 // Need to update the site instance immediately.
1431 site_instance->UpdateMaxPageID(max_restored_page_id);
1432
1433 // Also tell the renderer to update its internal representation. We
1434 // need to reserve enough IDs to make all restored page IDs less than
1435 // the max.
1436 if (curr_max_page_id < 0)
1437 curr_max_page_id = 0;
1438 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1439 }
1440 }
1441}
1442
1443void TabContents::UpdateHistoryForNavigation(
1444 const GURL& display_url,
1445 const ViewHostMsg_FrameNavigate_Params& params) {
1446 if (profile()->IsOffTheRecord())
1447 return;
1448
1449 // Add to history service.
1450 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1451 if (hs) {
1452 if (PageTransition::IsMainFrame(params.transition) &&
1453 display_url != params.url) {
1454 // Hack on the "display" URL so that it will appear in history. For some
1455 // types of URLs, we will display a magic URL that is different from where
1456 // the page is actually navigated. We want the user to see in history
1457 // what they saw in the URL bar, so we add the display URL as a redirect.
1458 // This only applies to the main frame, as the display URL doesn't apply
1459 // to sub-frames.
1460 std::vector<GURL> redirects = params.redirects;
1461 if (!redirects.empty())
1462 redirects.back() = display_url;
1463 hs->AddPage(display_url, this, params.page_id, params.referrer,
1464 params.transition, redirects);
1465 } else {
1466 hs->AddPage(params.url, this, params.page_id, params.referrer,
1467 params.transition, params.redirects);
1468 }
1469 }
1470}
1471
1472bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1473 const std::wstring& title) {
1474 // For file URLs without a title, use the pathname instead. In the case of a
1475 // synthesized title, we don't want the update to count toward the "one set
1476 // per page of the title to history."
1477 std::wstring final_title;
1478 bool explicit_set;
1479 if (entry->url().SchemeIsFile() && title.empty()) {
1480 final_title = UTF8ToWide(entry->url().ExtractFileName());
1481 explicit_set = false; // Don't count synthetic titles toward the set limit.
1482 } else {
1483 TrimWhitespace(title, TRIM_ALL, &final_title);
1484 explicit_set = true;
1485 }
1486
1487 if (final_title == UTF16ToWideHack(entry->title()))
1488 return false; // Nothing changed, don't bother.
1489
1490 entry->set_title(WideToUTF16Hack(final_title));
1491
1492 // Update the history system for this page.
1493 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1494 HistoryService* hs =
1495 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1496 if (hs)
1497 hs->SetPageTitle(entry->display_url(), final_title);
1498
1499 // Don't allow the title to be saved again for explicitly set ones.
1500 received_page_title_ = explicit_set;
1501 }
1502
1503 // Lastly, set the title for the view.
1504 view_->SetPageTitle(final_title);
1505
1506 return true;
1507}
1508
1509void TabContents::NotifySwapped() {
1510 // After sending out a swap notification, we need to send a disconnect
1511 // notification so that clients that pick up a pointer to |this| can NULL the
1512 // pointer. See Bug 1230284.
1513 notify_disconnection_ = true;
1514 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341515 NotificationType::TAB_CONTENTS_SWAPPED,
1516 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321517 NotificationService::NoDetails());
1518}
1519
1520void TabContents::NotifyConnected() {
1521 notify_disconnection_ = true;
1522 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341523 NotificationType::TAB_CONTENTS_CONNECTED,
1524 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321525 NotificationService::NoDetails());
1526}
1527
1528void TabContents::NotifyDisconnected() {
1529 if (!notify_disconnection_)
1530 return;
1531
1532 notify_disconnection_ = false;
1533 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341534 NotificationType::TAB_CONTENTS_DISCONNECTED,
1535 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321536 NotificationService::NoDetails());
1537}
1538
1539void TabContents::GenerateKeywordIfNecessary(
1540 const ViewHostMsg_FrameNavigate_Params& params) {
1541 if (!params.searchable_form_url.is_valid())
1542 return;
1543
1544 if (profile()->IsOffTheRecord())
1545 return;
1546
1547 int last_index = controller_.last_committed_entry_index();
1548 // When there was no previous page, the last index will be 0. This is
1549 // normally due to a form submit that opened in a new tab.
1550 // TODO(brettw) bug 916126: we should support keywords when form submits
1551 // happen in new tabs.
1552 if (last_index <= 0)
1553 return;
1554 const NavigationEntry* previous_entry =
1555 controller_.GetEntryAtIndex(last_index - 1);
1556 if (IsFormSubmit(previous_entry)) {
1557 // Only generate a keyword if the previous page wasn't itself a form
1558 // submit.
1559 return;
1560 }
1561
1562 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1563 previous_entry->user_typed_url() : previous_entry->url();
1564 std::wstring keyword =
1565 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1566 if (keyword.empty())
1567 return;
1568
1569 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1570 if (!url_model)
1571 return;
1572
1573 if (!url_model->loaded()) {
1574 url_model->Load();
1575 return;
1576 }
1577
1578 const TemplateURL* current_url;
1579 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1580 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1581 return;
1582
1583 if (current_url) {
1584 if (current_url->originating_url().is_valid()) {
1585 // The existing keyword was generated from an OpenSearch description
1586 // document, don't regenerate.
1587 return;
1588 }
1589 url_model->Remove(current_url);
1590 }
1591 TemplateURL* new_url = new TemplateURL();
1592 new_url->set_keyword(keyword);
1593 new_url->set_short_name(keyword);
1594 new_url->SetURL(url, 0, 0);
1595 new_url->add_input_encoding(params.searchable_form_encoding);
1596 DCHECK(controller_.GetLastCommittedEntry());
1597 const GURL& favicon_url =
1598 controller_.GetLastCommittedEntry()->favicon().url();
1599 if (favicon_url.is_valid()) {
1600 new_url->SetFavIconURL(favicon_url);
1601 } else {
1602 // The favicon url isn't valid. This means there really isn't a favicon,
1603 // or the favicon url wasn't obtained before the load started. This assumes
1604 // the later.
1605 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1606 // its url.
1607 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1608 }
1609 new_url->set_safe_for_autoreplace(true);
1610 url_model->Add(new_url);
1611}
1612
1613RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1614 return view_.get();
1615}
1616
1617RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1618 return save_package_.get(); // May be NULL, but we can return NULL.
1619}
1620
[email protected]6dfed102009-04-28 03:09:531621ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1622 RenderViewHost* render_view_host,
1623 const std::string& extension_id) {
1624 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1625 extension_id);
1626}
1627
[email protected]57c6a652009-05-04 07:58:341628TabContents* TabContents::GetAsTabContents() {
1629 return this;
1630}
1631
[email protected]420ae012009-04-24 05:16:321632void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1633 NavigationEntry* entry = controller_.GetActiveEntry();
1634 if (!entry)
1635 return;
1636
1637 // When we're creating views, we're still doing initial setup, so we always
1638 // use the pending DOM UI rather than any possibly existing committed one.
1639 if (render_manager_.pending_dom_ui()) {
1640 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1641 }
1642
1643 if (entry->IsViewSourceMode()) {
1644 // Put the renderer in view source mode.
1645 render_view_host->Send(
1646 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1647 }
[email protected]0666aef2009-05-13 19:48:081648
1649 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321650}
1651
1652void TabContents::RenderViewReady(RenderViewHost* rvh) {
1653 if (rvh != render_view_host()) {
1654 // Don't notify the world, since this came from a renderer in the
1655 // background.
1656 return;
1657 }
1658
1659 NotifyConnected();
1660 SetIsCrashed(false);
1661}
1662
1663void TabContents::RenderViewGone(RenderViewHost* rvh) {
1664 // Ask the print preview if this renderer was valuable.
1665 if (!printing_.OnRenderViewGone(rvh))
1666 return;
1667 if (rvh != render_view_host()) {
1668 // The pending page's RenderViewHost is gone.
1669 return;
1670 }
1671
1672 SetIsLoading(false, NULL);
1673 NotifyDisconnected();
1674 SetIsCrashed(true);
1675
1676 // Force an invalidation to render sad tab. The view will notice we crashed
1677 // when it paints.
1678 view_->Invalidate();
1679
1680 // Hide any visible hung renderer warning for this web contents' process.
[email protected]8897c382009-05-06 17:53:261681 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:321682}
1683
1684void TabContents::DidNavigate(RenderViewHost* rvh,
1685 const ViewHostMsg_FrameNavigate_Params& params) {
1686 if (PageTransition::IsMainFrame(params.transition))
1687 render_manager_.DidNavigateMainFrame(rvh);
1688
1689 // Update the site of the SiteInstance if it doesn't have one yet.
1690 if (!GetSiteInstance()->has_site())
1691 GetSiteInstance()->SetSite(params.url);
1692
1693 // Need to update MIME type here because it's referred to in
1694 // UpdateNavigationCommands() called by RendererDidNavigate() to
1695 // determine whether or not to enable the encoding menu.
1696 // It's updated only for the main frame. For a subframe,
1697 // RenderView::UpdateURL does not set params.contents_mime_type.
1698 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1699 // TODO(jungshik): Add a test for the encoding menu to avoid
1700 // regressing it again.
1701 if (PageTransition::IsMainFrame(params.transition))
1702 contents_mime_type_ = params.contents_mime_type;
1703
1704 NavigationController::LoadCommittedDetails details;
1705 if (!controller_.RendererDidNavigate(params, &details))
1706 return; // No navigation happened.
1707
1708 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1709 // for the appropriate notification (best) or you can add it to
1710 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1711 // necessary, please).
1712
1713 // Run post-commit tasks.
1714 if (details.is_main_frame)
1715 DidNavigateMainFramePostCommit(details, params);
1716 DidNavigateAnyFramePostCommit(rvh, details, params);
1717}
1718
1719void TabContents::UpdateState(RenderViewHost* rvh,
1720 int32 page_id,
1721 const std::string& state) {
1722 DCHECK(rvh == render_view_host());
1723
1724 // We must be prepared to handle state updates for any page, these occur
1725 // when the user is scrolling and entering form data, as well as when we're
1726 // leaving a page, in which case our state may have already been moved to
1727 // the next page. The navigation controller will look up the appropriate
1728 // NavigationEntry and update it when it is notified via the delegate.
1729
1730 int entry_index = controller_.GetEntryIndexWithPageID(
1731 GetSiteInstance(), page_id);
1732 if (entry_index < 0)
1733 return;
1734 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1735
1736 if (state == entry->content_state())
1737 return; // Nothing to update.
1738 entry->set_content_state(state);
1739 controller_.NotifyEntryChanged(entry, entry_index);
1740}
1741
1742void TabContents::UpdateTitle(RenderViewHost* rvh,
1743 int32 page_id, const std::wstring& title) {
1744 // If we have a title, that's a pretty good indication that we've started
1745 // getting useful data.
1746 SetNotWaitingForResponse();
1747
1748 DCHECK(rvh == render_view_host());
1749 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1750 page_id);
1751 if (!entry || !UpdateTitleForEntry(entry, title))
1752 return;
1753
1754 // Broadcast notifications when the UI should be updated.
1755 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501756 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321757}
1758
[email protected]420ae012009-04-24 05:16:321759void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1760 const std::wstring& encoding) {
1761 set_encoding(encoding);
1762}
1763
1764void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1765 if (delegate())
1766 delegate()->UpdateTargetURL(this, url);
1767}
1768
1769void TabContents::UpdateThumbnail(const GURL& url,
1770 const SkBitmap& bitmap,
1771 const ThumbnailScore& score) {
1772 // Tell History about this thumbnail
1773 HistoryService* hs;
1774 if (!profile()->IsOffTheRecord() &&
1775 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1776 hs->SetPageThumbnail(url, bitmap, score);
1777 }
1778}
1779
[email protected]0df30122009-06-03 12:13:081780void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
1781 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
1782 raw_settings);
1783}
1784
[email protected]420ae012009-04-24 05:16:321785void TabContents::Close(RenderViewHost* rvh) {
1786 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1787 if (delegate() && rvh == render_view_host())
1788 delegate()->CloseContents(this);
1789}
1790
1791void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1792 if (delegate() && delegate()->IsPopup(this))
1793 delegate()->MoveContents(this, new_bounds);
1794}
1795
[email protected]329581b2009-04-28 06:52:351796void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321797 SetIsLoading(true, NULL);
1798}
1799
[email protected]329581b2009-04-28 06:52:351800void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321801 scoped_ptr<LoadNotificationDetails> details;
1802
1803 NavigationEntry* entry = controller_.GetActiveEntry();
1804 // An entry may not exist for a stop when loading an initial blank page or
1805 // if an iframe injected by script into a blank page finishes loading.
1806 if (entry) {
1807 scoped_ptr<base::ProcessMetrics> metrics(
1808 base::ProcessMetrics::CreateProcessMetrics(
1809 process()->process().handle()));
1810
1811 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1812
1813 details.reset(new LoadNotificationDetails(
1814 entry->display_url(),
1815 entry->transition_type(),
1816 elapsed,
1817 &controller_,
1818 controller_.GetCurrentEntryIndex()));
1819 }
1820
1821 // Tell PasswordManager we've finished a page load, which serves as a
1822 // green light to save pending passwords and reset itself.
1823 GetPasswordManager()->DidStopLoading();
1824
1825 SetIsLoading(false, details.get());
1826}
1827
1828void TabContents::DidStartProvisionalLoadForFrame(
1829 RenderViewHost* render_view_host,
1830 bool is_main_frame,
1831 const GURL& url) {
1832 ProvisionalLoadDetails details(is_main_frame,
1833 controller_.IsURLInPageNavigation(url),
1834 url, std::string(), false);
1835 NotificationService::current()->Notify(
1836 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1837 Source<NavigationController>(&controller_),
1838 Details<ProvisionalLoadDetails>(&details));
1839}
1840
1841void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1842 const GURL& source_url,
1843 const GURL& target_url) {
1844 NavigationEntry* entry;
1845 if (page_id == -1)
1846 entry = controller_.pending_entry();
1847 else
1848 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1849 if (!entry || entry->url() != source_url)
1850 return;
1851 entry->set_url(target_url);
1852}
1853
1854void TabContents::DidLoadResourceFromMemoryCache(
1855 const GURL& url,
1856 const std::string& frame_origin,
1857 const std::string& main_frame_origin,
1858 const std::string& security_info) {
1859 // Send out a notification that we loaded a resource from our memory cache.
1860 int cert_id = 0, cert_status = 0, security_bits = 0;
1861 SSLManager::DeserializeSecurityInfo(security_info,
1862 &cert_id, &cert_status,
1863 &security_bits);
1864 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]9ae66cbf2009-05-12 16:21:031865 process()->pid(), cert_id, cert_status);
[email protected]420ae012009-04-24 05:16:321866
1867 NotificationService::current()->Notify(
1868 NotificationType::LOAD_FROM_MEMORY_CACHE,
1869 Source<NavigationController>(&controller_),
1870 Details<LoadFromMemoryCacheDetails>(&details));
1871}
1872
1873void TabContents::DidFailProvisionalLoadWithError(
1874 RenderViewHost* render_view_host,
1875 bool is_main_frame,
1876 int error_code,
1877 const GURL& url,
1878 bool showing_repost_interstitial) {
1879 if (net::ERR_ABORTED == error_code) {
1880 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1881 // This means that the interstitial won't be torn down properly, which is
1882 // bad. But if we have an interstitial, go back to another tab type, and
1883 // then load the same interstitial again, we could end up getting the first
1884 // interstitial's "failed" message (as a result of the cancel) when we're on
1885 // the second one.
1886 //
1887 // We can't tell this apart, so we think we're tearing down the current page
1888 // which will cause a crash later one. There is also some code in
1889 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1890 // out because of this problem.
1891 //
1892 // http://code.google.com/p/chromium/issues/detail?id=2855
1893 // Because this will not tear down the interstitial properly, if "back" is
1894 // back to another tab type, the interstitial will still be somewhat alive
1895 // in the previous tab type. If you navigate somewhere that activates the
1896 // tab with the interstitial again, you'll see a flash before the new load
1897 // commits of the interstitial page.
1898 if (showing_interstitial_page()) {
1899 LOG(WARNING) << "Discarding message during interstitial.";
1900 return;
1901 }
1902
1903 // This will discard our pending entry if we cancelled the load (e.g., if we
1904 // decided to download the file instead of load it). Only discard the
1905 // pending entry if the URLs match, otherwise the user initiated a navigate
1906 // before the page loaded so that the discard would discard the wrong entry.
1907 NavigationEntry* pending_entry = controller_.pending_entry();
1908 if (pending_entry && pending_entry->url() == url)
1909 controller_.DiscardNonCommittedEntries();
1910
1911 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1912 }
1913
1914 // Send out a notification that we failed a provisional load with an error.
1915 ProvisionalLoadDetails details(is_main_frame,
1916 controller_.IsURLInPageNavigation(url),
1917 url, std::string(), false);
1918 details.set_error_code(error_code);
1919
1920 NotificationService::current()->Notify(
1921 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1922 Source<NavigationController>(&controller_),
1923 Details<ProvisionalLoadDetails>(&details));
1924}
1925
1926void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1927 int32 page_id,
1928 const GURL& icon_url) {
1929 fav_icon_helper_.SetFavIconURL(icon_url);
1930}
1931
1932void TabContents::DidDownloadImage(
1933 RenderViewHost* render_view_host,
1934 int id,
1935 const GURL& image_url,
1936 bool errored,
1937 const SkBitmap& image) {
1938 // A notification for downloading would be more flexible, but for now I'm
1939 // forwarding to the two places that could possibly have initiated the
1940 // request. If we end up with another place invoking DownloadImage, probably
1941 // best to refactor out into notification service, or something similar.
1942 if (errored)
1943 fav_icon_helper_.FavIconDownloadFailed(id);
1944 else
1945 fav_icon_helper_.SetFavIcon(id, image_url, image);
1946}
1947
1948void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1949 WindowOpenDisposition disposition) {
1950 if (render_manager_.dom_ui()) {
1951 // When we're a DOM UI, it will provide a page transition type for us (this
1952 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1953 // generated suggestions).
1954 //
1955 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161956 // want web sites to see a referrer of "chrome://blah" (and some
1957 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321958 // send to the site), so we send no referrer.
1959 OpenURL(url, GURL(), disposition,
1960 render_manager_.dom_ui()->link_transition_type());
1961 } else {
1962 OpenURL(url, referrer, disposition, PageTransition::LINK);
1963 }
1964}
1965
1966void TabContents::DomOperationResponse(const std::string& json_string,
1967 int automation_id) {
1968 DomOperationNotificationDetails details(json_string, automation_id);
1969 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341970 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321971 Details<DomOperationNotificationDetails>(&details));
1972}
1973
1974void TabContents::ProcessDOMUIMessage(const std::string& message,
1975 const std::string& content) {
1976 if (!render_manager_.dom_ui()) {
1977 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1978 // Because the renderer might be owned and sending random messages, we need
1979 // to ignore these inproper ones.
1980 NOTREACHED();
1981 return;
1982 }
1983 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1984}
1985
1986void TabContents::ProcessExternalHostMessage(const std::string& message,
1987 const std::string& origin,
1988 const std::string& target) {
1989 if (delegate())
1990 delegate()->ForwardMessageToExternalHost(message, origin, target);
1991}
1992
1993void TabContents::GoToEntryAtOffset(int offset) {
1994 controller_.GoToOffset(offset);
1995}
1996
1997void TabContents::GetHistoryListCount(int* back_list_count,
1998 int* forward_list_count) {
1999 int current_index = controller_.last_committed_entry_index();
2000 *back_list_count = current_index;
2001 *forward_list_count = controller_.entry_count() - current_index - 1;
2002}
2003
2004void TabContents::RunFileChooser(bool multiple_files,
2005 const string16& title,
2006 const FilePath& default_file) {
2007 if (!select_file_dialog_.get())
2008 select_file_dialog_ = SelectFileDialog::Create(this);
2009 SelectFileDialog::Type dialog_type =
2010 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
2011 SelectFileDialog::SELECT_OPEN_FILE;
2012 select_file_dialog_->SelectFile(dialog_type, title, default_file,
2013 NULL, 0, FILE_PATH_LITERAL(""),
2014 view_->GetTopLevelNativeWindow(), NULL);
2015}
2016
2017void TabContents::RunJavaScriptMessage(
2018 const std::wstring& message,
2019 const std::wstring& default_prompt,
2020 const GURL& frame_url,
2021 const int flags,
2022 IPC::Message* reply_msg,
2023 bool* did_suppress_message) {
2024 // Suppress javascript messages when requested and when inside a constrained
2025 // popup window (because that activates them and breaks them out of the
2026 // constrained window jail).
2027 bool suppress_this_message = suppress_javascript_messages_;
2028 if (delegate())
2029 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:312030 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:322031
2032 *did_suppress_message = suppress_this_message;
2033
2034 if (!suppress_this_message) {
2035 base::TimeDelta time_since_last_message(
2036 base::TimeTicks::Now() - last_javascript_message_dismissal_);
2037 bool show_suppress_checkbox = false;
2038 // Show a checkbox offering to suppress further messages if this message is
2039 // being displayed within kJavascriptMessageExpectedDelay of the last one.
2040 if (time_since_last_message <
2041 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
2042 show_suppress_checkbox = true;
2043
2044 RunJavascriptMessageBox(AsWC(this), frame_url, flags, message, default_prompt,
2045 show_suppress_checkbox, reply_msg);
2046 } else {
2047 // If we are suppressing messages, just reply as is if the user immediately
2048 // pressed "Cancel".
2049 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
2050 }
2051}
2052
2053void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
2054 IPC::Message* reply_msg) {
2055 RunBeforeUnloadDialog(AsWC(this), message, reply_msg);
2056}
2057
2058void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
2059 const std::string& json_arguments,
2060 IPC::Message* reply_msg) {
2061 if (delegate()) {
2062 HtmlDialogUIDelegate* dialog_delegate =
2063 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
2064 reply_msg, AsWC(this));
2065 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
2066 }
2067}
2068
2069void TabContents::PasswordFormsSeen(
2070 const std::vector<PasswordForm>& forms) {
2071 GetPasswordManager()->PasswordFormsSeen(forms);
2072}
2073
2074void TabContents::AutofillFormSubmitted(
2075 const AutofillForm& form) {
2076 GetAutofillManager()->AutofillFormSubmitted(form);
2077}
2078
2079void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
2080 const std::wstring& user_text, int64 node_id, int request_id) {
2081 GetAutofillManager()->FetchValuesForName(field_name, user_text,
2082 kMaxAutofillMenuItems, node_id, request_id);
2083}
2084
2085void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
2086 const std::wstring& value) {
2087 GetAutofillManager()->RemoveValueForName(field_name, value);
2088}
2089
2090// Checks to see if we should generate a keyword based on the OSDD, and if
2091// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2092void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2093 int32 page_id, const GURL& url,
2094 bool autodetected) {
2095 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2096 DCHECK(url.is_valid());
2097 if (!IsActiveEntry(page_id))
2098 return;
2099 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2100 if (!url_model)
2101 return;
2102 if (!url_model->loaded()) {
2103 url_model->Load();
2104 return;
2105 }
2106 if (!profile()->GetTemplateURLFetcher())
2107 return;
2108
2109 if (profile()->IsOffTheRecord())
2110 return;
2111
2112 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2113 DCHECK(entry);
2114
2115 const NavigationEntry* base_entry = entry;
2116 if (IsFormSubmit(base_entry)) {
2117 // If the current page is a form submit, find the last page that was not
2118 // a form submit and use its url to generate the keyword from.
2119 int index = controller_.last_committed_entry_index() - 1;
2120 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2121 index--;
2122 if (index >= 0)
2123 base_entry = controller_.GetEntryAtIndex(index);
2124 else
2125 base_entry = NULL;
2126 }
2127
2128 // We want to use the user typed URL if available since that represents what
2129 // the user typed to get here, and fall back on the regular URL if not.
2130 if (!base_entry)
2131 return;
2132 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2133 base_entry->user_typed_url() : base_entry->url();
2134 if (!keyword_url.is_valid())
2135 return;
2136 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2137 autodetected);
2138 if (keyword.empty())
2139 return;
2140 const TemplateURL* template_url =
2141 url_model->GetTemplateURLForKeyword(keyword);
2142 if (template_url && (!template_url->safe_for_autoreplace() ||
2143 template_url->originating_url() == url)) {
2144 // Either there is a user created TemplateURL for this keyword, or the
2145 // keyword has the same OSDD url and we've parsed it.
2146 return;
2147 }
2148
2149 // Download the OpenSearch description document. If this is successful a
2150 // new keyword will be created when done.
2151#if defined(OS_WIN)
2152 gfx::NativeView ancestor = GetAncestor(view_->GetNativeView(), GA_ROOT);
2153#else
2154 gfx::NativeView ancestor = NULL;
2155#endif
2156 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2157 keyword,
2158 url,
2159 base_entry->favicon().url(),
2160 ancestor,
2161 autodetected);
2162}
2163
2164void TabContents::InspectElementReply(int num_resources) {
2165 // We have received reply from inspect element request. Notify the
2166 // automation provider in case we need to notify automation client.
2167 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:342168 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:322169 Details<int>(&num_resources));
2170}
2171
2172void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2173 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2174}
2175
2176void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2177 printing_.DidPrintPage(params);
2178}
2179
2180GURL TabContents::GetAlternateErrorPageURL() const {
2181 GURL url;
2182 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2183 if (profile()->IsOffTheRecord())
2184 return url;
2185
2186 PrefService* prefs = profile()->GetPrefs();
2187 DCHECK(prefs);
2188 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2189 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2190 url = google_util::AppendGoogleTLDParam(url);
2191 }
2192 return url;
2193}
2194
2195WebPreferences TabContents::GetWebkitPrefs() {
2196 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2197 bool isDomUI = false;
2198 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2199}
2200
2201void TabContents::OnMissingPluginStatus(int status) {
2202#if defined(OS_WIN)
2203// TODO(PORT): pull in when plug-ins work
2204 GetPluginInstaller()->OnMissingPluginStatus(status);
2205#endif
2206}
2207
2208void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2209#if defined(OS_WIN)
2210// TODO(PORT): pull in when plug-ins work
2211 DCHECK(!plugin_path.value().empty());
2212
2213 std::wstring plugin_name = plugin_path.ToWStringHack();
2214 scoped_ptr<FileVersionInfo> version_info(
2215 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2216 if (version_info.get()) {
2217 const std::wstring& product_name = version_info->product_name();
2218 if (!product_name.empty())
2219 plugin_name = product_name;
2220 }
2221 AddInfoBar(new SimpleAlertInfoBarDelegate(
2222 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2223 NULL));
2224#endif
2225}
2226
2227void TabContents::OnCrashedWorker() {
2228 AddInfoBar(new SimpleAlertInfoBarDelegate(
2229 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2230 NULL));
2231}
2232
2233void TabContents::OnJSOutOfMemory() {
2234 AddInfoBar(new SimpleAlertInfoBarDelegate(
2235 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2236}
2237
2238void TabContents::ShouldClosePage(bool proceed) {
2239 render_manager_.ShouldClosePage(proceed);
2240}
2241
2242void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2243 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342244 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322245 // delivered to a pending RenderViewHost. We must first run the onunload
2246 // handler of the old RenderViewHost before we can allow it to proceed.
2247 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2248 new_request_id);
2249}
2250
2251bool TabContents::CanBlur() const {
2252 return delegate() ? delegate()->CanBlur() : true;
2253}
2254
2255gfx::Rect TabContents::GetRootWindowResizerRect() const {
2256 if (delegate())
2257 return delegate()->GetRootWindowResizerRect();
2258 return gfx::Rect();
2259}
2260
2261void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2262 bool is_during_unload) {
2263 if (is_during_unload) {
2264 // Hang occurred while firing the beforeunload/unload handler.
2265 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112266 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322267
2268 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2269 return;
2270
2271 // If the tab hangs in the beforeunload/unload handler there's really
2272 // nothing we can do to recover. Pretend the unload listeners have
2273 // all fired and close the tab. If the hang is in the beforeunload handler
2274 // then the user will not have the option of cancelling the close.
2275 Close(rvh);
2276 return;
2277 }
2278
2279 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]8897c382009-05-06 17:53:262280 HungRendererDialog::ShowForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322281}
2282
2283void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]8897c382009-05-06 17:53:262284 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322285}
2286
2287void TabContents::LoadStateChanged(const GURL& url,
2288 net::LoadState load_state) {
2289 load_state_ = load_state;
[email protected]d686e812009-06-03 19:10:292290 std::wstring languages =
2291 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2292 load_state_host_.clear();
2293 std::string host = url.host();
2294 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322295 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2296 SetNotWaitingForResponse();
2297 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502298 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322299}
2300
2301void TabContents::OnDidGetApplicationInfo(
2302 int32 page_id,
2303 const webkit_glue::WebApplicationInfo& info) {
2304 if (pending_install_.page_id != page_id)
2305 return; // The user clicked create on a separate page. Ignore this.
2306
2307 pending_install_.callback_functor =
2308 new GearsCreateShortcutCallbackFunctor(this);
2309 GearsCreateShortcut(
2310 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2311 NewCallback(pending_install_.callback_functor,
2312 &GearsCreateShortcutCallbackFunctor::Run));
2313}
2314
[email protected]14ce83f2009-05-28 18:35:242315void TabContents::OnUserGesture() {
2316 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
2317#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]420ae012009-04-24 05:16:322318 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2319 if (drm)
2320 drm->OnUserGesture(this);
2321#endif
2322}
2323
2324void TabContents::OnFindReply(int request_id,
2325 int number_of_matches,
2326 const gfx::Rect& selection_rect,
2327 int active_match_ordinal,
2328 bool final_update) {
2329 // Ignore responses for requests other than the one we have most recently
2330 // issued. That way we won't act on stale results when the user has
2331 // already typed in another query.
2332 if (request_id != current_find_request_id_)
2333 return;
2334
2335 if (number_of_matches == -1)
[email protected]e491f1c2009-05-22 20:28:122336 number_of_matches = last_search_result_.number_of_matches();
[email protected]420ae012009-04-24 05:16:322337 if (active_match_ordinal == -1)
[email protected]e491f1c2009-05-22 20:28:122338 active_match_ordinal = last_search_result_.active_match_ordinal();
[email protected]420ae012009-04-24 05:16:322339
[email protected]2c355c282009-05-21 23:24:432340 gfx::Rect selection = selection_rect;
2341 if (selection.IsEmpty())
[email protected]e491f1c2009-05-22 20:28:122342 selection = last_search_result_.selection_rect();
[email protected]2c355c282009-05-21 23:24:432343
[email protected]420ae012009-04-24 05:16:322344 // Notify the UI, automation and any other observers that a find result was
2345 // found.
[email protected]e491f1c2009-05-22 20:28:122346 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
2347 selection, active_match_ordinal,
2348 final_update);
[email protected]420ae012009-04-24 05:16:322349 NotificationService::current()->Notify(
2350 NotificationType::FIND_RESULT_AVAILABLE,
2351 Source<TabContents>(this),
[email protected]e491f1c2009-05-22 20:28:122352 Details<FindNotificationDetails>(&last_search_result_));
[email protected]420ae012009-04-24 05:16:322353}
2354
[email protected]829e7612009-04-25 01:15:112355bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322356 if (!delegate())
[email protected]829e7612009-04-25 01:15:112357 return false;
[email protected]420ae012009-04-24 05:16:322358
[email protected]829e7612009-04-25 01:15:112359 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322360}
2361
2362void TabContents::FileSelected(const FilePath& path,
2363 int index, void* params) {
2364 render_view_host()->FileSelected(path);
2365}
2366
2367void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2368 void* params) {
2369 render_view_host()->MultiFilesSelected(files);
2370}
2371
2372void TabContents::FileSelectionCanceled(void* params) {
2373 // If the user cancels choosing a file to upload we pass back an
2374 // empty vector.
2375 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2376}
2377
2378void TabContents::BeforeUnloadFiredFromRenderManager(
2379 bool proceed,
2380 bool* proceed_to_fire_unload) {
2381 if (delegate())
2382 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2383}
2384
2385void TabContents::UpdateRenderViewSizeForRenderManager() {
2386 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2387 view_->SizeContents(view_->GetContainerSize());
2388}
2389
2390DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
2391 return DOMUIFactory::CreateDOMUIForURL(AsWC(this), url);
2392}
2393
2394NavigationEntry*
2395TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2396 return controller_.GetLastCommittedEntry();
2397}
2398
2399bool TabContents::CreateRenderViewForRenderManager(
2400 RenderViewHost* render_view_host) {
2401 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2402 // mode before CreateRenderView is called. When we're asked to create a
2403 // RenderView, that means it's for the pending entry, so we have to use the
2404 // pending DOM UI.
2405 if (render_manager_.pending_dom_ui())
2406 render_view_host->AllowDOMUIBindings();
2407
[email protected]1adff062009-06-02 18:39:552408 // Ditto for extension bindings.
2409 if (controller().pending_entry()->url().SchemeIs(chrome::kExtensionScheme))
2410 render_view_host->AllowExtensionBindings();
2411
[email protected]420ae012009-04-24 05:16:322412 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2413 if (!render_view_host->CreateRenderView())
2414 return false;
2415
2416 // Now that the RenderView has been created, we need to tell it its size.
2417 rwh_view->SetSize(view_->GetContainerSize());
2418
2419 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2420 render_view_host);
2421 return true;
2422}
2423
2424void TabContents::Observe(NotificationType type,
2425 const NotificationSource& source,
2426 const NotificationDetails& details) {
2427 switch (type.value) {
2428 case NotificationType::BOOKMARK_MODEL_LOADED:
2429 // BookmarkModel finished loading, fall through to update starred state.
2430 case NotificationType::URLS_STARRED: {
2431 // Somewhere, a URL has been starred.
2432 // Ignore notifications for profiles other than our current one.
2433 Profile* source_profile = Source<Profile>(source).ptr();
2434 if (!source_profile || !source_profile->IsSameProfile(profile()))
2435 return;
2436
2437 UpdateStarredStateForCurrentURL();
2438 break;
2439 }
2440 case NotificationType::PREF_CHANGED: {
2441 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2442 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2443 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2444 UpdateAlternateErrorPageURL();
2445 } else if (*pref_name_in == prefs::kDefaultCharset ||
2446 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2447 ) {
2448 UpdateWebPreferences();
2449 } else {
2450 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2451 }
2452 break;
2453 }
2454 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2455 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2456 break;
2457
2458 case NotificationType::NAV_ENTRY_COMMITTED: {
2459 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2460
2461 NavigationController::LoadCommittedDetails& committed_details =
2462 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2463 ExpireInfoBars(committed_details);
2464 break;
2465 }
2466
2467 default:
2468 NOTREACHED();
2469 }
2470}