blob: 47b3eb2b35a297f12ab2f0b1c1eb87894d13f868 [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]f3ec7742009-01-15 00:59:1637#include "chrome/browser/tab_contents/navigation_entry.h"
38#include "chrome/browser/tab_contents/tab_contents_delegate.h"
[email protected]fdd61c62009-04-22 19:22:5739#include "chrome/browser/tab_contents/tab_contents_view.h"
[email protected]449478302009-06-09 20:04:2840#include "chrome/browser/thumbnail_store.h"
[email protected]420ae012009-04-24 05:16:3241#include "chrome/browser/search_engines/template_url_fetcher.h"
42#include "chrome/browser/search_engines/template_url_model.h"
[email protected]35f7d212009-04-29 21:19:2743#include "chrome/common/chrome_switches.h"
[email protected]bfd04a62009-02-01 18:16:5644#include "chrome/common/notification_service.h"
[email protected]ce5c4502009-05-06 16:46:1145#include "chrome/common/page_action.h"
initial.commit09911bf2008-07-26 23:55:2946#include "chrome/common/pref_names.h"
[email protected]1eb89e82008-08-15 12:27:0347#include "chrome/common/pref_service.h"
[email protected]420ae012009-04-24 05:16:3248#include "chrome/common/render_messages.h"
[email protected]96d185d2009-04-24 03:28:5449#include "chrome/common/url_constants.h"
[email protected]8897c382009-05-06 17:53:2650#include "grit/generated_resources.h"
[email protected]420ae012009-04-24 05:16:3251#include "grit/locale_settings.h"
52#include "net/base/mime_util.h"
53#include "net/base/net_errors.h"
[email protected]d686e812009-06-03 19:10:2954#include "net/base/net_util.h"
[email protected]420ae012009-04-24 05:16:3255#include "net/base/registry_controlled_domain.h"
[email protected]3e45ba92009-02-20 21:09:0056
57#if defined(OS_WIN)
[email protected]66ba4932009-06-04 19:22:1358// For CRect
[email protected]9041a302009-06-04 19:36:3359#include <atlbase.h>
[email protected]326f7112009-06-04 19:30:2960#include <atlapp.h>
[email protected]66ba4932009-06-04 19:22:1361#include <atlmisc.h>
[email protected]3e45ba92009-02-20 21:09:0062// TODO(port): some of these headers should be ported.
[email protected]420ae012009-04-24 05:16:3263#include "chrome/browser/modal_html_dialog_delegate.h"
[email protected]2362e4f2009-05-08 00:34:0564#include "views/controls/scrollbar/native_scroll_bar.h"
[email protected]3e45ba92009-02-20 21:09:0065#endif
initial.commit09911bf2008-07-26 23:55:2966
[email protected]420ae012009-04-24 05:16:3267// Cross-Site Navigations
68//
69// If a TabContents is told to navigate to a different web site (as determined
70// by SiteInstance), it will replace its current RenderViewHost with a new
71// RenderViewHost dedicated to the new SiteInstance. This works as follows:
72//
73// - Navigate determines whether the destination is cross-site, and if so,
74// it creates a pending_render_view_host_ and moves into the PENDING
75// RendererState.
76// - The pending RVH is "suspended," so that no navigation messages are sent to
77// its renderer until the onbeforeunload JavaScript handler has a chance to
78// run in the current RVH.
79// - The pending RVH tells CrossSiteRequestManager (a thread-safe singleton)
80// that it has a pending cross-site request. ResourceDispatcherHost will
81// check for this when the response arrives.
82// - The current RVH runs its onbeforeunload handler. If it returns false, we
83// cancel all the pending logic and go back to NORMAL. Otherwise we allow
84// the pending RVH to send the navigation request to its renderer.
85// - ResourceDispatcherHost receives a ResourceRequest on the IO thread. It
86// checks CrossSiteRequestManager to see that the RVH responsible has a
87// pending cross-site request, and then installs a CrossSiteEventHandler.
88// - When RDH receives a response, the BufferedEventHandler determines whether
89// it is a download. If so, it sends a message to the new renderer causing
90// it to cancel the request, and the download proceeds in the download
91// thread. For now, we stay in a PENDING state (with a pending RVH) until
[email protected]57c6a652009-05-04 07:58:3492// the next DidNavigate event for this TabContents. This isn't ideal, but it
[email protected]420ae012009-04-24 05:16:3293// doesn't affect any functionality.
94// - After RDH receives a response and determines that it is safe and not a
95// download, it pauses the response to first run the old page's onunload
96// handler. It does this by asynchronously calling the OnCrossSiteResponse
[email protected]57c6a652009-05-04 07:58:3497// method of TabContents on the UI thread, which sends a ClosePage message
[email protected]420ae012009-04-24 05:16:3298// to the current RVH.
99// - Once the onunload handler is finished, a ClosePage_ACK message is sent to
100// the ResourceDispatcherHost, who unpauses the response. Data is then sent
101// to the pending RVH.
102// - The pending renderer sends a FrameNavigate message that invokes the
103// DidNavigate method. This replaces the current RVH with the
104// pending RVH and goes back to the NORMAL RendererState.
105
106namespace {
107
108// Amount of time we wait between when a key event is received and the renderer
109// is queried for its state and pushed to the NavigationEntry.
110const int kQueryStateDelay = 5000;
111
112const int kSyncWaitDelay = 40;
113
114// If another javascript message box is displayed within
115// kJavascriptMessageExpectedDelay of a previous javascript message box being
116// dismissed, display an option to suppress future message boxes from this
117// contents.
118const int kJavascriptMessageExpectedDelay = 1000;
119
[email protected]420ae012009-04-24 05:16:32120const char kLinkDoctorBaseURL[] =
121 "http://linkhelp.clients.google.com/tbproxy/lh/fixurl";
122
123// The printer icon in shell32.dll. That's a standard icon user will quickly
124// recognize.
125const int kShell32PrinterIcon = 17;
126
127// The list of prefs we want to observe.
128const wchar_t* kPrefsToObserve[] = {
129 prefs::kAlternateErrorPagesEnabled,
130 prefs::kWebKitJavaEnabled,
131 prefs::kWebKitJavascriptEnabled,
132 prefs::kWebKitLoadsImagesAutomatically,
133 prefs::kWebKitPluginsEnabled,
134 prefs::kWebKitUsesUniversalDetector,
[email protected]96d3fb52009-05-27 14:51:21135 prefs::kWebKitDeveloperExtrasEnabled,
[email protected]420ae012009-04-24 05:16:32136 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);
366 prefs->RegisterBooleanPref(prefs::kWebKitDeveloperExtrasEnabled,
[email protected]96d3fb52009-05-27 14:51:21367 pref_defaults.developer_extras_enabled);
[email protected]0df30122009-06-03 12:13:08368 prefs->RegisterStringPref(prefs::kWebKitInspectorSettings,
369 pref_defaults.inspector_settings);
[email protected]420ae012009-04-24 05:16:32370 prefs->RegisterBooleanPref(prefs::kWebKitTextAreasAreResizable,
371 pref_defaults.text_areas_are_resizable);
372 prefs->RegisterBooleanPref(prefs::kWebKitJavaEnabled,
373 pref_defaults.java_enabled);
374
375 prefs->RegisterLocalizedStringPref(prefs::kAcceptLanguages,
376 IDS_ACCEPT_LANGUAGES);
377 prefs->RegisterLocalizedStringPref(prefs::kDefaultCharset,
378 IDS_DEFAULT_ENCODING);
379 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitStandardFontIsSerif,
380 IDS_STANDARD_FONT_IS_SERIF);
381 prefs->RegisterLocalizedStringPref(prefs::kWebKitFixedFontFamily,
382 IDS_FIXED_FONT_FAMILY);
383 prefs->RegisterLocalizedStringPref(prefs::kWebKitSerifFontFamily,
384 IDS_SERIF_FONT_FAMILY);
385 prefs->RegisterLocalizedStringPref(prefs::kWebKitSansSerifFontFamily,
386 IDS_SANS_SERIF_FONT_FAMILY);
387 prefs->RegisterLocalizedStringPref(prefs::kWebKitCursiveFontFamily,
388 IDS_CURSIVE_FONT_FAMILY);
389 prefs->RegisterLocalizedStringPref(prefs::kWebKitFantasyFontFamily,
390 IDS_FANTASY_FONT_FAMILY);
391 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFontSize,
392 IDS_DEFAULT_FONT_SIZE);
393 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitDefaultFixedFontSize,
394 IDS_DEFAULT_FIXED_FONT_SIZE);
395 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumFontSize,
396 IDS_MINIMUM_FONT_SIZE);
397 prefs->RegisterLocalizedIntegerPref(prefs::kWebKitMinimumLogicalFontSize,
398 IDS_MINIMUM_LOGICAL_FONT_SIZE);
399 prefs->RegisterLocalizedBooleanPref(prefs::kWebKitUsesUniversalDetector,
400 IDS_USES_UNIVERSAL_DETECTOR);
401 prefs->RegisterLocalizedStringPref(prefs::kStaticEncodings,
402 IDS_STATIC_ENCODING_LIST);
initial.commit09911bf2008-07-26 23:55:29403}
404
[email protected]d5f942ba2008-09-26 19:30:34405bool TabContents::SupportsURL(GURL* url) {
[email protected]6e95706d2009-04-23 22:55:01406 // TODO(brettw) remove this function.
[email protected]9423d9412009-04-14 22:13:55407 return true;
[email protected]d5f942ba2008-09-26 19:30:34408}
409
[email protected]6e95706d2009-04-23 22:55:01410AutofillManager* TabContents::GetAutofillManager() {
411 if (autofill_manager_.get() == NULL)
412 autofill_manager_.reset(new AutofillManager(this));
413 return autofill_manager_.get();
414}
415
416PasswordManager* TabContents::GetPasswordManager() {
417 if (password_manager_.get() == NULL)
418 password_manager_.reset(new PasswordManager(this));
419 return password_manager_.get();
420}
421
422PluginInstaller* TabContents::GetPluginInstaller() {
423 if (plugin_installer_.get() == NULL)
424 plugin_installer_.reset(new PluginInstaller(this));
425 return plugin_installer_.get();
426}
427
[email protected]d5f942ba2008-09-26 19:30:34428const GURL& TabContents::GetURL() const {
429 // We may not have a navigation entry yet
[email protected]ce3fa3c2009-04-20 19:55:57430 NavigationEntry* entry = controller_.GetActiveEntry();
[email protected]d5f942ba2008-09-26 19:30:34431 return entry ? entry->display_url() : GURL::EmptyGURL();
432}
433
[email protected]96d185d2009-04-24 03:28:54434const string16& TabContents::GetTitle() const {
[email protected]4c6092c5b2009-06-06 00:23:55435 // Transient entries take precedence. They are used for interstitial pages
436 // that are shown on top of existing pages.
437 NavigationEntry* entry = controller_.GetTransientEntry();
438 if (entry)
439 return entry->GetTitleForDisplay(&controller_);
440
[email protected]96d185d2009-04-24 03:28:54441 DOMUI* our_dom_ui = render_manager_.pending_dom_ui() ?
442 render_manager_.pending_dom_ui() : render_manager_.dom_ui();
443 if (our_dom_ui) {
444 // Don't override the title in view source mode.
[email protected]4c6092c5b2009-06-06 00:23:55445 entry = controller_.GetActiveEntry();
[email protected]96d185d2009-04-24 03:28:54446 if (!(entry && entry->IsViewSourceMode())) {
447 // Give the DOM UI the chance to override our title.
448 const string16& title = our_dom_ui->overridden_title();
449 if (!title.empty())
450 return title;
451 }
452 }
453
454 // We use the title for the last committed entry rather than a pending
455 // navigation entry. For example, when the user types in a URL, we want to
456 // keep the old page's title until the new load has committed and we get a new
457 // title.
[email protected]96d185d2009-04-24 03:28:54458 entry = controller_.GetLastCommittedEntry();
459 if (entry)
460 return entry->GetTitleForDisplay(&controller_);
461 else if (controller_.LoadingURLLazily())
462 return controller_.GetLazyTitle();
463 return EmptyString16();
464}
465
[email protected]d5f942ba2008-09-26 19:30:34466int32 TabContents::GetMaxPageID() {
467 if (GetSiteInstance())
468 return GetSiteInstance()->max_page_id();
469 else
470 return max_page_id_;
471}
472
473void TabContents::UpdateMaxPageID(int32 page_id) {
474 // Ensure both the SiteInstance and RenderProcessHost update their max page
[email protected]57c6a652009-05-04 07:58:34475 // IDs in sync. Only TabContents will also have site instances, except during
[email protected]d5f942ba2008-09-26 19:30:34476 // testing.
477 if (GetSiteInstance())
478 GetSiteInstance()->UpdateMaxPageID(page_id);
[email protected]57c6a652009-05-04 07:58:34479 process()->UpdateMaxPageID(page_id);
[email protected]d5f942ba2008-09-26 19:30:34480}
481
[email protected]96d185d2009-04-24 03:28:54482SiteInstance* TabContents::GetSiteInstance() const {
483 return render_manager_.current_host()->site_instance();
484}
485
[email protected]d5f942ba2008-09-26 19:30:34486const std::wstring TabContents::GetDefaultTitle() const {
487 return l10n_util::GetString(IDS_DEFAULT_TAB_TITLE);
488}
489
[email protected]96d185d2009-04-24 03:28:54490bool TabContents::ShouldDisplayURL() {
491 // Don't hide the url in view source mode.
492 NavigationEntry* entry = controller_.GetActiveEntry();
493 if (entry && entry->IsViewSourceMode())
494 return true;
495 DOMUI* dom_ui = GetDOMUIForCurrentState();
496 if (dom_ui)
497 return !dom_ui->should_hide_url();
498 return true;
499}
500
[email protected]d5f942ba2008-09-26 19:30:34501SkBitmap TabContents::GetFavIcon() const {
502 // Like GetTitle(), we also want to use the favicon for the last committed
503 // entry rather than a pending navigation entry.
[email protected]ce3fa3c2009-04-20 19:55:57504 NavigationEntry* entry = controller_.GetTransientEntry();
[email protected]cbab76d2008-10-13 22:42:47505 if (entry)
506 return entry->favicon().bitmap();
507
[email protected]ce3fa3c2009-04-20 19:55:57508 entry = controller_.GetLastCommittedEntry();
[email protected]d5f942ba2008-09-26 19:30:34509 if (entry)
510 return entry->favicon().bitmap();
[email protected]ce3fa3c2009-04-20 19:55:57511 else if (controller_.LoadingURLLazily())
512 return controller_.GetLazyFavIcon();
[email protected]d5f942ba2008-09-26 19:30:34513 return SkBitmap();
514}
515
[email protected]96d185d2009-04-24 03:28:54516bool TabContents::ShouldDisplayFavIcon() {
517 // Always display a throbber during pending loads.
518 if (controller_.GetLastCommittedEntry() && controller_.pending_entry())
519 return true;
520
521 DOMUI* dom_ui = GetDOMUIForCurrentState();
522 if (dom_ui)
523 return !dom_ui->hide_favicon();
524 return true;
525}
526
[email protected]96d185d2009-04-24 03:28:54527std::wstring TabContents::GetStatusText() const {
528 if (!is_loading() || load_state_ == net::LOAD_STATE_IDLE)
529 return std::wstring();
530
531 switch (load_state_) {
532 case net::LOAD_STATE_WAITING_FOR_CACHE:
533 return l10n_util::GetString(IDS_LOAD_STATE_WAITING_FOR_CACHE);
534 case net::LOAD_STATE_RESOLVING_PROXY_FOR_URL:
535 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_PROXY_FOR_URL);
536 case net::LOAD_STATE_RESOLVING_HOST:
537 return l10n_util::GetString(IDS_LOAD_STATE_RESOLVING_HOST);
538 case net::LOAD_STATE_CONNECTING:
539 return l10n_util::GetString(IDS_LOAD_STATE_CONNECTING);
540 case net::LOAD_STATE_SENDING_REQUEST:
541 return l10n_util::GetString(IDS_LOAD_STATE_SENDING_REQUEST);
542 case net::LOAD_STATE_WAITING_FOR_RESPONSE:
543 return l10n_util::GetStringF(IDS_LOAD_STATE_WAITING_FOR_RESPONSE,
544 load_state_host_);
545 // Ignore net::LOAD_STATE_READING_RESPONSE and net::LOAD_STATE_IDLE
546 case net::LOAD_STATE_IDLE:
547 case net::LOAD_STATE_READING_RESPONSE:
548 break;
549 }
550
551 return std::wstring();
552}
553
[email protected]d5f942ba2008-09-26 19:30:34554void TabContents::SetIsCrashed(bool state) {
555 if (state == is_crashed_)
556 return;
557
558 is_crashed_ = state;
[email protected]c9cd2222009-05-06 05:16:50559 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]d5f942ba2008-09-26 19:30:34560}
561
[email protected]ce5c4502009-05-06 16:46:11562void TabContents::EnablePageAction(const PageAction* page_action) {
563 DCHECK(page_action);
564
565 if (IsPageActionEnabled(page_action))
566 return; // Already enabled.
567
568 enabled_page_actions_.insert(page_action);
569}
570
571bool TabContents::IsPageActionEnabled(const PageAction* page_action) {
572 DCHECK(page_action);
573 return enabled_page_actions_.end() != enabled_page_actions_.find(page_action);
574}
575
576
[email protected]d5f942ba2008-09-26 19:30:34577void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
578 if (delegate_)
579 delegate_->NavigationStateChanged(this, changed_flags);
580}
581
[email protected]96d185d2009-04-24 03:28:54582void TabContents::DidBecomeSelected() {
583 controller_.SetActive(true);
584
585 if (render_widget_host_view())
586 render_widget_host_view()->DidBecomeSelected();
587
588 // If pid() is -1, that means the RenderProcessHost still hasn't been
589 // initialized. It'll register with CacheManagerHost when it is.
590 if (process()->pid() != -1)
591 WebCacheManager::GetInstance()->ObserveActivity(process()->pid());
592}
593
594void TabContents::WasHidden() {
595 if (!capturing_contents()) {
596 // |render_view_host()| can be NULL if the user middle clicks a link to open
597 // a tab in then background, then closes the tab before selecting it. This
598 // is because closing the tab calls TabContents::Destroy(), which removes
599 // the |render_view_host()|; then when we actually destroy the window,
600 // OnWindowPosChanged() notices and calls HideContents() (which calls us).
601 if (render_widget_host_view())
602 render_widget_host_view()->WasHidden();
603
604 // Loop through children and send WasHidden to them, too.
605 int count = static_cast<int>(child_windows_.size());
606 for (int i = count - 1; i >= 0; --i) {
607 ConstrainedWindow* window = child_windows_.at(i);
608 window->WasHidden();
609 }
610 }
611
612 NotificationService::current()->Notify(
613 NotificationType::TAB_CONTENTS_HIDDEN,
614 Source<TabContents>(this),
615 NotificationService::NoDetails());
616}
617
[email protected]d5f942ba2008-09-26 19:30:34618void TabContents::Activate() {
619 if (delegate_)
620 delegate_->ActivateContents(this);
621}
622
[email protected]96d185d2009-04-24 03:28:54623void TabContents::ShowContents() {
624 if (render_widget_host_view())
625 render_widget_host_view()->DidBecomeSelected();
626
627 // Loop through children and send DidBecomeSelected to them, too.
628 int count = static_cast<int>(child_windows_.size());
629 for (int i = count - 1; i >= 0; --i) {
630 ConstrainedWindow* window = child_windows_.at(i);
631 window->DidBecomeSelected();
632 }
633}
634
635void TabContents::HideContents() {
636 // TODO(pkasting): http://b/1239839 Right now we purposefully don't call
637 // our superclass HideContents(), because some callers want to be very picky
638 // about the order in which these get called. In addition to making the code
639 // here practically impossible to understand, this also means we end up
640 // calling TabContents::WasHidden() twice if callers call both versions of
[email protected]57c6a652009-05-04 07:58:34641 // HideContents() on a TabContents.
[email protected]96d185d2009-04-24 03:28:54642 WasHidden();
643}
644
[email protected]c0588052008-10-27 23:01:50645void TabContents::OpenURL(const GURL& url, const GURL& referrer,
[email protected]d5f942ba2008-09-26 19:30:34646 WindowOpenDisposition disposition,
647 PageTransition::Type transition) {
648 if (delegate_)
[email protected]c0588052008-10-27 23:01:50649 delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
[email protected]d5f942ba2008-09-26 19:30:34650}
651
652bool TabContents::NavigateToPendingEntry(bool reload) {
[email protected]96d185d2009-04-24 03:28:54653 const NavigationEntry& entry = *controller_.pending_entry();
654
655 RenderViewHost* dest_render_view_host = render_manager_.Navigate(entry);
656 if (!dest_render_view_host)
657 return false; // Unable to create the desired render view host.
658
659 // Tell DevTools agent that it is attached prior to the navigation.
[email protected]684b4ba22009-05-07 06:27:41660 DevToolsManager* devtools_manager = g_browser_process->devtools_manager();
[email protected]7e8e6b62009-05-08 11:28:32661 if (devtools_manager) { // NULL in unit tests.
[email protected]684b4ba22009-05-07 06:27:41662 devtools_manager->OnNavigatingToPendingEntry(
663 render_view_host(),
664 dest_render_view_host,
665 controller_.pending_entry()->url());
[email protected]7e8e6b62009-05-08 11:28:32666 }
[email protected]96d185d2009-04-24 03:28:54667
668 // Used for page load time metrics.
669 current_load_start_ = base::TimeTicks::Now();
670
671 // Navigate in the desired RenderViewHost.
672 dest_render_view_host->NavigateToEntry(entry, reload);
673
674 if (entry.page_id() == -1) {
675 // HACK!! This code suppresses javascript: URLs from being added to
676 // session history, which is what we want to do for javascript: URLs that
677 // do not generate content. What we really need is a message from the
678 // renderer telling us that a new page was not created. The same message
679 // could be used for mailto: URLs and the like.
680 if (entry.url().SchemeIs(chrome::kJavaScriptScheme))
681 return false;
682 }
683
684 // Clear any provisional password saves - this stops password infobars
685 // showing up on pages the user navigates to while the right page is
686 // loading.
687 GetPasswordManager()->ClearProvisionalSave();
688
689 if (reload && !profile()->IsOffTheRecord()) {
690 HistoryService* history =
691 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
692 if (history)
693 history->SetFavIconOutOfDateForPage(entry.url());
694 }
695
[email protected]d5f942ba2008-09-26 19:30:34696 return true;
697}
698
[email protected]96d185d2009-04-24 03:28:54699void TabContents::Stop() {
700 render_manager_.Stop();
701 printing_.Stop();
702}
703
704void TabContents::Cut() {
705 render_view_host()->Cut();
706}
707
708void TabContents::Copy() {
709 render_view_host()->Copy();
710}
711
712void TabContents::Paste() {
713 render_view_host()->Paste();
714}
715
716void TabContents::DisassociateFromPopupCount() {
717 render_view_host()->DisassociateFromPopupCount();
718}
719
720TabContents* TabContents::Clone() {
721 // We create a new SiteInstance so that the new tab won't share processes
722 // with the old one. This can be changed in the future if we need it to share
723 // processes for some reason.
[email protected]420ae012009-04-24 05:16:32724 TabContents* tc = new TabContents(profile(),
[email protected]96d185d2009-04-24 03:28:54725 SiteInstance::CreateSiteInstance(profile()),
726 MSG_ROUTING_NONE, NULL);
727 tc->controller().CopyStateFrom(controller_);
728 return tc;
729}
730
[email protected]420ae012009-04-24 05:16:32731void TabContents::CreateShortcut() {
732 NavigationEntry* entry = controller_.GetLastCommittedEntry();
733 if (!entry)
734 return;
735
736 // We only allow one pending install request. By resetting the page id we
737 // effectively cancel the pending install request.
738 pending_install_.page_id = entry->page_id();
739 pending_install_.icon = GetFavIcon();
740 pending_install_.title = UTF16ToWideHack(GetTitle());
741 pending_install_.url = GetURL();
742 if (pending_install_.callback_functor) {
743 pending_install_.callback_functor->Cancel();
744 pending_install_.callback_functor = NULL;
745 }
746 DCHECK(!pending_install_.icon.isNull()) << "Menu item should be disabled.";
747 if (pending_install_.title.empty())
748 pending_install_.title = UTF8ToWide(GetURL().spec());
749
750 // Request the application info. When done OnDidGetApplicationInfo is invoked
751 // and we'll create the shortcut.
752 render_view_host()->GetApplicationInfo(pending_install_.page_id);
753}
754
[email protected]76f68dc2009-03-10 20:31:32755#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:29756ConstrainedWindow* TabContents::CreateConstrainedDialog(
[email protected]c2dacc92008-10-16 23:51:38757 views::WindowDelegate* window_delegate,
758 views::View* contents_view) {
initial.commit09911bf2008-07-26 23:55:29759 ConstrainedWindow* window =
760 ConstrainedWindow::CreateConstrainedDialog(
761 this, gfx::Rect(), contents_view, window_delegate);
762 child_windows_.push_back(window);
763 return window;
764}
[email protected]f3332e12009-03-23 15:28:57765#endif
initial.commit09911bf2008-07-26 23:55:29766
767void TabContents::AddNewContents(TabContents* new_contents,
768 WindowOpenDisposition disposition,
769 const gfx::Rect& initial_pos,
[email protected]c88a70fe2009-05-05 20:00:22770 bool user_gesture,
771 const GURL& creator_url) {
initial.commit09911bf2008-07-26 23:55:29772 if (!delegate_)
773 return;
774
[email protected]f3332e12009-03-23 15:28:57775#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:22776 bool constrain_popup = false;
[email protected]35f7d212009-04-29 21:19:27777 if ((disposition == NEW_POPUP) && !user_gesture &&
778 !CommandLine::ForCurrentProcess()->HasSwitch(
779 switches::kDisablePopupBlocking)) {
[email protected]2c4410d2009-05-06 23:46:22780 // Unrequested popups from normal pages are constrained unless they're in
[email protected]b6c874582009-05-08 19:38:31781 // the whitelist. The popup owner will handle checking this.
782 delegate_->GetConstrainingContents(this)->AddPopup(new_contents,
783 initial_pos,
784 creator_url.is_valid() ? creator_url.host() : std::string());
785 } else {
[email protected]0aa55312008-10-17 21:53:08786 new_contents->DisassociateFromPopupCount();
initial.commit09911bf2008-07-26 23:55:29787 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
788 user_gesture);
789 }
[email protected]b6c874582009-05-08 19:38:31790 PopupNotificationVisibilityChanged(ShowingBlockedPopupNotification());
[email protected]f3332e12009-03-23 15:28:57791#else
792 // TODO(port): implement the popup blocker stuff
793 delegate_->AddNewContents(this, new_contents, disposition, initial_pos,
794 user_gesture);
795#endif
initial.commit09911bf2008-07-26 23:55:29796}
797
initial.commit09911bf2008-07-26 23:55:29798void TabContents::CloseAllSuppressedPopups() {
[email protected]d6598c052008-11-05 19:03:25799 if (blocked_popups_)
[email protected]2c4410d2009-05-06 23:46:22800 blocked_popups_->CloseAll();
initial.commit09911bf2008-07-26 23:55:29801}
802
[email protected]96d185d2009-04-24 03:28:54803void TabContents::PopupNotificationVisibilityChanged(bool visible) {
804 render_view_host()->PopupNotificationVisibilityChanged(visible);
805}
806
807gfx::NativeView TabContents::GetContentNativeView() {
808 return view_->GetContentNativeView();
809}
810
811gfx::NativeView TabContents::GetNativeView() const {
812 return view_->GetNativeView();
813}
814
815void TabContents::GetContainerBounds(gfx::Rect *out) const {
816 view_->GetContainerBounds(out);
817}
818
819void TabContents::Focus() {
820 view_->Focus();
821}
822
[email protected]90daadb42009-06-08 21:27:28823void TabContents::FocusThroughTabTraversal(bool reverse) {
[email protected]96d185d2009-04-24 03:28:54824 render_view_host()->SetInitialFocus(reverse);
825}
826
827bool TabContents::FocusLocationBarByDefault() {
828 DOMUI* dom_ui = GetDOMUIForCurrentState();
829 if (dom_ui)
830 return dom_ui->focus_location_bar_by_default();
831 return false;
832}
833
[email protected]616ed5a2008-11-21 22:27:24834void TabContents::AddInfoBar(InfoBarDelegate* delegate) {
835 // Look through the existing InfoBarDelegates we have for a match. If we've
836 // already got one that matches, then we don't add the new one.
[email protected]f86a07022008-11-25 01:06:05837 for (int i = 0; i < infobar_delegate_count(); ++i) {
[email protected]616ed5a2008-11-21 22:27:24838 if (GetInfoBarDelegateAt(i)->EqualsDelegate(delegate))
839 return;
840 }
841
842 infobar_delegates_.push_back(delegate);
[email protected]bfd04a62009-02-01 18:16:56843 NotificationService::current()->Notify(
844 NotificationType::TAB_CONTENTS_INFOBAR_ADDED,
845 Source<TabContents>(this),
846 Details<InfoBarDelegate>(delegate));
[email protected]616ed5a2008-11-21 22:27:24847
848 // Add ourselves as an observer for navigations the first time a delegate is
849 // added. We use this notification to expire InfoBars that need to expire on
850 // page transitions.
851 if (infobar_delegates_.size() == 1) {
[email protected]bfd04a62009-02-01 18:16:56852 registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57853 Source<NavigationController>(&controller_));
[email protected]616ed5a2008-11-21 22:27:24854 }
855}
856
857void TabContents::RemoveInfoBar(InfoBarDelegate* delegate) {
858 std::vector<InfoBarDelegate*>::iterator it =
859 find(infobar_delegates_.begin(), infobar_delegates_.end(), delegate);
860 if (it != infobar_delegates_.end()) {
861 InfoBarDelegate* delegate = *it;
[email protected]bfd04a62009-02-01 18:16:56862 NotificationService::current()->Notify(
863 NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,
864 Source<TabContents>(this),
865 Details<InfoBarDelegate>(delegate));
[email protected]f86a07022008-11-25 01:06:05866 infobar_delegates_.erase(it);
[email protected]616ed5a2008-11-21 22:27:24867
[email protected]6a02963e2009-01-06 16:58:03868 // Remove ourselves as an observer if we are tracking no more InfoBars.
869 if (infobar_delegates_.empty()) {
[email protected]bfd04a62009-02-01 18:16:56870 registrar_.Remove(this, NotificationType::NAV_ENTRY_COMMITTED,
[email protected]ce3fa3c2009-04-20 19:55:57871 Source<NavigationController>(&controller_));
[email protected]6a02963e2009-01-06 16:58:03872 }
[email protected]616ed5a2008-11-21 22:27:24873 }
874}
[email protected]3edd9522009-03-04 22:19:41875
[email protected]96d185d2009-04-24 03:28:54876bool TabContents::IsBookmarkBarAlwaysVisible() {
877 // See GetDOMUIForCurrentState() comment for more info. This case is very
878 // similar, but for non-first loads, we want to use the committed entry. This
879 // is so the bookmarks bar disappears at the same time the page does.
880 if (controller_.GetLastCommittedEntry()) {
881 // Not the first load, always use the committed DOM UI.
882 if (render_manager_.dom_ui())
883 return render_manager_.dom_ui()->force_bookmark_bar_visible();
884 return false; // Default.
885 }
886
887 // When it's the first load, we know either the pending one or the committed
888 // one will have the DOM UI in it (see GetDOMUIForCurrentState), and only one
889 // of them will be valid, so we can just check both.
890 if (render_manager_.pending_dom_ui())
891 return render_manager_.pending_dom_ui()->force_bookmark_bar_visible();
892 if (render_manager_.dom_ui())
893 return render_manager_.dom_ui()->force_bookmark_bar_visible();
894 return false; // Default.
895}
896
[email protected]3edd9522009-03-04 22:19:41897void TabContents::ToolbarSizeChanged(bool is_animating) {
898 TabContentsDelegate* d = delegate();
899 if (d)
900 d->ToolbarSizeChanged(this, is_animating);
901}
[email protected]616ed5a2008-11-21 22:27:24902
[email protected]d5f942ba2008-09-26 19:30:34903void TabContents::OnStartDownload(DownloadItem* download) {
904 DCHECK(download);
[email protected]d5f942ba2008-09-26 19:30:34905
906 // Download in a constrained popup is shown in the tab that opened it.
[email protected]b6c874582009-05-08 19:38:31907 TabContents* tab_contents = delegate()->GetConstrainingContents(this);
[email protected]d5f942ba2008-09-26 19:30:34908
[email protected]59560e0b2009-06-04 03:30:22909 if (tab_contents && tab_contents->delegate())
910 tab_contents->delegate()->OnStartDownload(download);
[email protected]3edd9522009-03-04 22:19:41911}
[email protected]3edd9522009-03-04 22:19:41912
[email protected]d5f942ba2008-09-26 19:30:34913void TabContents::WillClose(ConstrainedWindow* window) {
914 ConstrainedWindowList::iterator it =
915 find(child_windows_.begin(), child_windows_.end(), window);
916 if (it != child_windows_.end())
917 child_windows_.erase(it);
[email protected]66ba4932009-06-04 19:22:13918}
[email protected]d5f942ba2008-09-26 19:30:34919
[email protected]66ba4932009-06-04 19:22:13920void TabContents::WillCloseBlockedPopupContainer(
921 BlockedPopupContainer* container) {
922 DCHECK(blocked_popups_ == container);
923 blocked_popups_ = NULL;
[email protected]d5f942ba2008-09-26 19:30:34924}
925
[email protected]d5f942ba2008-09-26 19:30:34926void TabContents::DidMoveOrResize(ConstrainedWindow* window) {
[email protected]332af7732009-03-11 13:21:35927#if defined(OS_WIN)
[email protected]92edc472009-02-10 20:32:06928 UpdateWindow(GetNativeView());
[email protected]332af7732009-03-11 13:21:35929#endif
[email protected]d5f942ba2008-09-26 19:30:34930}
931
[email protected]e491f1c2009-05-22 20:28:12932void TabContents::StartFinding(string16 find_text,
933 bool forward_direction,
934 bool case_sensitive) {
[email protected]6e95706d2009-04-23 22:55:01935 // If find_text is empty, it means FindNext was pressed with a keyboard
936 // shortcut so unless we have something to search for we return early.
[email protected]e491f1c2009-05-22 20:28:12937 if (find_text.empty() && find_text_.empty()) {
938 if (last_search_prepopulate_text_->empty())
939 return;
940 // Try whatever we searched for last in any tab.
941 find_text = *last_search_prepopulate_text_;
942 }
[email protected]6e95706d2009-04-23 22:55:01943
944 // This is a FindNext operation if we are searching for the same text again,
945 // or if the passed in search text is empty (FindNext keyboard shortcut). The
946 // exception to this is if the Find was aborted (then we don't want FindNext
947 // because the highlighting has been cleared and we need it to reappear). We
948 // therefore treat FindNext after an aborted Find operation as a full fledged
949 // Find.
950 bool find_next = (find_text_ == find_text || find_text.empty()) &&
[email protected]e491f1c2009-05-22 20:28:12951 (last_search_case_sensitive_ == case_sensitive) &&
[email protected]6e95706d2009-04-23 22:55:01952 !find_op_aborted_;
953 if (!find_next)
954 current_find_request_id_ = find_request_id_counter_++;
955
956 if (!find_text.empty())
957 find_text_ = find_text;
[email protected]e491f1c2009-05-22 20:28:12958 last_search_case_sensitive_ = case_sensitive;
[email protected]6e95706d2009-04-23 22:55:01959
960 find_op_aborted_ = false;
961
962 // Keep track of what the last search was across the tabs.
[email protected]e491f1c2009-05-22 20:28:12963 *last_search_prepopulate_text_ = find_text;
[email protected]6e95706d2009-04-23 22:55:01964
965 render_view_host()->StartFinding(current_find_request_id_,
966 find_text_,
967 forward_direction,
[email protected]e491f1c2009-05-22 20:28:12968 case_sensitive,
[email protected]6e95706d2009-04-23 22:55:01969 find_next);
970}
971
972void TabContents::StopFinding(bool clear_selection) {
[email protected]2d2dffc2009-06-09 21:41:00973 // When |clear_selection| is true, it means the find string has been cleared
974 // by the user, but the UI has not been dismissed.
975 if (!clear_selection)
976 find_ui_active_ = false;
[email protected]6e95706d2009-04-23 22:55:01977 find_op_aborted_ = true;
[email protected]e491f1c2009-05-22 20:28:12978 last_search_result_ = FindNotificationDetails();
[email protected]6e95706d2009-04-23 22:55:01979 render_view_host()->StopFinding(clear_selection);
980}
981
[email protected]420ae012009-04-24 05:16:32982void TabContents::OnJavaScriptMessageBoxClosed(IPC::Message* reply_msg,
983 bool success,
984 const std::wstring& prompt) {
985 last_javascript_message_dismissal_ = base::TimeTicks::Now();
986 render_manager_.OnJavaScriptMessageBoxClosed(reply_msg, success, prompt);
987}
988
[email protected]571e31152009-05-15 19:34:02989void TabContents::OnJavaScriptMessageBoxWindowDestroyed() {
990 render_manager_.OnJavaScriptMessageBoxWindowDestroyed();
991}
992
[email protected]420ae012009-04-24 05:16:32993void TabContents::OnSavePage() {
994 // If we can not save the page, try to download it.
995 if (!SavePackage::IsSavableContents(contents_mime_type())) {
996 DownloadManager* dlm = profile()->GetDownloadManager();
997 const GURL& current_page_url = GetURL();
998 if (dlm && current_page_url.is_valid())
[email protected]c9825a42009-05-01 22:51:50999 dlm->DownloadUrl(current_page_url, GURL(), "", AsWC(this));
[email protected]420ae012009-04-24 05:16:321000 return;
1001 }
1002
1003 Stop();
1004
1005 // Create the save package and possibly prompt the user for the name to save
1006 // the page as. The user prompt is an asynchronous operation that runs on
1007 // another thread.
1008 save_package_ = new SavePackage(AsWC(this));
1009 save_package_->GetSaveInfo();
1010}
1011
1012// Used in automated testing to bypass prompting the user for file names.
1013// Instead, the names and paths are hard coded rather than running them through
1014// file name sanitation and extension / mime checking.
1015void TabContents::SavePage(const std::wstring& main_file,
1016 const std::wstring& dir_path,
1017 SavePackage::SavePackageType save_type) {
1018 // Stop the page from navigating.
1019 Stop();
1020
1021 save_package_ = new SavePackage(AsWC(this), save_type,
1022 FilePath::FromWStringHack(main_file),
1023 FilePath::FromWStringHack(dir_path));
1024 save_package_->Init();
1025}
1026
1027void TabContents::PrintPreview() {
1028 // We don't show the print preview yet, only the print dialog.
1029 PrintNow();
1030}
1031
1032bool TabContents::PrintNow() {
1033 // We can't print interstitial page for now.
1034 if (showing_interstitial_page())
1035 return false;
1036
1037 return render_view_host()->PrintPages();
1038}
1039
1040bool TabContents::IsActiveEntry(int32 page_id) {
1041 NavigationEntry* active_entry = controller_.GetActiveEntry();
1042 return (active_entry != NULL &&
1043 active_entry->site_instance() == GetSiteInstance() &&
1044 active_entry->page_id() == page_id);
1045}
1046
[email protected]96d185d2009-04-24 03:28:541047// Notifies the RenderWidgetHost instance about the fact that the page is
1048// loading, or done loading and calls the base implementation.
1049void TabContents::SetIsLoading(bool is_loading,
1050 LoadNotificationDetails* details) {
1051 if (is_loading == is_loading_)
1052 return;
1053
1054 if (!is_loading) {
1055 load_state_ = net::LOAD_STATE_IDLE;
1056 load_state_host_.clear();
1057 }
1058
1059 render_manager_.SetIsLoading(is_loading);
1060
1061 is_loading_ = is_loading;
1062 waiting_for_response_ = is_loading;
1063
1064 if (delegate_)
1065 delegate_->LoadingStateChanged(this);
[email protected]329581b2009-04-28 06:52:351066 NotifyNavigationStateChanged(INVALIDATE_LOAD);
[email protected]96d185d2009-04-24 03:28:541067
1068 NotificationType type = is_loading ? NotificationType::LOAD_START :
1069 NotificationType::LOAD_STOP;
[email protected]ce5c4502009-05-06 16:46:111070 NotificationDetails det = NotificationService::NoDetails();
[email protected]96d185d2009-04-24 03:28:541071 if (details)
1072 det = Details<LoadNotificationDetails>(details);
1073 NotificationService::current()->Notify(type,
1074 Source<NavigationController>(&controller_),
1075 det);
1076}
1077
[email protected]76f68dc2009-03-10 20:31:321078#if defined(OS_WIN)
[email protected]2c4410d2009-05-06 23:46:221079void TabContents::CreateBlockedPopupContainerIfNecessary() {
1080 if (blocked_popups_)
1081 return;
1082
[email protected]4d4c0b92009-06-08 23:13:011083 blocked_popups_ = BlockedPopupContainer::Create(this, profile());
[email protected]2c4410d2009-05-06 23:46:221084}
1085
[email protected]b6c874582009-05-08 19:38:311086void TabContents::AddPopup(TabContents* new_contents,
1087 const gfx::Rect& initial_pos,
1088 const std::string& host) {
[email protected]2c4410d2009-05-06 23:46:221089 CreateBlockedPopupContainerIfNecessary();
1090 blocked_popups_->AddTabContents(new_contents, initial_pos, host);
[email protected]2c4410d2009-05-06 23:46:221091}
[email protected]66ba4932009-06-04 19:22:131092#endif
[email protected]2c4410d2009-05-06 23:46:221093
[email protected]e69bce3dd2009-04-20 22:05:121094// TODO(brettw) This should be on the TabContentsView.
[email protected]66ba4932009-06-04 19:22:131095void TabContents::RepositionSupressedPopupsToFit() {
[email protected]d6598c052008-11-05 19:03:251096 if (blocked_popups_)
[email protected]4d4c0b92009-06-08 23:13:011097 blocked_popups_->RepositionBlockedPopupContainer();
[email protected]d5f942ba2008-09-26 19:30:341098}
1099
[email protected]b9681312008-11-07 00:08:261100bool TabContents::ShowingBlockedPopupNotification() const {
1101 return blocked_popups_ != NULL &&
[email protected]2c4410d2009-05-06 23:46:221102 blocked_popups_->GetBlockedPopupCount() != 0;
[email protected]b9681312008-11-07 00:08:261103}
[email protected]616ed5a2008-11-21 22:27:241104
1105namespace {
1106bool TransitionIsReload(PageTransition::Type transition) {
1107 return PageTransition::StripQualifier(transition) == PageTransition::RELOAD;
1108}
1109}
1110
1111void TabContents::ExpireInfoBars(
1112 const NavigationController::LoadCommittedDetails& details) {
1113 // Only hide InfoBars when the user has done something that makes the main
1114 // frame load. We don't want various automatic or subframe navigations making
1115 // it disappear.
1116 if (!details.is_user_initiated_main_frame_load())
1117 return;
1118
[email protected]f86a07022008-11-25 01:06:051119 for (int i = infobar_delegate_count() - 1; i >= 0; --i) {
[email protected]616ed5a2008-11-21 22:27:241120 InfoBarDelegate* delegate = GetInfoBarDelegateAt(i);
[email protected]f86a07022008-11-25 01:06:051121 if (delegate->ShouldExpire(details))
[email protected]616ed5a2008-11-21 22:27:241122 RemoveInfoBar(delegate);
[email protected]616ed5a2008-11-21 22:27:241123 }
1124}
[email protected]fdd61c62009-04-22 19:22:571125
1126void TabContents::OnGearsCreateShortcutDone(
1127 const GearsShortcutData2& shortcut_data, bool success) {
1128 NavigationEntry* current_entry = controller_.GetLastCommittedEntry();
1129 bool same_page =
1130 current_entry && pending_install_.page_id == current_entry->page_id();
1131
1132 if (success && same_page) {
1133 // Only switch to app mode if the user chose to create a shortcut and
1134 // we're still on the same page that it corresponded to.
1135 if (delegate())
1136 delegate()->ConvertContentsToApplication(this);
1137 }
1138
1139 // Reset the page id to indicate no requests are pending.
1140 pending_install_.page_id = 0;
1141 pending_install_.callback_functor = NULL;
1142}
[email protected]96d185d2009-04-24 03:28:541143
1144DOMUI* TabContents::GetDOMUIForCurrentState() {
1145 // When there is a pending navigation entry, we want to use the pending DOMUI
1146 // that goes along with it to control the basic flags. For example, we want to
1147 // show the pending URL in the URL bar, so we want the display_url flag to
1148 // be from the pending entry.
1149 //
1150 // The confusion comes because there are multiple possibilities for the
1151 // initial load in a tab as a side effect of the way the RenderViewHostManager
1152 // works.
1153 //
1154 // - For the very first tab the load looks "normal". The new tab DOM UI is
1155 // the pending one, and we want it to apply here.
1156 //
1157 // - For subsequent new tabs, they'll get a new SiteInstance which will then
1158 // get switched to the one previously associated with the new tab pages.
1159 // This switching will cause the manager to commit the RVH/DOMUI. So we'll
1160 // have a committed DOM UI in this case.
1161 //
1162 // This condition handles all of these cases:
1163 //
1164 // - First load in first tab: no committed nav entry + pending nav entry +
1165 // pending dom ui:
1166 // -> Use pending DOM UI if any.
1167 //
1168 // - First load in second tab: no committed nav entry + pending nav entry +
1169 // no pending DOM UI:
1170 // -> Use the committed DOM UI if any.
1171 //
1172 // - Second navigation in any tab: committed nav entry + pending nav entry:
1173 // -> Use pending DOM UI if any.
1174 //
1175 // - Normal state with no load: committed nav entry + no pending nav entry:
1176 // -> Use committed DOM UI.
1177 if (controller_.pending_entry() &&
1178 (controller_.GetLastCommittedEntry() ||
1179 render_manager_.pending_dom_ui()))
1180 return render_manager_.pending_dom_ui();
1181 return render_manager_.dom_ui();
1182}
[email protected]420ae012009-04-24 05:16:321183
1184void TabContents::DidNavigateMainFramePostCommit(
1185 const NavigationController::LoadCommittedDetails& details,
1186 const ViewHostMsg_FrameNavigate_Params& params) {
[email protected]420ae012009-04-24 05:16:321187 if (details.is_user_initiated_main_frame_load()) {
1188 // Clear the status bubble. This is a workaround for a bug where WebKit
1189 // doesn't let us know that the cursor left an element during a
1190 // transition (this is also why the mouse cursor remains as a hand after
1191 // clicking on a link); see bugs 1184641 and 980803. We don't want to
1192 // clear the bubble when a user navigates to a named anchor in the same
1193 // page.
1194 UpdateTargetURL(details.entry->page_id(), GURL());
1195
1196 // UpdateHelpersForDidNavigate will handle the case where the password_form
1197 // origin is valid.
1198 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1199 // cleaned up and covered by tests.
1200 if (!params.password_form.origin.is_valid())
1201 GetPasswordManager()->DidNavigate();
1202 }
1203
1204 // The keyword generator uses the navigation entries, so must be called after
1205 // the commit.
1206 GenerateKeywordIfNecessary(params);
1207
1208 // Allow the new page to set the title again.
1209 received_page_title_ = false;
1210
1211 // Get the favicon, either from history or request it from the net.
1212 fav_icon_helper_.FetchFavIcon(details.entry->url());
1213
[email protected]ce5c4502009-05-06 16:46:111214 // Disable all page actions.
1215 enabled_page_actions_.clear();
1216
[email protected]420ae012009-04-24 05:16:321217 // Close constrained popups if necessary.
1218 MaybeCloseChildWindows(details.previous_url, details.entry->url());
1219
1220 // Update the starred state.
1221 UpdateStarredStateForCurrentURL();
1222}
1223
1224void TabContents::DidNavigateAnyFramePostCommit(
1225 RenderViewHost* render_view_host,
1226 const NavigationController::LoadCommittedDetails& details,
1227 const ViewHostMsg_FrameNavigate_Params& params) {
1228 // If we navigate, start showing messages again. This does nothing to prevent
1229 // a malicious script from spamming messages, since the script could just
1230 // reload the page to stop blocking.
1231 suppress_javascript_messages_ = false;
1232
1233 // Update history. Note that this needs to happen after the entry is complete,
1234 // which WillNavigate[Main,Sub]Frame will do before this function is called.
1235 if (params.should_update_history) {
1236 // Most of the time, the displayURL matches the loaded URL, but for about:
1237 // URLs, we use a data: URL as the real value. We actually want to save
1238 // the about: URL to the history db and keep the data: URL hidden. This is
1239 // what the TabContents' URL getter does.
1240 UpdateHistoryForNavigation(GetURL(), params);
1241 }
1242
1243 // Notify the password manager of the navigation or form submit.
1244 // TODO(brettw) bug 1343111: Password manager stuff in here needs to be
1245 // cleaned up and covered by tests.
1246 if (params.password_form.origin.is_valid())
1247 GetPasswordManager()->ProvisionallySavePassword(params.password_form);
1248}
1249
1250void TabContents::MaybeCloseChildWindows(const GURL& previous_url,
1251 const GURL& current_url) {
1252 if (net::RegistryControlledDomainService::SameDomainOrHost(
1253 previous_url, current_url))
1254 return;
1255
1256 // Clear out any child windows since we are leaving this page entirely.
1257 // We use indices instead of iterators in case CloseWindow does something
1258 // that may invalidate an iterator.
1259 int size = static_cast<int>(child_windows_.size());
1260 for (int i = size - 1; i >= 0; --i) {
1261 ConstrainedWindow* window = child_windows_[i];
1262 if (window)
1263 window->CloseConstrainedWindow();
1264 }
1265}
1266
1267void TabContents::UpdateStarredStateForCurrentURL() {
1268 BookmarkModel* model = profile()->GetBookmarkModel();
1269 const bool old_state = is_starred_;
1270 is_starred_ = (model && model->IsBookmarked(GetURL()));
1271
1272 if (is_starred_ != old_state && delegate())
1273 delegate()->URLStarredChanged(this, is_starred_);
1274}
1275
1276void TabContents::UpdateAlternateErrorPageURL() {
1277 GURL url = GetAlternateErrorPageURL();
1278 render_view_host()->SetAlternateErrorPageURL(url);
1279}
1280
1281void TabContents::UpdateWebPreferences() {
1282 render_view_host()->UpdateWebPreferences(GetWebkitPrefs());
1283}
1284
1285void TabContents::UpdateMaxPageIDIfNecessary(SiteInstance* site_instance,
1286 RenderViewHost* rvh) {
1287 // If we are creating a RVH for a restored controller, then we might
1288 // have more page IDs than the SiteInstance's current max page ID. We must
1289 // make sure that the max page ID is larger than any restored page ID.
1290 // Note that it is ok for conflicting page IDs to exist in another tab
1291 // (i.e., NavigationController), but if any page ID is larger than the max,
1292 // the back/forward list will get confused.
1293 int max_restored_page_id = controller_.max_restored_page_id();
1294 if (max_restored_page_id > 0) {
1295 int curr_max_page_id = site_instance->max_page_id();
1296 if (max_restored_page_id > curr_max_page_id) {
1297 // Need to update the site instance immediately.
1298 site_instance->UpdateMaxPageID(max_restored_page_id);
1299
1300 // Also tell the renderer to update its internal representation. We
1301 // need to reserve enough IDs to make all restored page IDs less than
1302 // the max.
1303 if (curr_max_page_id < 0)
1304 curr_max_page_id = 0;
1305 rvh->ReservePageIDRange(max_restored_page_id - curr_max_page_id);
1306 }
1307 }
1308}
1309
1310void TabContents::UpdateHistoryForNavigation(
1311 const GURL& display_url,
1312 const ViewHostMsg_FrameNavigate_Params& params) {
1313 if (profile()->IsOffTheRecord())
1314 return;
1315
1316 // Add to history service.
1317 HistoryService* hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1318 if (hs) {
1319 if (PageTransition::IsMainFrame(params.transition) &&
1320 display_url != params.url) {
1321 // Hack on the "display" URL so that it will appear in history. For some
1322 // types of URLs, we will display a magic URL that is different from where
1323 // the page is actually navigated. We want the user to see in history
1324 // what they saw in the URL bar, so we add the display URL as a redirect.
1325 // This only applies to the main frame, as the display URL doesn't apply
1326 // to sub-frames.
1327 std::vector<GURL> redirects = params.redirects;
1328 if (!redirects.empty())
1329 redirects.back() = display_url;
1330 hs->AddPage(display_url, this, params.page_id, params.referrer,
1331 params.transition, redirects);
1332 } else {
1333 hs->AddPage(params.url, this, params.page_id, params.referrer,
1334 params.transition, params.redirects);
1335 }
1336 }
1337}
1338
1339bool TabContents::UpdateTitleForEntry(NavigationEntry* entry,
1340 const std::wstring& title) {
1341 // For file URLs without a title, use the pathname instead. In the case of a
1342 // synthesized title, we don't want the update to count toward the "one set
1343 // per page of the title to history."
1344 std::wstring final_title;
1345 bool explicit_set;
1346 if (entry->url().SchemeIsFile() && title.empty()) {
1347 final_title = UTF8ToWide(entry->url().ExtractFileName());
1348 explicit_set = false; // Don't count synthetic titles toward the set limit.
1349 } else {
1350 TrimWhitespace(title, TRIM_ALL, &final_title);
1351 explicit_set = true;
1352 }
1353
1354 if (final_title == UTF16ToWideHack(entry->title()))
1355 return false; // Nothing changed, don't bother.
1356
1357 entry->set_title(WideToUTF16Hack(final_title));
1358
1359 // Update the history system for this page.
1360 if (!profile()->IsOffTheRecord() && !received_page_title_) {
1361 HistoryService* hs =
1362 profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
1363 if (hs)
1364 hs->SetPageTitle(entry->display_url(), final_title);
1365
1366 // Don't allow the title to be saved again for explicitly set ones.
1367 received_page_title_ = explicit_set;
1368 }
1369
1370 // Lastly, set the title for the view.
1371 view_->SetPageTitle(final_title);
1372
1373 return true;
1374}
1375
1376void TabContents::NotifySwapped() {
1377 // After sending out a swap notification, we need to send a disconnect
1378 // notification so that clients that pick up a pointer to |this| can NULL the
1379 // pointer. See Bug 1230284.
1380 notify_disconnection_ = true;
1381 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341382 NotificationType::TAB_CONTENTS_SWAPPED,
1383 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321384 NotificationService::NoDetails());
1385}
1386
1387void TabContents::NotifyConnected() {
1388 notify_disconnection_ = true;
1389 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341390 NotificationType::TAB_CONTENTS_CONNECTED,
1391 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321392 NotificationService::NoDetails());
1393}
1394
1395void TabContents::NotifyDisconnected() {
1396 if (!notify_disconnection_)
1397 return;
1398
1399 notify_disconnection_ = false;
1400 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341401 NotificationType::TAB_CONTENTS_DISCONNECTED,
1402 Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321403 NotificationService::NoDetails());
1404}
1405
1406void TabContents::GenerateKeywordIfNecessary(
1407 const ViewHostMsg_FrameNavigate_Params& params) {
1408 if (!params.searchable_form_url.is_valid())
1409 return;
1410
1411 if (profile()->IsOffTheRecord())
1412 return;
1413
1414 int last_index = controller_.last_committed_entry_index();
1415 // When there was no previous page, the last index will be 0. This is
1416 // normally due to a form submit that opened in a new tab.
1417 // TODO(brettw) bug 916126: we should support keywords when form submits
1418 // happen in new tabs.
1419 if (last_index <= 0)
1420 return;
1421 const NavigationEntry* previous_entry =
1422 controller_.GetEntryAtIndex(last_index - 1);
1423 if (IsFormSubmit(previous_entry)) {
1424 // Only generate a keyword if the previous page wasn't itself a form
1425 // submit.
1426 return;
1427 }
1428
1429 GURL keyword_url = previous_entry->user_typed_url().is_valid() ?
1430 previous_entry->user_typed_url() : previous_entry->url();
1431 std::wstring keyword =
1432 TemplateURLModel::GenerateKeyword(keyword_url, true); // autodetected
1433 if (keyword.empty())
1434 return;
1435
1436 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1437 if (!url_model)
1438 return;
1439
1440 if (!url_model->loaded()) {
1441 url_model->Load();
1442 return;
1443 }
1444
1445 const TemplateURL* current_url;
1446 std::wstring url = UTF8ToWide(params.searchable_form_url.spec());
1447 if (!url_model->CanReplaceKeyword(keyword, url, &current_url))
1448 return;
1449
1450 if (current_url) {
1451 if (current_url->originating_url().is_valid()) {
1452 // The existing keyword was generated from an OpenSearch description
1453 // document, don't regenerate.
1454 return;
1455 }
1456 url_model->Remove(current_url);
1457 }
1458 TemplateURL* new_url = new TemplateURL();
1459 new_url->set_keyword(keyword);
1460 new_url->set_short_name(keyword);
1461 new_url->SetURL(url, 0, 0);
1462 new_url->add_input_encoding(params.searchable_form_encoding);
1463 DCHECK(controller_.GetLastCommittedEntry());
1464 const GURL& favicon_url =
1465 controller_.GetLastCommittedEntry()->favicon().url();
1466 if (favicon_url.is_valid()) {
1467 new_url->SetFavIconURL(favicon_url);
1468 } else {
1469 // The favicon url isn't valid. This means there really isn't a favicon,
1470 // or the favicon url wasn't obtained before the load started. This assumes
1471 // the later.
1472 // TODO(sky): Need a way to set the favicon that doesn't involve generating
1473 // its url.
1474 new_url->SetFavIconURL(TemplateURL::GenerateFaviconURL(params.referrer));
1475 }
1476 new_url->set_safe_for_autoreplace(true);
1477 url_model->Add(new_url);
1478}
1479
1480RenderViewHostDelegate::View* TabContents::GetViewDelegate() const {
1481 return view_.get();
1482}
1483
1484RenderViewHostDelegate::Save* TabContents::GetSaveDelegate() const {
1485 return save_package_.get(); // May be NULL, but we can return NULL.
1486}
1487
[email protected]6dfed102009-04-28 03:09:531488ExtensionFunctionDispatcher* TabContents::CreateExtensionFunctionDispatcher(
1489 RenderViewHost* render_view_host,
1490 const std::string& extension_id) {
1491 return delegate()->CreateExtensionFunctionDispatcher(render_view_host,
1492 extension_id);
1493}
1494
[email protected]57c6a652009-05-04 07:58:341495TabContents* TabContents::GetAsTabContents() {
1496 return this;
1497}
1498
[email protected]420ae012009-04-24 05:16:321499void TabContents::RenderViewCreated(RenderViewHost* render_view_host) {
1500 NavigationEntry* entry = controller_.GetActiveEntry();
1501 if (!entry)
1502 return;
1503
1504 // When we're creating views, we're still doing initial setup, so we always
1505 // use the pending DOM UI rather than any possibly existing committed one.
1506 if (render_manager_.pending_dom_ui()) {
1507 render_manager_.pending_dom_ui()->RenderViewCreated(render_view_host);
1508 }
1509
1510 if (entry->IsViewSourceMode()) {
1511 // Put the renderer in view source mode.
1512 render_view_host->Send(
1513 new ViewMsg_EnableViewSourceMode(render_view_host->routing_id()));
1514 }
[email protected]0666aef2009-05-13 19:48:081515
1516 view()->RenderViewCreated(render_view_host);
[email protected]420ae012009-04-24 05:16:321517}
1518
1519void TabContents::RenderViewReady(RenderViewHost* rvh) {
1520 if (rvh != render_view_host()) {
1521 // Don't notify the world, since this came from a renderer in the
1522 // background.
1523 return;
1524 }
1525
1526 NotifyConnected();
1527 SetIsCrashed(false);
1528}
1529
1530void TabContents::RenderViewGone(RenderViewHost* rvh) {
1531 // Ask the print preview if this renderer was valuable.
1532 if (!printing_.OnRenderViewGone(rvh))
1533 return;
1534 if (rvh != render_view_host()) {
1535 // The pending page's RenderViewHost is gone.
1536 return;
1537 }
1538
1539 SetIsLoading(false, NULL);
1540 NotifyDisconnected();
1541 SetIsCrashed(true);
1542
1543 // Force an invalidation to render sad tab. The view will notice we crashed
1544 // when it paints.
1545 view_->Invalidate();
1546
1547 // Hide any visible hung renderer warning for this web contents' process.
[email protected]8897c382009-05-06 17:53:261548 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:321549}
1550
1551void TabContents::DidNavigate(RenderViewHost* rvh,
1552 const ViewHostMsg_FrameNavigate_Params& params) {
1553 if (PageTransition::IsMainFrame(params.transition))
1554 render_manager_.DidNavigateMainFrame(rvh);
1555
1556 // Update the site of the SiteInstance if it doesn't have one yet.
1557 if (!GetSiteInstance()->has_site())
1558 GetSiteInstance()->SetSite(params.url);
1559
1560 // Need to update MIME type here because it's referred to in
1561 // UpdateNavigationCommands() called by RendererDidNavigate() to
1562 // determine whether or not to enable the encoding menu.
1563 // It's updated only for the main frame. For a subframe,
1564 // RenderView::UpdateURL does not set params.contents_mime_type.
1565 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
1566 // TODO(jungshik): Add a test for the encoding menu to avoid
1567 // regressing it again.
1568 if (PageTransition::IsMainFrame(params.transition))
1569 contents_mime_type_ = params.contents_mime_type;
1570
1571 NavigationController::LoadCommittedDetails details;
1572 if (!controller_.RendererDidNavigate(params, &details))
1573 return; // No navigation happened.
1574
1575 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
1576 // for the appropriate notification (best) or you can add it to
1577 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
1578 // necessary, please).
1579
1580 // Run post-commit tasks.
1581 if (details.is_main_frame)
1582 DidNavigateMainFramePostCommit(details, params);
1583 DidNavigateAnyFramePostCommit(rvh, details, params);
1584}
1585
1586void TabContents::UpdateState(RenderViewHost* rvh,
1587 int32 page_id,
1588 const std::string& state) {
1589 DCHECK(rvh == render_view_host());
1590
1591 // We must be prepared to handle state updates for any page, these occur
1592 // when the user is scrolling and entering form data, as well as when we're
1593 // leaving a page, in which case our state may have already been moved to
1594 // the next page. The navigation controller will look up the appropriate
1595 // NavigationEntry and update it when it is notified via the delegate.
1596
1597 int entry_index = controller_.GetEntryIndexWithPageID(
1598 GetSiteInstance(), page_id);
1599 if (entry_index < 0)
1600 return;
1601 NavigationEntry* entry = controller_.GetEntryAtIndex(entry_index);
1602
1603 if (state == entry->content_state())
1604 return; // Nothing to update.
1605 entry->set_content_state(state);
1606 controller_.NotifyEntryChanged(entry, entry_index);
1607}
1608
1609void TabContents::UpdateTitle(RenderViewHost* rvh,
1610 int32 page_id, const std::wstring& title) {
1611 // If we have a title, that's a pretty good indication that we've started
1612 // getting useful data.
1613 SetNotWaitingForResponse();
1614
1615 DCHECK(rvh == render_view_host());
1616 NavigationEntry* entry = controller_.GetEntryWithPageID(GetSiteInstance(),
1617 page_id);
1618 if (!entry || !UpdateTitleForEntry(entry, title))
1619 return;
1620
1621 // Broadcast notifications when the UI should be updated.
1622 if (entry == controller_.GetEntryAtOffset(0))
[email protected]c9cd2222009-05-06 05:16:501623 NotifyNavigationStateChanged(INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:321624}
1625
[email protected]420ae012009-04-24 05:16:321626void TabContents::UpdateEncoding(RenderViewHost* render_view_host,
1627 const std::wstring& encoding) {
1628 set_encoding(encoding);
1629}
1630
1631void TabContents::UpdateTargetURL(int32 page_id, const GURL& url) {
1632 if (delegate())
1633 delegate()->UpdateTargetURL(this, url);
1634}
1635
1636void TabContents::UpdateThumbnail(const GURL& url,
1637 const SkBitmap& bitmap,
1638 const ThumbnailScore& score) {
1639 // Tell History about this thumbnail
[email protected]449478302009-06-09 20:04:281640 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kThumbnailStore)) {
1641 profile()->GetThumbnailStore()->
1642 SetPageThumbnail(url, bitmap, score, !profile()->IsOffTheRecord());
1643 } else {
1644 HistoryService* hs;
1645 if (!profile()->IsOffTheRecord() &&
1646 (hs = profile()->GetHistoryService(Profile::IMPLICIT_ACCESS))) {
1647 hs->SetPageThumbnail(url, bitmap, score);
1648 }
[email protected]420ae012009-04-24 05:16:321649 }
1650}
1651
[email protected]0df30122009-06-03 12:13:081652void TabContents::UpdateInspectorSettings(const std::wstring& raw_settings) {
1653 profile()->GetPrefs()->SetString(prefs::kWebKitInspectorSettings,
1654 raw_settings);
1655}
1656
[email protected]420ae012009-04-24 05:16:321657void TabContents::Close(RenderViewHost* rvh) {
1658 // Ignore this if it comes from a RenderViewHost that we aren't showing.
1659 if (delegate() && rvh == render_view_host())
1660 delegate()->CloseContents(this);
1661}
1662
1663void TabContents::RequestMove(const gfx::Rect& new_bounds) {
1664 if (delegate() && delegate()->IsPopup(this))
1665 delegate()->MoveContents(this, new_bounds);
1666}
1667
[email protected]329581b2009-04-28 06:52:351668void TabContents::DidStartLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321669 SetIsLoading(true, NULL);
1670}
1671
[email protected]329581b2009-04-28 06:52:351672void TabContents::DidStopLoading(RenderViewHost* rvh) {
[email protected]420ae012009-04-24 05:16:321673 scoped_ptr<LoadNotificationDetails> details;
1674
1675 NavigationEntry* entry = controller_.GetActiveEntry();
1676 // An entry may not exist for a stop when loading an initial blank page or
1677 // if an iframe injected by script into a blank page finishes loading.
1678 if (entry) {
1679 scoped_ptr<base::ProcessMetrics> metrics(
1680 base::ProcessMetrics::CreateProcessMetrics(
1681 process()->process().handle()));
1682
1683 base::TimeDelta elapsed = base::TimeTicks::Now() - current_load_start_;
1684
1685 details.reset(new LoadNotificationDetails(
1686 entry->display_url(),
1687 entry->transition_type(),
1688 elapsed,
1689 &controller_,
1690 controller_.GetCurrentEntryIndex()));
1691 }
1692
1693 // Tell PasswordManager we've finished a page load, which serves as a
1694 // green light to save pending passwords and reset itself.
1695 GetPasswordManager()->DidStopLoading();
1696
1697 SetIsLoading(false, details.get());
1698}
1699
1700void TabContents::DidStartProvisionalLoadForFrame(
1701 RenderViewHost* render_view_host,
1702 bool is_main_frame,
1703 const GURL& url) {
1704 ProvisionalLoadDetails details(is_main_frame,
1705 controller_.IsURLInPageNavigation(url),
1706 url, std::string(), false);
1707 NotificationService::current()->Notify(
1708 NotificationType::FRAME_PROVISIONAL_LOAD_START,
1709 Source<NavigationController>(&controller_),
1710 Details<ProvisionalLoadDetails>(&details));
1711}
1712
1713void TabContents::DidRedirectProvisionalLoad(int32 page_id,
1714 const GURL& source_url,
1715 const GURL& target_url) {
1716 NavigationEntry* entry;
1717 if (page_id == -1)
1718 entry = controller_.pending_entry();
1719 else
1720 entry = controller_.GetEntryWithPageID(GetSiteInstance(), page_id);
1721 if (!entry || entry->url() != source_url)
1722 return;
1723 entry->set_url(target_url);
1724}
1725
1726void TabContents::DidLoadResourceFromMemoryCache(
1727 const GURL& url,
1728 const std::string& frame_origin,
1729 const std::string& main_frame_origin,
1730 const std::string& security_info) {
1731 // Send out a notification that we loaded a resource from our memory cache.
1732 int cert_id = 0, cert_status = 0, security_bits = 0;
1733 SSLManager::DeserializeSecurityInfo(security_info,
1734 &cert_id, &cert_status,
1735 &security_bits);
1736 LoadFromMemoryCacheDetails details(url, frame_origin, main_frame_origin,
[email protected]9ae66cbf2009-05-12 16:21:031737 process()->pid(), cert_id, cert_status);
[email protected]420ae012009-04-24 05:16:321738
1739 NotificationService::current()->Notify(
1740 NotificationType::LOAD_FROM_MEMORY_CACHE,
1741 Source<NavigationController>(&controller_),
1742 Details<LoadFromMemoryCacheDetails>(&details));
1743}
1744
1745void TabContents::DidFailProvisionalLoadWithError(
1746 RenderViewHost* render_view_host,
1747 bool is_main_frame,
1748 int error_code,
1749 const GURL& url,
1750 bool showing_repost_interstitial) {
1751 if (net::ERR_ABORTED == error_code) {
1752 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
1753 // This means that the interstitial won't be torn down properly, which is
1754 // bad. But if we have an interstitial, go back to another tab type, and
1755 // then load the same interstitial again, we could end up getting the first
1756 // interstitial's "failed" message (as a result of the cancel) when we're on
1757 // the second one.
1758 //
1759 // We can't tell this apart, so we think we're tearing down the current page
1760 // which will cause a crash later one. There is also some code in
1761 // RenderViewHostManager::RendererAbortedProvisionalLoad that is commented
1762 // out because of this problem.
1763 //
1764 // http://code.google.com/p/chromium/issues/detail?id=2855
1765 // Because this will not tear down the interstitial properly, if "back" is
1766 // back to another tab type, the interstitial will still be somewhat alive
1767 // in the previous tab type. If you navigate somewhere that activates the
1768 // tab with the interstitial again, you'll see a flash before the new load
1769 // commits of the interstitial page.
1770 if (showing_interstitial_page()) {
1771 LOG(WARNING) << "Discarding message during interstitial.";
1772 return;
1773 }
1774
1775 // This will discard our pending entry if we cancelled the load (e.g., if we
1776 // decided to download the file instead of load it). Only discard the
1777 // pending entry if the URLs match, otherwise the user initiated a navigate
1778 // before the page loaded so that the discard would discard the wrong entry.
1779 NavigationEntry* pending_entry = controller_.pending_entry();
1780 if (pending_entry && pending_entry->url() == url)
1781 controller_.DiscardNonCommittedEntries();
1782
1783 render_manager_.RendererAbortedProvisionalLoad(render_view_host);
1784 }
1785
1786 // Send out a notification that we failed a provisional load with an error.
1787 ProvisionalLoadDetails details(is_main_frame,
1788 controller_.IsURLInPageNavigation(url),
1789 url, std::string(), false);
1790 details.set_error_code(error_code);
1791
1792 NotificationService::current()->Notify(
1793 NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,
1794 Source<NavigationController>(&controller_),
1795 Details<ProvisionalLoadDetails>(&details));
1796}
1797
1798void TabContents::UpdateFavIconURL(RenderViewHost* render_view_host,
1799 int32 page_id,
1800 const GURL& icon_url) {
1801 fav_icon_helper_.SetFavIconURL(icon_url);
1802}
1803
1804void TabContents::DidDownloadImage(
1805 RenderViewHost* render_view_host,
1806 int id,
1807 const GURL& image_url,
1808 bool errored,
1809 const SkBitmap& image) {
1810 // A notification for downloading would be more flexible, but for now I'm
1811 // forwarding to the two places that could possibly have initiated the
1812 // request. If we end up with another place invoking DownloadImage, probably
1813 // best to refactor out into notification service, or something similar.
1814 if (errored)
1815 fav_icon_helper_.FavIconDownloadFailed(id);
1816 else
1817 fav_icon_helper_.SetFavIcon(id, image_url, image);
1818}
1819
1820void TabContents::RequestOpenURL(const GURL& url, const GURL& referrer,
1821 WindowOpenDisposition disposition) {
1822 if (render_manager_.dom_ui()) {
1823 // When we're a DOM UI, it will provide a page transition type for us (this
1824 // is so the new tab page can specify AUTO_BOOKMARK for automatically
1825 // generated suggestions).
1826 //
1827 // Note also that we hide the referrer for DOM UI pages. We don't really
[email protected]60e448982009-05-06 04:21:161828 // want web sites to see a referrer of "chrome://blah" (and some
1829 // chrome: URLs might have search terms or other stuff we don't want to
[email protected]420ae012009-04-24 05:16:321830 // send to the site), so we send no referrer.
1831 OpenURL(url, GURL(), disposition,
1832 render_manager_.dom_ui()->link_transition_type());
1833 } else {
1834 OpenURL(url, referrer, disposition, PageTransition::LINK);
1835 }
1836}
1837
1838void TabContents::DomOperationResponse(const std::string& json_string,
1839 int automation_id) {
1840 DomOperationNotificationDetails details(json_string, automation_id);
1841 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:341842 NotificationType::DOM_OPERATION_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:321843 Details<DomOperationNotificationDetails>(&details));
1844}
1845
1846void TabContents::ProcessDOMUIMessage(const std::string& message,
1847 const std::string& content) {
1848 if (!render_manager_.dom_ui()) {
1849 // We shouldn't get a DOM UI message when we haven't enabled the DOM UI.
1850 // Because the renderer might be owned and sending random messages, we need
1851 // to ignore these inproper ones.
1852 NOTREACHED();
1853 return;
1854 }
1855 render_manager_.dom_ui()->ProcessDOMUIMessage(message, content);
1856}
1857
1858void TabContents::ProcessExternalHostMessage(const std::string& message,
1859 const std::string& origin,
1860 const std::string& target) {
1861 if (delegate())
1862 delegate()->ForwardMessageToExternalHost(message, origin, target);
1863}
1864
1865void TabContents::GoToEntryAtOffset(int offset) {
1866 controller_.GoToOffset(offset);
1867}
1868
1869void TabContents::GetHistoryListCount(int* back_list_count,
1870 int* forward_list_count) {
1871 int current_index = controller_.last_committed_entry_index();
1872 *back_list_count = current_index;
1873 *forward_list_count = controller_.entry_count() - current_index - 1;
1874}
1875
1876void TabContents::RunFileChooser(bool multiple_files,
1877 const string16& title,
1878 const FilePath& default_file) {
1879 if (!select_file_dialog_.get())
1880 select_file_dialog_ = SelectFileDialog::Create(this);
1881 SelectFileDialog::Type dialog_type =
1882 multiple_files ? SelectFileDialog::SELECT_OPEN_MULTI_FILE :
1883 SelectFileDialog::SELECT_OPEN_FILE;
1884 select_file_dialog_->SelectFile(dialog_type, title, default_file,
1885 NULL, 0, FILE_PATH_LITERAL(""),
1886 view_->GetTopLevelNativeWindow(), NULL);
1887}
1888
1889void TabContents::RunJavaScriptMessage(
1890 const std::wstring& message,
1891 const std::wstring& default_prompt,
1892 const GURL& frame_url,
1893 const int flags,
1894 IPC::Message* reply_msg,
1895 bool* did_suppress_message) {
1896 // Suppress javascript messages when requested and when inside a constrained
1897 // popup window (because that activates them and breaks them out of the
1898 // constrained window jail).
1899 bool suppress_this_message = suppress_javascript_messages_;
1900 if (delegate())
1901 suppress_this_message |=
[email protected]b6c874582009-05-08 19:38:311902 (delegate()->GetConstrainingContents(this) != this);
[email protected]420ae012009-04-24 05:16:321903
1904 *did_suppress_message = suppress_this_message;
1905
1906 if (!suppress_this_message) {
1907 base::TimeDelta time_since_last_message(
1908 base::TimeTicks::Now() - last_javascript_message_dismissal_);
1909 bool show_suppress_checkbox = false;
1910 // Show a checkbox offering to suppress further messages if this message is
1911 // being displayed within kJavascriptMessageExpectedDelay of the last one.
1912 if (time_since_last_message <
1913 base::TimeDelta::FromMilliseconds(kJavascriptMessageExpectedDelay))
1914 show_suppress_checkbox = true;
1915
1916 RunJavascriptMessageBox(AsWC(this), frame_url, flags, message, default_prompt,
1917 show_suppress_checkbox, reply_msg);
1918 } else {
1919 // If we are suppressing messages, just reply as is if the user immediately
1920 // pressed "Cancel".
1921 OnJavaScriptMessageBoxClosed(reply_msg, false, std::wstring());
1922 }
1923}
1924
1925void TabContents::RunBeforeUnloadConfirm(const std::wstring& message,
1926 IPC::Message* reply_msg) {
1927 RunBeforeUnloadDialog(AsWC(this), message, reply_msg);
1928}
1929
1930void TabContents::ShowModalHTMLDialog(const GURL& url, int width, int height,
1931 const std::string& json_arguments,
1932 IPC::Message* reply_msg) {
1933 if (delegate()) {
1934 HtmlDialogUIDelegate* dialog_delegate =
1935 new ModalHtmlDialogDelegate(url, width, height, json_arguments,
1936 reply_msg, AsWC(this));
1937 delegate()->ShowHtmlDialog(dialog_delegate, NULL);
1938 }
1939}
1940
1941void TabContents::PasswordFormsSeen(
1942 const std::vector<PasswordForm>& forms) {
1943 GetPasswordManager()->PasswordFormsSeen(forms);
1944}
1945
1946void TabContents::AutofillFormSubmitted(
1947 const AutofillForm& form) {
1948 GetAutofillManager()->AutofillFormSubmitted(form);
1949}
1950
1951void TabContents::GetAutofillSuggestions(const std::wstring& field_name,
1952 const std::wstring& user_text, int64 node_id, int request_id) {
1953 GetAutofillManager()->FetchValuesForName(field_name, user_text,
1954 kMaxAutofillMenuItems, node_id, request_id);
1955}
1956
1957void TabContents::RemoveAutofillEntry(const std::wstring& field_name,
1958 const std::wstring& value) {
1959 GetAutofillManager()->RemoveValueForName(field_name, value);
1960}
1961
1962// Checks to see if we should generate a keyword based on the OSDD, and if
1963// necessary uses TemplateURLFetcher to download the OSDD and create a keyword.
1964void TabContents::PageHasOSDD(RenderViewHost* render_view_host,
1965 int32 page_id, const GURL& url,
1966 bool autodetected) {
1967 // Make sure page_id is the current page, and the TemplateURLModel is loaded.
1968 DCHECK(url.is_valid());
1969 if (!IsActiveEntry(page_id))
1970 return;
1971 TemplateURLModel* url_model = profile()->GetTemplateURLModel();
1972 if (!url_model)
1973 return;
1974 if (!url_model->loaded()) {
1975 url_model->Load();
1976 return;
1977 }
1978 if (!profile()->GetTemplateURLFetcher())
1979 return;
1980
1981 if (profile()->IsOffTheRecord())
1982 return;
1983
1984 const NavigationEntry* entry = controller_.GetLastCommittedEntry();
1985 DCHECK(entry);
1986
1987 const NavigationEntry* base_entry = entry;
1988 if (IsFormSubmit(base_entry)) {
1989 // If the current page is a form submit, find the last page that was not
1990 // a form submit and use its url to generate the keyword from.
1991 int index = controller_.last_committed_entry_index() - 1;
1992 while (index >= 0 && IsFormSubmit(controller_.GetEntryAtIndex(index)))
1993 index--;
1994 if (index >= 0)
1995 base_entry = controller_.GetEntryAtIndex(index);
1996 else
1997 base_entry = NULL;
1998 }
1999
2000 // We want to use the user typed URL if available since that represents what
2001 // the user typed to get here, and fall back on the regular URL if not.
2002 if (!base_entry)
2003 return;
2004 GURL keyword_url = base_entry->user_typed_url().is_valid() ?
2005 base_entry->user_typed_url() : base_entry->url();
2006 if (!keyword_url.is_valid())
2007 return;
2008 std::wstring keyword = TemplateURLModel::GenerateKeyword(keyword_url,
2009 autodetected);
2010 if (keyword.empty())
2011 return;
2012 const TemplateURL* template_url =
2013 url_model->GetTemplateURLForKeyword(keyword);
2014 if (template_url && (!template_url->safe_for_autoreplace() ||
2015 template_url->originating_url() == url)) {
2016 // Either there is a user created TemplateURL for this keyword, or the
2017 // keyword has the same OSDD url and we've parsed it.
2018 return;
2019 }
2020
2021 // Download the OpenSearch description document. If this is successful a
2022 // new keyword will be created when done.
2023#if defined(OS_WIN)
2024 gfx::NativeView ancestor = GetAncestor(view_->GetNativeView(), GA_ROOT);
2025#else
2026 gfx::NativeView ancestor = NULL;
2027#endif
2028 profile()->GetTemplateURLFetcher()->ScheduleDownload(
2029 keyword,
2030 url,
2031 base_entry->favicon().url(),
2032 ancestor,
2033 autodetected);
2034}
2035
2036void TabContents::InspectElementReply(int num_resources) {
2037 // We have received reply from inspect element request. Notify the
2038 // automation provider in case we need to notify automation client.
2039 NotificationService::current()->Notify(
[email protected]57c6a652009-05-04 07:58:342040 NotificationType::DOM_INSPECT_ELEMENT_RESPONSE, Source<TabContents>(AsWC(this)),
[email protected]420ae012009-04-24 05:16:322041 Details<int>(&num_resources));
2042}
2043
2044void TabContents::DidGetPrintedPagesCount(int cookie, int number_pages) {
2045 printing_.DidGetPrintedPagesCount(cookie, number_pages);
2046}
2047
2048void TabContents::DidPrintPage(const ViewHostMsg_DidPrintPage_Params& params) {
2049 printing_.DidPrintPage(params);
2050}
2051
2052GURL TabContents::GetAlternateErrorPageURL() const {
2053 GURL url;
2054 // Disable alternate error pages when in OffTheRecord/Incognito mode.
2055 if (profile()->IsOffTheRecord())
2056 return url;
2057
2058 PrefService* prefs = profile()->GetPrefs();
2059 DCHECK(prefs);
2060 if (prefs->GetBoolean(prefs::kAlternateErrorPagesEnabled)) {
2061 url = google_util::AppendGoogleLocaleParam(GURL(kLinkDoctorBaseURL));
2062 url = google_util::AppendGoogleTLDParam(url);
2063 }
2064 return url;
2065}
2066
2067WebPreferences TabContents::GetWebkitPrefs() {
2068 PrefService* prefs = render_view_host()->process()->profile()->GetPrefs();
2069 bool isDomUI = false;
2070 return RenderViewHostDelegateHelper::GetWebkitPrefs(prefs, isDomUI);
2071}
2072
2073void TabContents::OnMissingPluginStatus(int status) {
2074#if defined(OS_WIN)
2075// TODO(PORT): pull in when plug-ins work
2076 GetPluginInstaller()->OnMissingPluginStatus(status);
2077#endif
2078}
2079
2080void TabContents::OnCrashedPlugin(const FilePath& plugin_path) {
2081#if defined(OS_WIN)
2082// TODO(PORT): pull in when plug-ins work
2083 DCHECK(!plugin_path.value().empty());
2084
2085 std::wstring plugin_name = plugin_path.ToWStringHack();
2086 scoped_ptr<FileVersionInfo> version_info(
2087 FileVersionInfo::CreateFileVersionInfo(plugin_path));
2088 if (version_info.get()) {
2089 const std::wstring& product_name = version_info->product_name();
2090 if (!product_name.empty())
2091 plugin_name = product_name;
2092 }
2093 AddInfoBar(new SimpleAlertInfoBarDelegate(
2094 this, l10n_util::GetStringF(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
2095 NULL));
2096#endif
2097}
2098
2099void TabContents::OnCrashedWorker() {
2100 AddInfoBar(new SimpleAlertInfoBarDelegate(
2101 this, l10n_util::GetString(IDS_WEBWORKER_CRASHED_PROMPT),
2102 NULL));
2103}
2104
2105void TabContents::OnJSOutOfMemory() {
2106 AddInfoBar(new SimpleAlertInfoBarDelegate(
2107 this, l10n_util::GetString(IDS_JS_OUT_OF_MEMORY_PROMPT), NULL));
2108}
2109
2110void TabContents::ShouldClosePage(bool proceed) {
2111 render_manager_.ShouldClosePage(proceed);
2112}
2113
2114void TabContents::OnCrossSiteResponse(int new_render_process_host_id,
2115 int new_request_id) {
[email protected]57c6a652009-05-04 07:58:342116 // Allows the TabContents to react when a cross-site response is ready to be
[email protected]420ae012009-04-24 05:16:322117 // delivered to a pending RenderViewHost. We must first run the onunload
2118 // handler of the old RenderViewHost before we can allow it to proceed.
2119 render_manager_.OnCrossSiteResponse(new_render_process_host_id,
2120 new_request_id);
2121}
2122
2123bool TabContents::CanBlur() const {
2124 return delegate() ? delegate()->CanBlur() : true;
2125}
2126
2127gfx::Rect TabContents::GetRootWindowResizerRect() const {
2128 if (delegate())
2129 return delegate()->GetRootWindowResizerRect();
2130 return gfx::Rect();
2131}
2132
2133void TabContents::RendererUnresponsive(RenderViewHost* rvh,
2134 bool is_during_unload) {
2135 if (is_during_unload) {
2136 // Hang occurred while firing the beforeunload/unload handler.
2137 // Pretend the handler fired so tab closing continues as if it had.
[email protected]829e7612009-04-25 01:15:112138 rvh->set_sudden_termination_allowed(true);
[email protected]420ae012009-04-24 05:16:322139
2140 if (!render_manager_.ShouldCloseTabOnUnresponsiveRenderer())
2141 return;
2142
2143 // If the tab hangs in the beforeunload/unload handler there's really
2144 // nothing we can do to recover. Pretend the unload listeners have
2145 // all fired and close the tab. If the hang is in the beforeunload handler
2146 // then the user will not have the option of cancelling the close.
2147 Close(rvh);
2148 return;
2149 }
2150
2151 if (render_view_host() && render_view_host()->IsRenderViewLive())
[email protected]8897c382009-05-06 17:53:262152 HungRendererDialog::ShowForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322153}
2154
2155void TabContents::RendererResponsive(RenderViewHost* render_view_host) {
[email protected]8897c382009-05-06 17:53:262156 HungRendererDialog::HideForTabContents(AsWC(this));
[email protected]420ae012009-04-24 05:16:322157}
2158
2159void TabContents::LoadStateChanged(const GURL& url,
2160 net::LoadState load_state) {
2161 load_state_ = load_state;
[email protected]d686e812009-06-03 19:10:292162 std::wstring languages =
2163 profile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
2164 load_state_host_.clear();
2165 std::string host = url.host();
2166 net::IDNToUnicode(host.c_str(), host.size(), languages, &load_state_host_);
[email protected]420ae012009-04-24 05:16:322167 if (load_state_ == net::LOAD_STATE_READING_RESPONSE)
2168 SetNotWaitingForResponse();
2169 if (is_loading())
[email protected]c9cd2222009-05-06 05:16:502170 NotifyNavigationStateChanged(INVALIDATE_LOAD | INVALIDATE_TAB);
[email protected]420ae012009-04-24 05:16:322171}
2172
2173void TabContents::OnDidGetApplicationInfo(
2174 int32 page_id,
2175 const webkit_glue::WebApplicationInfo& info) {
2176 if (pending_install_.page_id != page_id)
2177 return; // The user clicked create on a separate page. Ignore this.
2178
2179 pending_install_.callback_functor =
2180 new GearsCreateShortcutCallbackFunctor(this);
2181 GearsCreateShortcut(
2182 info, pending_install_.title, pending_install_.url, pending_install_.icon,
2183 NewCallback(pending_install_.callback_functor,
2184 &GearsCreateShortcutCallbackFunctor::Run));
2185}
2186
[email protected]14ce83f2009-05-28 18:35:242187void TabContents::OnUserGesture() {
2188 // See comment in RenderViewHostDelegate::OnUserGesture as to why we do this.
2189#if defined(OS_WIN) || defined(OS_LINUX)
[email protected]420ae012009-04-24 05:16:322190 DownloadRequestManager* drm = g_browser_process->download_request_manager();
2191 if (drm)
2192 drm->OnUserGesture(this);
2193#endif
2194}
2195
2196void TabContents::OnFindReply(int request_id,
2197 int number_of_matches,
2198 const gfx::Rect& selection_rect,
2199 int active_match_ordinal,
2200 bool final_update) {
2201 // Ignore responses for requests other than the one we have most recently
2202 // issued. That way we won't act on stale results when the user has
2203 // already typed in another query.
2204 if (request_id != current_find_request_id_)
2205 return;
2206
2207 if (number_of_matches == -1)
[email protected]e491f1c2009-05-22 20:28:122208 number_of_matches = last_search_result_.number_of_matches();
[email protected]420ae012009-04-24 05:16:322209 if (active_match_ordinal == -1)
[email protected]e491f1c2009-05-22 20:28:122210 active_match_ordinal = last_search_result_.active_match_ordinal();
[email protected]420ae012009-04-24 05:16:322211
[email protected]2c355c282009-05-21 23:24:432212 gfx::Rect selection = selection_rect;
2213 if (selection.IsEmpty())
[email protected]e491f1c2009-05-22 20:28:122214 selection = last_search_result_.selection_rect();
[email protected]2c355c282009-05-21 23:24:432215
[email protected]420ae012009-04-24 05:16:322216 // Notify the UI, automation and any other observers that a find result was
2217 // found.
[email protected]e491f1c2009-05-22 20:28:122218 last_search_result_ = FindNotificationDetails(request_id, number_of_matches,
2219 selection, active_match_ordinal,
2220 final_update);
[email protected]420ae012009-04-24 05:16:322221 NotificationService::current()->Notify(
2222 NotificationType::FIND_RESULT_AVAILABLE,
2223 Source<TabContents>(this),
[email protected]e491f1c2009-05-22 20:28:122224 Details<FindNotificationDetails>(&last_search_result_));
[email protected]420ae012009-04-24 05:16:322225}
2226
[email protected]829e7612009-04-25 01:15:112227bool TabContents::IsExternalTabContainer() const {
[email protected]420ae012009-04-24 05:16:322228 if (!delegate())
[email protected]829e7612009-04-25 01:15:112229 return false;
[email protected]420ae012009-04-24 05:16:322230
[email protected]829e7612009-04-25 01:15:112231 return delegate()->IsExternalTabContainer();
[email protected]420ae012009-04-24 05:16:322232}
2233
2234void TabContents::FileSelected(const FilePath& path,
2235 int index, void* params) {
2236 render_view_host()->FileSelected(path);
2237}
2238
2239void TabContents::MultiFilesSelected(const std::vector<FilePath>& files,
2240 void* params) {
2241 render_view_host()->MultiFilesSelected(files);
2242}
2243
2244void TabContents::FileSelectionCanceled(void* params) {
2245 // If the user cancels choosing a file to upload we pass back an
2246 // empty vector.
2247 render_view_host()->MultiFilesSelected(std::vector<FilePath>());
2248}
2249
2250void TabContents::BeforeUnloadFiredFromRenderManager(
2251 bool proceed,
2252 bool* proceed_to_fire_unload) {
2253 if (delegate())
2254 delegate()->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
2255}
2256
2257void TabContents::UpdateRenderViewSizeForRenderManager() {
2258 // TODO(brettw) this is a hack. See TabContentsView::SizeContents.
2259 view_->SizeContents(view_->GetContainerSize());
2260}
2261
2262DOMUI* TabContents::CreateDOMUIForRenderManager(const GURL& url) {
2263 return DOMUIFactory::CreateDOMUIForURL(AsWC(this), url);
2264}
2265
2266NavigationEntry*
2267TabContents::GetLastCommittedNavigationEntryForRenderManager() {
2268 return controller_.GetLastCommittedEntry();
2269}
2270
2271bool TabContents::CreateRenderViewForRenderManager(
2272 RenderViewHost* render_view_host) {
2273 // When we're running a DOM UI, the RenderViewHost needs to be put in DOM UI
2274 // mode before CreateRenderView is called. When we're asked to create a
2275 // RenderView, that means it's for the pending entry, so we have to use the
2276 // pending DOM UI.
2277 if (render_manager_.pending_dom_ui())
2278 render_view_host->AllowDOMUIBindings();
2279
[email protected]1adff062009-06-02 18:39:552280 // Ditto for extension bindings.
2281 if (controller().pending_entry()->url().SchemeIs(chrome::kExtensionScheme))
2282 render_view_host->AllowExtensionBindings();
2283
[email protected]420ae012009-04-24 05:16:322284 RenderWidgetHostView* rwh_view = view_->CreateViewForWidget(render_view_host);
2285 if (!render_view_host->CreateRenderView())
2286 return false;
2287
2288 // Now that the RenderView has been created, we need to tell it its size.
2289 rwh_view->SetSize(view_->GetContainerSize());
2290
2291 UpdateMaxPageIDIfNecessary(render_view_host->site_instance(),
2292 render_view_host);
2293 return true;
2294}
2295
2296void TabContents::Observe(NotificationType type,
2297 const NotificationSource& source,
2298 const NotificationDetails& details) {
2299 switch (type.value) {
2300 case NotificationType::BOOKMARK_MODEL_LOADED:
2301 // BookmarkModel finished loading, fall through to update starred state.
2302 case NotificationType::URLS_STARRED: {
2303 // Somewhere, a URL has been starred.
2304 // Ignore notifications for profiles other than our current one.
2305 Profile* source_profile = Source<Profile>(source).ptr();
2306 if (!source_profile || !source_profile->IsSameProfile(profile()))
2307 return;
2308
2309 UpdateStarredStateForCurrentURL();
2310 break;
2311 }
2312 case NotificationType::PREF_CHANGED: {
2313 std::wstring* pref_name_in = Details<std::wstring>(details).ptr();
2314 DCHECK(Source<PrefService>(source).ptr() == profile()->GetPrefs());
2315 if (*pref_name_in == prefs::kAlternateErrorPagesEnabled) {
2316 UpdateAlternateErrorPageURL();
2317 } else if (*pref_name_in == prefs::kDefaultCharset ||
2318 StartsWithASCII(WideToUTF8(*pref_name_in), "webkit.webprefs.", true)
2319 ) {
2320 UpdateWebPreferences();
2321 } else {
2322 NOTREACHED() << "unexpected pref change notification" << *pref_name_in;
2323 }
2324 break;
2325 }
2326 case NotificationType::RENDER_WIDGET_HOST_DESTROYED:
2327 view_->RenderWidgetHostDestroyed(Source<RenderWidgetHost>(source).ptr());
2328 break;
2329
2330 case NotificationType::NAV_ENTRY_COMMITTED: {
2331 DCHECK(&controller_ == Source<NavigationController>(source).ptr());
2332
2333 NavigationController::LoadCommittedDetails& committed_details =
2334 *(Details<NavigationController::LoadCommittedDetails>(details).ptr());
2335 ExpireInfoBars(committed_details);
2336 break;
2337 }
2338
2339 default:
2340 NOTREACHED();
2341 }
2342}