blob: 0ccd7249f36f4b689c737ac455d1a4addb54dc42 [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]66ba4932009-06-04 19:22:1314#include "chrome/browser/blocked_popup_container.h"
[email protected]420ae012009-04-24 05:16:3215#include "chrome/browser/bookmarks/bookmark_model.h"
[email protected]96d185d2009-04-24 03:28:5416#include "chrome/browser/browser_process.h"
initial.commit09911bf2008-07-26 23:55:2917#include "chrome/browser/cert_store.h"
[email protected]96d185d2009-04-24 03:28:5418#include "chrome/browser/debugger/devtools_manager.h"
[email protected]420ae012009-04-24 05:16:3219#include "chrome/browser/dom_operation_notification_details.h"
[email protected]96d185d2009-04-24 03:28:5420#include "chrome/browser/dom_ui/dom_ui.h"
21#include "chrome/browser/dom_ui/dom_ui_factory.h"
[email protected]bcef0dc02009-02-28 00:35:0222#include "chrome/browser/download/download_item_model.h"
[email protected]420ae012009-04-24 05:16:3223#include "chrome/browser/download/download_manager.h"
24#include "chrome/browser/download/download_request_manager.h"
[email protected]420ae012009-04-24 05:16:3225#include "chrome/browser/gears_integration.h"
26#include "chrome/browser/google_util.h"
[email protected]8897c382009-05-06 17:53:2627#include "chrome/browser/hung_renderer_dialog.h"
[email protected]420ae012009-04-24 05:16:3228#include "chrome/browser/jsmessage_box_handler.h"
29#include "chrome/browser/load_from_memory_cache_details.h"
30#include "chrome/browser/load_notification_details.h"
[email protected]fdd61c62009-04-22 19:22:5731#include "chrome/browser/password_manager/password_manager.h"
32#include "chrome/browser/plugin_installer.h"
[email protected]ce560f82009-06-03 09:39:4433#include "chrome/browser/profile.h"
[email protected]96d185d2009-04-24 03:28:5434#include "chrome/browser/renderer_host/render_widget_host_view.h"
35#include "chrome/browser/renderer_host/web_cache_manager.h"
[email protected]bd1ad682009-05-15 22:19:1736#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]7e383692009-06-12 19:14:5437#include "chrome/browser/tab_contents/interstitial_page.h"
[email protected]f3ec7742009-01-15 00:59:1638#include "chrome/browser/tab_contents/navigation_entry.h"
39#include "chrome/browser/tab_contents/tab_contents_delegate.h"
[email protected]fdd61c62009-04-22 19:22:5740#include "chrome/browser/tab_contents/tab_contents_view.h"
[email protected]449478302009-06-09 20:04:2841#include "chrome/browser/thumbnail_store.h"
[email protected]420ae012009-04-24 05:16:3242#include "chrome/browser/search_engines/template_url_fetcher.h"
43#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2744#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5645#include "chrome/common/notification_service.h"
[email protected]ce5c4502009-05-06 16:46:1146#include "chrome/common/page_action.h"
initial.commit09911bf2008-07-26 23:55:2947#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0348#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3249#include "chrome/common/render_messages.h"
[email protected]96d185d2009-04-24 03:28:5450#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2651#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3252#include "grit/locale_settings.h"
53#include "net/base/mime_util.h"
54#include "net/base/net_errors.h"
[email protected]d686e812009-06-03 19:10:2955#include "net/base/net_util.h"
[email protected]420ae012009-04-24 05:16:3256#include "net/base/registry_controlled_domain.h"
[email protected]3e45ba92009-02-20 21:09:0057
58#if defined(OS_WIN)
[email protected]66ba4932009-06-04 19:22:1359// For CRect
[email protected]9041a302009-06-04 19:36:3360#include <atlbase.h>
[email protected]326f7112009-06-04 19:30:2961#include <atlapp.h>
[email protected]66ba4932009-06-04 19:22:1362#include <atlmisc.h>
[email protected]3e45ba92009-02-20 21:09:0063// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3264#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]2362e4f2009-05-08 00:34:0565#include "views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0066#endif
initial.commit09911bf2008-07-26 23:55:2967
[email protected]420ae012009-04-24 05:16:3268// Cross-Site Navigations
69//
70// If a TabContents is told to navigate to a different web site (as determined
71// by SiteInstance), it will replace its current RenderViewHost with a new
72// RenderViewHost dedicated to the new SiteInstance. This works as follows:
73//
74// - Navigate determines whether the destination is cross-site, and if so,
75// it creates a pending_render_view_host_ and moves into the PENDING
76// RendererState.
77// - The pending RVH is "suspended," so that no navigation messages are sent to
78// its renderer until the onbeforeunload JavaScript handler has a chance to
79// run in the current RVH.
80// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
81// that it has a pending cross-site request. ResourceDispatcherHost will
82// check for this when the response arrives.
83// - The current RVH runs its onbeforeunload handler. If it returns false, we
84// cancel all the pending logic and go back to NORMAL. Otherwise we allow
85// the pending RVH to send the navigation request to its renderer.
86// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
87// checks CrossSiteRequestManager to see that the RVH responsible has a
88// pending cross-site request, and then installs a CrossSiteEventHandler.
89// - When RDH receives a response, the BufferedEventHandler determines whether
90// it is a download. If so, it sends a message to the new renderer causing
91// it to cancel the request, and the download proceeds in the download
92// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:3493// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:3294// doesn't affect any functionality.
95// - After RDH receives a response and determines that it is safe and not a
96// download, it pauses the response to first run the old page's onunload
97// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:3498// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:3299// to the current RVH.
100// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
101// the ResourceDispatcherHost, who unpauses the response. Data is then sent
102// to the pending RVH.
103// - The pending renderer sends a FrameNavigate message that invokes the
104// DidNavigate method. This replaces the current RVH with the
105// pending RVH and goes back to the NORMAL RendererState.
106
107namespace {
108
109// Amount of time we wait between when a key event is received and the renderer
110// is queried for its state and pushed to the NavigationEntry.
111const int kQueryStateDelay = 5000;
112
113const int kSyncWaitDelay = 40;
114
115// If another javascript message box is displayed within
116// kJavascriptMessageExpectedDelay of a previous javascript message box being
117// dismissed, display an option to suppress future message boxes from this
118// contents.
119const int kJavascriptMessageExpectedDelay = 1000;
120
[email protected]420ae012009-04-24 05:16:32121const char kLinkDoctorBaseURL[] =
122 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
123
124// The printer icon in shell32.dll. That's a standard icon user will quickly
125// recognize.
126const int kShell32PrinterIcon = 17;
127
128// The list of prefs we want to observe.
129const wchar_t* kPrefsToObserve[] = {
130 prefs::kAlternateErrorPagesEnabled,
131 prefs::kWebKitJavaEnabled,
132 prefs::kWebKitJavascriptEnabled,
133 prefs::kWebKitLoadsImagesAutomatically,
134 prefs::kWebKitPluginsEnabled,
135 prefs::kWebKitUsesUniversalDetector,
136 prefs::kWebKitSerifFontFamily,
137 prefs::kWebKitSansSerifFontFamily,
138 prefs::kWebKitFixedFontFamily,
139 prefs::kWebKitDefaultFontSize,
140 prefs::kWebKitDefaultFixedFontSize,
141 prefs::kDefaultCharset
142 // kWebKitStandardFontIsSerif needs to be added
143 // if we let users pick which font to use, serif or sans-serif when
144 // no font is specified or a CSS generic family (serif or sans-serif)
145 // is not specified.
146};
147
148const int kPrefsToObserveLength = arraysize(kPrefsToObserve);
149
150// Limit on the number of suggestions to appear in the pop-up menu under an
151// text input element in a form.
152const int kMaxAutofillMenuItems = 6;
153
154// Returns true if the entry's transition type is FORM_SUBMIT.
155bool IsFormSubmit(const NavigationEntry* entry) {
156 return (PageTransition::StripQualifier(entry->transition_type()) ==
157 PageTransition::FORM_SUBMIT);
158}
159
160#if defined(OS_WIN)
161
162BOOL CALLBACK InvalidateWindow(HWND hwnd, LPARAM lparam) {
163 // Note: erase is required to properly paint some widgets borders. This can
164 // be seen with textfields.
165 InvalidateRect(hwnd, NULL, TRUE);
166 return TRUE;
167}
168#endif
169
[email protected]57c6a652009-05-04 07:58:34170// TODO(brettw) TabContents should be removed, then this hack is unnecessary.
171TabContents* AsWC(TabContents* tc) {
172 return static_cast<TabContents*>(tc);
[email protected]420ae012009-04-24 05:16:32173}
174
175} // namespace
176
177// -----------------------------------------------------------------------------
178
[email protected]fdd61c62009-04-22 19:22:57179// static
180int TabContents::find_request_id_counter_ = -1;
181
[email protected]420ae012009-04-24 05:16:32182class TabContents::GearsCreateShortcutCallbackFunctor {
183 public:
184 explicit GearsCreateShortcutCallbackFunctor(TabContents* contents)
185 : contents_(contents) {}
186
187 void Run(const GearsShortcutData2& shortcut_data, bool success) {
188 if (contents_)
189 contents_->OnGearsCreateShortcutDone(shortcut_data, success);
190 delete this;
191 }
192 void Cancel() {
193 contents_ = NULL;
194 }
195
196 private:
197 TabContents* contents_;
198};
199
[email protected]57c6a652009-05-04 07:58:34200// TODO(brettw) many of the data members here have casts to TabContents.
201// This object is the same as TabContents and is currently being merged.
[email protected]fdd61c62009-04-22 19:22:57202// When this merge is done, the casts can be removed.
[email protected]420ae012009-04-24 05:16:32203TabContents::TabContents(Profile* profile,
204 SiteInstance* site_instance,
205 int routing_id,
206 base::WaitableEvent* modal_dialog_event)
[email protected]b680ad22009-04-15 23:19:42207 : delegate_(NULL),
[email protected]66ba4932009-06-04 19:22:13208 ALLOW_THIS_IN_INITIALIZER_LIST(controller_(this, profile)),
209 ALLOW_THIS_IN_INITIALIZER_LIST(view_(
210 TabContentsView::Create(static_cast<TabContents*>(this)))),
[email protected]fdd61c62009-04-22 19:22:57211 ALLOW_THIS_IN_INITIALIZER_LIST(render_manager_(
[email protected]57c6a652009-05-04 07:58:34212 static_cast<TabContents*>(this),
213 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57214 property_bag_(),
215 registrar_(),
[email protected]66ba4932009-06-04 19:22:13216 ALLOW_THIS_IN_INITIALIZER_LIST(printing_(
217 *static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57218 save_package_(),
219 cancelable_consumer_(),
220 autofill_manager_(),
221 password_manager_(),
222 plugin_installer_(),
223 ALLOW_THIS_IN_INITIALIZER_LIST(fav_icon_helper_(
[email protected]57c6a652009-05-04 07:58:34224 static_cast<TabContents*>(this))),
[email protected]fdd61c62009-04-22 19:22:57225 select_file_dialog_(),
226 pending_install_(),
[email protected]d5f942ba2008-09-26 19:30:34227 is_loading_(false),
initial.commit09911bf2008-07-26 23:55:29228 is_crashed_(false),
[email protected]d5f942ba2008-09-26 19:30:34229 waiting_for_response_(false),
[email protected]d5f942ba2008-09-26 19:30:34230 max_page_id_(-1),
[email protected]fdd61c62009-04-22 19:22:57231 current_load_start_(),
232 load_state_(net::LOAD_STATE_IDLE),
233 load_state_host_(),
234 received_page_title_(false),
235 is_starred_(false),
236 contents_mime_type_(),
237 encoding_(),
[email protected]332af7732009-03-11 13:21:35238 blocked_popups_(NULL),
[email protected]fdd61c62009-04-22 19:22:57239 infobar_delegates_(),
[email protected]fdd61c62009-04-22 19:22:57240 find_ui_active_(false),
241 find_op_aborted_(false),
242 current_find_request_id_(find_request_id_counter_++),
243 find_text_(),
[email protected]e491f1c2009-05-22 20:28:12244 last_search_case_sensitive_(false),
245 last_search_prepopulate_text_(NULL),
246 last_search_result_(),
[email protected]fdd61c62009-04-22 19:22:57247 capturing_contents_(false),
248 is_being_destroyed_(false),
249 notify_disconnection_(false),
250 history_requests_(),
251#if defined(OS_WIN)
252 message_box_active_(CreateEvent(NULL, TRUE, FALSE, NULL)),
253#endif
254 last_javascript_message_dismissal_(),
255 suppress_javascript_messages_(false) {
[email protected]420ae012009-04-24 05:16:32256 pending_install_.page_id = 0;
257 pending_install_.callback_functor = NULL;
258
259 render_manager_.Init(profile, site_instance, routing_id, modal_dialog_event);
260
261 view_->CreateView();
262
263 // Register for notifications about all interested prefs change.
264 PrefService* prefs = profile->GetPrefs();
265 if (prefs) {
266 for (int i = 0; i < kPrefsToObserveLength; ++i)
267 prefs->AddPrefObserver(kPrefsToObserve[i], this);
268 }
269
270 // Register for notifications about URL starredness changing on any profile.
271 registrar_.Add(this, NotificationType::URLS_STARRED,
272 NotificationService::AllSources());
273 registrar_.Add(this, NotificationType::BOOKMARK_MODEL_LOADED,
274 NotificationService::AllSources());
275 registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED,
276 NotificationService::AllSources());
277
278 // Keep a global copy of the previous search string (if any).
279 static string16 global_last_search = string16();
[email protected]e491f1c2009-05-22 20:28:12280 last_search_prepopulate_text_ = &global_last_search;
[email protected]332af7732009-03-11 13:21:35281}
initial.commit09911bf2008-07-26 23:55:29282
283TabContents::~TabContents() {
[email protected]420ae012009-04-24 05:16:32284 is_being_destroyed_ = true;
285
286 // We don't want any notifications while we're runnign our destructor.
287 registrar_.RemoveAll();
288
289 // Unregister the notifications of all observed prefs change.
290 PrefService* prefs = profile()->GetPrefs();
291 if (prefs) {
292 for (int i = 0; i < kPrefsToObserveLength; ++i)
293 prefs->RemovePrefObserver(kPrefsToObserve[i], this);
294 }
295
296 // Clean up subwindows like plugins and the find in page bar.
297 view_->OnContentsDestroy();
298
299 NotifyDisconnected();
[email protected]8897c382009-05-06 17:53:26300 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:32301
302 if (pending_install_.callback_functor)
303 pending_install_.callback_functor->Cancel();
304
305 // First cleanly close all child windows.
306 // TODO(mpcomplete): handle case if MaybeCloseChildWindows() already asked
307 // some of these to close. CloseWindows is async, so it might get called
308 // twice before it runs.
309 int size = static_cast<int>(child_windows_.size());
310 for (int i = size - 1; i >= 0; --i) {
311 ConstrainedWindow* window = child_windows_[i];
312 if (window)
313 window->CloseConstrainedWindow();
314 }
315
[email protected]66ba4932009-06-04 19:22:13316 if (blocked_popups_)
317 blocked_popups_->Destroy();
318
[email protected]420ae012009-04-24 05:16:32319 // Notify any observer that have a reference on this tab contents.
320 NotificationService::current()->Notify(
321 NotificationType::TAB_CONTENTS_DESTROYED,
322 Source<TabContents>(this),
323 NotificationService::NoDetails());
324
[email protected]1e5e74f2009-05-27 20:55:12325 // Notify any lasting InfobarDelegates that have not yet been removed that
326 // whatever infobar they were handling in this TabContents has closed,
327 // because the TabContents is going away entirely.
328 // This must happen after the TAB_CONTENTS_DESTROYED notification as the
329 // notification may trigger infobars calls that access their delegate. (and
330 // some implementations of InfoBarDelegate do delete themselves on
331 // InfoBarClosed()).
332 for (int i = 0; i < infobar_delegate_count(); ++i) {
333 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
334 delegate->InfoBarClosed();
335 }
336 infobar_delegates_.clear();
337
[email protected]420ae012009-04-24 05:16:32338 // TODO(brettw) this should be moved to the view.
339#if defined(OS_WIN)
340 // If we still have a window handle, destroy it. GetNativeView can return
341 // NULL if this contents was part of a window that closed.
342 if (GetNativeView())
343 ::DestroyWindow(GetNativeView());
344#endif
initial.commit09911bf2008-07-26 23:55:29345}
346
[email protected]d5f942ba2008-09-26 19:30:34347// static
348void TabContents::RegisterUserPrefs(PrefService* prefs) {
[email protected]420ae012009-04-24 05:16:32349 prefs->RegisterBooleanPref(prefs::kAlternateErrorPagesEnabled, true);
350
351 WebPreferences pref_defaults;
352 prefs->RegisterBooleanPref(prefs::kWebKitJavascriptEnabled,
353 pref_defaults.javascript_enabled);
354 prefs->RegisterBooleanPref(prefs::kWebKitWebSecurityEnabled,
355 pref_defaults.web_security_enabled);
356 prefs->RegisterBooleanPref(
357 prefs::kWebKitJavascriptCanOpenWindowsAutomatically, true);
358 prefs->RegisterBooleanPref(prefs::kWebKitLoadsImagesAutomatically,
359 pref_defaults.loads_images_automatically);
360 prefs->RegisterBooleanPref(prefs::kWebKitPluginsEnabled,
361 pref_defaults.plugins_enabled);
362 prefs->RegisterBooleanPref(prefs::kWebKitDomPasteEnabled,
363 pref_defaults.dom_paste_enabled);
364 prefs->RegisterBooleanPref(prefs::kWebKitShrinksStandaloneImagesToFit,
365 pref_defaults.shrinks_standalone_images_to_fit);
[email protected]0df30122009-06-03 12:13:08366 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
367 pref_defaults.inspector_settings);
[email protected]420ae012009-04-24 05:16:32368 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
369 pref_defaults.text_areas_are_resizable);
370 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
371 pref_defaults.java_enabled);
372
373 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
374 IDS_ACCEPT_LANGUAGES);
375 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
376 IDS_DEFAULT_ENCODING);
377 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
378 IDS_STANDARD_FONT_IS_SERIF);
379 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
380 IDS_FIXED_FONT_FAMILY);
381 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
382 IDS_SERIF_FONT_FAMILY);
383 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
384 IDS_SANS_SERIF_FONT_FAMILY);
385 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
386 IDS_CURSIVE_FONT_FAMILY);
387 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
388 IDS_FANTASY_FONT_FAMILY);
389 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
390 IDS_DEFAULT_FONT_SIZE);
391 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
392 IDS_DEFAULT_FIXED_FONT_SIZE);
393 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
394 IDS_MINIMUM_FONT_SIZE);
395 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
396 IDS_MINIMUM_LOGICAL_FONT_SIZE);
397 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
398 IDS_USES_UNIVERSAL_DETECTOR);
399 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
400 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29401}
402
[email protected]d5f942ba2008-09-26 19:30:34403bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01404 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55405 return true;
[email protected]d5f942ba2008-09-26 19:30:34406}
407
[email protected]6e95706d2009-04-23 22:55:01408AutofillManager* TabContents::GetAutofillManager() {
409 if (autofill_manager_.get() == NULL)
410 autofill_manager_.reset(new AutofillManager(this));
411 return autofill_manager_.get();
412}
413
414PasswordManager* TabContents::GetPasswordManager() {
415 if (password_manager_.get() == NULL)
416 password_manager_.reset(new PasswordManager(this));
417 return password_manager_.get();
418}
419
420PluginInstaller* TabContents::GetPluginInstaller() {
421 if (plugin_installer_.get() == NULL)
422 plugin_installer_.reset(new PluginInstaller(this));
423 return plugin_installer_.get();
424}
425
[email protected]d5f942ba2008-09-26 19:30:34426const GURL& TabContents::GetURL() const {
427 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57428 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34429 return entry ? entry->display_url() : GURL::EmptyGURL();
430}
431
[email protected]96d185d2009-04-24 03:28:54432const string16& TabContents::GetTitle() const {
[email protected]4c6092c5b2009-06-06 00:23:55433 // Transient entries take precedence. They are used for interstitial pages
434 // that are shown on top of existing pages.
435 NavigationEntry* entry = controller_.GetTransientEntry();
436 if (entry)
437 return entry->GetTitleForDisplay(&controller_);
438
[email protected]96d185d2009-04-24 03:28:54439 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
440 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
441 if (our_dom_ui) {
442 // Don't override the title in view source mode.
[email protected]4c6092c5b2009-06-06 00:23:55443 entry = controller_.GetActiveEntry();
[email protected]96d185d2009-04-24 03:28:54444 if (!(entry && entry->IsViewSourceMode())) {
445 // Give the DOM UI the chance to override our title.
446 const string16& title = our_dom_ui->overridden_title();
447 if (!title.empty())
448 return title;
449 }
450 }
451
452 // We use the title for the last committed entry rather than a pending
453 // navigation entry. For example, when the user types in a URL, we want to
454 // keep the old page's title until the new load has committed and we get a new
455 // title.
[email protected]96d185d2009-04-24 03:28:54456 entry = controller_.GetLastCommittedEntry();
457 if (entry)
458 return entry->GetTitleForDisplay(&controller_);
459 else if (controller_.LoadingURLLazily())
460 return controller_.GetLazyTitle();
461 return EmptyString16();
462}
463
[email protected]d5f942ba2008-09-26 19:30:34464int32 TabContents::GetMaxPageID() {
465 if (GetSiteInstance())
466 return GetSiteInstance()->max_page_id();
467 else
468 return max_page_id_;
469}
470
471void TabContents::UpdateMaxPageID(int32 page_id) {
472 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34473 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34474 // testing.
475 if (GetSiteInstance())
476 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34477 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34478}
479
[email protected]96d185d2009-04-24 03:28:54480SiteInstance* TabContents::GetSiteInstance() const {
481 return render_manager_.current_host()->site_instance();
482}
483
[email protected]d5f942ba2008-09-26 19:30:34484const std::wstring TabContents::GetDefaultTitle() const {
485 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
486}
487
[email protected]96d185d2009-04-24 03:28:54488bool TabContents::ShouldDisplayURL() {
489 // Don't hide the url in view source mode.
490 NavigationEntry* entry = controller_.GetActiveEntry();
491 if (entry && entry->IsViewSourceMode())
492 return true;
[email protected]83e3895b2009-06-11 00:07:16493
494 // Hide the URL in chrome-extension://.
495 if (GetURL().SchemeIs(chrome::kExtensionScheme))
496 return false;
497
[email protected]96d185d2009-04-24 03:28:54498 DOMUI* dom_ui = GetDOMUIForCurrentState();
499 if (dom_ui)
500 return !dom_ui->should_hide_url();
501 return true;
502}
503
[email protected]d5f942ba2008-09-26 19:30:34504SkBitmap TabContents::GetFavIcon() const {
505 // Like GetTitle(), we also want to use the favicon for the last committed
506 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57507 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47508 if (entry)
509 return entry->favicon().bitmap();
510
[email protected]ce3fa3c2009-04-20 19:55:57511 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34512 if (entry)
513 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57514 else if (controller_.LoadingURLLazily())
515 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34516 return SkBitmap();
517}
518
[email protected]96d185d2009-04-24 03:28:54519bool TabContents::ShouldDisplayFavIcon() {
520 // Always display a throbber during pending loads.
521 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
522 return true;
523
524 DOMUI* dom_ui = GetDOMUIForCurrentState();
525 if (dom_ui)
526 return !dom_ui->hide_favicon();
527 return true;
528}
529
[email protected]96d185d2009-04-24 03:28:54530std::wstring TabContents::GetStatusText() const {
531 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
532 return std::wstring();
533
534 switch (load_state_) {
535 case net::LOAD_STATE_WAITING_FOR_CACHE:
536 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
537 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
538 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
539 case net::LOAD_STATE_RESOLVING_HOST:
540 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
541 case net::LOAD_STATE_CONNECTING:
542 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
543 case net::LOAD_STATE_SENDING_REQUEST:
544 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
545 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
546 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
547 load_state_host_);
548 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
549 case net::LOAD_STATE_IDLE:
550 case net::LOAD_STATE_READING_RESPONSE:
551 break;
552 }
553
554 return std::wstring();
555}
556
[email protected]d5f942ba2008-09-26 19:30:34557void TabContents::SetIsCrashed(bool state) {
558 if (state == is_crashed_)
559 return;
560
561 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50562 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34563}
564
[email protected]ce5c4502009-05-06 16:46:11565void TabContents::EnablePageAction(const PageAction* page_action) {
566 DCHECK(page_action);
567
568 if (IsPageActionEnabled(page_action))
569 return; // Already enabled.
570
571 enabled_page_actions_.insert(page_action);
572}
573
574bool TabContents::IsPageActionEnabled(const PageAction* page_action) {
575 DCHECK(page_action);
576 return enabled_page_actions_.end() != enabled_page_actions_.find(page_action);
577}
578
579
[email protected]d5f942ba2008-09-26 19:30:34580void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
581 if (delegate_)
582 delegate_->NavigationStateChanged(this, changed_flags);
583}
584
[email protected]96d185d2009-04-24 03:28:54585void TabContents::DidBecomeSelected() {
586 controller_.SetActive(true);
587
588 if (render_widget_host_view())
589 render_widget_host_view()->DidBecomeSelected();
590
591 // If pid() is -1, that means the RenderProcessHost still hasn't been
592 // initialized. It'll register with CacheManagerHost when it is.
593 if (process()->pid() != -1)
594 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
595}
596
597void TabContents::WasHidden() {
598 if (!capturing_contents()) {
599 // |render_view_host()| can be NULL if the user middle clicks a link to open
600 // a tab in then background, then closes the tab before selecting it. This
601 // is because closing the tab calls TabContents::Destroy(), which removes
602 // the |render_view_host()|; then when we actually destroy the window,
603 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
604 if (render_widget_host_view())
605 render_widget_host_view()->WasHidden();
606
607 // Loop through children and send WasHidden to them, too.
608 int count = static_cast<int>(child_windows_.size());
609 for (int i = count - 1; i >= 0; --i) {
610 ConstrainedWindow* window = child_windows_.at(i);
611 window->WasHidden();
612 }
613 }
614
615 NotificationService::current()->Notify(
616 NotificationType::TAB_CONTENTS_HIDDEN,
617 Source<TabContents>(this),
618 NotificationService::NoDetails());
619}
620
[email protected]d5f942ba2008-09-26 19:30:34621void TabContents::Activate() {
622 if (delegate_)
623 delegate_->ActivateContents(this);
624}
625
[email protected]96d185d2009-04-24 03:28:54626void TabContents::ShowContents() {
627 if (render_widget_host_view())
628 render_widget_host_view()->DidBecomeSelected();
629
630 // Loop through children and send DidBecomeSelected to them, too.
631 int count = static_cast<int>(child_windows_.size());
632 for (int i = count - 1; i >= 0; --i) {
633 ConstrainedWindow* window = child_windows_.at(i);
634 window->DidBecomeSelected();
635 }
636}
637
638void TabContents::HideContents() {
639 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
640 // our superclass HideContents(), because some callers want to be very picky
641 // about the order in which these get called. In addition to making the code
642 // here practically impossible to understand, this also means we end up
643 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34644 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54645 WasHidden();
646}
647
[email protected]c0588052008-10-27 23:01:50648void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34649 WindowOpenDisposition disposition,
650 PageTransition::Type transition) {
651 if (delegate_)
[email protected]c0588052008-10-27 23:01:50652 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34653}
654
655bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54656 const NavigationEntry& entry = *controller_.pending_entry();
657
658 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
659 if (!dest_render_view_host)
660 return false; // Unable to create the desired render view host.
661
662 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]684b4ba22009-05-07 06:27:41663 DevToolsManager* devtools_manager = g_browser_process->devtools_manager();
[email protected]7e8e6b62009-05-08 11:28:32664 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41665 devtools_manager->OnNavigatingToPendingEntry(
666 render_view_host(),
667 dest_render_view_host,
668 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32669 }
[email protected]96d185d2009-04-24 03:28:54670
671 // Used for page load time metrics.
672 current_load_start_ = base::TimeTicks::Now();
673
674 // Navigate in the desired RenderViewHost.
675 dest_render_view_host->NavigateToEntry(entry, reload);
676
677 if (entry.page_id() == -1) {
678 // HACK!! This code suppresses javascript: URLs from being added to
679 // session history, which is what we want to do for javascript: URLs that
680 // do not generate content. What we really need is a message from the
681 // renderer telling us that a new page was not created. The same message
682 // could be used for mailto: URLs and the like.
683 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
684 return false;
685 }
686
687 // Clear any provisional password saves - this stops password infobars
688 // showing up on pages the user navigates to while the right page is
689 // loading.
690 GetPasswordManager()->ClearProvisionalSave();
691
692 if (reload && !profile()->IsOffTheRecord()) {
693 HistoryService* history =
694 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
695 if (history)
696 history->SetFavIconOutOfDateForPage(entry.url());
697 }
698
[email protected]d5f942ba2008-09-26 19:30:34699 return true;
700}
701
[email protected]96d185d2009-04-24 03:28:54702void TabContents::Stop() {
703 render_manager_.Stop();
704 printing_.Stop();
705}
706
707void TabContents::Cut() {
708 render_view_host()->Cut();
709}
710
711void TabContents::Copy() {
712 render_view_host()->Copy();
713}
714
715void TabContents::Paste() {
716 render_view_host()->Paste();
717}
718
719void TabContents::DisassociateFromPopupCount() {
720 render_view_host()->DisassociateFromPopupCount();
721}
722
723TabContents* TabContents::Clone() {
724 // We create a new SiteInstance so that the new tab won't share processes
725 // with the old one. This can be changed in the future if we need it to share
726 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32727 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54728 SiteInstance::CreateSiteInstance(profile()),
729 MSG_ROUTING_NONE, NULL);
730 tc->controller().CopyStateFrom(controller_);
731 return tc;
732}
733
[email protected]420ae012009-04-24 05:16:32734void TabContents::CreateShortcut() {
735 NavigationEntry* entry = controller_.GetLastCommittedEntry();
736 if (!entry)
737 return;
738
739 // We only allow one pending install request. By resetting the page id we
740 // effectively cancel the pending install request.
741 pending_install_.page_id = entry->page_id();
742 pending_install_.icon = GetFavIcon();
743 pending_install_.title = UTF16ToWideHack(GetTitle());
744 pending_install_.url = GetURL();
745 if (pending_install_.callback_functor) {
746 pending_install_.callback_functor->Cancel();
747 pending_install_.callback_functor = NULL;
748 }
749 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
750 if (pending_install_.title.empty())
751 pending_install_.title = UTF8ToWide(GetURL().spec());
752
753 // Request the application info. When done OnDidGetApplicationInfo is invoked
754 // and we'll create the shortcut.
755 render_view_host()->GetApplicationInfo(pending_install_.page_id);
756}
757
[email protected]76f68dc2009-03-10 20:31:32758#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29759ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]c2dacc92008-10-16 23:51:38760 views::WindowDelegate* window_delegate,
761 views::View* contents_view) {
initial.commit09911bf2008-07-26 23:55:29762 ConstrainedWindow* window =
763 ConstrainedWindow::CreateConstrainedDialog(
764 this, gfx::Rect(), contents_view, window_delegate);
765 child_windows_.push_back(window);
766 return window;
767}
[email protected]f3332e12009-03-23 15:28:57768#endif
initial.commit09911bf2008-07-26 23:55:29769
770void TabContents::AddNewContents(TabContents* new_contents,
771 WindowOpenDisposition disposition,
772 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22773 bool user_gesture,
774 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29775 if (!delegate_)
776 return;
777
[email protected]ce494a312009-06-10 23:54:20778#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]35f7d212009-04-29 21:19:27779 if ((disposition == NEW_POPUP) && !user_gesture &&
780 !CommandLine::ForCurrentProcess()->HasSwitch(
781 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22782 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31783 // the whitelist. The popup owner will handle checking this.
784 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
785 initial_pos,
786 creator_url.is_valid() ? creator_url.host() : std::string());
787 } else {
[email protected]0aa55312008-10-17 21:53:08788 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29789 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
790 user_gesture);
791 }
[email protected]b6c874582009-05-08 19:38:31792 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
[email protected]f3332e12009-03-23 15:28:57793#else
794 // TODO(port): implement the popup blocker stuff
795 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
796 user_gesture);
797#endif
initial.commit09911bf2008-07-26 23:55:29798}
799
initial.commit09911bf2008-07-26 23:55:29800void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25801 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22802 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29803}
804
[email protected]96d185d2009-04-24 03:28:54805void TabContents::PopupNotificationVisibilityChanged(bool visible) {
806 render_view_host()->PopupNotificationVisibilityChanged(visible);
807}
808
809gfx::NativeView TabContents::GetContentNativeView() {
810 return view_->GetContentNativeView();
811}
812
813gfx::NativeView TabContents::GetNativeView() const {
814 return view_->GetNativeView();
815}
816
817void TabContents::GetContainerBounds(gfx::Rect *out) const {
818 view_->GetContainerBounds(out);
819}
820
821void TabContents::Focus() {
822 view_->Focus();
823}
824
[email protected]90daadb42009-06-08 21:27:28825void TabContents::FocusThroughTabTraversal(bool reverse) {
[email protected]7e383692009-06-12 19:14:54826 if (showing_interstitial_page()) {
827 render_manager_.interstitial_page()->FocusThroughTabTraversal(reverse);
828 return;
829 }
[email protected]96d185d2009-04-24 03:28:54830 render_view_host()->SetInitialFocus(reverse);
831}
832
833bool TabContents::FocusLocationBarByDefault() {
834 DOMUI* dom_ui = GetDOMUIForCurrentState();
835 if (dom_ui)
836 return dom_ui->focus_location_bar_by_default();
837 return false;
838}
839
[email protected]616ed5a2008-11-21 22:27:24840void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
841 // Look through the existing InfoBarDelegates we have for a match. If we've
842 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05843 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24844 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
845 return;
846 }
847
848 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56849 NotificationService::current()->Notify(
850 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
851 Source<TabContents>(this),
852 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24853
854 // Add ourselves as an observer for navigations the first time a delegate is
855 // added. We use this notification to expire InfoBars that need to expire on
856 // page transitions.
857 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56858 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57859 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24860 }
861}
862
863void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
864 std::vector<InfoBarDelegate*>::iterator it =
865 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
866 if (it != infobar_delegates_.end()) {
867 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56868 NotificationService::current()->Notify(
869 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
870 Source<TabContents>(this),
871 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05872 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24873
[email protected]6a02963e2009-01-06 16:58:03874 // Remove ourselves as an observer if we are tracking no more InfoBars.
875 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56876 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57877 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03878 }
[email protected]616ed5a2008-11-21 22:27:24879 }
880}
[email protected]3edd9522009-03-04 22:19:41881
[email protected]96d185d2009-04-24 03:28:54882bool TabContents::IsBookmarkBarAlwaysVisible() {
883 // See GetDOMUIForCurrentState() comment for more info. This case is very
884 // similar, but for non-first loads, we want to use the committed entry. This
885 // is so the bookmarks bar disappears at the same time the page does.
886 if (controller_.GetLastCommittedEntry()) {
887 // Not the first load, always use the committed DOM UI.
888 if (render_manager_.dom_ui())
889 return render_manager_.dom_ui()->force_bookmark_bar_visible();
890 return false; // Default.
891 }
892
893 // When it's the first load, we know either the pending one or the committed
894 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
895 // of them will be valid, so we can just check both.
896 if (render_manager_.pending_dom_ui())
897 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
898 if (render_manager_.dom_ui())
899 return render_manager_.dom_ui()->force_bookmark_bar_visible();
900 return false; // Default.
901}
902
[email protected]3edd9522009-03-04 22:19:41903void TabContents::ToolbarSizeChanged(bool is_animating) {
904 TabContentsDelegate* d = delegate();
905 if (d)
906 d->ToolbarSizeChanged(this, is_animating);
907}
[email protected]616ed5a2008-11-21 22:27:24908
[email protected]d5f942ba2008-09-26 19:30:34909void TabContents::OnStartDownload(DownloadItem* download) {
910 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34911
912 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31913 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34914
[email protected]59560e0b2009-06-04 03:30:22915 if (tab_contents && tab_contents->delegate())
916 tab_contents->delegate()->OnStartDownload(download);
[email protected]3edd9522009-03-04 22:19:41917}
[email protected]3edd9522009-03-04 22:19:41918
[email protected]d5f942ba2008-09-26 19:30:34919void TabContents::WillClose(ConstrainedWindow* window) {
920 ConstrainedWindowList::iterator it =
921 find(child_windows_.begin(), child_windows_.end(), window);
922 if (it != child_windows_.end())
923 child_windows_.erase(it);
[email protected]66ba4932009-06-04 19:22:13924}
[email protected]d5f942ba2008-09-26 19:30:34925
[email protected]66ba4932009-06-04 19:22:13926void TabContents::WillCloseBlockedPopupContainer(
927 BlockedPopupContainer* container) {
928 DCHECK(blocked_popups_ == container);
929 blocked_popups_ = NULL;
[email protected]d5f942ba2008-09-26 19:30:34930}
931
[email protected]d5f942ba2008-09-26 19:30:34932void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:35933#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:06934 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:35935#endif
[email protected]d5f942ba2008-09-26 19:30:34936}
937
[email protected]e491f1c2009-05-22 20:28:12938void TabContents::StartFinding(string16 find_text,
939 bool forward_direction,
940 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:01941 // If find_text is empty, it means FindNext was pressed with a keyboard
942 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:12943 if (find_text.empty() && find_text_.empty()) {
944 if (last_search_prepopulate_text_->empty())
945 return;
946 // Try whatever we searched for last in any tab.
947 find_text = *last_search_prepopulate_text_;
948 }
[email protected]6e95706d2009-04-23 22:55:01949
950 // This is a FindNext operation if we are searching for the same text again,
951 // or if the passed in search text is empty (FindNext keyboard shortcut). The
952 // exception to this is if the Find was aborted (then we don't want FindNext
953 // because the highlighting has been cleared and we need it to reappear). We
954 // therefore treat FindNext after an aborted Find operation as a full fledged
955 // Find.
956 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:12957 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:01958 !find_op_aborted_;
959 if (!find_next)
960 current_find_request_id_ = find_request_id_counter_++;
961
962 if (!find_text.empty())
963 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:12964 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:01965
966 find_op_aborted_ = false;
967
968 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:12969 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:01970
971 render_view_host()->StartFinding(current_find_request_id_,
972 find_text_,
973 forward_direction,
[email protected]e491f1c2009-05-22 20:28:12974 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:01975 find_next);
976}
977
978void TabContents::StopFinding(bool clear_selection) {
[email protected]2d2dffc2009-06-09 21:41:00979 // When |clear_selection| is true, it means the find string has been cleared
980 // by the user, but the UI has not been dismissed.
981 if (!clear_selection)
982 find_ui_active_ = false;
[email protected]6e95706d2009-04-23 22:55:01983 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:12984 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:01985 render_view_host()->StopFinding(clear_selection);
986}
987
[email protected]420ae012009-04-24 05:16:32988void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
989 bool success,
990 const std::wstring& prompt) {
991 last_javascript_message_dismissal_ = base::TimeTicks::Now();
992 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
993}
994
[email protected]571e31152009-05-15 19:34:02995void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
996 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
997}
998
[email protected]420ae012009-04-24 05:16:32999void TabContents::OnSavePage() {
1000 // If we can not save the page, try to download it.
1001 if (!SavePackage::IsSavableContents(contents_mime_type())) {
1002 DownloadManager* dlm = profile()->GetDownloadManager();
1003 const GURL& current_page_url = GetURL();
1004 if (dlm && current_page_url.is_valid())
[email protected]c9825a42009-05-01 22:51:501005 dlm->DownloadUrl(current_page_url, GURL(), "", AsWC(this));
[email protected]420ae012009-04-24 05:16:321006 return;
1007 }
1008
1009 Stop();
1010
1011 // Create the save package and possibly prompt the user for the name to save
1012 // the page as. The user prompt is an asynchronous operation that runs on
1013 // another thread.
1014 save_package_ = new SavePackage(AsWC(this));
1015 save_package_->GetSaveInfo();
1016}
1017
1018// Used in automated testing to bypass prompting the user for file names.
1019// Instead, the names and paths are hard coded rather than running them through
1020// file name sanitation and extension / mime checking.
1021void TabContents::SavePage(const std::wstring& main_file,
1022 const std::wstring& dir_path,
1023 SavePackage::SavePackageType save_type) {
1024 // Stop the page from navigating.
1025 Stop();
1026
1027 save_package_ = new SavePackage(AsWC(this), save_type,
1028 FilePath::FromWStringHack(main_file),
1029 FilePath::FromWStringHack(dir_path));
1030 save_package_->Init();
1031}
1032
1033void TabContents::PrintPreview() {
1034 // We don't show the print preview yet, only the print dialog.
1035 PrintNow();
1036}
1037
1038bool TabContents::PrintNow() {
1039 // We can't print interstitial page for now.
1040 if (showing_interstitial_page())
1041 return false;
1042
1043 return render_view_host()->PrintPages();
1044}
1045
1046bool TabContents::IsActiveEntry(int32 page_id) {
1047 NavigationEntry* active_entry = controller_.GetActiveEntry();
1048 return (active_entry != NULL &&
1049 active_entry->site_instance() == GetSiteInstance() &&
1050 active_entry->page_id() == page_id);
1051}
1052
[email protected]96d185d2009-04-24 03:28:541053// Notifies the RenderWidgetHost instance about the fact that the page is
1054// loading, or done loading and calls the base implementation.
1055void TabContents::SetIsLoading(bool is_loading,
1056 LoadNotificationDetails* details) {
1057 if (is_loading == is_loading_)
1058 return;
1059
1060 if (!is_loading) {
1061 load_state_ = net::LOAD_STATE_IDLE;
1062 load_state_host_.clear();
1063 }
1064
1065 render_manager_.SetIsLoading(is_loading);
1066
1067 is_loading_ = is_loading;
1068 waiting_for_response_ = is_loading;
1069
1070 if (delegate_)
1071 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351072 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541073
1074 NotificationType type = is_loading ? NotificationType::LOAD_START :
1075 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111076 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541077 if (details)
1078 det = Details<LoadNotificationDetails>(details);
1079 NotificationService::current()->Notify(type,
1080 Source<NavigationController>(&controller_),
1081 det);
1082}
1083
[email protected]ce494a312009-06-10 23:54:201084#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]2c4410d2009-05-06 23:46:221085void TabContents::CreateBlockedPopupContainerIfNecessary() {
1086 if (blocked_popups_)
1087 return;
1088
[email protected]4d4c0b92009-06-08 23:13:011089 blocked_popups_ = BlockedPopupContainer::Create(this, profile());
[email protected]2c4410d2009-05-06 23:46:221090}
1091
[email protected]b6c874582009-05-08 19:38:311092void TabContents::AddPopup(TabContents* new_contents,
1093 const gfx::Rect& initial_pos,
1094 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221095 CreateBlockedPopupContainerIfNecessary();
1096 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221097}
[email protected]66ba4932009-06-04 19:22:131098#endif
[email protected]2c4410d2009-05-06 23:46:221099
[email protected]e69bce3dd2009-04-20 22:05:121100// TODO(brettw) This should be on the TabContentsView.
[email protected]66ba4932009-06-04 19:22:131101void TabContents::RepositionSupressedPopupsToFit() {
[email protected]d6598c052008-11-05 19:03:251102 if (blocked_popups_)
[email protected]4d4c0b92009-06-08 23:13:011103 blocked_popups_->RepositionBlockedPopupContainer();
[email protected]d5f942ba2008-09-26 19:30:341104}
1105
[email protected]b9681312008-11-07 00:08:261106bool TabContents::ShowingBlockedPopupNotification() const {
1107 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221108 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261109}
[email protected]616ed5a2008-11-21 22:27:241110
1111namespace {
1112bool TransitionIsReload(PageTransition::Type transition) {
1113 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1114}
1115}
1116
1117void TabContents::ExpireInfoBars(
1118 const NavigationController::LoadCommittedDetails& details) {
1119 // Only hide InfoBars when the user has done something that makes the main
1120 // frame load. We don't want various automatic or subframe navigations making
1121 // it disappear.
1122 if (!details.is_user_initiated_main_frame_load())
1123 return;
1124
[email protected]f86a07022008-11-25 01:06:051125 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241126 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051127 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241128 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241129 }
1130}
[email protected]fdd61c62009-04-22 19:22:571131
1132void TabContents::OnGearsCreateShortcutDone(
1133 const GearsShortcutData2& shortcut_data, bool success) {
1134 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1135 bool same_page =
1136 current_entry && pending_install_.page_id == current_entry->page_id();
1137
1138 if (success && same_page) {
1139 // Only switch to app mode if the user chose to create a shortcut and
1140 // we're still on the same page that it corresponded to.
1141 if (delegate())
1142 delegate()->ConvertContentsToApplication(this);
1143 }
1144
1145 // Reset the page id to indicate no requests are pending.
1146 pending_install_.page_id = 0;
1147 pending_install_.callback_functor = NULL;
1148}
[email protected]96d185d2009-04-24 03:28:541149
1150DOMUI* TabContents::GetDOMUIForCurrentState() {
1151 // When there is a pending navigation entry, we want to use the pending DOMUI
1152 // that goes along with it to control the basic flags. For example, we want to
1153 // show the pending URL in the URL bar, so we want the display_url flag to
1154 // be from the pending entry.
1155 //
1156 // The confusion comes because there are multiple possibilities for the
1157 // initial load in a tab as a side effect of the way the RenderViewHostManager
1158 // works.
1159 //
1160 // - For the very first tab the load looks "normal". The new tab DOM UI is
1161 // the pending one, and we want it to apply here.
1162 //
1163 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1164 // get switched to the one previously associated with the new tab pages.
1165 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1166 // have a committed DOM UI in this case.
1167 //
1168 // This condition handles all of these cases:
1169 //
1170 // - First load in first tab: no committed nav entry + pending nav entry +
1171 // pending dom ui:
1172 // -> Use pending DOM UI if any.
1173 //
1174 // - First load in second tab: no committed nav entry + pending nav entry +
1175 // no pending DOM UI:
1176 // -> Use the committed DOM UI if any.
1177 //
1178 // - Second navigation in any tab: committed nav entry + pending nav entry:
1179 // -> Use pending DOM UI if any.
1180 //
1181 // - Normal state with no load: committed nav entry + no pending nav entry:
1182 // -> Use committed DOM UI.
1183 if (controller_.pending_entry() &&
1184 (controller_.GetLastCommittedEntry() ||
1185 render_manager_.pending_dom_ui()))
1186 return render_manager_.pending_dom_ui();
1187 return render_manager_.dom_ui();
1188}
[email protected]420ae012009-04-24 05:16:321189
1190void TabContents::DidNavigateMainFramePostCommit(
1191 const NavigationController::LoadCommittedDetails& details,
1192 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]420ae012009-04-24 05:16:321193 if (details.is_user_initiated_main_frame_load()) {
1194 // Clear the status bubble. This is a workaround for a bug where WebKit
1195 // doesn't let us know that the cursor left an element during a
1196 // transition (this is also why the mouse cursor remains as a hand after
1197 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1198 // clear the bubble when a user navigates to a named anchor in the same
1199 // page.
1200 UpdateTargetURL(details.entry->page_id(), GURL());
1201
1202 // UpdateHelpersForDidNavigate will handle the case where the password_form
1203 // origin is valid.
1204 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1205 // cleaned up and covered by tests.
1206 if (!params.password_form.origin.is_valid())
1207 GetPasswordManager()->DidNavigate();
1208 }
1209
1210 // The keyword generator uses the navigation entries, so must be called after
1211 // the commit.
1212 GenerateKeywordIfNecessary(params);
1213
1214 // Allow the new page to set the title again.
1215 received_page_title_ = false;
1216
1217 // Get the favicon, either from history or request it from the net.
1218 fav_icon_helper_.FetchFavIcon(details.entry->url());
1219
[email protected]ce5c4502009-05-06 16:46:111220 // Disable all page actions.
1221 enabled_page_actions_.clear();
1222
[email protected]420ae012009-04-24 05:16:321223 // Close constrained popups if necessary.
1224 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1225
1226 // Update the starred state.
1227 UpdateStarredStateForCurrentURL();
1228}
1229
1230void TabContents::DidNavigateAnyFramePostCommit(
1231 RenderViewHost* render_view_host,
1232 const NavigationController::LoadCommittedDetails& details,
1233 const ViewHostMsg_FrameNavigate_Params& params) {
1234 // If we navigate, start showing messages again. This does nothing to prevent
1235 // a malicious script from spamming messages, since the script could just
1236 // reload the page to stop blocking.
1237 suppress_javascript_messages_ = false;
1238
1239 // Update history. Note that this needs to happen after the entry is complete,
1240 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1241 if (params.should_update_history) {
1242 // Most of the time, the displayURL matches the loaded URL, but for about:
1243 // URLs, we use a data: URL as the real value. We actually want to save
1244 // the about: URL to the history db and keep the data: URL hidden. This is
1245 // what the TabContents' URL getter does.
1246 UpdateHistoryForNavigation(GetURL(), params);
1247 }
1248
1249 // Notify the password manager of the navigation or form submit.
1250 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1251 // cleaned up and covered by tests.
1252 if (params.password_form.origin.is_valid())
1253 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1254}
1255
1256void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1257 const GURL& current_url) {
1258 if (net::RegistryControlledDomainService::SameDomainOrHost(
1259 previous_url, current_url))
1260 return;
1261
1262 // Clear out any child windows since we are leaving this page entirely.
1263 // We use indices instead of iterators in case CloseWindow does something
1264 // that may invalidate an iterator.
1265 int size = static_cast<int>(child_windows_.size());
1266 for (int i = size - 1; i >= 0; --i) {
1267 ConstrainedWindow* window = child_windows_[i];
1268 if (window)
1269 window->CloseConstrainedWindow();
1270 }
1271}
1272
1273void TabContents::UpdateStarredStateForCurrentURL() {
1274 BookmarkModel* model = profile()->GetBookmarkModel();
1275 const bool old_state = is_starred_;
1276 is_starred_ = (model && model->IsBookmarked(GetURL()));
1277
1278 if (is_starred_ != old_state && delegate())
1279 delegate()->URLStarredChanged(this, is_starred_);
1280}
1281
1282void TabContents::UpdateAlternateErrorPageURL() {
1283 GURL url = GetAlternateErrorPageURL();
1284 render_view_host()->SetAlternateErrorPageURL(url);
1285}
1286
1287void TabContents::UpdateWebPreferences() {
1288 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1289}
1290
1291void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1292 RenderViewHost* rvh) {
1293 // If we are creating a RVH for a restored controller, then we might
1294 // have more page IDs than the SiteInstance's current max page ID. We must
1295 // make sure that the max page ID is larger than any restored page ID.
1296 // Note that it is ok for conflicting page IDs to exist in another tab
1297 // (i.e., NavigationController), but if any page ID is larger than the max,
1298 // the back/forward list will get confused.
1299 int max_restored_page_id = controller_.max_restored_page_id();
1300 if (max_restored_page_id > 0) {
1301 int curr_max_page_id = site_instance->max_page_id();
1302 if (max_restored_page_id > curr_max_page_id) {
1303 // Need to update the site instance immediately.
1304 site_instance->UpdateMaxPageID(max_restored_page_id);
1305
1306 // Also tell the renderer to update its internal representation. We
1307 // need to reserve enough IDs to make all restored page IDs less than
1308 // the max.
1309 if (curr_max_page_id < 0)
1310 curr_max_page_id = 0;
1311 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1312 }
1313 }
1314}
1315
1316void TabContents::UpdateHistoryForNavigation(
1317 const GURL& display_url,
1318 const ViewHostMsg_FrameNavigate_Params& params) {
1319 if (profile()->IsOffTheRecord())
1320 return;
1321
1322 // Add to history service.
1323 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1324 if (hs) {
1325 if (PageTransition::IsMainFrame(params.transition) &&
1326 display_url != params.url) {
1327 // Hack on the "display" URL so that it will appear in history. For some
1328 // types of URLs, we will display a magic URL that is different from where
1329 // the page is actually navigated. We want the user to see in history
1330 // what they saw in the URL bar, so we add the display URL as a redirect.
1331 // This only applies to the main frame, as the display URL doesn't apply
1332 // to sub-frames.
1333 std::vector<GURL> redirects = params.redirects;
1334 if (!redirects.empty())
1335 redirects.back() = display_url;
1336 hs->AddPage(display_url, this, params.page_id, params.referrer,
1337 params.transition, redirects);
1338 } else {
1339 hs->AddPage(params.url, this, params.page_id, params.referrer,
1340 params.transition, params.redirects);
1341 }
1342 }
1343}
1344
1345bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1346 const std::wstring& title) {
1347 // For file URLs without a title, use the pathname instead. In the case of a
1348 // synthesized title, we don't want the update to count toward the "one set
1349 // per page of the title to history."
1350 std::wstring final_title;
1351 bool explicit_set;
1352 if (entry->url().SchemeIsFile() && title.empty()) {
1353 final_title = UTF8ToWide(entry->url().ExtractFileName());
1354 explicit_set = false; // Don't count synthetic titles toward the set limit.
1355 } else {
1356 TrimWhitespace(title, TRIM_ALL, &final_title);
1357 explicit_set = true;
1358 }
1359
1360 if (final_title == UTF16ToWideHack(entry->title()))
1361 return false; // Nothing changed, don't bother.
1362
1363 entry->set_title(WideToUTF16Hack(final_title));
1364
1365 // Update the history system for this page.
1366 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1367 HistoryService* hs =
1368 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1369 if (hs)
1370 hs->SetPageTitle(entry->display_url(), final_title);
1371
1372 // Don't allow the title to be saved again for explicitly set ones.
1373 received_page_title_ = explicit_set;
1374 }
1375
1376 // Lastly, set the title for the view.
1377 view_->SetPageTitle(final_title);
1378
1379 return true;
1380}
1381
1382void TabContents::NotifySwapped() {
1383 // After sending out a swap notification, we need to send a disconnect
1384 // notification so that clients that pick up a pointer to |this| can NULL the
1385 // pointer. See Bug 1230284.
1386 notify_disconnection_ = true;
1387 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341388 NotificationType::TAB_CONTENTS_SWAPPED,
1389 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321390 NotificationService::NoDetails());
1391}
1392
1393void TabContents::NotifyConnected() {
1394 notify_disconnection_ = true;
1395 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341396 NotificationType::TAB_CONTENTS_CONNECTED,
1397 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321398 NotificationService::NoDetails());
1399}
1400
1401void TabContents::NotifyDisconnected() {
1402 if (!notify_disconnection_)
1403 return;
1404
1405 notify_disconnection_ = false;
1406 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341407 NotificationType::TAB_CONTENTS_DISCONNECTED,
1408 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321409 NotificationService::NoDetails());
1410}
1411
1412void TabContents::GenerateKeywordIfNecessary(
1413 const ViewHostMsg_FrameNavigate_Params& params) {
1414 if (!params.searchable_form_url.is_valid())
1415 return;
1416
1417 if (profile()->IsOffTheRecord())
1418 return;
1419
1420 int last_index = controller_.last_committed_entry_index();
1421 // When there was no previous page, the last index will be 0. This is
1422 // normally due to a form submit that opened in a new tab.
1423 // TODO(brettw) bug 916126: we should support keywords when form submits
1424 // happen in new tabs.
1425 if (last_index <= 0)
1426 return;
1427 const NavigationEntry* previous_entry =
1428 controller_.GetEntryAtIndex(last_index - 1);
1429 if (IsFormSubmit(previous_entry)) {
1430 // Only generate a keyword if the previous page wasn't itself a form
1431 // submit.
1432 return;
1433 }
1434
1435 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1436 previous_entry->user_typed_url() : previous_entry->url();
1437 std::wstring keyword =
1438 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1439 if (keyword.empty())
1440 return;
1441
1442 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1443 if (!url_model)
1444 return;
1445
1446 if (!url_model->loaded()) {
1447 url_model->Load();
1448 return;
1449 }
1450
1451 const TemplateURL* current_url;
1452 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1453 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1454 return;
1455
1456 if (current_url) {
1457 if (current_url->originating_url().is_valid()) {
1458 // The existing keyword was generated from an OpenSearch description
1459 // document, don't regenerate.
1460 return;
1461 }
1462 url_model->Remove(current_url);
1463 }
1464 TemplateURL* new_url = new TemplateURL();
1465 new_url->set_keyword(keyword);
1466 new_url->set_short_name(keyword);
1467 new_url->SetURL(url, 0, 0);
1468 new_url->add_input_encoding(params.searchable_form_encoding);
1469 DCHECK(controller_.GetLastCommittedEntry());
1470 const GURL& favicon_url =
1471 controller_.GetLastCommittedEntry()->favicon().url();
1472 if (favicon_url.is_valid()) {
1473 new_url->SetFavIconURL(favicon_url);
1474 } else {
1475 // The favicon url isn't valid. This means there really isn't a favicon,
1476 // or the favicon url wasn't obtained before the load started. This assumes
1477 // the later.
1478 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1479 // its url.
1480 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1481 }
1482 new_url->set_safe_for_autoreplace(true);
1483 url_model->Add(new_url);
1484}
1485
1486RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1487 return view_.get();
1488}
1489
1490RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1491 return save_package_.get(); // May be NULL, but we can return NULL.
1492}
1493
[email protected]80d96fa2009-06-10 22:34:511494RendererPreferences TabContents::GetRendererPrefs() const {
1495 if (delegate())
1496 return delegate()->GetRendererPrefs();
1497 else
1498 return RendererPreferences();
1499}
1500
[email protected]6dfed102009-04-28 03:09:531501ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1502 RenderViewHost* render_view_host,
1503 const std::string& extension_id) {
1504 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1505 extension_id);
1506}
1507
[email protected]57c6a652009-05-04 07:58:341508TabContents* TabContents::GetAsTabContents() {
1509 return this;
1510}
1511
[email protected]420ae012009-04-24 05:16:321512void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1513 NavigationEntry* entry = controller_.GetActiveEntry();
1514 if (!entry)
1515 return;
1516
1517 // When we're creating views, we're still doing initial setup, so we always
1518 // use the pending DOM UI rather than any possibly existing committed one.
1519 if (render_manager_.pending_dom_ui()) {
1520 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1521 }
1522
1523 if (entry->IsViewSourceMode()) {
1524 // Put the renderer in view source mode.
1525 render_view_host->Send(
1526 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1527 }
[email protected]0666aef2009-05-13 19:48:081528
1529 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321530}
1531
1532void TabContents::RenderViewReady(RenderViewHost* rvh) {
1533 if (rvh != render_view_host()) {
1534 // Don't notify the world, since this came from a renderer in the
1535 // background.
1536 return;
1537 }
1538
1539 NotifyConnected();
1540 SetIsCrashed(false);
1541}
1542
1543void TabContents::RenderViewGone(RenderViewHost* rvh) {
1544 // Ask the print preview if this renderer was valuable.
1545 if (!printing_.OnRenderViewGone(rvh))
1546 return;
1547 if (rvh != render_view_host()) {
1548 // The pending page's RenderViewHost is gone.
1549 return;
1550 }
1551
1552 SetIsLoading(false, NULL);
1553 NotifyDisconnected();
1554 SetIsCrashed(true);
1555
[email protected]8e537302009-06-10 21:19:581556 // Tell the view that we've crashed so it can prepare the sad tab page.
1557 view_->OnTabCrashed();
[email protected]420ae012009-04-24 05:16:321558
1559 // Hide any visible hung renderer warning for this web contents' process.
[email protected]8897c382009-05-06 17:53:261560 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:321561}
1562
1563void TabContents::DidNavigate(RenderViewHost* rvh,
1564 const ViewHostMsg_FrameNavigate_Params& params) {
1565 if (PageTransition::IsMainFrame(params.transition))
1566 render_manager_.DidNavigateMainFrame(rvh);
1567
1568 // Update the site of the SiteInstance if it doesn't have one yet.
1569 if (!GetSiteInstance()->has_site())
1570 GetSiteInstance()->SetSite(params.url);
1571
1572 // Need to update MIME type here because it's referred to in
1573 // UpdateNavigationCommands() called by RendererDidNavigate() to
1574 // determine whether or not to enable the encoding menu.
1575 // It's updated only for the main frame. For a subframe,
1576 // RenderView::UpdateURL does not set params.contents_mime_type.
1577 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1578 // TODO(jungshik): Add a test for the encoding menu to avoid
1579 // regressing it again.
1580 if (PageTransition::IsMainFrame(params.transition))
1581 contents_mime_type_ = params.contents_mime_type;
1582
1583 NavigationController::LoadCommittedDetails details;
1584 if (!controller_.RendererDidNavigate(params, &details))
1585 return; // No navigation happened.
1586
1587 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1588 // for the appropriate notification (best) or you can add it to
1589 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1590 // necessary, please).
1591
1592 // Run post-commit tasks.
1593 if (details.is_main_frame)
1594 DidNavigateMainFramePostCommit(details, params);
1595 DidNavigateAnyFramePostCommit(rvh, details, params);
1596}
1597
1598void TabContents::UpdateState(RenderViewHost* rvh,
1599 int32 page_id,
1600 const std::string& state) {
1601 DCHECK(rvh == render_view_host());
1602
1603 // We must be prepared to handle state updates for any page, these occur
1604 // when the user is scrolling and entering form data, as well as when we're
1605 // leaving a page, in which case our state may have already been moved to
1606 // the next page. The navigation controller will look up the appropriate
1607 // NavigationEntry and update it when it is notified via the delegate.
1608
1609 int entry_index = controller_.GetEntryIndexWithPageID(
1610 GetSiteInstance(), page_id);
1611 if (entry_index < 0)
1612 return;
1613 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1614
1615 if (state == entry->content_state())
1616 return; // Nothing to update.
1617 entry->set_content_state(state);
1618 controller_.NotifyEntryChanged(entry, entry_index);
1619}
1620
1621void TabContents::UpdateTitle(RenderViewHost* rvh,
1622 int32 page_id, const std::wstring& title) {
1623 // If we have a title, that's a pretty good indication that we've started
1624 // getting useful data.
1625 SetNotWaitingForResponse();
1626
1627 DCHECK(rvh == render_view_host());
1628 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1629 page_id);
1630 if (!entry || !UpdateTitleForEntry(entry, title))
1631 return;
1632
1633 // Broadcast notifications when the UI should be updated.
1634 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501635 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321636}
1637
[email protected]420ae012009-04-24 05:16:321638void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1639 const std::wstring& encoding) {
1640 set_encoding(encoding);
1641}
1642
1643void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1644 if (delegate())
1645 delegate()->UpdateTargetURL(this, url);
1646}
1647
1648void TabContents::UpdateThumbnail(const GURL& url,
1649 const SkBitmap& bitmap,
1650 const ThumbnailScore& score) {
1651 // Tell History about this thumbnail
[email protected]449478302009-06-09 20:04:281652 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kThumbnailStore)) {
1653 profile()->GetThumbnailStore()->
1654 SetPageThumbnail(url, bitmap, score, !profile()->IsOffTheRecord());
1655 } else {
1656 HistoryService* hs;
1657 if (!profile()->IsOffTheRecord() &&
1658 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1659 hs->SetPageThumbnail(url, bitmap, score);
1660 }
[email protected]420ae012009-04-24 05:16:321661 }
1662}
1663
[email protected]0df30122009-06-03 12:13:081664void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
1665 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
1666 raw_settings);
1667}
1668
[email protected]420ae012009-04-24 05:16:321669void TabContents::Close(RenderViewHost* rvh) {
1670 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1671 if (delegate() && rvh == render_view_host())
1672 delegate()->CloseContents(this);
1673}
1674
1675void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1676 if (delegate() && delegate()->IsPopup(this))
1677 delegate()->MoveContents(this, new_bounds);
1678}
1679
[email protected]329581b2009-04-28 06:52:351680void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321681 SetIsLoading(true, NULL);
1682}
1683
[email protected]329581b2009-04-28 06:52:351684void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321685 scoped_ptr<LoadNotificationDetails> details;
1686
1687 NavigationEntry* entry = controller_.GetActiveEntry();
1688 // An entry may not exist for a stop when loading an initial blank page or
1689 // if an iframe injected by script into a blank page finishes loading.
1690 if (entry) {
1691 scoped_ptr<base::ProcessMetrics> metrics(
1692 base::ProcessMetrics::CreateProcessMetrics(
1693 process()->process().handle()));
1694
1695 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1696
1697 details.reset(new LoadNotificationDetails(
1698 entry->display_url(),
1699 entry->transition_type(),
1700 elapsed,
1701 &controller_,
1702 controller_.GetCurrentEntryIndex()));
1703 }
1704
1705 // Tell PasswordManager we've finished a page load, which serves as a
1706 // green light to save pending passwords and reset itself.
1707 GetPasswordManager()->DidStopLoading();
1708
1709 SetIsLoading(false, details.get());
1710}
1711
1712void TabContents::DidStartProvisionalLoadForFrame(
1713 RenderViewHost* render_view_host,
1714 bool is_main_frame,
1715 const GURL& url) {
1716 ProvisionalLoadDetails details(is_main_frame,
1717 controller_.IsURLInPageNavigation(url),
1718 url, std::string(), false);
1719 NotificationService::current()->Notify(
1720 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1721 Source<NavigationController>(&controller_),
1722 Details<ProvisionalLoadDetails>(&details));
1723}
1724
1725void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1726 const GURL& source_url,
1727 const GURL& target_url) {
1728 NavigationEntry* entry;
1729 if (page_id == -1)
1730 entry = controller_.pending_entry();
1731 else
1732 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1733 if (!entry || entry->url() != source_url)
1734 return;
1735 entry->set_url(target_url);
1736}
1737
1738void TabContents::DidLoadResourceFromMemoryCache(
1739 const GURL& url,
1740 const std::string& frame_origin,
1741 const std::string& main_frame_origin,
1742 const std::string& security_info) {
1743 // Send out a notification that we loaded a resource from our memory cache.
1744 int cert_id = 0, cert_status = 0, security_bits = 0;
1745 SSLManager::DeserializeSecurityInfo(security_info,
1746 &cert_id, &cert_status,
1747 &security_bits);
1748 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]9ae66cbf2009-05-12 16:21:031749 process()->pid(), cert_id, cert_status);
[email protected]420ae012009-04-24 05:16:321750
1751 NotificationService::current()->Notify(
1752 NotificationType::LOAD_FROM_MEMORY_CACHE,
1753 Source<NavigationController>(&controller_),
1754 Details<LoadFromMemoryCacheDetails>(&details));
1755}
1756
1757void TabContents::DidFailProvisionalLoadWithError(
1758 RenderViewHost* render_view_host,
1759 bool is_main_frame,
1760 int error_code,
1761 const GURL& url,
1762 bool showing_repost_interstitial) {
1763 if (net::ERR_ABORTED == error_code) {
1764 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1765 // This means that the interstitial won't be torn down properly, which is
1766 // bad. But if we have an interstitial, go back to another tab type, and
1767 // then load the same interstitial again, we could end up getting the first
1768 // interstitial's "failed" message (as a result of the cancel) when we're on
1769 // the second one.
1770 //
1771 // We can't tell this apart, so we think we're tearing down the current page
1772 // which will cause a crash later one. There is also some code in
1773 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1774 // out because of this problem.
1775 //
1776 // http://code.google.com/p/chromium/issues/detail?id=2855
1777 // Because this will not tear down the interstitial properly, if "back" is
1778 // back to another tab type, the interstitial will still be somewhat alive
1779 // in the previous tab type. If you navigate somewhere that activates the
1780 // tab with the interstitial again, you'll see a flash before the new load
1781 // commits of the interstitial page.
1782 if (showing_interstitial_page()) {
1783 LOG(WARNING) << "Discarding message during interstitial.";
1784 return;
1785 }
1786
1787 // This will discard our pending entry if we cancelled the load (e.g., if we
1788 // decided to download the file instead of load it). Only discard the
1789 // pending entry if the URLs match, otherwise the user initiated a navigate
1790 // before the page loaded so that the discard would discard the wrong entry.
1791 NavigationEntry* pending_entry = controller_.pending_entry();
1792 if (pending_entry && pending_entry->url() == url)
1793 controller_.DiscardNonCommittedEntries();
1794
1795 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1796 }
1797
1798 // Send out a notification that we failed a provisional load with an error.
1799 ProvisionalLoadDetails details(is_main_frame,
1800 controller_.IsURLInPageNavigation(url),
1801 url, std::string(), false);
1802 details.set_error_code(error_code);
1803
1804 NotificationService::current()->Notify(
1805 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1806 Source<NavigationController>(&controller_),
1807 Details<ProvisionalLoadDetails>(&details));
1808}
1809
1810void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1811 int32 page_id,
1812 const GURL& icon_url) {
1813 fav_icon_helper_.SetFavIconURL(icon_url);
1814}
1815
1816void TabContents::DidDownloadImage(
1817 RenderViewHost* render_view_host,
1818 int id,
1819 const GURL& image_url,
1820 bool errored,
1821 const SkBitmap& image) {
1822 // A notification for downloading would be more flexible, but for now I'm
1823 // forwarding to the two places that could possibly have initiated the
1824 // request. If we end up with another place invoking DownloadImage, probably
1825 // best to refactor out into notification service, or something similar.
1826 if (errored)
1827 fav_icon_helper_.FavIconDownloadFailed(id);
1828 else
1829 fav_icon_helper_.SetFavIcon(id, image_url, image);
1830}
1831
1832void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1833 WindowOpenDisposition disposition) {
1834 if (render_manager_.dom_ui()) {
1835 // When we're a DOM UI, it will provide a page transition type for us (this
1836 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1837 // generated suggestions).
1838 //
1839 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161840 // want web sites to see a referrer of "chrome://blah" (and some
1841 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321842 // send to the site), so we send no referrer.
1843 OpenURL(url, GURL(), disposition,
1844 render_manager_.dom_ui()->link_transition_type());
1845 } else {
1846 OpenURL(url, referrer, disposition, PageTransition::LINK);
1847 }
1848}
1849
1850void TabContents::DomOperationResponse(const std::string& json_string,
1851 int automation_id) {
1852 DomOperationNotificationDetails details(json_string, automation_id);
1853 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341854 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321855 Details<DomOperationNotificationDetails>(&details));
1856}
1857
1858void TabContents::ProcessDOMUIMessage(const std::string& message,
1859 const std::string& content) {
1860 if (!render_manager_.dom_ui()) {
1861 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1862 // Because the renderer might be owned and sending random messages, we need
1863 // to ignore these inproper ones.
1864 NOTREACHED();
1865 return;
1866 }
1867 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1868}
1869
[email protected]b8028622009-06-15 08:20:171870void TabContents::DocumentLoadedInFrame() {
1871 controller_.DocumentLoadedInFrame();
1872}
1873
[email protected]420ae012009-04-24 05:16:321874void TabContents::ProcessExternalHostMessage(const std::string& message,
1875 const std::string& origin,
1876 const std::string& target) {
1877 if (delegate())
1878 delegate()->ForwardMessageToExternalHost(message, origin, target);
1879}
1880
1881void TabContents::GoToEntryAtOffset(int offset) {
1882 controller_.GoToOffset(offset);
1883}
1884
1885void TabContents::GetHistoryListCount(int* back_list_count,
1886 int* forward_list_count) {
1887 int current_index = controller_.last_committed_entry_index();
1888 *back_list_count = current_index;
1889 *forward_list_count = controller_.entry_count() - current_index - 1;
1890}
1891
1892void TabContents::RunFileChooser(bool multiple_files,
1893 const string16& title,
1894 const FilePath& default_file) {
1895 if (!select_file_dialog_.get())
1896 select_file_dialog_ = SelectFileDialog::Create(this);
1897 SelectFileDialog::Type dialog_type =
1898 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
1899 SelectFileDialog::SELECT_OPEN_FILE;
1900 select_file_dialog_->SelectFile(dialog_type, title, default_file,
1901 NULL, 0, FILE_PATH_LITERAL(""),
1902 view_->GetTopLevelNativeWindow(), NULL);
1903}
1904
1905void TabContents::RunJavaScriptMessage(
1906 const std::wstring& message,
1907 const std::wstring& default_prompt,
1908 const GURL& frame_url,
1909 const int flags,
1910 IPC::Message* reply_msg,
1911 bool* did_suppress_message) {
1912 // Suppress javascript messages when requested and when inside a constrained
1913 // popup window (because that activates them and breaks them out of the
1914 // constrained window jail).
1915 bool suppress_this_message = suppress_javascript_messages_;
1916 if (delegate())
1917 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:311918 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:321919
1920 *did_suppress_message = suppress_this_message;
1921
1922 if (!suppress_this_message) {
1923 base::TimeDelta time_since_last_message(
1924 base::TimeTicks::Now() - last_javascript_message_dismissal_);
1925 bool show_suppress_checkbox = false;
1926 // Show a checkbox offering to suppress further messages if this message is
1927 // being displayed within kJavascriptMessageExpectedDelay of the last one.
1928 if (time_since_last_message <
1929 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
1930 show_suppress_checkbox = true;
1931
1932 RunJavascriptMessageBox(AsWC(this), frame_url, flags, message, default_prompt,
1933 show_suppress_checkbox, reply_msg);
1934 } else {
1935 // If we are suppressing messages, just reply as is if the user immediately
1936 // pressed "Cancel".
1937 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
1938 }
1939}
1940
1941void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
1942 IPC::Message* reply_msg) {
1943 RunBeforeUnloadDialog(AsWC(this), message, reply_msg);
1944}
1945
1946void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
1947 const std::string& json_arguments,
1948 IPC::Message* reply_msg) {
1949 if (delegate()) {
1950 HtmlDialogUIDelegate* dialog_delegate =
1951 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
1952 reply_msg, AsWC(this));
1953 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
1954 }
1955}
1956
1957void TabContents::PasswordFormsSeen(
1958 const std::vector<PasswordForm>& forms) {
1959 GetPasswordManager()->PasswordFormsSeen(forms);
1960}
1961
1962void TabContents::AutofillFormSubmitted(
[email protected]daa8c58e2009-06-15 17:21:101963 const webkit_glue::AutofillForm& form) {
[email protected]420ae012009-04-24 05:16:321964 GetAutofillManager()->AutofillFormSubmitted(form);
1965}
1966
1967void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
1968 const std::wstring& user_text, int64 node_id, int request_id) {
1969 GetAutofillManager()->FetchValuesForName(field_name, user_text,
1970 kMaxAutofillMenuItems, node_id, request_id);
1971}
1972
1973void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
1974 const std::wstring& value) {
1975 GetAutofillManager()->RemoveValueForName(field_name, value);
1976}
1977
1978// Checks to see if we should generate a keyword based on the OSDD, and if
1979// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
1980void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
1981 int32 page_id, const GURL& url,
1982 bool autodetected) {
1983 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
1984 DCHECK(url.is_valid());
1985 if (!IsActiveEntry(page_id))
1986 return;
1987 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1988 if (!url_model)
1989 return;
1990 if (!url_model->loaded()) {
1991 url_model->Load();
1992 return;
1993 }
1994 if (!profile()->GetTemplateURLFetcher())
1995 return;
1996
1997 if (profile()->IsOffTheRecord())
1998 return;
1999
2000 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
2001 DCHECK(entry);
2002
2003 const NavigationEntry* base_entry = entry;
2004 if (IsFormSubmit(base_entry)) {
2005 // If the current page is a form submit, find the last page that was not
2006 // a form submit and use its url to generate the keyword from.
2007 int index = controller_.last_committed_entry_index() - 1;
2008 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
2009 index--;
2010 if (index >= 0)
2011 base_entry = controller_.GetEntryAtIndex(index);
2012 else
2013 base_entry = NULL;
2014 }
2015
2016 // We want to use the user typed URL if available since that represents what
2017 // the user typed to get here, and fall back on the regular URL if not.
2018 if (!base_entry)
2019 return;
2020 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2021 base_entry->user_typed_url() : base_entry->url();
2022 if (!keyword_url.is_valid())
2023 return;
2024 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2025 autodetected);
2026 if (keyword.empty())
2027 return;
2028 const TemplateURL* template_url =
2029 url_model->GetTemplateURLForKeyword(keyword);
2030 if (template_url && (!template_url->safe_for_autoreplace() ||
2031 template_url->originating_url() == url)) {
2032 // Either there is a user created TemplateURL for this keyword, or the
2033 // keyword has the same OSDD url and we've parsed it.
2034 return;
2035 }
2036
2037 // Download the OpenSearch description document. If this is successful a
2038 // new keyword will be created when done.
2039#if defined(OS_WIN)
2040 gfx::NativeView ancestor = GetAncestor(view_->GetNativeView(), GA_ROOT);
2041#else
2042 gfx::NativeView ancestor = NULL;
2043#endif
2044 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2045 keyword,
2046 url,
2047 base_entry->favicon().url(),
2048 ancestor,
2049 autodetected);
2050}
2051
2052void TabContents::InspectElementReply(int num_resources) {
2053 // We have received reply from inspect element request. Notify the
2054 // automation provider in case we need to notify automation client.
2055 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:342056 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:322057 Details<int>(&num_resources));
2058}
2059
2060void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2061 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2062}
2063
2064void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2065 printing_.DidPrintPage(params);
2066}
2067
2068GURL TabContents::GetAlternateErrorPageURL() const {
2069 GURL url;
2070 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2071 if (profile()->IsOffTheRecord())
2072 return url;
2073
2074 PrefService* prefs = profile()->GetPrefs();
2075 DCHECK(prefs);
2076 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2077 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2078 url = google_util::AppendGoogleTLDParam(url);
2079 }
2080 return url;
2081}
2082
2083WebPreferences TabContents::GetWebkitPrefs() {
2084 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2085 bool isDomUI = false;
2086 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2087}
2088
2089void TabContents::OnMissingPluginStatus(int status) {
2090#if defined(OS_WIN)
2091// TODO(PORT): pull in when plug-ins work
2092 GetPluginInstaller()->OnMissingPluginStatus(status);
2093#endif
2094}
2095
2096void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2097#if defined(OS_WIN)
2098// TODO(PORT): pull in when plug-ins work
2099 DCHECK(!plugin_path.value().empty());
2100
2101 std::wstring plugin_name = plugin_path.ToWStringHack();
2102 scoped_ptr<FileVersionInfo> version_info(
2103 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2104 if (version_info.get()) {
2105 const std::wstring& product_name = version_info->product_name();
2106 if (!product_name.empty())
2107 plugin_name = product_name;
2108 }
2109 AddInfoBar(new SimpleAlertInfoBarDelegate(
2110 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2111 NULL));
2112#endif
2113}
2114
2115void TabContents::OnCrashedWorker() {
2116 AddInfoBar(new SimpleAlertInfoBarDelegate(
2117 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2118 NULL));
2119}
2120
2121void TabContents::OnJSOutOfMemory() {
2122 AddInfoBar(new SimpleAlertInfoBarDelegate(
2123 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2124}
2125
2126void TabContents::ShouldClosePage(bool proceed) {
2127 render_manager_.ShouldClosePage(proceed);
2128}
2129
2130void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2131 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342132 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322133 // delivered to a pending RenderViewHost. We must first run the onunload
2134 // handler of the old RenderViewHost before we can allow it to proceed.
2135 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2136 new_request_id);
2137}
2138
2139bool TabContents::CanBlur() const {
2140 return delegate() ? delegate()->CanBlur() : true;
2141}
2142
2143gfx::Rect TabContents::GetRootWindowResizerRect() const {
2144 if (delegate())
2145 return delegate()->GetRootWindowResizerRect();
2146 return gfx::Rect();
2147}
2148
2149void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2150 bool is_during_unload) {
2151 if (is_during_unload) {
2152 // Hang occurred while firing the beforeunload/unload handler.
2153 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112154 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322155
2156 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2157 return;
2158
2159 // If the tab hangs in the beforeunload/unload handler there's really
2160 // nothing we can do to recover. Pretend the unload listeners have
2161 // all fired and close the tab. If the hang is in the beforeunload handler
2162 // then the user will not have the option of cancelling the close.
2163 Close(rvh);
2164 return;
2165 }
2166
2167 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]8897c382009-05-06 17:53:262168 HungRendererDialog::ShowForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322169}
2170
2171void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]8897c382009-05-06 17:53:262172 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322173}
2174
2175void TabContents::LoadStateChanged(const GURL& url,
2176 net::LoadState load_state) {
2177 load_state_ = load_state;
[email protected]d686e812009-06-03 19:10:292178 std::wstring languages =
2179 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2180 load_state_host_.clear();
2181 std::string host = url.host();
2182 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322183 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2184 SetNotWaitingForResponse();
2185 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502186 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322187}
2188
2189void TabContents::OnDidGetApplicationInfo(
2190 int32 page_id,
2191 const webkit_glue::WebApplicationInfo& info) {
2192 if (pending_install_.page_id != page_id)
2193 return; // The user clicked create on a separate page. Ignore this.
2194
2195 pending_install_.callback_functor =
2196 new GearsCreateShortcutCallbackFunctor(this);
2197 GearsCreateShortcut(
2198 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2199 NewCallback(pending_install_.callback_functor,
2200 &GearsCreateShortcutCallbackFunctor::Run));
2201}
2202
[email protected]14ce83f2009-05-28 18:35:242203void TabContents::OnUserGesture() {
2204 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
2205#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]420ae012009-04-24 05:16:322206 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2207 if (drm)
2208 drm->OnUserGesture(this);
2209#endif
[email protected]b8028622009-06-15 08:20:172210 controller_.OnUserGesture();
[email protected]420ae012009-04-24 05:16:322211}
2212
2213void TabContents::OnFindReply(int request_id,
2214 int number_of_matches,
2215 const gfx::Rect& selection_rect,
2216 int active_match_ordinal,
2217 bool final_update) {
2218 // Ignore responses for requests other than the one we have most recently
2219 // issued. That way we won't act on stale results when the user has
2220 // already typed in another query.
2221 if (request_id != current_find_request_id_)
2222 return;
2223
2224 if (number_of_matches == -1)
[email protected]e491f1c2009-05-22 20:28:122225 number_of_matches = last_search_result_.number_of_matches();
[email protected]420ae012009-04-24 05:16:322226 if (active_match_ordinal == -1)
[email protected]e491f1c2009-05-22 20:28:122227 active_match_ordinal = last_search_result_.active_match_ordinal();
[email protected]420ae012009-04-24 05:16:322228
[email protected]2c355c282009-05-21 23:24:432229 gfx::Rect selection = selection_rect;
2230 if (selection.IsEmpty())
[email protected]e491f1c2009-05-22 20:28:122231 selection = last_search_result_.selection_rect();
[email protected]2c355c282009-05-21 23:24:432232
[email protected]420ae012009-04-24 05:16:322233 // Notify the UI, automation and any other observers that a find result was
2234 // found.
[email protected]e491f1c2009-05-22 20:28:122235 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
2236 selection, active_match_ordinal,
2237 final_update);
[email protected]420ae012009-04-24 05:16:322238 NotificationService::current()->Notify(
2239 NotificationType::FIND_RESULT_AVAILABLE,
2240 Source<TabContents>(this),
[email protected]e491f1c2009-05-22 20:28:122241 Details<FindNotificationDetails>(&last_search_result_));
[email protected]420ae012009-04-24 05:16:322242}
2243
[email protected]829e7612009-04-25 01:15:112244bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322245 if (!delegate())
[email protected]829e7612009-04-25 01:15:112246 return false;
[email protected]420ae012009-04-24 05:16:322247
[email protected]829e7612009-04-25 01:15:112248 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322249}
2250
2251void TabContents::FileSelected(const FilePath& path,
2252 int index, void* params) {
2253 render_view_host()->FileSelected(path);
2254}
2255
2256void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2257 void* params) {
2258 render_view_host()->MultiFilesSelected(files);
2259}
2260
2261void TabContents::FileSelectionCanceled(void* params) {
2262 // If the user cancels choosing a file to upload we pass back an
2263 // empty vector.
2264 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2265}
2266
2267void TabContents::BeforeUnloadFiredFromRenderManager(
2268 bool proceed,
2269 bool* proceed_to_fire_unload) {
2270 if (delegate())
2271 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2272}
2273
2274void TabContents::UpdateRenderViewSizeForRenderManager() {
2275 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2276 view_->SizeContents(view_->GetContainerSize());
2277}
2278
2279DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
2280 return DOMUIFactory::CreateDOMUIForURL(AsWC(this), url);
2281}
2282
2283NavigationEntry*
2284TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2285 return controller_.GetLastCommittedEntry();
2286}
2287
2288bool TabContents::CreateRenderViewForRenderManager(
2289 RenderViewHost* render_view_host) {
2290 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2291 // mode before CreateRenderView is called. When we're asked to create a
2292 // RenderView, that means it's for the pending entry, so we have to use the
2293 // pending DOM UI.
2294 if (render_manager_.pending_dom_ui())
2295 render_view_host->AllowDOMUIBindings();
2296
[email protected]1adff062009-06-02 18:39:552297 // Ditto for extension bindings.
2298 if (controller().pending_entry()->url().SchemeIs(chrome::kExtensionScheme))
2299 render_view_host->AllowExtensionBindings();
2300
[email protected]420ae012009-04-24 05:16:322301 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2302 if (!render_view_host->CreateRenderView())
2303 return false;
2304
2305 // Now that the RenderView has been created, we need to tell it its size.
2306 rwh_view->SetSize(view_->GetContainerSize());
2307
2308 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2309 render_view_host);
2310 return true;
2311}
2312
2313void TabContents::Observe(NotificationType type,
2314 const NotificationSource& source,
2315 const NotificationDetails& details) {
2316 switch (type.value) {
2317 case NotificationType::BOOKMARK_MODEL_LOADED:
2318 // BookmarkModel finished loading, fall through to update starred state.
2319 case NotificationType::URLS_STARRED: {
2320 // Somewhere, a URL has been starred.
2321 // Ignore notifications for profiles other than our current one.
2322 Profile* source_profile = Source<Profile>(source).ptr();
2323 if (!source_profile || !source_profile->IsSameProfile(profile()))
2324 return;
2325
2326 UpdateStarredStateForCurrentURL();
2327 break;
2328 }
2329 case NotificationType::PREF_CHANGED: {
2330 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2331 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2332 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2333 UpdateAlternateErrorPageURL();
2334 } else if (*pref_name_in == prefs::kDefaultCharset ||
2335 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2336 ) {
2337 UpdateWebPreferences();
2338 } else {
2339 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2340 }
2341 break;
2342 }
2343 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2344 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2345 break;
2346
2347 case NotificationType::NAV_ENTRY_COMMITTED: {
2348 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2349
2350 NavigationController::LoadCommittedDetails& committed_details =
2351 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2352 ExpireInfoBars(committed_details);
2353 break;
2354 }
2355
2356 default:
2357 NOTREACHED();
2358 }
2359}