blob: 4bc43666173b4146904928be93eb8559151afe7f [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]420ae012009-04-24 05:16:3224#include "chrome/browser/gears_integration.h"
25#include "chrome/browser/google_util.h"
[email protected]8897c382009-05-06 17:53:2626#include "chrome/browser/hung_renderer_dialog.h"
[email protected]420ae012009-04-24 05:16:3227#include "chrome/browser/jsmessage_box_handler.h"
28#include "chrome/browser/load_from_memory_cache_details.h"
29#include "chrome/browser/load_notification_details.h"
[email protected]fdd61c62009-04-22 19:22:5730#include "chrome/browser/password_manager/password_manager.h"
31#include "chrome/browser/plugin_installer.h"
[email protected]ce560f82009-06-03 09:39:4432#include "chrome/browser/profile.h"
[email protected]96d185d2009-04-24 03:28:5433#include "chrome/browser/renderer_host/render_widget_host_view.h"
34#include "chrome/browser/renderer_host/web_cache_manager.h"
[email protected]bd1ad682009-05-15 22:19:1735#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]f3ec7742009-01-15 00:59:1636#include "chrome/browser/tab_contents/navigation_entry.h"
37#include "chrome/browser/tab_contents/tab_contents_delegate.h"
[email protected]fdd61c62009-04-22 19:22:5738#include "chrome/browser/tab_contents/tab_contents_view.h"
[email protected]420ae012009-04-24 05:16:3239#include "chrome/browser/search_engines/template_url_fetcher.h"
40#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2741#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5642#include "chrome/common/notification_service.h"
[email protected]ce5c4502009-05-06 16:46:1143#include "chrome/common/page_action.h"
initial.commit09911bf2008-07-26 23:55:2944#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0345#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3246#include "chrome/common/render_messages.h"
[email protected]96d185d2009-04-24 03:28:5447#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2648#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3249#include "grit/locale_settings.h"
50#include "net/base/mime_util.h"
51#include "net/base/net_errors.h"
[email protected]d686e812009-06-03 19:10:2952#include "net/base/net_util.h"
[email protected]420ae012009-04-24 05:16:3253#include "net/base/registry_controlled_domain.h"
[email protected]3e45ba92009-02-20 21:09:0054
55#if defined(OS_WIN)
56// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3257#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]0c9ee992009-06-03 16:56:3858#include "chrome/browser/views/blocked_popup_container.h"
[email protected]2362e4f2009-05-08 00:34:0559#include "views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0060#endif
initial.commit09911bf2008-07-26 23:55:2961
[email protected]420ae012009-04-24 05:16:3262// Cross-Site Navigations
63//
64// If a TabContents is told to navigate to a different web site (as determined
65// by SiteInstance), it will replace its current RenderViewHost with a new
66// RenderViewHost dedicated to the new SiteInstance. This works as follows:
67//
68// - Navigate determines whether the destination is cross-site, and if so,
69// it creates a pending_render_view_host_ and moves into the PENDING
70// RendererState.
71// - The pending RVH is "suspended," so that no navigation messages are sent to
72// its renderer until the onbeforeunload JavaScript handler has a chance to
73// run in the current RVH.
74// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
75// that it has a pending cross-site request. ResourceDispatcherHost will
76// check for this when the response arrives.
77// - The current RVH runs its onbeforeunload handler. If it returns false, we
78// cancel all the pending logic and go back to NORMAL. Otherwise we allow
79// the pending RVH to send the navigation request to its renderer.
80// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
81// checks CrossSiteRequestManager to see that the RVH responsible has a
82// pending cross-site request, and then installs a CrossSiteEventHandler.
83// - When RDH receives a response, the BufferedEventHandler determines whether
84// it is a download. If so, it sends a message to the new renderer causing
85// it to cancel the request, and the download proceeds in the download
86// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:3487// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:3288// doesn't affect any functionality.
89// - After RDH receives a response and determines that it is safe and not a
90// download, it pauses the response to first run the old page's onunload
91// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:3492// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:3293// to the current RVH.
94// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
95// the ResourceDispatcherHost, who unpauses the response. Data is then sent
96// to the pending RVH.
97// - The pending renderer sends a FrameNavigate message that invokes the
98// DidNavigate method. This replaces the current RVH with the
99// pending RVH and goes back to the NORMAL RendererState.
100
101namespace {
102
103// Amount of time we wait between when a key event is received and the renderer
104// is queried for its state and pushed to the NavigationEntry.
105const int kQueryStateDelay = 5000;
106
107const int kSyncWaitDelay = 40;
108
109// If another javascript message box is displayed within
110// kJavascriptMessageExpectedDelay of a previous javascript message box being
111// dismissed, display an option to suppress future message boxes from this
112// contents.
113const int kJavascriptMessageExpectedDelay = 1000;
114
[email protected]420ae012009-04-24 05:16:32115const char kLinkDoctorBaseURL[] =
116 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
117
118// The printer icon in shell32.dll. That's a standard icon user will quickly
119// recognize.
120const int kShell32PrinterIcon = 17;
121
122// The list of prefs we want to observe.
123const wchar_t* kPrefsToObserve[] = {
124 prefs::kAlternateErrorPagesEnabled,
125 prefs::kWebKitJavaEnabled,
126 prefs::kWebKitJavascriptEnabled,
127 prefs::kWebKitLoadsImagesAutomatically,
128 prefs::kWebKitPluginsEnabled,
129 prefs::kWebKitUsesUniversalDetector,
[email protected]96d3fb52009-05-27 14:51:21130 prefs::kWebKitDeveloperExtrasEnabled,
[email protected]420ae012009-04-24 05:16:32131 prefs::kWebKitSerifFontFamily,
132 prefs::kWebKitSansSerifFontFamily,
133 prefs::kWebKitFixedFontFamily,
134 prefs::kWebKitDefaultFontSize,
135 prefs::kWebKitDefaultFixedFontSize,
136 prefs::kDefaultCharset
137 // kWebKitStandardFontIsSerif needs to be added
138 // if we let users pick which font to use, serif or sans-serif when
139 // no font is specified or a CSS generic family (serif or sans-serif)
140 // is not specified.
141};
142
143const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
144
145// Limit on the number of suggestions to appear in the pop-up menu under an
146// text input element in a form.
147const int kMaxAutofillMenuItems = 6;
148
149// Returns true if the entry's transition type is FORM_SUBMIT.
150bool IsFormSubmit(const NavigationEntry* entry) {
151 return (PageTransition::StripQualifier(entry->transition_type()) ==
152 PageTransition::FORM_SUBMIT);
153}
154
155#if defined(OS_WIN)
156
157BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
158 // Note: erase is required to properly paint some widgets borders. This can
159 // be seen with textfields.
160 InvalidateRect(hwnd, NULL, TRUE);
161 return TRUE;
162}
163#endif
164
[email protected]57c6a652009-05-04 07:58:34165// TODO(brettw) TabContents should be removed, then this hack is unnecessary.
166TabContents* AsWC(TabContents* tc) {
167 return static_cast<TabContents*>(tc);
[email protected]420ae012009-04-24 05:16:32168}
169
170} // namespace
171
172// -----------------------------------------------------------------------------
173
[email protected]fdd61c62009-04-22 19:22:57174// static
175int TabContents::find_request_id_counter_ = -1;
176
[email protected]420ae012009-04-24 05:16:32177class TabContents::GearsCreateShortcutCallbackFunctor {
178 public:
179 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
180 : contents_(contents) {}
181
182 void Run(const GearsShortcutData2& shortcut_data, bool success) {
183 if (contents_)
184 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
185 delete this;
186 }
187 void Cancel() {
188 contents_ = NULL;
189 }
190
191 private:
192 TabContents* contents_;
193};
194
[email protected]57c6a652009-05-04 07:58:34195// TODO(brettw) many of the data members here have casts to TabContents.
196// This object is the same as TabContents and is currently being merged.
[email protected]fdd61c62009-04-22 19:22:57197// When this merge is done, the casts can be removed.
[email protected]420ae012009-04-24 05:16:32198TabContents::TabContents(Profile* profile,
199 SiteInstance* site_instance,
200 int routing_id,
201 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42202 : delegate_(NULL),
[email protected]ce3fa3c2009-04-20 19:55:57203 controller_(this, profile),
[email protected]57c6a652009-05-04 07:58:34204 view_(TabContentsView::Create(static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57205 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(
[email protected]57c6a652009-05-04 07:58:34206 static_cast<TabContents*>(this),
207 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57208 property_bag_(),
209 registrar_(),
[email protected]57c6a652009-05-04 07:58:34210 printing_(*static_cast<TabContents*>(this)),
[email protected]fdd61c62009-04-22 19:22:57211 save_package_(),
212 cancelable_consumer_(),
213 autofill_manager_(),
214 password_manager_(),
215 plugin_installer_(),
216 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(
[email protected]57c6a652009-05-04 07:58:34217 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57218 select_file_dialog_(),
219 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34220 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29221 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34222 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34223 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57224 current_load_start_(),
225 load_state_(net::LOAD_STATE_IDLE),
226 load_state_host_(),
227 received_page_title_(false),
228 is_starred_(false),
229 contents_mime_type_(),
230 encoding_(),
[email protected]332af7732009-03-11 13:21:35231 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57232 infobar_delegates_(),
[email protected]fdd61c62009-04-22 19:22:57233 find_ui_active_(false),
234 find_op_aborted_(false),
235 current_find_request_id_(find_request_id_counter_++),
236 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12237 last_search_case_sensitive_(false),
238 last_search_prepopulate_text_(NULL),
239 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57240 capturing_contents_(false),
241 is_being_destroyed_(false),
242 notify_disconnection_(false),
243 history_requests_(),
244#if defined(OS_WIN)
245 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
246#endif
247 last_javascript_message_dismissal_(),
248 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32249 pending_install_.page_id = 0;
250 pending_install_.callback_functor = NULL;
251
252 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
253
254 view_->CreateView();
255
256 // Register for notifications about all interested prefs change.
257 PrefService* prefs = profile->GetPrefs();
258 if (prefs) {
259 for (int i = 0; i < kPrefsToObserveLength; ++i)
260 prefs->AddPrefObserver(kPrefsToObserve[i], this);
261 }
262
263 // Register for notifications about URL starredness changing on any profile.
264 registrar_.Add(this, NotificationType::URLS_STARRED,
265 NotificationService::AllSources());
266 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
267 NotificationService::AllSources());
268 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
269 NotificationService::AllSources());
270
271 // Keep a global copy of the previous search string (if any).
272 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12273 last_search_prepopulate_text_ = &global_last_search;
[email protected]332af7732009-03-11 13:21:35274}
initial.commit09911bf2008-07-26 23:55:29275
276TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32277 is_being_destroyed_ = true;
278
279 // We don't want any notifications while we're runnign our destructor.
280 registrar_.RemoveAll();
281
282 // Unregister the notifications of all observed prefs change.
283 PrefService* prefs = profile()->GetPrefs();
284 if (prefs) {
285 for (int i = 0; i < kPrefsToObserveLength; ++i)
286 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
287 }
288
289 // Clean up subwindows like plugins and the find in page bar.
290 view_->OnContentsDestroy();
291
292 NotifyDisconnected();
[email protected]8897c382009-05-06 17:53:26293 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:32294
295 if (pending_install_.callback_functor)
296 pending_install_.callback_functor->Cancel();
297
298 // First cleanly close all child windows.
299 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
300 // some of these to close. CloseWindows is async, so it might get called
301 // twice before it runs.
302 int size = static_cast<int>(child_windows_.size());
303 for (int i = size - 1; i >= 0; --i) {
304 ConstrainedWindow* window = child_windows_[i];
305 if (window)
306 window->CloseConstrainedWindow();
307 }
308
[email protected]420ae012009-04-24 05:16:32309 // Notify any observer that have a reference on this tab contents.
310 NotificationService::current()->Notify(
311 NotificationType::TAB_CONTENTS_DESTROYED,
312 Source<TabContents>(this),
313 NotificationService::NoDetails());
314
[email protected]1e5e74f2009-05-27 20:55:12315 // Notify any lasting InfobarDelegates that have not yet been removed that
316 // whatever infobar they were handling in this TabContents has closed,
317 // because the TabContents is going away entirely.
318 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
319 // notification may trigger infobars calls that access their delegate. (and
320 // some implementations of InfoBarDelegate do delete themselves on
321 // InfoBarClosed()).
322 for (int i = 0; i < infobar_delegate_count(); ++i) {
323 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
324 delegate->InfoBarClosed();
325 }
326 infobar_delegates_.clear();
327
[email protected]420ae012009-04-24 05:16:32328 // TODO(brettw) this should be moved to the view.
329#if defined(OS_WIN)
330 // If we still have a window handle, destroy it. GetNativeView can return
331 // NULL if this contents was part of a window that closed.
332 if (GetNativeView())
333 ::DestroyWindow(GetNativeView());
334#endif
initial.commit09911bf2008-07-26 23:55:29335}
336
[email protected]d5f942ba2008-09-26 19:30:34337// static
338void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32339 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
340
341 WebPreferences pref_defaults;
342 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
343 pref_defaults.javascript_enabled);
344 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
345 pref_defaults.web_security_enabled);
346 prefs->RegisterBooleanPref(
347 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
348 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
349 pref_defaults.loads_images_automatically);
350 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
351 pref_defaults.plugins_enabled);
352 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
353 pref_defaults.dom_paste_enabled);
354 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
355 pref_defaults.shrinks_standalone_images_to_fit);
356 prefs->RegisterBooleanPref(prefs::kWebKitDeveloperExtrasEnabled,
[email protected]96d3fb52009-05-27 14:51:21357 pref_defaults.developer_extras_enabled);
[email protected]0df30122009-06-03 12:13:08358 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
359 pref_defaults.inspector_settings);
[email protected]420ae012009-04-24 05:16:32360 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
361 pref_defaults.text_areas_are_resizable);
362 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
363 pref_defaults.java_enabled);
364
365 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
366 IDS_ACCEPT_LANGUAGES);
367 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
368 IDS_DEFAULT_ENCODING);
369 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
370 IDS_STANDARD_FONT_IS_SERIF);
371 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
372 IDS_FIXED_FONT_FAMILY);
373 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
374 IDS_SERIF_FONT_FAMILY);
375 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
376 IDS_SANS_SERIF_FONT_FAMILY);
377 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
378 IDS_CURSIVE_FONT_FAMILY);
379 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
380 IDS_FANTASY_FONT_FAMILY);
381 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
382 IDS_DEFAULT_FONT_SIZE);
383 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
384 IDS_DEFAULT_FIXED_FONT_SIZE);
385 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
386 IDS_MINIMUM_FONT_SIZE);
387 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
388 IDS_MINIMUM_LOGICAL_FONT_SIZE);
389 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
390 IDS_USES_UNIVERSAL_DETECTOR);
391 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
392 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29393}
394
[email protected]d5f942ba2008-09-26 19:30:34395bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01396 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55397 return true;
[email protected]d5f942ba2008-09-26 19:30:34398}
399
[email protected]6e95706d2009-04-23 22:55:01400AutofillManager* TabContents::GetAutofillManager() {
401 if (autofill_manager_.get() == NULL)
402 autofill_manager_.reset(new AutofillManager(this));
403 return autofill_manager_.get();
404}
405
406PasswordManager* TabContents::GetPasswordManager() {
407 if (password_manager_.get() == NULL)
408 password_manager_.reset(new PasswordManager(this));
409 return password_manager_.get();
410}
411
412PluginInstaller* TabContents::GetPluginInstaller() {
413 if (plugin_installer_.get() == NULL)
414 plugin_installer_.reset(new PluginInstaller(this));
415 return plugin_installer_.get();
416}
417
[email protected]d5f942ba2008-09-26 19:30:34418const GURL& TabContents::GetURL() const {
419 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57420 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34421 return entry ? entry->display_url() : GURL::EmptyGURL();
422}
423
[email protected]96d185d2009-04-24 03:28:54424const string16& TabContents::GetTitle() const {
425 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
426 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
427 if (our_dom_ui) {
428 // Don't override the title in view source mode.
429 NavigationEntry* entry = controller_.GetActiveEntry();
430 if (!(entry && entry->IsViewSourceMode())) {
431 // Give the DOM UI the chance to override our title.
432 const string16& title = our_dom_ui->overridden_title();
433 if (!title.empty())
434 return title;
435 }
436 }
437
438 // We use the title for the last committed entry rather than a pending
439 // navigation entry. For example, when the user types in a URL, we want to
440 // keep the old page's title until the new load has committed and we get a new
441 // title.
442 // The exception is with transient pages, for which we really want to use
443 // their title, as they are not committed.
444 NavigationEntry* entry = controller_.GetTransientEntry();
445 if (entry)
446 return entry->GetTitleForDisplay(&controller_);
447
448 entry = controller_.GetLastCommittedEntry();
449 if (entry)
450 return entry->GetTitleForDisplay(&controller_);
451 else if (controller_.LoadingURLLazily())
452 return controller_.GetLazyTitle();
453 return EmptyString16();
454}
455
[email protected]d5f942ba2008-09-26 19:30:34456int32 TabContents::GetMaxPageID() {
457 if (GetSiteInstance())
458 return GetSiteInstance()->max_page_id();
459 else
460 return max_page_id_;
461}
462
463void TabContents::UpdateMaxPageID(int32 page_id) {
464 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34465 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34466 // testing.
467 if (GetSiteInstance())
468 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34469 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34470}
471
[email protected]96d185d2009-04-24 03:28:54472SiteInstance* TabContents::GetSiteInstance() const {
473 return render_manager_.current_host()->site_instance();
474}
475
[email protected]d5f942ba2008-09-26 19:30:34476const std::wstring TabContents::GetDefaultTitle() const {
477 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
478}
479
[email protected]96d185d2009-04-24 03:28:54480bool TabContents::ShouldDisplayURL() {
481 // Don't hide the url in view source mode.
482 NavigationEntry* entry = controller_.GetActiveEntry();
483 if (entry && entry->IsViewSourceMode())
484 return true;
485 DOMUI* dom_ui = GetDOMUIForCurrentState();
486 if (dom_ui)
487 return !dom_ui->should_hide_url();
488 return true;
489}
490
[email protected]d5f942ba2008-09-26 19:30:34491SkBitmap TabContents::GetFavIcon() const {
492 // Like GetTitle(), we also want to use the favicon for the last committed
493 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57494 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47495 if (entry)
496 return entry->favicon().bitmap();
497
[email protected]ce3fa3c2009-04-20 19:55:57498 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34499 if (entry)
500 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57501 else if (controller_.LoadingURLLazily())
502 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34503 return SkBitmap();
504}
505
[email protected]96d185d2009-04-24 03:28:54506bool TabContents::ShouldDisplayFavIcon() {
507 // Always display a throbber during pending loads.
508 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
509 return true;
510
511 DOMUI* dom_ui = GetDOMUIForCurrentState();
512 if (dom_ui)
513 return !dom_ui->hide_favicon();
514 return true;
515}
516
[email protected]3e45ba92009-02-20 21:09:00517#if defined(OS_WIN)
[email protected]d5f942ba2008-09-26 19:30:34518SecurityStyle TabContents::GetSecurityStyle() const {
519 // We may not have a navigation entry yet.
[email protected]ce3fa3c2009-04-20 19:55:57520 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34521 return entry ? entry->ssl().security_style() : SECURITY_STYLE_UNKNOWN;
522}
523
524bool TabContents::GetSSLEVText(std::wstring* ev_text,
525 std::wstring* ev_tooltip_text) const {
526 DCHECK(ev_text && ev_tooltip_text);
527 ev_text->clear();
528 ev_tooltip_text->clear();
529
[email protected]ce3fa3c2009-04-20 19:55:57530 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34531 if (!entry ||
532 net::IsCertStatusError(entry->ssl().cert_status()) ||
533 ((entry->ssl().cert_status() & net::CERT_STATUS_IS_EV) == 0))
534 return false;
535
536 scoped_refptr<net::X509Certificate> cert;
537 CertStore::GetSharedInstance()->RetrieveCert(entry->ssl().cert_id(), &cert);
538 if (!cert.get()) {
539 NOTREACHED();
540 return false;
541 }
542
543 return SSLManager::GetEVCertNames(*cert, ev_text, ev_tooltip_text);
544}
[email protected]76f68dc2009-03-10 20:31:32545#endif
[email protected]d5f942ba2008-09-26 19:30:34546
[email protected]96d185d2009-04-24 03:28:54547std::wstring TabContents::GetStatusText() const {
548 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
549 return std::wstring();
550
551 switch (load_state_) {
552 case net::LOAD_STATE_WAITING_FOR_CACHE:
553 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
554 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
555 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
556 case net::LOAD_STATE_RESOLVING_HOST:
557 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
558 case net::LOAD_STATE_CONNECTING:
559 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
560 case net::LOAD_STATE_SENDING_REQUEST:
561 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
562 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
563 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
564 load_state_host_);
565 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
566 case net::LOAD_STATE_IDLE:
567 case net::LOAD_STATE_READING_RESPONSE:
568 break;
569 }
570
571 return std::wstring();
572}
573
[email protected]d5f942ba2008-09-26 19:30:34574void TabContents::SetIsCrashed(bool state) {
575 if (state == is_crashed_)
576 return;
577
578 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50579 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34580}
581
[email protected]ce5c4502009-05-06 16:46:11582void TabContents::EnablePageAction(const PageAction* page_action) {
583 DCHECK(page_action);
584
585 if (IsPageActionEnabled(page_action))
586 return; // Already enabled.
587
588 enabled_page_actions_.insert(page_action);
589}
590
591bool TabContents::IsPageActionEnabled(const PageAction* page_action) {
592 DCHECK(page_action);
593 return enabled_page_actions_.end() != enabled_page_actions_.find(page_action);
594}
595
596
[email protected]d5f942ba2008-09-26 19:30:34597void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
598 if (delegate_)
599 delegate_->NavigationStateChanged(this, changed_flags);
600}
601
[email protected]96d185d2009-04-24 03:28:54602void TabContents::DidBecomeSelected() {
603 controller_.SetActive(true);
604
605 if (render_widget_host_view())
606 render_widget_host_view()->DidBecomeSelected();
607
608 // If pid() is -1, that means the RenderProcessHost still hasn't been
609 // initialized. It'll register with CacheManagerHost when it is.
610 if (process()->pid() != -1)
611 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
612}
613
614void TabContents::WasHidden() {
615 if (!capturing_contents()) {
616 // |render_view_host()| can be NULL if the user middle clicks a link to open
617 // a tab in then background, then closes the tab before selecting it. This
618 // is because closing the tab calls TabContents::Destroy(), which removes
619 // the |render_view_host()|; then when we actually destroy the window,
620 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
621 if (render_widget_host_view())
622 render_widget_host_view()->WasHidden();
623
624 // Loop through children and send WasHidden to them, too.
625 int count = static_cast<int>(child_windows_.size());
626 for (int i = count - 1; i >= 0; --i) {
627 ConstrainedWindow* window = child_windows_.at(i);
628 window->WasHidden();
629 }
630 }
631
632 NotificationService::current()->Notify(
633 NotificationType::TAB_CONTENTS_HIDDEN,
634 Source<TabContents>(this),
635 NotificationService::NoDetails());
636}
637
[email protected]d5f942ba2008-09-26 19:30:34638void TabContents::Activate() {
639 if (delegate_)
640 delegate_->ActivateContents(this);
641}
642
[email protected]96d185d2009-04-24 03:28:54643void TabContents::ShowContents() {
644 if (render_widget_host_view())
645 render_widget_host_view()->DidBecomeSelected();
646
647 // Loop through children and send DidBecomeSelected to them, too.
648 int count = static_cast<int>(child_windows_.size());
649 for (int i = count - 1; i >= 0; --i) {
650 ConstrainedWindow* window = child_windows_.at(i);
651 window->DidBecomeSelected();
652 }
653}
654
655void TabContents::HideContents() {
656 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
657 // our superclass HideContents(), because some callers want to be very picky
658 // about the order in which these get called. In addition to making the code
659 // here practically impossible to understand, this also means we end up
660 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34661 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54662 WasHidden();
663}
664
[email protected]c0588052008-10-27 23:01:50665void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34666 WindowOpenDisposition disposition,
667 PageTransition::Type transition) {
668 if (delegate_)
[email protected]c0588052008-10-27 23:01:50669 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34670}
671
672bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54673 const NavigationEntry& entry = *controller_.pending_entry();
674
675 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
676 if (!dest_render_view_host)
677 return false; // Unable to create the desired render view host.
678
679 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]684b4ba22009-05-07 06:27:41680 DevToolsManager* devtools_manager = g_browser_process->devtools_manager();
[email protected]7e8e6b62009-05-08 11:28:32681 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41682 devtools_manager->OnNavigatingToPendingEntry(
683 render_view_host(),
684 dest_render_view_host,
685 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32686 }
[email protected]96d185d2009-04-24 03:28:54687
688 // Used for page load time metrics.
689 current_load_start_ = base::TimeTicks::Now();
690
691 // Navigate in the desired RenderViewHost.
692 dest_render_view_host->NavigateToEntry(entry, reload);
693
694 if (entry.page_id() == -1) {
695 // HACK!! This code suppresses javascript: URLs from being added to
696 // session history, which is what we want to do for javascript: URLs that
697 // do not generate content. What we really need is a message from the
698 // renderer telling us that a new page was not created. The same message
699 // could be used for mailto: URLs and the like.
700 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
701 return false;
702 }
703
704 // Clear any provisional password saves - this stops password infobars
705 // showing up on pages the user navigates to while the right page is
706 // loading.
707 GetPasswordManager()->ClearProvisionalSave();
708
709 if (reload && !profile()->IsOffTheRecord()) {
710 HistoryService* history =
711 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
712 if (history)
713 history->SetFavIconOutOfDateForPage(entry.url());
714 }
715
[email protected]d5f942ba2008-09-26 19:30:34716 return true;
717}
718
[email protected]96d185d2009-04-24 03:28:54719void TabContents::Stop() {
720 render_manager_.Stop();
721 printing_.Stop();
722}
723
724void TabContents::Cut() {
725 render_view_host()->Cut();
726}
727
728void TabContents::Copy() {
729 render_view_host()->Copy();
730}
731
732void TabContents::Paste() {
733 render_view_host()->Paste();
734}
735
736void TabContents::DisassociateFromPopupCount() {
737 render_view_host()->DisassociateFromPopupCount();
738}
739
740TabContents* TabContents::Clone() {
741 // We create a new SiteInstance so that the new tab won't share processes
742 // with the old one. This can be changed in the future if we need it to share
743 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32744 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54745 SiteInstance::CreateSiteInstance(profile()),
746 MSG_ROUTING_NONE, NULL);
747 tc->controller().CopyStateFrom(controller_);
748 return tc;
749}
750
[email protected]420ae012009-04-24 05:16:32751void TabContents::CreateShortcut() {
752 NavigationEntry* entry = controller_.GetLastCommittedEntry();
753 if (!entry)
754 return;
755
756 // We only allow one pending install request. By resetting the page id we
757 // effectively cancel the pending install request.
758 pending_install_.page_id = entry->page_id();
759 pending_install_.icon = GetFavIcon();
760 pending_install_.title = UTF16ToWideHack(GetTitle());
761 pending_install_.url = GetURL();
762 if (pending_install_.callback_functor) {
763 pending_install_.callback_functor->Cancel();
764 pending_install_.callback_functor = NULL;
765 }
766 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
767 if (pending_install_.title.empty())
768 pending_install_.title = UTF8ToWide(GetURL().spec());
769
770 // Request the application info. When done OnDidGetApplicationInfo is invoked
771 // and we'll create the shortcut.
772 render_view_host()->GetApplicationInfo(pending_install_.page_id);
773}
774
[email protected]76f68dc2009-03-10 20:31:32775#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29776ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]c2dacc92008-10-16 23:51:38777 views::WindowDelegate* window_delegate,
778 views::View* contents_view) {
initial.commit09911bf2008-07-26 23:55:29779 ConstrainedWindow* window =
780 ConstrainedWindow::CreateConstrainedDialog(
781 this, gfx::Rect(), contents_view, window_delegate);
782 child_windows_.push_back(window);
783 return window;
784}
[email protected]f3332e12009-03-23 15:28:57785#endif
initial.commit09911bf2008-07-26 23:55:29786
787void TabContents::AddNewContents(TabContents* new_contents,
788 WindowOpenDisposition disposition,
789 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22790 bool user_gesture,
791 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29792 if (!delegate_)
793 return;
794
[email protected]f3332e12009-03-23 15:28:57795#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:22796 bool constrain_popup = false;
[email protected]35f7d212009-04-29 21:19:27797 if ((disposition == NEW_POPUP) && !user_gesture &&
798 !CommandLine::ForCurrentProcess()->HasSwitch(
799 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22800 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31801 // the whitelist. The popup owner will handle checking this.
802 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
803 initial_pos,
804 creator_url.is_valid() ? creator_url.host() : std::string());
805 } else {
[email protected]0aa55312008-10-17 21:53:08806 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29807 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
808 user_gesture);
809 }
[email protected]b6c874582009-05-08 19:38:31810 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
[email protected]f3332e12009-03-23 15:28:57811#else
812 // TODO(port): implement the popup blocker stuff
813 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
814 user_gesture);
815#endif
initial.commit09911bf2008-07-26 23:55:29816}
817
[email protected]0c9ee992009-06-03 16:56:38818#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29819void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25820 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22821 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29822}
[email protected]0c9ee992009-06-03 16:56:38823#endif
initial.commit09911bf2008-07-26 23:55:29824
[email protected]96d185d2009-04-24 03:28:54825void TabContents::PopupNotificationVisibilityChanged(bool visible) {
826 render_view_host()->PopupNotificationVisibilityChanged(visible);
827}
828
829gfx::NativeView TabContents::GetContentNativeView() {
830 return view_->GetContentNativeView();
831}
832
833gfx::NativeView TabContents::GetNativeView() const {
834 return view_->GetNativeView();
835}
836
837void TabContents::GetContainerBounds(gfx::Rect *out) const {
838 view_->GetContainerBounds(out);
839}
840
841void TabContents::Focus() {
842 view_->Focus();
843}
844
845void TabContents::SetInitialFocus(bool reverse) {
846 render_view_host()->SetInitialFocus(reverse);
847}
848
849bool TabContents::FocusLocationBarByDefault() {
850 DOMUI* dom_ui = GetDOMUIForCurrentState();
851 if (dom_ui)
852 return dom_ui->focus_location_bar_by_default();
853 return false;
854}
855
[email protected]616ed5a2008-11-21 22:27:24856void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
857 // Look through the existing InfoBarDelegates we have for a match. If we've
858 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05859 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24860 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
861 return;
862 }
863
864 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56865 NotificationService::current()->Notify(
866 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
867 Source<TabContents>(this),
868 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24869
870 // Add ourselves as an observer for navigations the first time a delegate is
871 // added. We use this notification to expire InfoBars that need to expire on
872 // page transitions.
873 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56874 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57875 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24876 }
877}
878
879void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
880 std::vector<InfoBarDelegate*>::iterator it =
881 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
882 if (it != infobar_delegates_.end()) {
883 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56884 NotificationService::current()->Notify(
885 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
886 Source<TabContents>(this),
887 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05888 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24889
[email protected]6a02963e2009-01-06 16:58:03890 // Remove ourselves as an observer if we are tracking no more InfoBars.
891 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56892 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57893 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03894 }
[email protected]616ed5a2008-11-21 22:27:24895 }
896}
[email protected]3edd9522009-03-04 22:19:41897
[email protected]96d185d2009-04-24 03:28:54898bool TabContents::IsBookmarkBarAlwaysVisible() {
899 // See GetDOMUIForCurrentState() comment for more info. This case is very
900 // similar, but for non-first loads, we want to use the committed entry. This
901 // is so the bookmarks bar disappears at the same time the page does.
902 if (controller_.GetLastCommittedEntry()) {
903 // Not the first load, always use the committed DOM UI.
904 if (render_manager_.dom_ui())
905 return render_manager_.dom_ui()->force_bookmark_bar_visible();
906 return false; // Default.
907 }
908
909 // When it's the first load, we know either the pending one or the committed
910 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
911 // of them will be valid, so we can just check both.
912 if (render_manager_.pending_dom_ui())
913 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
914 if (render_manager_.dom_ui())
915 return render_manager_.dom_ui()->force_bookmark_bar_visible();
916 return false; // Default.
917}
918
[email protected]3edd9522009-03-04 22:19:41919void TabContents::ToolbarSizeChanged(bool is_animating) {
920 TabContentsDelegate* d = delegate();
921 if (d)
922 d->ToolbarSizeChanged(this, is_animating);
923}
[email protected]616ed5a2008-11-21 22:27:24924
[email protected]d5f942ba2008-09-26 19:30:34925void TabContents::OnStartDownload(DownloadItem* download) {
926 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34927
928 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31929 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34930
[email protected]59560e0b2009-06-04 03:30:22931 if (tab_contents && tab_contents->delegate())
932 tab_contents->delegate()->OnStartDownload(download);
[email protected]3edd9522009-03-04 22:19:41933}
[email protected]3edd9522009-03-04 22:19:41934
[email protected]d5f942ba2008-09-26 19:30:34935void TabContents::WillClose(ConstrainedWindow* window) {
936 ConstrainedWindowList::iterator it =
937 find(child_windows_.begin(), child_windows_.end(), window);
938 if (it != child_windows_.end())
939 child_windows_.erase(it);
940
[email protected]0c9ee992009-06-03 16:56:38941#if defined(OS_WIN)
942 if (window == blocked_popups_)
943 blocked_popups_ = NULL;
944
945 if (::IsWindow(GetNativeView())) {
946 CRect client_rect;
947 GetClientRect(GetNativeView(), &client_rect);
948 RepositionSupressedPopupsToFit(
949 gfx::Size(client_rect.Width(), client_rect.Height()));
950 }
951#endif
[email protected]d5f942ba2008-09-26 19:30:34952}
953
[email protected]d5f942ba2008-09-26 19:30:34954void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:35955#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:06956 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:35957#endif
[email protected]d5f942ba2008-09-26 19:30:34958}
959
[email protected]e491f1c2009-05-22 20:28:12960void TabContents::StartFinding(string16 find_text,
961 bool forward_direction,
962 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:01963 // If find_text is empty, it means FindNext was pressed with a keyboard
964 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:12965 if (find_text.empty() && find_text_.empty()) {
966 if (last_search_prepopulate_text_->empty())
967 return;
968 // Try whatever we searched for last in any tab.
969 find_text = *last_search_prepopulate_text_;
970 }
[email protected]6e95706d2009-04-23 22:55:01971
972 // This is a FindNext operation if we are searching for the same text again,
973 // or if the passed in search text is empty (FindNext keyboard shortcut). The
974 // exception to this is if the Find was aborted (then we don't want FindNext
975 // because the highlighting has been cleared and we need it to reappear). We
976 // therefore treat FindNext after an aborted Find operation as a full fledged
977 // Find.
978 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:12979 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:01980 !find_op_aborted_;
981 if (!find_next)
982 current_find_request_id_ = find_request_id_counter_++;
983
984 if (!find_text.empty())
985 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:12986 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:01987
988 find_op_aborted_ = false;
989
990 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:12991 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:01992
993 render_view_host()->StartFinding(current_find_request_id_,
994 find_text_,
995 forward_direction,
[email protected]e491f1c2009-05-22 20:28:12996 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:01997 find_next);
998}
999
1000void TabContents::StopFinding(bool clear_selection) {
1001 find_ui_active_ = false;
1002 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:121003 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:011004 render_view_host()->StopFinding(clear_selection);
1005}
1006
[email protected]420ae012009-04-24 05:16:321007void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
1008 bool success,
1009 const std::wstring& prompt) {
1010 last_javascript_message_dismissal_ = base::TimeTicks::Now();
1011 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
1012}
1013
[email protected]571e31152009-05-15 19:34:021014void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
1015 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
1016}
1017
[email protected]420ae012009-04-24 05:16:321018void TabContents::OnSavePage() {
1019 // If we can not save the page, try to download it.
1020 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1021 DownloadManager* dlm = profile()->GetDownloadManager();
1022 const GURL& current_page_url = GetURL();
1023 if (dlm && current_page_url.is_valid())
[email protected]c9825a42009-05-01 22:51:501024 dlm->DownloadUrl(current_page_url, GURL(), "", AsWC(this));
[email protected]420ae012009-04-24 05:16:321025 return;
1026 }
1027
1028 Stop();
1029
1030 // Create the save package and possibly prompt the user for the name to save
1031 // the page as. The user prompt is an asynchronous operation that runs on
1032 // another thread.
1033 save_package_ = new SavePackage(AsWC(this));
1034 save_package_->GetSaveInfo();
1035}
1036
1037// Used in automated testing to bypass prompting the user for file names.
1038// Instead, the names and paths are hard coded rather than running them through
1039// file name sanitation and extension / mime checking.
1040void TabContents::SavePage(const std::wstring& main_file,
1041 const std::wstring& dir_path,
1042 SavePackage::SavePackageType save_type) {
1043 // Stop the page from navigating.
1044 Stop();
1045
1046 save_package_ = new SavePackage(AsWC(this), save_type,
1047 FilePath::FromWStringHack(main_file),
1048 FilePath::FromWStringHack(dir_path));
1049 save_package_->Init();
1050}
1051
1052void TabContents::PrintPreview() {
1053 // We don't show the print preview yet, only the print dialog.
1054 PrintNow();
1055}
1056
1057bool TabContents::PrintNow() {
1058 // We can't print interstitial page for now.
1059 if (showing_interstitial_page())
1060 return false;
1061
1062 return render_view_host()->PrintPages();
1063}
1064
1065bool TabContents::IsActiveEntry(int32 page_id) {
1066 NavigationEntry* active_entry = controller_.GetActiveEntry();
1067 return (active_entry != NULL &&
1068 active_entry->site_instance() == GetSiteInstance() &&
1069 active_entry->page_id() == page_id);
1070}
1071
[email protected]96d185d2009-04-24 03:28:541072// Notifies the RenderWidgetHost instance about the fact that the page is
1073// loading, or done loading and calls the base implementation.
1074void TabContents::SetIsLoading(bool is_loading,
1075 LoadNotificationDetails* details) {
1076 if (is_loading == is_loading_)
1077 return;
1078
1079 if (!is_loading) {
1080 load_state_ = net::LOAD_STATE_IDLE;
1081 load_state_host_.clear();
1082 }
1083
1084 render_manager_.SetIsLoading(is_loading);
1085
1086 is_loading_ = is_loading;
1087 waiting_for_response_ = is_loading;
1088
1089 if (delegate_)
1090 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351091 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541092
1093 NotificationType type = is_loading ? NotificationType::LOAD_START :
1094 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111095 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541096 if (details)
1097 det = Details<LoadNotificationDetails>(details);
1098 NotificationService::current()->Notify(type,
1099 Source<NavigationController>(&controller_),
1100 det);
1101}
1102
[email protected]76f68dc2009-03-10 20:31:321103#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:221104void TabContents::CreateBlockedPopupContainerIfNecessary() {
1105 if (blocked_popups_)
1106 return;
1107
1108 CRect client_rect;
1109 GetClientRect(GetNativeView(), &client_rect);
1110 gfx::Point anchor_position(
1111 client_rect.Width() - views::NativeScrollBar::GetVerticalScrollBarWidth(),
1112 client_rect.Height());
1113 blocked_popups_ = BlockedPopupContainer::Create(this, profile(),
1114 anchor_position);
[email protected]0c9ee992009-06-03 16:56:381115 child_windows_.push_back(blocked_popups_);
[email protected]2c4410d2009-05-06 23:46:221116}
1117
[email protected]b6c874582009-05-08 19:38:311118void TabContents::AddPopup(TabContents* new_contents,
1119 const gfx::Rect& initial_pos,
1120 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221121 CreateBlockedPopupContainerIfNecessary();
1122 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221123}
1124
[email protected]e69bce3dd2009-04-20 22:05:121125// TODO(brettw) This should be on the TabContentsView.
[email protected]0c9ee992009-06-03 16:56:381126void TabContents::RepositionSupressedPopupsToFit(const gfx::Size& new_size) {
1127 // TODO(erg): There's no way to detect whether scroll bars are
1128 // visible, so for beta, we're just going to assume that the
1129 // vertical scroll bar is visible, and not care about covering up
1130 // the horizontal scroll bar. Fixing this is half of
1131 // http://b/1118139.
1132 gfx::Point anchor_position(
1133 new_size.width() -
1134 views::NativeScrollBar::GetVerticalScrollBarWidth(),
1135 new_size.height());
1136
[email protected]d6598c052008-11-05 19:03:251137 if (blocked_popups_)
[email protected]0c9ee992009-06-03 16:56:381138 blocked_popups_->RepositionConstrainedWindowTo(anchor_position);
[email protected]d5f942ba2008-09-26 19:30:341139}
1140
[email protected]b9681312008-11-07 00:08:261141bool TabContents::ShowingBlockedPopupNotification() const {
1142 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221143 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261144}
[email protected]0c9ee992009-06-03 16:56:381145#endif // defined(OS_WIN)
[email protected]616ed5a2008-11-21 22:27:241146
1147namespace {
1148bool TransitionIsReload(PageTransition::Type transition) {
1149 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1150}
1151}
1152
1153void TabContents::ExpireInfoBars(
1154 const NavigationController::LoadCommittedDetails& details) {
1155 // Only hide InfoBars when the user has done something that makes the main
1156 // frame load. We don't want various automatic or subframe navigations making
1157 // it disappear.
1158 if (!details.is_user_initiated_main_frame_load())
1159 return;
1160
[email protected]f86a07022008-11-25 01:06:051161 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241162 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051163 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241164 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241165 }
1166}
[email protected]fdd61c62009-04-22 19:22:571167
1168void TabContents::OnGearsCreateShortcutDone(
1169 const GearsShortcutData2& shortcut_data, bool success) {
1170 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1171 bool same_page =
1172 current_entry && pending_install_.page_id == current_entry->page_id();
1173
1174 if (success && same_page) {
1175 // Only switch to app mode if the user chose to create a shortcut and
1176 // we're still on the same page that it corresponded to.
1177 if (delegate())
1178 delegate()->ConvertContentsToApplication(this);
1179 }
1180
1181 // Reset the page id to indicate no requests are pending.
1182 pending_install_.page_id = 0;
1183 pending_install_.callback_functor = NULL;
1184}
[email protected]96d185d2009-04-24 03:28:541185
1186DOMUI* TabContents::GetDOMUIForCurrentState() {
1187 // When there is a pending navigation entry, we want to use the pending DOMUI
1188 // that goes along with it to control the basic flags. For example, we want to
1189 // show the pending URL in the URL bar, so we want the display_url flag to
1190 // be from the pending entry.
1191 //
1192 // The confusion comes because there are multiple possibilities for the
1193 // initial load in a tab as a side effect of the way the RenderViewHostManager
1194 // works.
1195 //
1196 // - For the very first tab the load looks "normal". The new tab DOM UI is
1197 // the pending one, and we want it to apply here.
1198 //
1199 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1200 // get switched to the one previously associated with the new tab pages.
1201 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1202 // have a committed DOM UI in this case.
1203 //
1204 // This condition handles all of these cases:
1205 //
1206 // - First load in first tab: no committed nav entry + pending nav entry +
1207 // pending dom ui:
1208 // -> Use pending DOM UI if any.
1209 //
1210 // - First load in second tab: no committed nav entry + pending nav entry +
1211 // no pending DOM UI:
1212 // -> Use the committed DOM UI if any.
1213 //
1214 // - Second navigation in any tab: committed nav entry + pending nav entry:
1215 // -> Use pending DOM UI if any.
1216 //
1217 // - Normal state with no load: committed nav entry + no pending nav entry:
1218 // -> Use committed DOM UI.
1219 if (controller_.pending_entry() &&
1220 (controller_.GetLastCommittedEntry() ||
1221 render_manager_.pending_dom_ui()))
1222 return render_manager_.pending_dom_ui();
1223 return render_manager_.dom_ui();
1224}
[email protected]420ae012009-04-24 05:16:321225
1226void TabContents::DidNavigateMainFramePostCommit(
1227 const NavigationController::LoadCommittedDetails& details,
1228 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]420ae012009-04-24 05:16:321229 if (details.is_user_initiated_main_frame_load()) {
1230 // Clear the status bubble. This is a workaround for a bug where WebKit
1231 // doesn't let us know that the cursor left an element during a
1232 // transition (this is also why the mouse cursor remains as a hand after
1233 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1234 // clear the bubble when a user navigates to a named anchor in the same
1235 // page.
1236 UpdateTargetURL(details.entry->page_id(), GURL());
1237
1238 // UpdateHelpersForDidNavigate will handle the case where the password_form
1239 // origin is valid.
1240 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1241 // cleaned up and covered by tests.
1242 if (!params.password_form.origin.is_valid())
1243 GetPasswordManager()->DidNavigate();
1244 }
1245
1246 // The keyword generator uses the navigation entries, so must be called after
1247 // the commit.
1248 GenerateKeywordIfNecessary(params);
1249
1250 // Allow the new page to set the title again.
1251 received_page_title_ = false;
1252
1253 // Get the favicon, either from history or request it from the net.
1254 fav_icon_helper_.FetchFavIcon(details.entry->url());
1255
[email protected]ce5c4502009-05-06 16:46:111256 // Disable all page actions.
1257 enabled_page_actions_.clear();
1258
[email protected]420ae012009-04-24 05:16:321259 // Close constrained popups if necessary.
1260 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1261
1262 // Update the starred state.
1263 UpdateStarredStateForCurrentURL();
1264}
1265
1266void TabContents::DidNavigateAnyFramePostCommit(
1267 RenderViewHost* render_view_host,
1268 const NavigationController::LoadCommittedDetails& details,
1269 const ViewHostMsg_FrameNavigate_Params& params) {
1270 // If we navigate, start showing messages again. This does nothing to prevent
1271 // a malicious script from spamming messages, since the script could just
1272 // reload the page to stop blocking.
1273 suppress_javascript_messages_ = false;
1274
1275 // Update history. Note that this needs to happen after the entry is complete,
1276 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1277 if (params.should_update_history) {
1278 // Most of the time, the displayURL matches the loaded URL, but for about:
1279 // URLs, we use a data: URL as the real value. We actually want to save
1280 // the about: URL to the history db and keep the data: URL hidden. This is
1281 // what the TabContents' URL getter does.
1282 UpdateHistoryForNavigation(GetURL(), params);
1283 }
1284
1285 // Notify the password manager of the navigation or form submit.
1286 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1287 // cleaned up and covered by tests.
1288 if (params.password_form.origin.is_valid())
1289 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1290}
1291
1292void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1293 const GURL& current_url) {
1294 if (net::RegistryControlledDomainService::SameDomainOrHost(
1295 previous_url, current_url))
1296 return;
1297
1298 // Clear out any child windows since we are leaving this page entirely.
1299 // We use indices instead of iterators in case CloseWindow does something
1300 // that may invalidate an iterator.
1301 int size = static_cast<int>(child_windows_.size());
1302 for (int i = size - 1; i >= 0; --i) {
1303 ConstrainedWindow* window = child_windows_[i];
1304 if (window)
1305 window->CloseConstrainedWindow();
1306 }
1307}
1308
1309void TabContents::UpdateStarredStateForCurrentURL() {
1310 BookmarkModel* model = profile()->GetBookmarkModel();
1311 const bool old_state = is_starred_;
1312 is_starred_ = (model && model->IsBookmarked(GetURL()));
1313
1314 if (is_starred_ != old_state && delegate())
1315 delegate()->URLStarredChanged(this, is_starred_);
1316}
1317
1318void TabContents::UpdateAlternateErrorPageURL() {
1319 GURL url = GetAlternateErrorPageURL();
1320 render_view_host()->SetAlternateErrorPageURL(url);
1321}
1322
1323void TabContents::UpdateWebPreferences() {
1324 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1325}
1326
1327void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1328 RenderViewHost* rvh) {
1329 // If we are creating a RVH for a restored controller, then we might
1330 // have more page IDs than the SiteInstance's current max page ID. We must
1331 // make sure that the max page ID is larger than any restored page ID.
1332 // Note that it is ok for conflicting page IDs to exist in another tab
1333 // (i.e., NavigationController), but if any page ID is larger than the max,
1334 // the back/forward list will get confused.
1335 int max_restored_page_id = controller_.max_restored_page_id();
1336 if (max_restored_page_id > 0) {
1337 int curr_max_page_id = site_instance->max_page_id();
1338 if (max_restored_page_id > curr_max_page_id) {
1339 // Need to update the site instance immediately.
1340 site_instance->UpdateMaxPageID(max_restored_page_id);
1341
1342 // Also tell the renderer to update its internal representation. We
1343 // need to reserve enough IDs to make all restored page IDs less than
1344 // the max.
1345 if (curr_max_page_id < 0)
1346 curr_max_page_id = 0;
1347 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1348 }
1349 }
1350}
1351
1352void TabContents::UpdateHistoryForNavigation(
1353 const GURL& display_url,
1354 const ViewHostMsg_FrameNavigate_Params& params) {
1355 if (profile()->IsOffTheRecord())
1356 return;
1357
1358 // Add to history service.
1359 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1360 if (hs) {
1361 if (PageTransition::IsMainFrame(params.transition) &&
1362 display_url != params.url) {
1363 // Hack on the "display" URL so that it will appear in history. For some
1364 // types of URLs, we will display a magic URL that is different from where
1365 // the page is actually navigated. We want the user to see in history
1366 // what they saw in the URL bar, so we add the display URL as a redirect.
1367 // This only applies to the main frame, as the display URL doesn't apply
1368 // to sub-frames.
1369 std::vector<GURL> redirects = params.redirects;
1370 if (!redirects.empty())
1371 redirects.back() = display_url;
1372 hs->AddPage(display_url, this, params.page_id, params.referrer,
1373 params.transition, redirects);
1374 } else {
1375 hs->AddPage(params.url, this, params.page_id, params.referrer,
1376 params.transition, params.redirects);
1377 }
1378 }
1379}
1380
1381bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1382 const std::wstring& title) {
1383 // For file URLs without a title, use the pathname instead. In the case of a
1384 // synthesized title, we don't want the update to count toward the "one set
1385 // per page of the title to history."
1386 std::wstring final_title;
1387 bool explicit_set;
1388 if (entry->url().SchemeIsFile() && title.empty()) {
1389 final_title = UTF8ToWide(entry->url().ExtractFileName());
1390 explicit_set = false; // Don't count synthetic titles toward the set limit.
1391 } else {
1392 TrimWhitespace(title, TRIM_ALL, &final_title);
1393 explicit_set = true;
1394 }
1395
1396 if (final_title == UTF16ToWideHack(entry->title()))
1397 return false; // Nothing changed, don't bother.
1398
1399 entry->set_title(WideToUTF16Hack(final_title));
1400
1401 // Update the history system for this page.
1402 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1403 HistoryService* hs =
1404 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1405 if (hs)
1406 hs->SetPageTitle(entry->display_url(), final_title);
1407
1408 // Don't allow the title to be saved again for explicitly set ones.
1409 received_page_title_ = explicit_set;
1410 }
1411
1412 // Lastly, set the title for the view.
1413 view_->SetPageTitle(final_title);
1414
1415 return true;
1416}
1417
1418void TabContents::NotifySwapped() {
1419 // After sending out a swap notification, we need to send a disconnect
1420 // notification so that clients that pick up a pointer to |this| can NULL the
1421 // pointer. See Bug 1230284.
1422 notify_disconnection_ = true;
1423 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341424 NotificationType::TAB_CONTENTS_SWAPPED,
1425 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321426 NotificationService::NoDetails());
1427}
1428
1429void TabContents::NotifyConnected() {
1430 notify_disconnection_ = true;
1431 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341432 NotificationType::TAB_CONTENTS_CONNECTED,
1433 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321434 NotificationService::NoDetails());
1435}
1436
1437void TabContents::NotifyDisconnected() {
1438 if (!notify_disconnection_)
1439 return;
1440
1441 notify_disconnection_ = false;
1442 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341443 NotificationType::TAB_CONTENTS_DISCONNECTED,
1444 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321445 NotificationService::NoDetails());
1446}
1447
1448void TabContents::GenerateKeywordIfNecessary(
1449 const ViewHostMsg_FrameNavigate_Params& params) {
1450 if (!params.searchable_form_url.is_valid())
1451 return;
1452
1453 if (profile()->IsOffTheRecord())
1454 return;
1455
1456 int last_index = controller_.last_committed_entry_index();
1457 // When there was no previous page, the last index will be 0. This is
1458 // normally due to a form submit that opened in a new tab.
1459 // TODO(brettw) bug 916126: we should support keywords when form submits
1460 // happen in new tabs.
1461 if (last_index <= 0)
1462 return;
1463 const NavigationEntry* previous_entry =
1464 controller_.GetEntryAtIndex(last_index - 1);
1465 if (IsFormSubmit(previous_entry)) {
1466 // Only generate a keyword if the previous page wasn't itself a form
1467 // submit.
1468 return;
1469 }
1470
1471 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1472 previous_entry->user_typed_url() : previous_entry->url();
1473 std::wstring keyword =
1474 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1475 if (keyword.empty())
1476 return;
1477
1478 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1479 if (!url_model)
1480 return;
1481
1482 if (!url_model->loaded()) {
1483 url_model->Load();
1484 return;
1485 }
1486
1487 const TemplateURL* current_url;
1488 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1489 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1490 return;
1491
1492 if (current_url) {
1493 if (current_url->originating_url().is_valid()) {
1494 // The existing keyword was generated from an OpenSearch description
1495 // document, don't regenerate.
1496 return;
1497 }
1498 url_model->Remove(current_url);
1499 }
1500 TemplateURL* new_url = new TemplateURL();
1501 new_url->set_keyword(keyword);
1502 new_url->set_short_name(keyword);
1503 new_url->SetURL(url, 0, 0);
1504 new_url->add_input_encoding(params.searchable_form_encoding);
1505 DCHECK(controller_.GetLastCommittedEntry());
1506 const GURL& favicon_url =
1507 controller_.GetLastCommittedEntry()->favicon().url();
1508 if (favicon_url.is_valid()) {
1509 new_url->SetFavIconURL(favicon_url);
1510 } else {
1511 // The favicon url isn't valid. This means there really isn't a favicon,
1512 // or the favicon url wasn't obtained before the load started. This assumes
1513 // the later.
1514 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1515 // its url.
1516 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1517 }
1518 new_url->set_safe_for_autoreplace(true);
1519 url_model->Add(new_url);
1520}
1521
1522RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1523 return view_.get();
1524}
1525
1526RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1527 return save_package_.get(); // May be NULL, but we can return NULL.
1528}
1529
[email protected]6dfed102009-04-28 03:09:531530ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1531 RenderViewHost* render_view_host,
1532 const std::string& extension_id) {
1533 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1534 extension_id);
1535}
1536
[email protected]57c6a652009-05-04 07:58:341537TabContents* TabContents::GetAsTabContents() {
1538 return this;
1539}
1540
[email protected]420ae012009-04-24 05:16:321541void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1542 NavigationEntry* entry = controller_.GetActiveEntry();
1543 if (!entry)
1544 return;
1545
1546 // When we're creating views, we're still doing initial setup, so we always
1547 // use the pending DOM UI rather than any possibly existing committed one.
1548 if (render_manager_.pending_dom_ui()) {
1549 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1550 }
1551
1552 if (entry->IsViewSourceMode()) {
1553 // Put the renderer in view source mode.
1554 render_view_host->Send(
1555 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1556 }
[email protected]0666aef2009-05-13 19:48:081557
1558 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321559}
1560
1561void TabContents::RenderViewReady(RenderViewHost* rvh) {
1562 if (rvh != render_view_host()) {
1563 // Don't notify the world, since this came from a renderer in the
1564 // background.
1565 return;
1566 }
1567
1568 NotifyConnected();
1569 SetIsCrashed(false);
1570}
1571
1572void TabContents::RenderViewGone(RenderViewHost* rvh) {
1573 // Ask the print preview if this renderer was valuable.
1574 if (!printing_.OnRenderViewGone(rvh))
1575 return;
1576 if (rvh != render_view_host()) {
1577 // The pending page's RenderViewHost is gone.
1578 return;
1579 }
1580
1581 SetIsLoading(false, NULL);
1582 NotifyDisconnected();
1583 SetIsCrashed(true);
1584
1585 // Force an invalidation to render sad tab. The view will notice we crashed
1586 // when it paints.
1587 view_->Invalidate();
1588
1589 // Hide any visible hung renderer warning for this web contents' process.
[email protected]8897c382009-05-06 17:53:261590 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:321591}
1592
1593void TabContents::DidNavigate(RenderViewHost* rvh,
1594 const ViewHostMsg_FrameNavigate_Params& params) {
1595 if (PageTransition::IsMainFrame(params.transition))
1596 render_manager_.DidNavigateMainFrame(rvh);
1597
1598 // Update the site of the SiteInstance if it doesn't have one yet.
1599 if (!GetSiteInstance()->has_site())
1600 GetSiteInstance()->SetSite(params.url);
1601
1602 // Need to update MIME type here because it's referred to in
1603 // UpdateNavigationCommands() called by RendererDidNavigate() to
1604 // determine whether or not to enable the encoding menu.
1605 // It's updated only for the main frame. For a subframe,
1606 // RenderView::UpdateURL does not set params.contents_mime_type.
1607 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1608 // TODO(jungshik): Add a test for the encoding menu to avoid
1609 // regressing it again.
1610 if (PageTransition::IsMainFrame(params.transition))
1611 contents_mime_type_ = params.contents_mime_type;
1612
1613 NavigationController::LoadCommittedDetails details;
1614 if (!controller_.RendererDidNavigate(params, &details))
1615 return; // No navigation happened.
1616
1617 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1618 // for the appropriate notification (best) or you can add it to
1619 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1620 // necessary, please).
1621
1622 // Run post-commit tasks.
1623 if (details.is_main_frame)
1624 DidNavigateMainFramePostCommit(details, params);
1625 DidNavigateAnyFramePostCommit(rvh, details, params);
1626}
1627
1628void TabContents::UpdateState(RenderViewHost* rvh,
1629 int32 page_id,
1630 const std::string& state) {
1631 DCHECK(rvh == render_view_host());
1632
1633 // We must be prepared to handle state updates for any page, these occur
1634 // when the user is scrolling and entering form data, as well as when we're
1635 // leaving a page, in which case our state may have already been moved to
1636 // the next page. The navigation controller will look up the appropriate
1637 // NavigationEntry and update it when it is notified via the delegate.
1638
1639 int entry_index = controller_.GetEntryIndexWithPageID(
1640 GetSiteInstance(), page_id);
1641 if (entry_index < 0)
1642 return;
1643 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1644
1645 if (state == entry->content_state())
1646 return; // Nothing to update.
1647 entry->set_content_state(state);
1648 controller_.NotifyEntryChanged(entry, entry_index);
1649}
1650
1651void TabContents::UpdateTitle(RenderViewHost* rvh,
1652 int32 page_id, const std::wstring& title) {
1653 // If we have a title, that's a pretty good indication that we've started
1654 // getting useful data.
1655 SetNotWaitingForResponse();
1656
1657 DCHECK(rvh == render_view_host());
1658 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1659 page_id);
1660 if (!entry || !UpdateTitleForEntry(entry, title))
1661 return;
1662
1663 // Broadcast notifications when the UI should be updated.
1664 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501665 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321666}
1667
[email protected]420ae012009-04-24 05:16:321668void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1669 const std::wstring& encoding) {
1670 set_encoding(encoding);
1671}
1672
1673void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1674 if (delegate())
1675 delegate()->UpdateTargetURL(this, url);
1676}
1677
1678void TabContents::UpdateThumbnail(const GURL& url,
1679 const SkBitmap& bitmap,
1680 const ThumbnailScore& score) {
1681 // Tell History about this thumbnail
1682 HistoryService* hs;
1683 if (!profile()->IsOffTheRecord() &&
1684 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1685 hs->SetPageThumbnail(url, bitmap, score);
1686 }
1687}
1688
[email protected]0df30122009-06-03 12:13:081689void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
1690 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
1691 raw_settings);
1692}
1693
[email protected]420ae012009-04-24 05:16:321694void TabContents::Close(RenderViewHost* rvh) {
1695 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1696 if (delegate() && rvh == render_view_host())
1697 delegate()->CloseContents(this);
1698}
1699
1700void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1701 if (delegate() && delegate()->IsPopup(this))
1702 delegate()->MoveContents(this, new_bounds);
1703}
1704
[email protected]329581b2009-04-28 06:52:351705void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321706 SetIsLoading(true, NULL);
1707}
1708
[email protected]329581b2009-04-28 06:52:351709void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321710 scoped_ptr<LoadNotificationDetails> details;
1711
1712 NavigationEntry* entry = controller_.GetActiveEntry();
1713 // An entry may not exist for a stop when loading an initial blank page or
1714 // if an iframe injected by script into a blank page finishes loading.
1715 if (entry) {
1716 scoped_ptr<base::ProcessMetrics> metrics(
1717 base::ProcessMetrics::CreateProcessMetrics(
1718 process()->process().handle()));
1719
1720 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1721
1722 details.reset(new LoadNotificationDetails(
1723 entry->display_url(),
1724 entry->transition_type(),
1725 elapsed,
1726 &controller_,
1727 controller_.GetCurrentEntryIndex()));
1728 }
1729
1730 // Tell PasswordManager we've finished a page load, which serves as a
1731 // green light to save pending passwords and reset itself.
1732 GetPasswordManager()->DidStopLoading();
1733
1734 SetIsLoading(false, details.get());
1735}
1736
1737void TabContents::DidStartProvisionalLoadForFrame(
1738 RenderViewHost* render_view_host,
1739 bool is_main_frame,
1740 const GURL& url) {
1741 ProvisionalLoadDetails details(is_main_frame,
1742 controller_.IsURLInPageNavigation(url),
1743 url, std::string(), false);
1744 NotificationService::current()->Notify(
1745 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1746 Source<NavigationController>(&controller_),
1747 Details<ProvisionalLoadDetails>(&details));
1748}
1749
1750void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1751 const GURL& source_url,
1752 const GURL& target_url) {
1753 NavigationEntry* entry;
1754 if (page_id == -1)
1755 entry = controller_.pending_entry();
1756 else
1757 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1758 if (!entry || entry->url() != source_url)
1759 return;
1760 entry->set_url(target_url);
1761}
1762
1763void TabContents::DidLoadResourceFromMemoryCache(
1764 const GURL& url,
1765 const std::string& frame_origin,
1766 const std::string& main_frame_origin,
1767 const std::string& security_info) {
1768 // Send out a notification that we loaded a resource from our memory cache.
1769 int cert_id = 0, cert_status = 0, security_bits = 0;
1770 SSLManager::DeserializeSecurityInfo(security_info,
1771 &cert_id, &cert_status,
1772 &security_bits);
1773 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]9ae66cbf2009-05-12 16:21:031774 process()->pid(), cert_id, cert_status);
[email protected]420ae012009-04-24 05:16:321775
1776 NotificationService::current()->Notify(
1777 NotificationType::LOAD_FROM_MEMORY_CACHE,
1778 Source<NavigationController>(&controller_),
1779 Details<LoadFromMemoryCacheDetails>(&details));
1780}
1781
1782void TabContents::DidFailProvisionalLoadWithError(
1783 RenderViewHost* render_view_host,
1784 bool is_main_frame,
1785 int error_code,
1786 const GURL& url,
1787 bool showing_repost_interstitial) {
1788 if (net::ERR_ABORTED == error_code) {
1789 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1790 // This means that the interstitial won't be torn down properly, which is
1791 // bad. But if we have an interstitial, go back to another tab type, and
1792 // then load the same interstitial again, we could end up getting the first
1793 // interstitial's "failed" message (as a result of the cancel) when we're on
1794 // the second one.
1795 //
1796 // We can't tell this apart, so we think we're tearing down the current page
1797 // which will cause a crash later one. There is also some code in
1798 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1799 // out because of this problem.
1800 //
1801 // http://code.google.com/p/chromium/issues/detail?id=2855
1802 // Because this will not tear down the interstitial properly, if "back" is
1803 // back to another tab type, the interstitial will still be somewhat alive
1804 // in the previous tab type. If you navigate somewhere that activates the
1805 // tab with the interstitial again, you'll see a flash before the new load
1806 // commits of the interstitial page.
1807 if (showing_interstitial_page()) {
1808 LOG(WARNING) << "Discarding message during interstitial.";
1809 return;
1810 }
1811
1812 // This will discard our pending entry if we cancelled the load (e.g., if we
1813 // decided to download the file instead of load it). Only discard the
1814 // pending entry if the URLs match, otherwise the user initiated a navigate
1815 // before the page loaded so that the discard would discard the wrong entry.
1816 NavigationEntry* pending_entry = controller_.pending_entry();
1817 if (pending_entry && pending_entry->url() == url)
1818 controller_.DiscardNonCommittedEntries();
1819
1820 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1821 }
1822
1823 // Send out a notification that we failed a provisional load with an error.
1824 ProvisionalLoadDetails details(is_main_frame,
1825 controller_.IsURLInPageNavigation(url),
1826 url, std::string(), false);
1827 details.set_error_code(error_code);
1828
1829 NotificationService::current()->Notify(
1830 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1831 Source<NavigationController>(&controller_),
1832 Details<ProvisionalLoadDetails>(&details));
1833}
1834
1835void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1836 int32 page_id,
1837 const GURL& icon_url) {
1838 fav_icon_helper_.SetFavIconURL(icon_url);
1839}
1840
1841void TabContents::DidDownloadImage(
1842 RenderViewHost* render_view_host,
1843 int id,
1844 const GURL& image_url,
1845 bool errored,
1846 const SkBitmap& image) {
1847 // A notification for downloading would be more flexible, but for now I'm
1848 // forwarding to the two places that could possibly have initiated the
1849 // request. If we end up with another place invoking DownloadImage, probably
1850 // best to refactor out into notification service, or something similar.
1851 if (errored)
1852 fav_icon_helper_.FavIconDownloadFailed(id);
1853 else
1854 fav_icon_helper_.SetFavIcon(id, image_url, image);
1855}
1856
1857void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1858 WindowOpenDisposition disposition) {
1859 if (render_manager_.dom_ui()) {
1860 // When we're a DOM UI, it will provide a page transition type for us (this
1861 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1862 // generated suggestions).
1863 //
1864 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161865 // want web sites to see a referrer of "chrome://blah" (and some
1866 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321867 // send to the site), so we send no referrer.
1868 OpenURL(url, GURL(), disposition,
1869 render_manager_.dom_ui()->link_transition_type());
1870 } else {
1871 OpenURL(url, referrer, disposition, PageTransition::LINK);
1872 }
1873}
1874
1875void TabContents::DomOperationResponse(const std::string& json_string,
1876 int automation_id) {
1877 DomOperationNotificationDetails details(json_string, automation_id);
1878 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341879 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321880 Details<DomOperationNotificationDetails>(&details));
1881}
1882
1883void TabContents::ProcessDOMUIMessage(const std::string& message,
1884 const std::string& content) {
1885 if (!render_manager_.dom_ui()) {
1886 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1887 // Because the renderer might be owned and sending random messages, we need
1888 // to ignore these inproper ones.
1889 NOTREACHED();
1890 return;
1891 }
1892 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1893}
1894
1895void TabContents::ProcessExternalHostMessage(const std::string& message,
1896 const std::string& origin,
1897 const std::string& target) {
1898 if (delegate())
1899 delegate()->ForwardMessageToExternalHost(message, origin, target);
1900}
1901
1902void TabContents::GoToEntryAtOffset(int offset) {
1903 controller_.GoToOffset(offset);
1904}
1905
1906void TabContents::GetHistoryListCount(int* back_list_count,
1907 int* forward_list_count) {
1908 int current_index = controller_.last_committed_entry_index();
1909 *back_list_count = current_index;
1910 *forward_list_count = controller_.entry_count() - current_index - 1;
1911}
1912
1913void TabContents::RunFileChooser(bool multiple_files,
1914 const string16& title,
1915 const FilePath& default_file) {
1916 if (!select_file_dialog_.get())
1917 select_file_dialog_ = SelectFileDialog::Create(this);
1918 SelectFileDialog::Type dialog_type =
1919 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
1920 SelectFileDialog::SELECT_OPEN_FILE;
1921 select_file_dialog_->SelectFile(dialog_type, title, default_file,
1922 NULL, 0, FILE_PATH_LITERAL(""),
1923 view_->GetTopLevelNativeWindow(), NULL);
1924}
1925
1926void TabContents::RunJavaScriptMessage(
1927 const std::wstring& message,
1928 const std::wstring& default_prompt,
1929 const GURL& frame_url,
1930 const int flags,
1931 IPC::Message* reply_msg,
1932 bool* did_suppress_message) {
1933 // Suppress javascript messages when requested and when inside a constrained
1934 // popup window (because that activates them and breaks them out of the
1935 // constrained window jail).
1936 bool suppress_this_message = suppress_javascript_messages_;
1937 if (delegate())
1938 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:311939 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:321940
1941 *did_suppress_message = suppress_this_message;
1942
1943 if (!suppress_this_message) {
1944 base::TimeDelta time_since_last_message(
1945 base::TimeTicks::Now() - last_javascript_message_dismissal_);
1946 bool show_suppress_checkbox = false;
1947 // Show a checkbox offering to suppress further messages if this message is
1948 // being displayed within kJavascriptMessageExpectedDelay of the last one.
1949 if (time_since_last_message <
1950 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
1951 show_suppress_checkbox = true;
1952
1953 RunJavascriptMessageBox(AsWC(this), frame_url, flags, message, default_prompt,
1954 show_suppress_checkbox, reply_msg);
1955 } else {
1956 // If we are suppressing messages, just reply as is if the user immediately
1957 // pressed "Cancel".
1958 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
1959 }
1960}
1961
1962void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
1963 IPC::Message* reply_msg) {
1964 RunBeforeUnloadDialog(AsWC(this), message, reply_msg);
1965}
1966
1967void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
1968 const std::string& json_arguments,
1969 IPC::Message* reply_msg) {
1970 if (delegate()) {
1971 HtmlDialogUIDelegate* dialog_delegate =
1972 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
1973 reply_msg, AsWC(this));
1974 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
1975 }
1976}
1977
1978void TabContents::PasswordFormsSeen(
1979 const std::vector<PasswordForm>& forms) {
1980 GetPasswordManager()->PasswordFormsSeen(forms);
1981}
1982
1983void TabContents::AutofillFormSubmitted(
1984 const AutofillForm& form) {
1985 GetAutofillManager()->AutofillFormSubmitted(form);
1986}
1987
1988void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
1989 const std::wstring& user_text, int64 node_id, int request_id) {
1990 GetAutofillManager()->FetchValuesForName(field_name, user_text,
1991 kMaxAutofillMenuItems, node_id, request_id);
1992}
1993
1994void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
1995 const std::wstring& value) {
1996 GetAutofillManager()->RemoveValueForName(field_name, value);
1997}
1998
1999// Checks to see if we should generate a keyword based on the OSDD, and if
2000// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
2001void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
2002 int32 page_id, const GURL& url,
2003 bool autodetected) {
2004 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
2005 DCHECK(url.is_valid());
2006 if (!IsActiveEntry(page_id))
2007 return;
2008 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
2009 if (!url_model)
2010 return;
2011 if (!url_model->loaded()) {
2012 url_model->Load();
2013 return;
2014 }
2015 if (!profile()->GetTemplateURLFetcher())
2016 return;
2017
2018 if (profile()->IsOffTheRecord())
2019 return;
2020
2021 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2022 DCHECK(entry);
2023
2024 const NavigationEntry* base_entry = entry;
2025 if (IsFormSubmit(base_entry)) {
2026 // If the current page is a form submit, find the last page that was not
2027 // a form submit and use its url to generate the keyword from.
2028 int index = controller_.last_committed_entry_index() - 1;
2029 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2030 index--;
2031 if (index >= 0)
2032 base_entry = controller_.GetEntryAtIndex(index);
2033 else
2034 base_entry = NULL;
2035 }
2036
2037 // We want to use the user typed URL if available since that represents what
2038 // the user typed to get here, and fall back on the regular URL if not.
2039 if (!base_entry)
2040 return;
2041 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2042 base_entry->user_typed_url() : base_entry->url();
2043 if (!keyword_url.is_valid())
2044 return;
2045 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2046 autodetected);
2047 if (keyword.empty())
2048 return;
2049 const TemplateURL* template_url =
2050 url_model->GetTemplateURLForKeyword(keyword);
2051 if (template_url && (!template_url->safe_for_autoreplace() ||
2052 template_url->originating_url() == url)) {
2053 // Either there is a user created TemplateURL for this keyword, or the
2054 // keyword has the same OSDD url and we've parsed it.
2055 return;
2056 }
2057
2058 // Download the OpenSearch description document. If this is successful a
2059 // new keyword will be created when done.
2060#if defined(OS_WIN)
2061 gfx::NativeView ancestor = GetAncestor(view_->GetNativeView(), GA_ROOT);
2062#else
2063 gfx::NativeView ancestor = NULL;
2064#endif
2065 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2066 keyword,
2067 url,
2068 base_entry->favicon().url(),
2069 ancestor,
2070 autodetected);
2071}
2072
2073void TabContents::InspectElementReply(int num_resources) {
2074 // We have received reply from inspect element request. Notify the
2075 // automation provider in case we need to notify automation client.
2076 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:342077 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:322078 Details<int>(&num_resources));
2079}
2080
2081void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2082 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2083}
2084
2085void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2086 printing_.DidPrintPage(params);
2087}
2088
2089GURL TabContents::GetAlternateErrorPageURL() const {
2090 GURL url;
2091 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2092 if (profile()->IsOffTheRecord())
2093 return url;
2094
2095 PrefService* prefs = profile()->GetPrefs();
2096 DCHECK(prefs);
2097 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2098 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2099 url = google_util::AppendGoogleTLDParam(url);
2100 }
2101 return url;
2102}
2103
2104WebPreferences TabContents::GetWebkitPrefs() {
2105 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2106 bool isDomUI = false;
2107 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2108}
2109
2110void TabContents::OnMissingPluginStatus(int status) {
2111#if defined(OS_WIN)
2112// TODO(PORT): pull in when plug-ins work
2113 GetPluginInstaller()->OnMissingPluginStatus(status);
2114#endif
2115}
2116
2117void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2118#if defined(OS_WIN)
2119// TODO(PORT): pull in when plug-ins work
2120 DCHECK(!plugin_path.value().empty());
2121
2122 std::wstring plugin_name = plugin_path.ToWStringHack();
2123 scoped_ptr<FileVersionInfo> version_info(
2124 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2125 if (version_info.get()) {
2126 const std::wstring& product_name = version_info->product_name();
2127 if (!product_name.empty())
2128 plugin_name = product_name;
2129 }
2130 AddInfoBar(new SimpleAlertInfoBarDelegate(
2131 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2132 NULL));
2133#endif
2134}
2135
2136void TabContents::OnCrashedWorker() {
2137 AddInfoBar(new SimpleAlertInfoBarDelegate(
2138 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2139 NULL));
2140}
2141
2142void TabContents::OnJSOutOfMemory() {
2143 AddInfoBar(new SimpleAlertInfoBarDelegate(
2144 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2145}
2146
2147void TabContents::ShouldClosePage(bool proceed) {
2148 render_manager_.ShouldClosePage(proceed);
2149}
2150
2151void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2152 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342153 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322154 // delivered to a pending RenderViewHost. We must first run the onunload
2155 // handler of the old RenderViewHost before we can allow it to proceed.
2156 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2157 new_request_id);
2158}
2159
2160bool TabContents::CanBlur() const {
2161 return delegate() ? delegate()->CanBlur() : true;
2162}
2163
2164gfx::Rect TabContents::GetRootWindowResizerRect() const {
2165 if (delegate())
2166 return delegate()->GetRootWindowResizerRect();
2167 return gfx::Rect();
2168}
2169
2170void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2171 bool is_during_unload) {
2172 if (is_during_unload) {
2173 // Hang occurred while firing the beforeunload/unload handler.
2174 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112175 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322176
2177 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2178 return;
2179
2180 // If the tab hangs in the beforeunload/unload handler there's really
2181 // nothing we can do to recover. Pretend the unload listeners have
2182 // all fired and close the tab. If the hang is in the beforeunload handler
2183 // then the user will not have the option of cancelling the close.
2184 Close(rvh);
2185 return;
2186 }
2187
2188 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]8897c382009-05-06 17:53:262189 HungRendererDialog::ShowForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322190}
2191
2192void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]8897c382009-05-06 17:53:262193 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322194}
2195
2196void TabContents::LoadStateChanged(const GURL& url,
2197 net::LoadState load_state) {
2198 load_state_ = load_state;
[email protected]d686e812009-06-03 19:10:292199 std::wstring languages =
2200 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2201 load_state_host_.clear();
2202 std::string host = url.host();
2203 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322204 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2205 SetNotWaitingForResponse();
2206 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502207 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322208}
2209
2210void TabContents::OnDidGetApplicationInfo(
2211 int32 page_id,
2212 const webkit_glue::WebApplicationInfo& info) {
2213 if (pending_install_.page_id != page_id)
2214 return; // The user clicked create on a separate page. Ignore this.
2215
2216 pending_install_.callback_functor =
2217 new GearsCreateShortcutCallbackFunctor(this);
2218 GearsCreateShortcut(
2219 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2220 NewCallback(pending_install_.callback_functor,
2221 &GearsCreateShortcutCallbackFunctor::Run));
2222}
2223
[email protected]14ce83f2009-05-28 18:35:242224void TabContents::OnUserGesture() {
2225 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
2226#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]420ae012009-04-24 05:16:322227 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2228 if (drm)
2229 drm->OnUserGesture(this);
2230#endif
2231}
2232
2233void TabContents::OnFindReply(int request_id,
2234 int number_of_matches,
2235 const gfx::Rect& selection_rect,
2236 int active_match_ordinal,
2237 bool final_update) {
2238 // Ignore responses for requests other than the one we have most recently
2239 // issued. That way we won't act on stale results when the user has
2240 // already typed in another query.
2241 if (request_id != current_find_request_id_)
2242 return;
2243
2244 if (number_of_matches == -1)
[email protected]e491f1c2009-05-22 20:28:122245 number_of_matches = last_search_result_.number_of_matches();
[email protected]420ae012009-04-24 05:16:322246 if (active_match_ordinal == -1)
[email protected]e491f1c2009-05-22 20:28:122247 active_match_ordinal = last_search_result_.active_match_ordinal();
[email protected]420ae012009-04-24 05:16:322248
[email protected]2c355c282009-05-21 23:24:432249 gfx::Rect selection = selection_rect;
2250 if (selection.IsEmpty())
[email protected]e491f1c2009-05-22 20:28:122251 selection = last_search_result_.selection_rect();
[email protected]2c355c282009-05-21 23:24:432252
[email protected]420ae012009-04-24 05:16:322253 // Notify the UI, automation and any other observers that a find result was
2254 // found.
[email protected]e491f1c2009-05-22 20:28:122255 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
2256 selection, active_match_ordinal,
2257 final_update);
[email protected]420ae012009-04-24 05:16:322258 NotificationService::current()->Notify(
2259 NotificationType::FIND_RESULT_AVAILABLE,
2260 Source<TabContents>(this),
[email protected]e491f1c2009-05-22 20:28:122261 Details<FindNotificationDetails>(&last_search_result_));
[email protected]420ae012009-04-24 05:16:322262}
2263
[email protected]829e7612009-04-25 01:15:112264bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322265 if (!delegate())
[email protected]829e7612009-04-25 01:15:112266 return false;
[email protected]420ae012009-04-24 05:16:322267
[email protected]829e7612009-04-25 01:15:112268 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322269}
2270
2271void TabContents::FileSelected(const FilePath& path,
2272 int index, void* params) {
2273 render_view_host()->FileSelected(path);
2274}
2275
2276void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2277 void* params) {
2278 render_view_host()->MultiFilesSelected(files);
2279}
2280
2281void TabContents::FileSelectionCanceled(void* params) {
2282 // If the user cancels choosing a file to upload we pass back an
2283 // empty vector.
2284 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2285}
2286
2287void TabContents::BeforeUnloadFiredFromRenderManager(
2288 bool proceed,
2289 bool* proceed_to_fire_unload) {
2290 if (delegate())
2291 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2292}
2293
2294void TabContents::UpdateRenderViewSizeForRenderManager() {
2295 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2296 view_->SizeContents(view_->GetContainerSize());
2297}
2298
2299DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
2300 return DOMUIFactory::CreateDOMUIForURL(AsWC(this), url);
2301}
2302
2303NavigationEntry*
2304TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2305 return controller_.GetLastCommittedEntry();
2306}
2307
2308bool TabContents::CreateRenderViewForRenderManager(
2309 RenderViewHost* render_view_host) {
2310 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2311 // mode before CreateRenderView is called. When we're asked to create a
2312 // RenderView, that means it's for the pending entry, so we have to use the
2313 // pending DOM UI.
2314 if (render_manager_.pending_dom_ui())
2315 render_view_host->AllowDOMUIBindings();
2316
[email protected]1adff062009-06-02 18:39:552317 // Ditto for extension bindings.
2318 if (controller().pending_entry()->url().SchemeIs(chrome::kExtensionScheme))
2319 render_view_host->AllowExtensionBindings();
2320
[email protected]420ae012009-04-24 05:16:322321 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2322 if (!render_view_host->CreateRenderView())
2323 return false;
2324
2325 // Now that the RenderView has been created, we need to tell it its size.
2326 rwh_view->SetSize(view_->GetContainerSize());
2327
2328 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2329 render_view_host);
2330 return true;
2331}
2332
2333void TabContents::Observe(NotificationType type,
2334 const NotificationSource& source,
2335 const NotificationDetails& details) {
2336 switch (type.value) {
2337 case NotificationType::BOOKMARK_MODEL_LOADED:
2338 // BookmarkModel finished loading, fall through to update starred state.
2339 case NotificationType::URLS_STARRED: {
2340 // Somewhere, a URL has been starred.
2341 // Ignore notifications for profiles other than our current one.
2342 Profile* source_profile = Source<Profile>(source).ptr();
2343 if (!source_profile || !source_profile->IsSameProfile(profile()))
2344 return;
2345
2346 UpdateStarredStateForCurrentURL();
2347 break;
2348 }
2349 case NotificationType::PREF_CHANGED: {
2350 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2351 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2352 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2353 UpdateAlternateErrorPageURL();
2354 } else if (*pref_name_in == prefs::kDefaultCharset ||
2355 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2356 ) {
2357 UpdateWebPreferences();
2358 } else {
2359 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2360 }
2361 break;
2362 }
2363 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2364 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2365 break;
2366
2367 case NotificationType::NAV_ENTRY_COMMITTED: {
2368 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2369
2370 NavigationController::LoadCommittedDetails& committed_details =
2371 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2372 ExpireInfoBars(committed_details);
2373 break;
2374 }
2375
2376 default:
2377 NOTREACHED();
2378 }
2379}